@stacksjs/build 0.75.558 → 0.75.560
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +121 -121
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var ye=(e,t,i)=>()=>{if(e)try{t=e(e=0)}catch(r){i=[r]}if(i)throw i[0];return t};var
|
|
2
|
+
var ye=(e,t,i)=>()=>{if(e)try{t=e(e=0)}catch(r){i=[r]}if(i)throw i[0];return t};var Ch=import.meta.require;function mr(e){if(Sh)return Bun.hash(e);let t=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);t=(t<<5)-t+r,t=t&t}return t}var Sh;var ts=ye(()=>{Sh=typeof globalThis.Bun?.hash==="function"});import{existsSync as rn,mkdirSync as Eh,readFileSync as rs,renameSync as Ah,rmdirSync as kh,rmSync as Al,statSync as Sl,writeFileSync as kl}from"fs";import{join as ns,relative as tn,resolve as El}from"path";function Th(e){try{Al(ns(e,Tl),{force:!0});try{kh(e)}catch{}}catch{}}class os{cacheDir;manifestPath;manifest=null;configHash;constructor(e,t){this.cacheDir=El(e.cwd,e.cacheDir??nn),this.manifestPath=ns(this.cacheDir,Tl),this.configHash=this.hashConfig(e,t)}hashConfig(e,t){let i={resolutionContext:t,keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,moduleSpecifierMode:e.moduleSpecifierMode??"preserve",root:El(e.cwd,e.root),exclude:e.exclude??[],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(mr(JSON.stringify(i)))}hashString(e){return String(mr(e))}load(){try{if(!rn(this.manifestPath))return!1;let e=rs(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==is)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:is,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!rn(this.cacheDir))Eh(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{kl(e,JSON.stringify(this.manifest,null,2)),Ah(e,this.manifestPath)}finally{if(rn(e))Al(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 i=tn(t,e),r=this.manifest.entries[i];if(!r)return null;if(typeof r.dtsContent!=="string"||typeof r.dtsHash!=="string"||r.configHash!==this.configHash||this.hashString(r.dtsContent)!==r.dtsHash)return null;try{let n=Sl(e),{mtimeMs:o,ctimeMs:s}=n;if(n.size!==r.sourceSize)return null;if(o!==r.sourceMtime||s!==r.sourceCtime){let a=rs(e,"utf-8");if(this.hashString(a)!==r.sourceHash)return null;r.sourceMtime=o,r.sourceCtime=s}return r.dtsContent}catch{return null}}update(e,t,i,r){if(!this.manifest)this.manifest={version:is,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let n=tn(r,e),o,s,a;try{let l=Sl(e);o=l.mtimeMs,s=l.ctimeMs,a=l.size}catch{o=Date.now(),s=o,a=Buffer.byteLength(t)}this.manifest.entries[n]={sourcePath:n,sourceHash:this.hashString(t),sourceMtime:o,sourceCtime:s,sourceSize:a,dtsContent:i,dtsHash:this.hashString(i),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let i=tn(t,e);delete this.manifest.entries[i]}clear(){this.manifest=null,Th(this.cacheDir)}getStats(){if(!this.manifest)return{entries:0,size:0};let e=Object.keys(this.manifest.entries).length,t=0;for(let i of Object.values(this.manifest.entries))t+=i.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let i=0,r=new Set(Array.from(e).map((n)=>tn(t,n)));for(let n of Object.keys(this.manifest.entries))if(!r.has(n))delete this.manifest.entries[n],i++;return i}}function Ol(e){let t=ns(e,".gitignore");try{let i="";if(rn(t))i=rs(t,"utf-8");if(!i.split(/\r?\n/).some((r)=>r.trim()===nn||r.trim()===`${nn}/`)){let r=i.trimEnd(),n=`${r}${r?`
|
|
3
3
|
|
|
4
4
|
`:""}# dtsx cache
|
|
5
5
|
${nn}/
|
|
6
|
-
`;
|
|
6
|
+
`;kl(t,n)}}catch{}}var is=29,nn=".dtsx-cache",Tl="manifest.json";var Rl=ye(()=>{ts()});import{readFile as Oh,stat as v0,writeFile as Rh}from"fs/promises";async function Pl(e,t){if(on)return globalThis.Bun.write(e,t);let i=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await Rh(e,i),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function Et(e){if(on)return globalThis.Bun.file(e).text();return Oh(e,"utf-8")}var on,b0;var gr=ye(()=>{on=typeof globalThis.Bun<"u",b0=!on&&typeof process<"u"&&!!process.versions?.node});function Ml(e,t){let i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1;if(e===void 0||!Number.isFinite(e))return i;return Math.max(1,Math.floor(e))}var Dl=()=>{};function cn(e){return e.endsWith(".vue")}function Ph(e){let t={script:null,scriptSetup:null},i=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,r;while((r=i.exec(e))!==null){let n=r[1]||"",o=/lang\s*=\s*["']([^"']+)["']/i.exec(n)?.[1]?.toLowerCase()??"js",s={content:r[2]??"",attrs:n,setup:/\bsetup\b/.test(n),lang:o};if(s.setup)t.scriptSetup=s;else t.script=s}return t}function At(e,t){let i=e[t];t++;while(t<e.length){let r=e[t];if(r==="\\"){t+=2;continue}if(r===i)return t+1;t++}return t}function Pt(e,t){t++;let i=0;while(t<e.length){let r=e[t];if(r==="\\"){t+=2;continue}if(r==="`"&&i===0)return t+1;if(r==="$"&&e[t+1]==="{"){i++,t+=2;continue}if(r==="}"){if(i>0)i--;t++;continue}t++}return t}function Ut(e,t){if(e[t+1]==="/"){let i=e.indexOf(`
|
|
7
7
|
`,t+2);return i===-1?e.length:i+1}if(e[t+1]==="*"){let i=e.indexOf("*/",t+2);return i===-1?e.length:i+2}return t+1}function as(e,t){let i=e[t];if(i==='"'||i==="'")return At(e,t);if(i==="`")return Pt(e,t);if(i==="/"&&(e[t+1]==="/"||e[t+1]==="*"))return Ut(e,t);return t}function ls(e){let t=e.split(""),i=0;while(i<e.length){let r=as(e,i);if(r>i){for(let n=i;n<r;n++)if(t[n]!==`
|
|
8
|
-
`&&t[n]!=="\r")t[n]=" ";i=r;continue}i++}return t.join("")}function at(e,t,i,r){let n=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=At(e,o);continue}if(s==="`"){o=Pt(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=Ut(e,o);continue}if(s===i)n++;else if(s===r){if(n--,n===0)return o}o++}return-1}function cs(e,t){let i=0,r=t;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=At(e,r);continue}if(n==="`"){r=Pt(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=Ut(e,r);continue}if(n==="="&&e[r+1]===">"){r+=2;continue}if(n==="<")i++;else if(n===">"){if(i--,i===0)return r}r++}return-1}function Li(e,t=","){let i=[],r=0,n="",o=0;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){let a=At(e,o);n+=e.slice(o,a),o=a;continue}if(s==="`"){let a=Pt(e,o);n+=e.slice(o,a),o=a;continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=Ut(e,o);continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if(s===t&&r===0){i.push(n),n="",o++;continue}n+=s,o++}if(n.trim()!=="")i.push(n);return i}function Cr(e){let t=e.trim();if(!t.startsWith("{"))return[];let i=at(t,0,"{","}");if(i===-1)return[];let r=t.slice(1,i),n=[];for(let o of Li(r)){let s=-1,a=0;for(let u=0;u<o.length;u++){let d=o[u];if(d==='"'||d==="'"){u=At(o,u)-1;continue}if(d==="`"){u=Pt(o,u)-1;continue}if(d==="{"||d==="["||d==="("||d==="<")a++;else if(d==="}"||d==="]"||d===")"||d===">")a--;else if(d===":"&&a===0){s=u;break}}if(s!==-1){n.push({key:yr(o.slice(0,s).trim()),value:o.slice(s+1).trim(),isMethod:!1});continue}let l=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(o.trim());if(l){n.push({key:yr(l[1]),value:o.trim(),isMethod:!0});continue}let f=o.trim();if(f)n.push({key:yr(f),value:"",isMethod:!1})}return n}function yr(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function wr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function vr(e,t){let i=new RegExp(`\\b${t}\\b`,"g"),r;while((r=i.exec(e))!==null){let n=r.index+r[0].length;while(n<e.length&&/\s/.test(e[n]))n++;let o=null;if(e[n]==="<"){let l=cs(e,n);if(l===-1)return null;o=e.slice(n+1,l).trim(),n=l+1;while(n<e.length&&/\s/.test(e[n]))n++}if(e[n]!=="(")continue;let s=at(e,n,"(",")");if(s===-1)return null;let a=Li(e.slice(n+1,s));return{generic:o,arg:a.length>0?a[0].trim():null}}return null}function
|
|
9
|
-
`)&&o===0)break;n++}return{kind:"type",start:r.index,end:n,bodyStart:s}}return null}function
|
|
10
|
-
`)&&i===0){if(r.trim()!=="")t.push(r.trim());r="",n++;continue}r+=o,n++}if(r.trim()!=="")t.push(r.trim());return t}function
|
|
8
|
+
`&&t[n]!=="\r")t[n]=" ";i=r;continue}i++}return t.join("")}function at(e,t,i,r){let n=0,o=t;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){o=At(e,o);continue}if(s==="`"){o=Pt(e,o);continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=Ut(e,o);continue}if(s===i)n++;else if(s===r){if(n--,n===0)return o}o++}return-1}function cs(e,t){let i=0,r=t;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=At(e,r);continue}if(n==="`"){r=Pt(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=Ut(e,r);continue}if(n==="="&&e[r+1]===">"){r+=2;continue}if(n==="<")i++;else if(n===">"){if(i--,i===0)return r}r++}return-1}function Li(e,t=","){let i=[],r=0,n="",o=0;while(o<e.length){let s=e[o];if(s==='"'||s==="'"){let a=At(e,o);n+=e.slice(o,a),o=a;continue}if(s==="`"){let a=Pt(e,o);n+=e.slice(o,a),o=a;continue}if(s==="/"&&(e[o+1]==="/"||e[o+1]==="*")){o=Ut(e,o);continue}if(s==="{"||s==="["||s==="("||s==="<")r++;else if(s==="}"||s==="]"||s===")"||s===">")r--;if(s===t&&r===0){i.push(n),n="",o++;continue}n+=s,o++}if(n.trim()!=="")i.push(n);return i}function Cr(e){let t=e.trim();if(!t.startsWith("{"))return[];let i=at(t,0,"{","}");if(i===-1)return[];let r=t.slice(1,i),n=[];for(let o of Li(r)){let s=-1,a=0;for(let u=0;u<o.length;u++){let d=o[u];if(d==='"'||d==="'"){u=At(o,u)-1;continue}if(d==="`"){u=Pt(o,u)-1;continue}if(d==="{"||d==="["||d==="("||d==="<")a++;else if(d==="}"||d==="]"||d===")"||d===">")a--;else if(d===":"&&a===0){s=u;break}}if(s!==-1){n.push({key:yr(o.slice(0,s).trim()),value:o.slice(s+1).trim(),isMethod:!1});continue}let l=/^([A-Za-z_$][\w$]*|['"][^'"]+['"])\s*\(/.exec(o.trim());if(l){n.push({key:yr(l[1]),value:o.trim(),isMethod:!0});continue}let f=o.trim();if(f)n.push({key:yr(f),value:"",isMethod:!1})}return n}function yr(e){if(e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);return e}function wr(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function vr(e,t){let i=new RegExp(`\\b${t}\\b`,"g"),r;while((r=i.exec(e))!==null){let n=r.index+r[0].length;while(n<e.length&&/\s/.test(e[n]))n++;let o=null;if(e[n]==="<"){let l=cs(e,n);if(l===-1)return null;o=e.slice(n+1,l).trim(),n=l+1;while(n<e.length&&/\s/.test(e[n]))n++}if(e[n]!=="(")continue;let s=at(e,n,"(",")");if(s===-1)return null;let a=Li(e.slice(n+1,s));return{generic:o,arg:a.length>0?a[0].trim():null}}return null}function Mh(e,t){let i=Nl(e,t);if(!i)return null;return i.kind==="interface"?e.slice(i.bodyStart,i.end):e.slice(i.bodyStart,i.end).trim()}function Nl(e,t){let i=new RegExp(`\\binterface\\s+${t}\\b[^{]*\\{`,"m").exec(e);if(i){let n=i.index+i[0].length-1,o=at(e,n,"{","}");if(o!==-1)return{kind:"interface",start:i.index,end:o+1,bodyStart:n}}let r=new RegExp(`\\btype\\s+${t}\\b[^=]*=`,"m").exec(e);if(r){let n=r.index+r[0].length,o=0,s=n;while(n<e.length){let a=e[n];if(a==='"'||a==="'"){n=At(e,n);continue}if(a==="`"){n=Pt(e,n);continue}if(a==="{"||a==="["||a==="("||a==="<")o++;else if(a==="}"||a==="]"||a===")"||a===">")o--;else if((a===";"||a===`
|
|
9
|
+
`)&&o===0)break;n++}return{kind:"type",start:r.index,end:n,bodyStart:s}}return null}function Dh(e){let t=e.search(/\bas\s+PropType\s*</);if(t===-1)return null;let i=e.indexOf("<",t),r=cs(e,i);if(r===-1)return null;if(e.slice(r+1).trim()!=="")return null;return e.slice(i+1,r).trim()}function ss(e){let t=e.trim(),i=Dh(t);if(i!==null)return{type:i,optional:!0};if(t==="null")return{type:"unknown",optional:!0};if(t.startsWith("[")){let r=at(t,0,"[","]");if(r!==-1){let n=Li(t.slice(1,r)).map((o)=>ss(o).type).filter((o)=>o!=="unknown");return{type:n.length>0?[...new Set(n)].join(" | "):"unknown",optional:!0}}}if(t.startsWith("{")){let r=Cr(t),n=r.find((l)=>l.key==="type"),o=r.find((l)=>l.key==="required"),s=n?ss(n.value).type:"unknown",a=!(o&&o.value.trim()==="true");return{type:s,optional:a}}if(Il[t])return{type:Il[t],optional:!0};if(/^[A-Za-z_$][\w$.]*$/.test(t))return{type:t,optional:!0};return{type:"unknown",optional:!0}}function fn(e){let t=e.trim();if(t.startsWith("{")){let i=Cr(t);if(i.length===0)return"{}";return`{ ${i.map((r)=>{if(r.isMethod||r.value==="")return`${wr(r.key)}?: unknown`;let n=ss(r.value);return`${wr(r.key)}${n.optional?"?":""}: ${n.type}`}).join(", ")} }`}if(t.startsWith("[")){let i=at(t,0,"[","]");if(i===-1)return null;let r=Li(t.slice(1,i)).map((n)=>yr(n.trim())).filter((n)=>n!=="");if(r.length===0)return"{}";return`{ ${r.map((n)=>`${wr(n)}?: unknown`).join(", ")} }`}return null}function Ih(e){let t=e.trim();if(!t.startsWith("["))return null;let i=at(t,0,"[","]");if(i===-1)return null;let r=Li(t.slice(1,i)).map((n)=>n.trim());if(r.length===0)return"{}";if(!r.every((n)=>n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"')))return"string[]";return`[${r.map((n)=>JSON.stringify(yr(n))).join(", ")}]`}function Nh(e){let t=e.trim();if(!t.startsWith("{"))return null;let i=Cr(t);if(i.length===0)return"{}";return`{ ${i.map((r)=>`${JSON.stringify(r.key)}: (...args: any[]) => void`).join(", ")} }`}function Fl(e){return Ih(e)??Nh(e)}function Fh(e){let t=[],i=0,r="",n=0;while(n<e.length){let o=e[n];if(o==='"'||o==="'"){let s=At(e,n);r+=e.slice(n,s),n=s;continue}if(o==="`"){let s=Pt(e,n);r+=e.slice(n,s),n=s;continue}if(o==="/"&&(e[n+1]==="/"||e[n+1]==="*")){let s=Ut(e,n);r+=e.slice(n,s),n=s;continue}if(o==="="&&e[n+1]===">"){r+="=>",n+=2;continue}if(o==="{"||o==="["||o==="("||o==="<")i++;else if(o==="}"||o==="]"||o===")"||o===">")i--;if((o===";"||o===","||o===`
|
|
10
|
+
`)&&i===0){if(r.trim()!=="")t.push(r.trim());r="",n++;continue}r+=o,n++}if(r.trim()!=="")t.push(r.trim());return t}function Wh(e){let t=e.trim();if(!t.startsWith("{"))return null;let i=at(t,0,"{","}");if(i===-1||t.slice(i+1).trim()!=="")return null;let r=Fh(t.slice(1,i));if(r.length===0)return"{}";let n=[];for(let o of r){let s=/^\(\s*\w+\s*:\s*/.exec(o);if(!s)return null;let a=s[0].length,l=o[a];if(l!=="'"&&l!=='"'&&l!=="`")return null;let f=At(o,a),u=o.slice(a+1,f-1),d=at(o,o.indexOf("(",0),"(",")");if(d===-1)return null;let h=o.slice(a,d),p=Li(h).slice(1),m=o.slice(d+1).trim();if(m.startsWith(":"))m=m.slice(1).trim();if(m==="")m="void";n.push(`${JSON.stringify(u)}: (${p.map((g)=>g.trim()).join(", ")}) => ${m}`)}return`{ ${n.join(", ")} }`}function fs(e){let t=e;for(let i of["defineProps","defineEmits","defineExpose","defineSlots","defineOptions"])t=Lh(t,i);return t}function Lh(e,t){let i=new RegExp(`\\b${t}\\b`,"g"),r=[],n=e,o;while((o=i.exec(e))!==null){let s=e.lastIndexOf(`
|
|
11
11
|
`,o.index)+1,a=e.slice(s,o.index),l=/^\s*(?:(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*(?::[^=]+)?=\s*)?(withDefaults\s*\(\s*)?$/.exec(a);if(!l)continue;let f=o.index+o[0].length;while(f<e.length&&/\s/.test(e[f]))f++;if(e[f]==="<"){let h=cs(e,f);if(h===-1)continue;f=h+1;while(f<e.length&&/\s/.test(e[f]))f++}if(e[f]!=="(")continue;let u=at(e,f,"(",")");if(u===-1)continue;if(l[1]){let h=s+a.length-l[1].length,p=e.indexOf("(",h);if(p!==-1){let m=at(e,p,"(",")");if(m!==-1)u=m}}let d=u+1;while(d<e.length&&e[d]!==`
|
|
12
12
|
`&&/\s|;/.test(e[d]))d++;if(e[d]===`
|
|
13
|
-
`)d++;r.push([s,d])}for(let s=r.length-1;s>=0;s--)n=n.slice(0,r[s][0])+n.slice(r[s][1]);return n}function us(e){let t=
|
|
13
|
+
`)d++;r.push([s,d])}for(let s=r.length-1;s>=0;s--)n=n.slice(0,r[s][0])+n.slice(r[s][1]);return n}function us(e){let t=Bh(e);if(t!==-1){let i=/^export\s+default\b/.exec(e.slice(t))?.[0];if(!i)return{options:null,script:e,passthrough:!1};let r=t+i.length;while(r<e.length&&/\s/.test(e[r]))r++;let n=-1,o=-1,s=-1;if(e[r]==="{")n=r,o=at(e,r,"{","}"),s=o;else if(e.startsWith("defineComponent",r)){let f=e.indexOf("(",r);if(f!==-1){let u=f+1;while(u<e.length&&/\s/.test(e[u]))u++;if(e[u]==="{")n=u,o=at(e,u,"{","}"),s=at(e,f,"(",")")}}if(n===-1||o===-1||s===-1)return{options:null,script:e,passthrough:!0};let a=s+1;if(e[a]===";")a++;let l=(e.slice(0,t)+e.slice(a)).trim();return{options:e.slice(n,o+1),script:l,passthrough:!1}}return{options:null,script:e,passthrough:!1}}function Bh(e){let t=0,i=0;while(i<e.length){let r=e[i];if(r==='"'||r==="'"){i=At(e,i);continue}if(r==="`"){i=Pt(e,i);continue}if(r==="/"&&(e[i+1]==="/"||e[i+1]==="*")){i=Ut(e,i);continue}if(r==="{"||r==="["||r==="(")t++;else if(r==="}"||r==="]"||r===")")t=Math.max(0,t-1);else if(t===0&&e.startsWith("export",i)){let n=i===0?"":e[i-1],o=e[i+6]??"";if(!/[\w$]/.test(n)&&!/[\w$]/.test(o)){if(/^export\s+default\b/.exec(e.slice(i)))return i}}i++}return-1}function sn(e,t){let i=Cr(e).find((r)=>r.key===t);return i&&i.value!==""?i.value:null}function an(e,t){let i=jh(e),r=e;for(let n=i.length-1;n>=0;n--){let o=i[n],s=r.slice(0,o.start)+r.slice(o.end);if(_h(s,o.name))continue;if(new RegExp(`\\btypeof\\s+${o.name}\\b`).test(t))continue;r=s}return r}function _h(e,t){let i=0;while(i<e.length){let r=e[i];if(r==='"'||r==="'"){i=At(e,i);continue}if(r==="`"){i=Pt(e,i);continue}if(r==="/"&&(e[i+1]==="/"||e[i+1]==="*")){i=Ut(e,i);continue}if(/[A-Za-z_$]/.test(r)){let n=i+1;while(n<e.length&&/[\w$]/.test(e[n]))n++;if(e.slice(i,n)===t)return!0;i=n;continue}i++}return!1}function jh(e){let t=[],i=Gh(e),r=/^[ \t]*(const|let|var|(?:async[ \t]+)?function)[ \t]+([A-Za-z_$][\w$]*)[ \t]*(?::[^=\n]+)?=?/gm,n;while((n=r.exec(e))!==null){let o=e.lastIndexOf(`
|
|
14
14
|
`,n.index)+1;if(!i.has(o))continue;if(/\bexport\b/.test(e.slice(o,n.index)))continue;let s=n[1],a=n[2],l=n.index+n[0].length,f=-1;if(s.endsWith("function")){let u=e.indexOf("(",l);if(u===-1)continue;let d=at(e,u,"(",")");if(d===-1)continue;l=d+1;while(l<e.length&&/\s/.test(e[l]))l++;if(e[l]===":")while(l<e.length&&e[l]!=="{"&&e[l]!==`
|
|
15
15
|
`)l++;while(l<e.length&&/\s/.test(e[l])&&e[l]!==`
|
|
16
16
|
`)l++;if(e[l]!=="{")continue;let h=at(e,l,"{","}");if(h===-1)continue;f=h+1}else{let u=0;while(l<e.length){let d=e[l];if(d==='"'||d==="'"){l=At(e,l);continue}if(d==="`"){l=Pt(e,l);continue}if(d==="/"&&(e[l+1]==="/"||e[l+1]==="*")){l=Ut(e,l);continue}if(d==="{"||d==="["||d==="(")u++;else if(d==="}"||d==="]"||d===")")u--;else if(d===";"&&u===0){f=l+1;break}else if(d===`
|
|
17
17
|
`&&u===0){f=l;break}l++}if(f===-1)f=e.length}if(e[f]===`
|
|
18
|
-
`)f++;t.push({name:a,start:n.index,end:f})}return t}function
|
|
18
|
+
`)f++;t.push({name:a,start:n.index,end:f})}return t}function Gh(e){let t=new Set([0]),i=0,r=0;while(r<e.length){let n=e[r];if(n==='"'||n==="'"){r=At(e,r);continue}if(n==="`"){r=Pt(e,r);continue}if(n==="/"&&(e[r+1]==="/"||e[r+1]==="*")){r=Ut(e,r);continue}if(n==="{"||n==="["||n==="(")i++;else if(n==="}"||n==="]"||n===")")i=Math.max(0,i-1);if(n===`
|
|
19
19
|
`&&i===0)t.add(r+1);r++}return t}function ln(e,t,i){let r=e.indexOf(i);if(r===-1)return e;let n=e.lastIndexOf(`
|
|
20
20
|
`,r)+1;if(/\bexport\b/.test(e.slice(n,r)))return e;let o=e.slice(0,r)+e.slice(r+i.length);if(new RegExp(`\\b${t}\\b`).test(o))return e;return o}function ds(e){let t="",i=0,r=()=>{for(let o=t.length-1;o>=0;o--)if(!/\s/.test(t[o]))return t[o];return""},n=(o)=>{for(let s=o;s<e.length;s++)if(!/\s/.test(e[s]))return e[s];return""};while(i<e.length){let o=e[i];if(o==='"'||o==="'"){let s=At(e,i);t+=e.slice(i,s),i=s;continue}if(o==="`"){let s=Pt(e,i);t+=e.slice(i,s),i=s;continue}if(o==="/"&&e[i+1]==="*"){let s=Ut(e,i);t+=e.slice(i,s).replace(/\s*\n\s*/g," "),i=s;continue}if(o==="/"&&e[i+1]==="/"){let s=i+2;while(s<e.length&&e[s]!==`
|
|
21
21
|
`)s++;let a=e.slice(i+2,s).trim();if(a!==""&&!a.includes("*/"))t+=`/* ${a} */`;i=s;continue}if(o===`
|
|
22
|
-
`){let s=r(),a=n(i+1);if(s===""||a===""){i++;continue}let l=
|
|
23
|
-
${t.scriptSetup.content}`:t.script.content;if(i=C.script,C.options){let b=sn(C.options,"props");if(b)r=fn(b);let c=sn(C.options,"emits");if(c)n=
|
|
24
|
-
`)}var
|
|
25
|
-
defineProps<${i}>()`,null)}function
|
|
26
|
-
`)&&r===0){let l=n+1;if(!
|
|
27
|
-
`),i=null,r=us(t);if(r.passthrough)return t;if(t=r.script,r.options){let g=sn(r.options,"props");if(g)i=fn(g)}let n=t,o=
|
|
22
|
+
`){let s=r(),a=n(i+1);if(s===""||a===""){i++;continue}let l=Vh(t);if(!l&&("{;,(<:=[".includes(s)||"}),]>;|&".includes(a))){if(!t.endsWith(" ")&&!t.endsWith(";"))t+=" "}else if(l){if(!t.endsWith(" "))t+=" "}else{if(t.endsWith(" "))t=t.slice(0,-1);t+="; "}i++;while(i<e.length&&(e[i]===" "||e[i]==="\t"))i++;continue}t+=o,i++}return t}function Vh(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 i=e.lastIndexOf("/*",t);if(i===-1)return!1;for(let r=i-1;r>=0;r--){let n=e[r];if(/\s/.test(n))continue;return"{;,(<:".includes(n)}return!0}function un(e,t){let i=[e,t].filter((r)=>r!==null);for(let r of i){let n=vr(r,"defineProps");if(!n)continue;if(n.generic){let o=n.generic;if(o.startsWith("{"))return{type:o};if(/^[A-Za-z_$][\w$]*$/.test(o)){for(let s of i){let a=Nl(s,o);if(!a)continue;let l=Mh(s,o);if(l===null)continue;return{type:l,inlinedLocal:{name:o,declText:s.slice(a.start,a.end)}}}return{type:o}}return{type:o}}if(n.arg){let o=fn(n.arg);if(o!==null)return{type:o}}}return null}function hs(e,t){let i=[e,t].filter((r)=>r!==null);for(let r of i){let n=vr(r,"defineEmits");if(!n)continue;if(n.generic)return Wh(n.generic)??n.generic;if(n.arg){let o=Fl(n.arg);if(o!==null)return o}}return null}function ps(e,t){let i=[e,t].filter((r)=>r!==null);for(let r of i){let n=vr(r,"defineExpose");if(!n||!n.arg||!n.arg.startsWith("{"))continue;let o=Cr(n.arg);if(o.length===0)return null;return`{ ${o.map((s)=>{if(s.value===""&&/^[A-Za-z_$][\w$]*$/.test(s.key))return`${wr(s.key)}: typeof ${s.key}`;let a=s.isMethod||/=>|^\s*function\b/.test(s.value);return`${wr(s.key)}: ${a?"(...args: any[]) => any":"unknown"}`}).join(", ")} }`}return null}function dn(e){let t=Ph(e),i="",r=null,n=null;if(t.script){let C=us(t.script.content);if(C.passthrough)return t.scriptSetup?`${t.script.content}
|
|
23
|
+
${t.scriptSetup.content}`:t.script.content;if(i=C.script,C.options){let b=sn(C.options,"props");if(b)r=fn(b);let c=sn(C.options,"emits");if(c)n=Fl(c)}}let o=t.scriptSetup?.content??null,s=o!==null?fs(o):null,a=un(o,o!==null?null:i),l=a?.type??r??"{}",f=hs(o,null)??n,u=ps(o,null),d=a?.inlinedLocal;if(d){if(i=ln(i,d.name,d.declText),s!==null)s=ln(s,d.name,d.declText)}let h=[l,u??"{}"];if(f)h.push("{}","{}","{}","{}","{}",f);let p=ds(`DefineComponent<${h.join(", ")}>`),m=[],g=an(i,p);if(g.trim()!=="")m.push(g);if(s&&s.trim()!==""){let C=an(s,p);if(C.trim()!=="")m.push(C)}return m.push("import type { DefineComponent } from 'vue'"),m.push(`type __DtsxComponentType = ${p}`),m.push("const __dtsx_component__: __DtsxComponentType = null as unknown as __DtsxComponentType"),m.push("export default __dtsx_component__"),m.join(`
|
|
24
|
+
`)}var Il;var hn=ye(()=>{Il={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 pn(e){return e.endsWith(".stx")}function Uh(e){let t=[],i=/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi,r;while((r=i.exec(e))!==null){let n=r[1]??"",o=/\blang\s*=\s*["']([^"']+)["']/i.exec(n)?.[1]?.toLowerCase()??(/\b(?:type\s*=\s*["'](?:text\/)?typescript["']|typescript)\b/i.test(n)?"ts":"js"),s=/\bserver\b/i.test(n)?"server":/\bclient\b/i.test(n)?"client":"universal";t.push({content:r[2]??"",kind:"script",attrs:n,context:s,lang:o,start:r.index})}return t}function zh(e){let t=[],i=/^[ \t]*@ts[ \t]*(?:\r?\n|$)/gm,r;while((r=i.exec(e))!==null){let n=i.lastIndex,o=/^[ \t]*@endts[ \t]*(?:\r?\n|$)/gm;o.lastIndex=n;let s=o.exec(e),a=s?.index??e.length;if(t.push({content:e.slice(n,a),kind:"ts",attrs:"",context:"universal",lang:"ts",start:r.index}),!s)break;i.lastIndex=o.lastIndex}return t}function Kh(e){return[...Uh(e),...zh(e)].sort((t,i)=>t.start-i.start)}function Hh(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 qh(e){let t=/(?:\$?props)\s+as\s+/g,i;while((i=t.exec(e))!==null){let r=t.lastIndex;while(r<e.length&&/\s/.test(e[r]))r++;if(e[r]==="{"){let s=at(e,r,"{","}");if(s!==-1)return e.slice(r,s+1).trim();continue}let n=/^[A-Za-z_$][\w$]*/.exec(e.slice(r))?.[0];if(!n)continue;let o=r+n.length;while(o<e.length&&/\s/.test(e[o]))o++;if(e[o]==="<"){let s=at(e,o,"<",">");if(s!==-1)o=s+1}return e.slice(r,o).trim()}return null}function Jh(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function Yh(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 Xh(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function Zh(e){let t=ls(e),i=new Map,r=/\$props(?:\.([A-Za-z_$][\w$]*)|\[\s*(['"])([^'"\n]+)\2\s*\])/g,n;while((n=r.exec(e))!==null){if(t.slice(n.index,n.index+6)!=="$props")continue;let o=n[1]??n[3],s=Yh(e.slice(r.lastIndex));i.set(o,Xh(i.get(o),s))}if(i.size===0)return null;return{type:`{ ${[...i].map(([o,s])=>`${/^[A-Za-z_$][\w$]*$/.test(o)?o:JSON.stringify(o)}?: ${s}`).join(", ")} }`}}function Qh(e){let t=un(e,null);if(t)return t;let i=qh(e)??Jh(e);if(!i)return Zh(e);if(/^[A-Za-z_$][\w$]*$/.test(i)){let r=i.replace(/[$]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:declare\\s+)?(?:interface|type)\\s+${r}\\b`).test(e))return{type:i}}return un(`${e}
|
|
25
|
+
defineProps<${i}>()`,null)}function ep(e){return fs(e)}function Wl(e){let t=ls(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 tp(e){let t=[],i=0,r=0,n=0;while(n<e.length){let s=e[n],a=as(e,n);if(a>n){n=a;continue}if(s==="{"||s==="["||s==="(")r++;else if(s==="}"||s==="]"||s===")")r=Math.max(0,r-1);if((s===";"||s===`
|
|
26
|
+
`)&&r===0){let l=n+1;if(!Wl(e.slice(i,l)))t.push([i,l]);i=l}n++}if(i<e.length&&!Wl(e.slice(i)))t.push([i,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 mn(e){let t=Kh(e).filter(Hh).map((g)=>g.content).join(`
|
|
27
|
+
`),i=null,r=us(t);if(r.passthrough)return t;if(t=r.script,r.options){let g=sn(r.options,"props");if(g)i=fn(g)}let n=t,o=ep(t),s=Qh(n),a=s?.type??i??"{}",l=hs(n,null),f=ps(n,null),u=vr(n,"defineSlots")?.generic??null,d=s?.inlinedLocal;if(d)o=ln(o,d.name,d.declText);let h=`DefineComponent<${a}>`,p=[];if(l)p.push(`readonly __stxEmits?: ${l}`);if(u)p.push(`readonly __stxSlots?: ${u}`);if(f)p.push(`readonly __stxExposed?: ${f}`);if(p.length>0)h+=` & { ${p.join(", ")} }`;h=ds(h),o=tp(an(o,h));let m=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${h}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(o.trim()!=="")m.push(o);return m.join(`
|
|
28
28
|
`)}var ms=ye(()=>{hn()});function ht(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36||e>127}function je(e){return ht(e)||e>=48&&e<=57}function gs(e,t){let i=t;for(;;){while(i>=0&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9||e.charCodeAt(i)===10||e.charCodeAt(i)===13))i--;if(i<0)return-1;if(e.charCodeAt(i)===47&&i>0&&e.charCodeAt(i-1)===42){let o=e.lastIndexOf("/*",i-2);if(o===-1)return-1;i=o-1;continue}let r=e.lastIndexOf(`
|
|
29
|
-
`,i)+1,n=
|
|
30
|
-
`,f+2);if(h===-1||h>t)return{regexAllowed:l,closesControlHeader:!1,lineCommentStart:f};f=h===-1?e.length:h+1;continue}if(d===47&&e.charCodeAt(f+1)===42){let h=e.indexOf("*/",f+2);f=h===-1?e.length:h+2;continue}if(d===39||d===34){let h=d;f++;while(f<e.length){let p=e.charCodeAt(f++);if(p===92)f++;else if(p===h)break}u("literal");continue}if(d===96){o=!0,f++;continue}if(ht(d)||d===35&&ht(e.charCodeAt(f+1))){let h=f++;while(je(e.charCodeAt(f)))f++;let p=e.slice(h,f);u(p,s!=="."&&
|
|
31
|
-
`,o+2);o=m===-1?i:m+1;continue}if(p===42){let m=e.indexOf("*/",o+2);o=m===-1?i:m+2;continue}if(!r.has(o)&&kt(e,o,t.at(-1)?.end??0)){o=bt(e,o),t.push({start:d,end:o,kind:"literal"});continue}}else if(h===96){s();continue}else if(h===34||h===39){o++;let p=!1;while(o<i){let m=e.charCodeAt(o++);if(m===92)o++;else if(m===h){p=!0;break}}t.push({start:d,end:Math.min(o,i),kind:p?"quoted":"literal"});continue}else if(ht(h)){while(je(e.charCodeAt(++o)));t.push({start:d,end:o,kind:"word"});continue}if(t.push({start:d,end:++o,kind:"punctuation"}),l){if(h===123)f++;else if(h===125){if(f===0)return;f--}}}}return a(),t}function Mt(e){if(e!==
|
|
29
|
+
`,i)+1,n=ip(e,r,i);if(n!==-1){i=n-1;continue}return i}}function ip(e,t,i){if(!e.slice(t,i+1).includes("//"))return-1;return ys(e,i).lineCommentStart??-1}function Ll(e){return e===61||e===40||e===91||e===33||e===38||e===124||e===63||e===58||e===44||e===59||e===123||e===125||e===94||e===126||e===43||e===45||e===42||e===37||e===60||e===62}function Bl(e){return e==="return"||e==="typeof"||e==="void"||e==="delete"||e==="throw"||e==="new"||e==="in"||e==="of"||e==="case"||e==="instanceof"||e==="yield"||e==="await"||e==="else"||e==="do"}function ys(e,t){let i=[],r=[],n=0,o=!1,s="",a="",l=!0,f=0,u=(d,h=!1)=>{a=s,s=d,l=h};while(f<=t){let d=e.charCodeAt(f);if(o){if(d===92){f+=2;continue}if(d===96)o=!1,u("literal");else if(d===36&&e.charCodeAt(f+1)===123)r.push(n++),o=!1,u("{",!0),f++;f++;continue}if(d===32||d===9||d===10||d===13){f++;continue}if(d===47&&e.charCodeAt(f+1)===47){let h=e.indexOf(`
|
|
30
|
+
`,f+2);if(h===-1||h>t)return{regexAllowed:l,closesControlHeader:!1,lineCommentStart:f};f=h===-1?e.length:h+1;continue}if(d===47&&e.charCodeAt(f+1)===42){let h=e.indexOf("*/",f+2);f=h===-1?e.length:h+2;continue}if(d===39||d===34){let h=d;f++;while(f<e.length){let p=e.charCodeAt(f++);if(p===92)f++;else if(p===h)break}u("literal");continue}if(d===96){o=!0,f++;continue}if(ht(d)||d===35&&ht(e.charCodeAt(f+1))){let h=f++;while(je(e.charCodeAt(f)))f++;let p=e.slice(h,f);u(p,s!=="."&&Bl(p));continue}if((d===43||d===45)&&e.charCodeAt(f+1)===d){u(e.slice(f,f+2),l),f+=2;continue}if(d===33&&e.charCodeAt(f+1)!==61){u("!",l),f++;continue}if(d===40){let h=a!=="."&&(s==="if"||s==="while"||s==="for"||s==="with"||s==="switch"||s==="catch"||s==="await"&&a==="for");i.push(h),u("(",!0)}else if(d===41){let h=i.pop()??!1;if(f===t)return{regexAllowed:h,closesControlHeader:h};u(")",h)}else if(d===47&&l){f=bt(e,f),u("literal");continue}else{if(d===123)n++;else if(d===125){if(n--,r.at(-1)===n)r.pop(),o=!0}u(e[f],d===47||Ll(d))}f++}return{regexAllowed:l,closesControlHeader:!1}}function kt(e,t,i){let r=i===void 0?gs(e,t-1):i-1;if(r<0)return!0;let n=e.charCodeAt(r);if(n===33||(n===43||n===45)&&e.charCodeAt(r-1)===n)return ys(e,r).regexAllowed;if(n===41)return ys(e,r).closesControlHeader;if(Ll(n))return!0;if(je(n)){let o=r;while(o>=0&&je(e.charCodeAt(o)))o--;let s=e.charCodeAt(gs(e,o));if(s===46||s===35)return!1;return Bl(e.slice(o+1,r+1))}return!1}function bt(e,t){let i=t,r=e.length;i++;let n=!1;while(i<r){let o=e.charCodeAt(i);if(o===92){i+=2;continue}if(n){if(o===93)n=!1;i++;continue}if(o===91){n=!0,i++;continue}if(o===47){i++;break}if(o===10||o===13)break;i++}while(i<r&&je(e.charCodeAt(i)))i++;return i}function br(e,t,i){let r=i===void 0?gs(e,t-1):i-1;if(r<0)return!0;let n=e[r];if("=([{,:;!?+-*/%&|^~<".includes(n))return!0;if(n===">"&&e[r-1]==="=")return!0;let o=r;while(o>=0&&je(e.charCodeAt(o)))o--;return["return","throw","yield","await","case","void","typeof","delete","new","else","do"].includes(e.slice(o+1,r+1))}function ws(e,t,i,r){let n=e.length;if(e.charCodeAt(t)!==60||t+1>=n)return null;let o=e.charCodeAt(t+1);if(o===62)return{delta:1,end:t+1};if(o===47){let m=t+2;if(e.charCodeAt(m)!==62){if(!ht(e.charCodeAt(m)))return null;while(m<n&&(je(e.charCodeAt(m))||".:-".includes(e[m])))m++;while(m<n&&/\s/.test(e[m]))m++}return e.charCodeAt(m)===62?{delta:-1,end:m}:null}if(!ht(o))return null;let s=t+2;while(s<n){let m=e.charCodeAt(s);if(!je(m)&&m!==46&&m!==58&&m!==45)break;s++}let a=e.slice(t+1,s),l=e.charCodeAt(s);if(l>32&&l!==62&&l!==47)return null;let f=0,u=0,d=s,h=s;for(;d<n;d++){let m=e.charCodeAt(d);if(u!==0){if(m===92)d++;else if(m===u)u=0,h=d+1;continue}if(m===60&&f>0&&(e[d+1]==="/"||br(e,d,h))){let g=r?r(d):ws(e,d,i);if(g){d=g.end,h=d+1;continue}}if(m===47&&f>0){let g=e.charCodeAt(d+1);if(g===47){while(d<n&&e.charCodeAt(d)!==10&&e.charCodeAt(d)!==13)d++;continue}if(g===42){let C=e.indexOf("*/",d+2);if(C===-1)return null;d=C+1;continue}if(kt(e,d,h)){d=bt(e,d)-1,h=d+1;continue}}if(m===39||m===34||m===96)u=m;else if(m===123)f++;else if(m===125&&f>0)f--;else if(m===60&&f===0)return null;else if(m===62&&f===0)break;if(m>32)h=d+1}if(d>=n)return null;let p=d-1;while(p>t&&e.charCodeAt(p)<=32)p--;if(e.charCodeAt(p)===47)return{delta:0,end:d};return(i?i.get(a)??-1:e.indexOf(`</${a}`,d+1))>d?{delta:1,end:d}:null}function gn(e,t){let i,r=new Map;function n(o){if(r.has(o))return r.get(o);if(!i){i=new Map;let a=e.indexOf("</");while(a!==-1){let l=ws(e,a);if(l){let f=a+2;while(f<l.end&&!/\s/.test(e[f]))f++;i.set(e.slice(a+2,f),a)}a=e.indexOf("</",a+2)}}let s=ws(e,o,i,n);if(r.set(o,s),s&&e[s.end-1]==="/")t?.add(s.end-1);return s}return n}var Bi=()=>{};function ue(e){let t=[],i=e.length,r=new Set,n=gn(e,r),o=0;function s(){let l=o++;while(o<i){let f=e.charCodeAt(o);if(f===92)o+=2;else if(f===96){t.push({start:l,end:++o,kind:"literal"});return}else if(f===36&&e.charCodeAt(o+1)===123)t.push({start:l,end:o+1,kind:"literal"}),t.push({start:o+1,end:o+2,kind:"punctuation"}),o+=2,a(!0),l=o;else o++}t.push({start:l,end:o,kind:"literal"})}function a(l=!1){let f=0,u=0;while(o<i){let d=o,h=e.charCodeAt(o);if(h===60&&(u>0||e[o+1]!=="/"&&br(e,o,t.at(-1)?.end??0))){let p=n(o);if(p){if(u=Math.max(0,u+p.delta),p.delta<0){o=p.end+1,t.push({start:d,end:o,kind:"literal"});continue}}}if(h===32||h>=9&&h<=13||h>127&&/\s/.test(e[o])){o++;continue}if(h===47){let p=e.charCodeAt(o+1);if(p===47){let m=e.indexOf(`
|
|
31
|
+
`,o+2);o=m===-1?i:m+1;continue}if(p===42){let m=e.indexOf("*/",o+2);o=m===-1?i:m+2;continue}if(!r.has(o)&&kt(e,o,t.at(-1)?.end??0)){o=bt(e,o),t.push({start:d,end:o,kind:"literal"});continue}}else if(h===96){s();continue}else if(h===34||h===39){o++;let p=!1;while(o<i){let m=e.charCodeAt(o++);if(m===92)o++;else if(m===h){p=!0;break}}t.push({start:d,end:Math.min(o,i),kind:p?"quoted":"literal"});continue}else if(ht(h)){while(je(e.charCodeAt(++o)));t.push({start:d,end:o,kind:"word"});continue}if(t.push({start:d,end:++o,kind:"punctuation"}),l){if(h===123)f++;else if(h===125){if(f===0)return;f--}}}}return a(),t}function Mt(e){if(e!==_l)jl=ue(e),_l=e;return jl}function $t(e){let t="",i=e.length-1;for(let r=1;r<i;r++){if(e[r]!=="\\"){t+=e[r];continue}let n=e[++r];if(r>=i)return;switch(n){case`
|
|
32
32
|
`:break;case"\r":if(e[r+1]===`
|
|
33
33
|
`)r++;break;case"n":t+=`
|
|
34
|
-
`;break;case"r":t+="\r";break;case"t":t+="\t";break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="\v";break;case"0":if(/\d/.test(e[r+1]??""))return;t+="\x00";break;case"x":case"u":{let o=n==="u"&&e[r+1]==="{",s=r+(o?2:1),a=o?e.indexOf("}",s):s+(n==="x"?2:4),l=e.slice(s,a);if(a<s||a>i||!/^[\da-f]+$/i.test(l)||o&&l.length>6)return;let f=Number.parseInt(l,16);if(f>1114111)return;t+=String.fromCodePoint(f),r=o?a:a-1;break}default:if(/\d/.test(n))return;t+=n}}return t}function hi(e,t){let i=t;for(let r of e){let n=r.charCodeAt(0);if(r===t||r==="\\")i+=`\\${r}`;else if(n<32||n===8232||n===8233||r.length===1&&n>=55296&&n<=57343)i+=`\\u${n.toString(16).padStart(4,"0")}`;else i+=r}return i+t}function yn(e){let t=ue(e),i=(a)=>t[a]?e.slice(t[a].start,t[a].end):"";if(i(0)!=="import")return;let r=i(1)==="type"&&i(2)!=="=",n=r?2:1;if(t[n]?.kind!=="word"||i(n+1)!=="="||i(n+2)!=="require"||i(n+3)!=="("||t[n+4]?.kind!=="quoted"||i(n+5)!==")")return;let o=n+6;if(t.length!==o&&!(t.length===o+1&&i(o)===";"))return;let s=$t(i(n+4));if(s===void 0)return;return{name:i(n),source:s,isTypeOnly:r,end:t[t.length-1].end}}function Wt(e){let t=ue(e),i=[],r=new Set,n=(h)=>h>=0&&h<t.length?e.slice(t[h].start,t[h].end):"",o=(h)=>t[h]?.kind==="quoted",s=(h)=>t[h]?.kind==="word",a=[],l=!1,f=0;if(e.includes("declare")&&e.includes("module"))for(let h=0;h<t.length;h++){let p=n(h);if(f===0&&s(h)&&n(h-1)!=="."&&n(h-1)!=="#"){if(p==="export"||p==="import"&&n(h+1)!=="("&&n(h+1)!==".")l=!0;if(p==="declare"&&n(h+1)==="module"&&o(h+2)&&n(h+3)==="{")a.push(h+2)}if(p==="{"||p==="("||p==="[")f++;else if(p==="}"||p===")"||p==="]")f--}function u(h,p=!1){if(n(h)==="*"){if(n(h+1)==="as")return s(h+2)||p&&o(h+2)?h+3:-1;return p?h+1:-1}if(n(h)!=="{")return-1;let m=1;for(let g=h+1;g<t.length;g++)if(n(g)==="{")m++;else if(n(g)==="}"&&--m===0)return g+1;else if(t[g].kind==="literal"||n(g)===";")return-1;return-1}function d(h,p,m,g){let C=t[h];if(!C||C.kind!=="quoted"||r.has(C.start))return;let b=$t(e.slice(C.start,C.end));if(b===void 0)return;r.add(C.start),i.push({specifier:b,kind:p,isTypeOnly:m,category:g,start:C.start,end:C.end})}for(let h=0;h<t.length;h++){if(!s(h)||n(h-1)==="."||n(h-1)==="#")continue;let p=n(h),m=h+1;if(p==="export"){let g=n(m)==="type";if(g)m++;let C=n(m)==="*"?n(m+1)==="as"?"export-star-as":"export-star":"export-named",b=u(m,!0);if(b>=0&&n(b)==="from")d(b+1,C,g,"export")}else if(p==="import"){if(o(m)){d(m,"import",!1,"static-import");continue}if(n(m)==="("){if(n(m+2)===")"||n(m+2)===",")d(m+1,"import",!1,"import-type");continue}let g=n(m)==="type"&&n(m+1)!=="from"&&n(m+1)!=="="&&n(m+1)!==",";if(g)m++;if(s(m)){if(m++,n(m)==="="){if(n(m+1)==="require"&&n(m+2)==="("&&n(m+4)===")")d(m+3,"import",g,"static-import");continue}if(n(m)===",")m=u(m+1)}else m=u(m);if(m>=0&&n(m)==="from")d(m+1,"import",g,"static-import")}}if(l&&a.length){for(let h of a)d(h,"import",!0,"augmentation");i.sort((h,p)=>h.start-p.start)}return i}var Bl,_l;var pt=ye(()=>{Bi();_l=[]});function jl(e){let t=ue(e),i=(l)=>t[l]?e.slice(t[l].start,t[l].end):"",r=new Map,n=[];for(let l=0;l<t.length;l++)if(["(","[","{"].includes(i(l)))n.push(l);else if([")","]","}"].includes(i(l))){let f=n.pop();if(f===void 0||!["()","[]","{}"].includes(i(f)+i(l)))throw Error("Unbalanced binding pattern");r.set(f,l)}if(n.length)throw Error("Unbalanced binding pattern");for(let l=0;l<t.length;l++){if(i(l)!=="<")continue;let f=["=",",","(",":","?","[","{"].includes(i(l-1)),u=1;for(let d=l+1;d<t.length;d++){if(i(d)==="="&&i(d+1)!==">"&&u===1&&!f)break;if(i(d)==="<")u++;else if(i(d)===">"&&i(d-1)!=="="&&--u===0){if(d+1===t.length||["(","[",".",",","}","]",")","?",":",";","=",">"].includes(i(d+1)))r.set(l,d);break}let h=r.get(d);if(h!==void 0)d=h}}let o=(l,f)=>({text:l<f?e.slice(t[l].start,t[f-1].end):"",offset:t[l]?.start??e.length}),s=(l,f,u)=>{for(let d=l;d<f;d++){if(i(d)===u)return d;let h=r.get(d);if(h!==void 0)d=h}return},a=(l,f)=>{let u=s(l,f,"="),d=u===void 0?void 0:o(u+1,f);if(u!==void 0)f=u;if(l+1===f&&t[l]?.kind==="word")return{kind:"name",name:i(l),defaultValue:d};let h=i(l)==="{"?"object":i(l)==="["?"array":void 0;if(!h||r.get(l)!==f-1)throw Error(`Invalid binding target: ${o(l,f).text}`);let p=[],m=l+1;while(m<f-1){let g=s(m,f-1,","),C=g??f-1;if(m===C)p.push(void 0);else if(i(m)==="."&&i(m+1)==="."&&i(m+2)===".")p.push({rest:!0,target:a(m+3,C)});else if(h==="array")p.push({rest:!1,target:a(m,C)});else if(i(m)==="["){let b=r.get(m);if(b===void 0||i(b+1)!==":")throw Error("Computed binding needs a target");p.push({computed:o(m+1,b),rest:!1,target:a(b+2,C)})}else{let b=m+1;if(t[m].kind!=="word"&&t[m].kind!=="quoted")while(b<C&&i(b)!==":")b++;let c=i(b)===":";if(!c&&t[m].kind!=="word")throw Error("Invalid object binding key");p.push({key:o(m,c?b:m+1).text,rest:!1,target:a(c?b+1:m,C)})}if(g===void 0)break;m=g+1}return{kind:h,elements:p,defaultValue:d}};return a(0,t.length)}function Cs(e,t){if(e.kind==="name")t.push(e.name);else for(let i of e.elements)if(i)Cs(i.target,t)}function wn(e){let t=[];return Cs(jl(e),t),t}function Gl(e){let t=jl(e.pattern),i=[];if(Cs(t,i),!i.length)return[];let r=[e.root],n=!1,o={start:e.root.start,end:e.root.end},s=(l,f)=>{let u=e.allocateName();return r.push({kind:"variable",name:u,text:`declare ${f} ${u}: unknown;`,value:l.text,initializerStart:e.patternOffset+l.offset,modifiers:[f],isExported:!1,...o}),u},a=(l,f)=>{if(l.defaultValue){let c=s(l.defaultValue,e.kind),A=e.allocateName();f=`(${f}) extends infer ${A} ? ${A} extends undefined ? typeof ${c} : ${A} : never`}if(l.kind==="name"){let c=n?void 0:e.comments;n=!0,r.push({kind:"variable",name:l.name,text:`${e.exported?"export ":""}declare ${e.kind} ${l.name}: ${f};`,typeAnnotation:f,modifiers:[e.kind],isExported:e.exported,leadingComments:c,...o});return}let u=l.elements,d=[],h=[],p=[];for(let c of u){if(!c){d.push("");continue}let A=e.allocateName(),M=c.key;if(c.computed)M=`[${s(c.computed,"const")}]`;d.push(c.rest?`...${A}`:l.kind==="object"?`${M}: ${A}`:A),h.push({target:c.target,index:p.length}),p.push(`typeof ${A}`)}let m=e.allocateName(),g=e.allocateName(),C=e.allocateName(),b=l.kind==="object"?`{ ${d.join(", ")} }`:`[${d.join(", ")}]`;r.push({kind:"function",name:m,text:`declare function ${m}(${b}: ${f}): [${p.join(", ")}];`,isExported:!1,...o}),r.push({kind:"type",name:g,text:`type ${g} = (typeof ${m}) extends (...args: never[]) => infer ${C} ? ${C} : never;`,isExported:!1,...o});for(let c of h)a(c.target,`${g}[${c.index}]`)};return a(t,`typeof ${e.root.name}`),r}var Cn=ye(()=>{pt()});function vn(e,t){let i=ue(e),r=0,n=0;for(let o=0;o<i.length;o++){let s=i[o],a=e.slice(s.start,s.end),l=i[o+1];if(r===0&&a==="function"&&l?.kind==="word"&&e.slice(l.start,l.end)===t)n++;if(["{","(","["].includes(a))r++;else if(["}",")","]"].includes(a))r--}return n}var vs=ye(()=>{pt()});function Lt(e,t,i=0){if(i>=64)return;let r=e.trim(),n=ue(r);if(!n.length)return;if(n[0].start!==0||n[n.length-1].end!==r.length)return Lt(r.slice(n[0].start,n[n.length-1].end),t,i+1);if(n.length===1&&n[0].kind==="quoted")return $t(r);if(n.length===1&&n[0].kind==="word"){let u=t.get(r);return typeof u==="object"?void 0:u}if(Vl.exec(r)?.[0].length===r.length){let u=Number(r.replaceAll("_",""));return Number.isFinite(u)?u:void 0}let o=0,s;for(let u=0;u<n.length;u++){let d=n[u],h=r.slice(d.start,d.end);if(d.kind!=="punctuation")continue;if(["(","[","{"].includes(h)){o++;continue}if([")","]","}"].includes(h)){o--;continue}let p=Vl.exec(r.slice(d.start));if(p){while(n[u+1]?.start<d.start+p[0].length)u++;continue}if(o)continue;let m=rp.find((b)=>r.startsWith(b,d.start));if(!m)continue;let g=n[u-1],C=g?r.slice(g.start,g.end):"";if(!(!g||g.kind==="punctuation"&&![")","]"].includes(C)&&!/\d/.test(C))&&(!s||bs[m]<s.priority||bs[m]===s.priority&&m!=="**"))s={start:d.start,operator:m,priority:bs[m]};while(n[u+1]?.start<d.start+m.length)u++}if(s){let u=Lt(r.slice(0,s.start),t,i+1),d=Lt(r.slice(s.start+s.operator.length),t,i+1);if(u===void 0||d===void 0)return;if(s.operator==="+"&&(typeof u==="string"||typeof d==="string"))return String(u)+String(d);if(typeof u!=="number"||typeof d!=="number")return;let h;switch(s.operator){case"+":h=u+d;break;case"-":h=u-d;break;case"*":h=u*d;break;case"/":h=u/d;break;case"%":h=u%d;break;case"**":h=u**d;break;case"<<":h=u<<d;break;case">>":h=u>>d;break;case">>>":h=u>>>d;break;case"|":h=u|d;break;case"^":h=u^d;break;case"&":h=u&d;break;default:return}return Number.isFinite(h)?h:void 0}if(r.startsWith("(")&&r.endsWith(")")){let u=0;if(n.every((d,h)=>{let p=r.slice(d.start,d.end);if(p==="(")u++;if(p===")")u--;return u!==0||h===n.length-1}))return Lt(r.slice(1,-1),t,i+1)}if(["+","-","~"].includes(r[0])){let u=Lt(r.slice(1),t,i+1);if(typeof u!=="number")return;return r[0]==="-"?-u:r[0]==="~"?~u:u}if(!r.startsWith("`")||!r.endsWith("`"))return;let a="",l=1;for(let u=1;u<r.length-1;u++){if(r[u]==="\\"){u++;continue}if(r[u]!=="$"||r[u+1]!=="{")continue;let d=$t(`\`${r.slice(l,u)}\``);if(d===void 0)return;a+=d;let h=0,p=n.find((g)=>{if(g.start<u+2||g.kind!=="punctuation")return!1;let C=r.slice(g.start,g.end);if(C==="{")h++;if(C!=="}")return!1;if(h===0)return!0;return h--,!1});if(!p)return;let m=Lt(r.slice(u+2,p.start),t,i+1);if(m===void 0)return;a+=String(m),u=p.start,l=u+1}let f=$t(`\`${r.slice(l,-1)}\``);return f===void 0?void 0:a+f}function Ul(e,t){let i=[...new Set([...e,...t.values()])];if(!i.some((s)=>s.kind==="variable"&&typeof s.value==="string"&&/[\[{]/.test(s.value)))return;i.sort((s,a)=>(s.start??0)-(a.start??0));let r=new Map,n=new Map,o=i.some((s)=>s.name==="Symbol");for(let s of i){if(s.kind!=="variable"||typeof s.value!=="string")continue;if(s.value.includes("{")||s.value.includes("[")){let u=new Map(r);u.mutableBindingTypes=new Map(n),s.computedKeyConstants=u}let a=ue(s.value),l=a.length===1&&a[0].kind==="word"?r.get(s.value.slice(a[0].start,a[0].end)):void 0;if(s.typeAnnotation==="unique symbol"||s.typeAnnotation==="symbol"||typeof l==="object"||!o&&a[0]?.kind==="word"&&s.value.slice(a[0].start,a[0].end)==="Symbol"&&["(","."].includes(s.value.slice(a[1]?.start,a[1]?.end))){r.set(s.name,ip);continue}if(s.modifiers?.[0]!=="const"||s.typeAnnotation||s.modifiers.includes("const assertion"))continue;let f=Lt(s.value,r);if(f!==void 0){if(r.set(s.name,f),!(a.length===1&&a[0].kind==="word")||n.has(s.value.trim()))n.set(s.name,typeof f)}else if(s.value.trim()==="true"||s.value.trim()==="false")n.set(s.name,"boolean");else if(a.length===1&&a[0].kind==="word"){let u=n.get(s.value.trim());if(u)n.set(s.name,u)}}}function zl(e,t){if(!e.trimStart().startsWith("[")||!e.includes("`"))return;let i=ue(e);if(e[i[0]?.start]!=="["||e[i[1]?.start]!=="`"||e[i.at(-1)?.start??-1]!=="]")return;let r=e.slice(i[0].end,i.at(-1).start).trim(),n=Lt(r,t??new Map);return typeof n==="string"?{name:hi(n,"'")}:{index:!0}}function Kl(e,t){if(!t||!e.trimStart().startsWith("["))return!1;let i=ue(e);return i.length===3&&e[i[0].start]==="["&&i[1].kind==="word"&&e[i[2].start]==="]"&&typeof t.get(e.slice(i[1].start,i[1].end))==="object"}function Hl(e){if(!e.trimStart().startsWith("[")||!e.includes("`"))return!1;let t=ue(e);return e[t[1]?.start]==="`"&&t.some((i)=>i.kind==="punctuation"&&e[i.start]==="{")}var ip,Vl,bs,rp;var bn=ye(()=>{pt();ip={kind:"symbol"},Vl=/^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:[\d_]+(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?)/,bs={"|":1,"^":2,"&":3,"<<":4,">>":4,">>>":4,"+":5,"-":5,"*":6,"/":6,"%":6,"**":7},rp=[">>>","<<",">>","**","+","-","*","/","%","|","^","&"]});function $n(e){let t=ue(e);if(t.length!==1||t[0].kind!=="word")return;let i=e.slice(t[0].start,t[0].end);return["true","false","null","undefined","this","super"].includes(i)?void 0:i}function $s(e){let t=ue(e);if(t.length===0)return!0;let i=t[t.length-1],r=e.slice(i.start,i.end);if(i.kind==="word"&&(r==="is"||r==="extends"))return!0;if(r==="|"||r==="&")return!0;let n=t[t.length-2];return r===">"&&n!==void 0&&e.slice(n.start,n.end)==="="}function _i(e){return Jl(e,Mt(e))}function ql(e){for(let t=1024;t<e.length;t*=8){let i=e.slice(0,t),r=Yl(i,ue(i),t);if(r!==void 0)return r}return Jl(e,ue(e))}function Jl(e,t){return Yl(e,t,1/0)??!1}function Yl(e,t,i){let r=0;for(let n=0;n<t.length;n++){let o=t[n];if(o.end>=i)return;if(o.kind==="punctuation"){let a=e.charCodeAt(o.start);if(a===123||a===40||a===91)r++;else if(a===125||a===41||a===93)r--;continue}if(r!==0||o.kind!=="word"||o.end-o.start!==6)continue;let s=e.slice(o.start,o.end);if(s==="export")return!0;if(s==="import"){let a=t[n+1];if(a===void 0?i!==1/0:a.end>=i)return;let l=a?e.slice(a.start,a.end):"";if(l!=="("&&l!==".")return!0}}return i===1/0?!1:void 0}function Xl(e){if(e.isExported)return!1;if(["function","variable","interface","type","class","enum","namespace"].includes(e.kind))return!0;return e.kind==="module"&&(e.moduleForm==="namespace"||e.moduleForm==="identifier")}function Zl(e,t,i){let r=e.text,n=ue(r),o=(C)=>n[C]?r.slice(n[C].start,n[C].end):"",s=(C)=>n[C]?.kind==="word",a=new Map,l=new Map,f=[];for(let C=0;C<n.length;C++){let b=o(C);if(b==="("||b==="["||b==="{"||b==="<")f.push(C);else if(b===")"||b==="]"||b==="}"||b===">"&&o(C-1)!=="="){let c=f.at(-1);if(c!==void 0&&(o(c)==="("&&b===")"||o(c)==="["&&b==="]"||o(c)==="{"&&b==="}"||o(c)==="<"&&b===">")){if(f.pop(),a.set(c,C),o(c)==="<")l.set(C,c)}}}let u=(C)=>{let b=C;while(["readonly","public","private","protected","static","abstract","override","declare","accessor","get","set","async"].includes(o(b))&&(s(b+1)||n[b+1]?.kind==="quoted"||o(b+1)==="["||/^[0-9]/.test(o(b+1))))b++;if(o(b)==="(")return o((a.get(b)??n.length)+1)===":";if(o(b)==="<")return o((a.get(b)??n.length)+1)==="(";let c=b+1;if(o(b)==="[")c=(a.get(b)??n.length)+1;else if(r.charCodeAt(n[b]?.start??r.length)>=48&&r.charCodeAt(n[b]?.start??r.length)<=57)while(c<n.length&&n[c-1].end===n[c].start&&/^[\da-fxob_e.+-]+$/i.test(o(c)))c++;else if(!s(b)&&n[b]?.kind!=="quoted"&&n[b]?.kind!=="literal")return!1;if(o(c)==="?")c++;if(o(c)==="<")c=(a.get(c)??n.length)+1;return o(c)===":"||o(c)==="("},d=[],h=[];for(let C=0;C<n.length;C++){if(o(C)!=="(")continue;let b=a.get(C);if(b===void 0||!(o(b+1)===":"||o(b+1)==="="&&o(b+2)===">"))continue;let c=new Set,A=C+1;while(A<b){let O=A;while(O<b&&o(O)!==","){let ee=a.get(O);if(ee!==void 0)O=ee+1;else O++}let N=A;while(N<O&&o(N)!==":"&&o(N)!=="="){let ee=a.get(N);if(ee!==void 0)N=ee+1;else N++}let B=A;while([".","public","private","protected","readonly","override"].includes(o(B)))B++;if(o(B)==="{"||o(B)==="[")for(let ee of wn(r.slice(n[B].start,n[N-1].end)))c.add(ee);else if(s(B))c.add(o(B));A=O+1}let M=b+(o(b+1)===":"?2:3);while(M<n.length){if(M>b+2&&r.slice(n[M-1].end,n[M].start).includes(`
|
|
35
|
-
`)&&!["|","&","?","extends","keyof","typeof","readonly","new","infer","is"].includes(o(M-1))&&u(M))break;if([";",",",")","]","}"].includes(o(M))||o(M)===">"&&o(M-1)!=="=")break;let O=a.get(M);if(O!==void 0)M=O+1;else M++}d.push({start:C,end:M,names:c});let S=l.get(C-1);if(i&&S!==void 0){let O=new Set,N=S+1;while(N<C-1){while(["const","in","out"].includes(o(N)))N++;if(s(N))O.add(o(N));while(N<C-1&&o(N)!==",")N=(a.get(N)??N)+1;N++}h.push({start:S,end:M,names:O})}}let p=i?new Set:void 0,m=(C)=>{if(!s(C))return;p?.add(n[C].start);let b=o(C);if(!d.some((c)=>C>=c.start&&C<c.end&&c.names.has(b)))t.add(b)},g=(C,b)=>{for(let c=C;c<b;c++){if(o(c)==="<"&&a.has(c)){c=a.get(c);continue}if(!s(c)||o(c-1)==="."||o(c+1)===":")continue;if(["true","false","null","undefined","new","this","super","as","satisfies","typeof","void","keyof"].includes(o(c)))continue;m(c)}};for(let C=0;C<n.length;C++){if(o(C)==="typeof")m(C+1);if(o(C)==="export"){let b=C+1;if(o(b)==="default"){if(!["function","class","abstract"].includes(o(b+1))){if(g(b+1,n.length),s(b+1)&&i?.candidates.has(o(b+1))&&(o(b+2)===";"||b+2===n.length))i.references.add(o(b+1))}continue}let c=o(b)==="type";if(c)b++;if(o(b)==="{"){let A=a.get(b);if(A===void 0||o(A+1)==="from")continue;for(let M=b+1;M<A;){let S=o(M)==="type"&&s(M+1)&&o(M+1)!=="as";if(S)M++;let O=i?.candidates.has(o(M));if(O)i.references.add(o(M));if(!O||!c&&!S)m(M);else p?.add(n[M].start);while(M<A&&o(M)!==",")M++;M++}}}if(o(C)==="["){let b=a.get(C);if(b!==void 0&&[":","?","("].includes(o(b+1))&&o(C+2)!==":"&&o(C+2)!=="in")g(C+1,b)}}if(e.kind==="class"){let C=-1;for(let b=0;b<n.length&&o(b)!=="{";b++)if(o(b)==="<"&&a.has(b))b=a.get(b);else if(o(b)==="extends"){C=b;break}if(C!==-1){let b=C+1;while(b<n.length&&o(b)!=="{"&&o(b)!=="implements"){let c=a.get(b);if(c!==void 0)b=c+1;else b++}g(C+1,b)}}if(i){let C=new Set,b=ue(e.generics??""),c=0,A=!1;for(let N of b){let B=(e.generics??"").slice(N.start,N.end);if(["<","(","[","{"].includes(B)){if(c++,B==="<"&&c===1)A=!0}else if([">",")","]","}"].includes(B)&&!(B===">"&&(e.generics??"").slice(N.start-1,N.start)==="="))c--;else if(B===","&&c===1)A=!0;else if(A&&c===1&&N.kind==="word"&&!["const","in","out"].includes(B))C.add(B),A=!1}let M=h.flatMap((N)=>[...N.names].flatMap((B)=>[{index:N.start,name:B,delta:1},{index:N.end,name:B,delta:-1}])).sort((N,B)=>N.index-B.index),S=new Map,O=0;for(let N=0;N<n.length;N++){while(O<M.length&&M[O].index<=N){let K=M[O++];S.set(K.name,(S.get(K.name)??0)+K.delta)}if(!s(N)||p?.has(n[N].start)||!i.candidates.has(o(N))||C.has(o(N))||(S.get(o(N))??0)>0)continue;let B=o(N-1),ee=o(N+1);if(B==="."||B==="as"&&e.kind==="export"||["const","let","var","function","class","interface","type","enum","namespace","module"].includes(B))continue;if(ee===":"&&B!=="?"||ee==="?"&&[":","("].includes(o(N+2))||ee==="("||ee==="<"&&o((a.get(N+1)??n.length)+1)==="(")continue;i.references.add(o(N))}}}var $r=ye(()=>{pt();Cn()});function xs(e){return typeof e==="string"?hi(e,"'"):String(e)}function np(e,t,i=new Map){let r=ue(e),n=new Map(i),o=new Map,s=[],a=1,l=0,f=0;for(let d=1;d<r.length;d++){let h=r[d],p=e.slice(h.start,h.end);if(h.kind==="punctuation"&&l===0&&(p===","||p==="}")){let m=r.slice(a,d),g=m[0];if(g){let C=g.kind==="quoted"?$t(e.slice(g.start,g.end)):e.slice(g.start,g.end),b=m.findIndex((A)=>A.kind==="punctuation"&&e[A.start]==="="),c=f;if(b>=0){let A=m.slice(b+1),M="",S=m[b].end;for(let O=0;O+2<A.length;O++){let[N,B,ee]=A.slice(O,O+3);if(N.kind!=="word"||ee.kind!=="word"||e.slice(B.start,B.end)!==".")continue;let K=n.get(`${e.slice(N.start,N.end)}.${e.slice(ee.start,ee.end)}`);if(K===void 0||typeof K==="object")continue;M+=e.slice(S,N.start)+xs(K),S=ee.end,O+=2}M+=e.slice(S,m.at(-1).end),c=Lt(M,n),s.push({start:m[b].start,end:m.at(-1).end,text:c===void 0?"":`= ${xs(c)}`})}else if(c!==void 0)s.push({start:g.end,end:g.end,text:` = ${xs(c)}`});if(f=typeof c==="number"?c+1:void 0,C!==void 0){if(n.delete(C),n.delete(`${t}.${C}`),c!==void 0)o.set(C,c),n.set(C,c),n.set(`${t}.${C}`,c)}}a=d+1}else if(h.kind==="punctuation"){if("([{".includes(p))l++;else if(")]}".includes(p))l--}}let u=e;for(let d of s.reverse())u=u.slice(0,d.start)+d.text+u.slice(d.end);return{body:u,members:o}}function Ql(e,t){let i=[...new Set([...e,...t.values()])];if(!i.some((n)=>n.kind==="enum"))return;i.sort((n,o)=>(n.start??0)-(o.start??0));let r=new Map;for(let n of i)if(n.kind==="enum"){let o=n.text.indexOf("{");if(o<0)continue;if(ue(n.text.slice(0,o)).some((a)=>n.text.slice(a.start,a.end)==="declare"))continue;let s=np(n.text.slice(o),n.name,r);n.text=n.text.slice(0,o)+s.body;for(let[a,l]of s.members)r.set(`${n.name}.${a}`,l)}else if(n.kind==="variable"&&n.modifiers?.[0]==="const"&&!n.typeAnnotation&&!n.modifiers.includes("const assertion")&&typeof n.value==="string"){let o=Lt(n.value,r);if(o!==void 0)r.set(n.name,o)}}var ec=ye(()=>{pt();bn()});function tc(e,t){if(t===2)return e===48||e===49;if(t===8)return e>=48&&e<=55;if(t===10)return e>=48&&e<=57;return e>=48&&e<=57||e>=97&&e<=102||e>=65&&e<=70}function ji(e,t,i){let r=!1,n=!1;while(t.at<e.length){let o=e.charCodeAt(t.at);if(tc(o,i))r=!0,n=!1,t.at++;else if(o===95&&r&&!n&&t.at+1<e.length&&tc(e.charCodeAt(t.at+1),i))n=!0,t.at++;else break}return r&&!n}function ic(e,t){if(e.charCodeAt(t)!==48||t+1>=e.length)return 0;let i=e.charCodeAt(t+1)|32;return i===120?16:i===98?2:i===111?8:0}function zt(e){if(e.length===0)return!1;let t={at:0};if(e.charCodeAt(0)===45)t.at++;if(t.at>=e.length)return!1;let i=ic(e,t.at);if(i)return t.at+=2,ji(e,t,i)&&t.at===e.length;let r=ji(e,t,10);if(e.charCodeAt(t.at)===46){t.at++;let o=ji(e,t,10);if(!r&&!o)return!1}else if(!r)return!1;let n=e.charCodeAt(t.at);if(n===101||n===69){if(t.at++,e.charCodeAt(t.at)===43||e.charCodeAt(t.at)===45)t.at++;if(!ji(e,t,10))return!1}return t.at===e.length}function xn(e){if(e.length<2||e.charCodeAt(e.length-1)!==110)return!1;let t=e.slice(0,-1),i={at:0};if(t.charCodeAt(0)===45)i.at++;if(i.at>=t.length)return!1;let r=ic(t,i.at);if(r)return i.at+=2,ji(t,i,r)&&i.at===t.length;return ji(t,i,10)&&i.at===t.length}function xr(e){return e.includes("_")?e.replaceAll("_",""):e}var Sn=()=>{};function xi(e){let t=Mt(e),i=0,r,n,o,s=[new Map,new Map],a=(G=i)=>t[G]?e.slice(t[G].start,t[G].end):"",l=(G=i)=>t[G]?.kind==="word",f=(G,Z)=>/[\r\n]/.test(e.slice(G,Z));function u(G){if(a()!==G)return!1;return i++,!0}function d(G){let Z=i;for(let ae of G)if(!u(ae)||i>Z+1&&t[i-2].end!==t[i-1].start)return i=Z,!1;return!0}function h(G){let Z=i;if(G())return!0;return i=Z,!1}function p(){if(!l())return!1;return i++,!0}function m(){let G=i,Z=i;while(Z<t.length&&(Z===G||t[Z-1].end===t[Z].start)){let J=a(Z),le=(J==="+"||J==="-")&&/[eE]$/.test(a(Z-1));if(!l(Z)&&!/^[0-9.]$/.test(J)&&!le)break;Z++}if(Z===G)return!1;let ae=e.slice(t[G].start,t[Z-1].end);if(!zt(ae)&&!xn(ae))return!1;return i=Z,!0}function g(){if(!["(","[","{"].includes(a()))return!1;if(!r){r=new Map;let Z=[];for(let ae=0;ae<t.length;ae++){let J=a(ae);if(["(","[","{"].includes(J))Z.push(ae);else if([")","]","}"].includes(J)){let le=Z.pop();if(le!==void 0&&["()","[]","{}"].includes(a(le)+J))r.set(le,ae+1);else Z.length=0}}}let G=r.get(i);if(G===void 0)return!1;return i=G,!0}function C(){return p()||(a()==="{"||a()==="[")&&g()}function b(){if(!u("("))return!1;if(u(")"))return!0;do{if(d("..."),!C())return!1;if(u("?"),u(":")&&!re())return!1;if(a()===")")break}while(u(",")&&a()!==")");return u(")")}function c(){if(!u("<"))return!1;if(a()===">")return!1;do{if(a()==="const")i++;while((a()==="in"||a()==="out")&&l(i+1)&&a(i+1)!=="extends")i++;if(!p())return!1;if(u("extends")&&!re(!1))return!1;if(u("=")&&!re())return!1;if(a()===">")break}while(u(",")&&a()!==">");return u(">")}function A(){if(!u("<")||a()===">")return!1;do{if(!re())return!1;if(a()===">")break}while(u(",")&&a()!==">");return u(">")}function M(){if(u("abstract"),u("new"),a()==="<"&&!c())return!1;return b()&&d("=>")&&N()}function S(){if(t[i]?.kind!=="literal"||e.charCodeAt(t[i].start)!==96)return!1;for(;;){let G=t[i++];if(!G)return!1;if(e.charCodeAt(G.end-1)===96)return!0;if(e.charCodeAt(G.end-1)!==36||!u("{")||!re()||!u("}"))return!1;if(t[i]?.kind!=="literal")return!1}}function O(){if(!u("["))return!1;if(u("]"))return!0;do{d("...");let G=i;if(l()||t[i]?.kind==="quoted"){if(i++,u("?"),!u(":"))i=G}if(!re())return!1;if(u("?"),a()==="]")break}while(u(",")&&a()!=="]");return u("]")}function N(){if(u("asserts")){if(!p())return!1;return!u("is")||re()}if(l()&&a(i+1)==="is")return i+=2,re();return re()}function B(){if(a()==="<"&&!c())return!1;if(!b())return!1;return!u(":")||N()}function ee(){if(!u("["))return!1;if(l()&&(a(i+1)==="in"||a(i+1)===":")){i++;let G=u("in");if(!G&&!u(":"))return!1;if(!re())return!1;if(G&&u("as")&&!re())return!1}else{if(!p()&&!m()){if(t[i]?.kind!=="quoted")return!1;i++}while(u("."))if(!p())return!1}return u("]")}function K(){if(a()==="[")return ee();if(p()||m())return!0;if(t[i]?.kind!=="quoted")return!1;return i++,!0}function te(){if(a()!=="get"&&a()!=="set")return;let G=i++;i=K()&&a()==="("?G+1:G}function he(){if(!u("{"))return!1;while(!u("}")){if(i>=t.length)return!1;let G=i;if((a()==="+"||a()==="-")&&a(i+1)==="readonly")i++;if(a()==="readonly"&&a(i+1)!==":"&&a(i+1)!=="?"&&a(i+1)!=="("&&a(i+1)!==";"&&a(i+1)!=="}")i++;if(a()==="new"&&(a(i+1)==="("||a(i+1)==="<"))i++;if(a()==="("||a()==="<"){if(!B())return!1}else{if(te(),!K())return!1;if(a()==="+"||a()==="-"){if(i++,!u("?"))return!1}else u("?");if(u(":")){if(!re())return!1}else if(a()==="("||a()==="<"){if(!B())return!1}}if(i===G)return!1;if(u(";")||u(","))continue;if(a()!=="}"&&!f(t[i-1].end,t[i]?.start??e.length))return!1}return!0}function Ae(){if(h(M))return!0;if(u("("))return re()&&u(")");if(a()==="{")return he();if(a()==="[")return O();if(h(S))return!0;if(t[i]?.kind==="quoted")return i++,!0;if(u("-"))return m();if(h(m))return!0;if(u("typeof")){if(a()==="import")return Ae();if(!p())return!1;while(u("."))if(!p())return!1;if(a()==="<"&&!A())return!1;return!0}if(u("import")){if(!u("(")||!re())return!1;if(u(",")&&!he())return!1;return u(")")}if(["export","function","class","const","let","var","return","throw","default","new","abstract"].includes(a()))return!1;return p()}function Se(){if(a()==="keyof"||a()==="readonly"||a()==="unique")return i++,Se();if(u("infer")){if(!p())return!1;if(u("extends")&&!re(!1))return!1;return!0}if(!Ae())return!1;for(;;)if(u(".")){if(!p())return!1}else if(a()==="<"){if(f(t[i-1].end,t[i].start))return!0;if(!A())return!1}else if(a()==="["){if(f(t[i-1].end,t[i].start))return!0;if(i++,!u("]")&&!(re()&&u("]")))return!1}else return!0}function fe(){if(u("&"),!Se())return!1;while(u("&"))if(!Se())return!1;return!0}function re(G=!0){let Z=i,ae=s[G?1:0],J=ae.get(Z);if(J!==void 0){if(J<0)return!1;return i=J,!0}let le=pe(G);if(ae.set(Z,le?i:-1),!le)i=Z;return le}function pe(G){if(u("|"),!fe())return!1;while(u("|"))if(!fe())return!1;if(G&&a()==="extends"&&!f(t[i-1].end,t[i].start))return i++,re(!1)&&u("?")&&re()&&u(":")&&re();return!0}function D(){if(a()!=="("||!g())return!1;if(u(":")&&!N())return!1;return d("=>")}function qe(){u("async");let G=u("function");if(G){if(u("*"),l())i++}if(a()==="<"&&!c())return!1;if(a()!=="("||!g())return!1;if(u(":")&&!N())return!1;return G?a()==="{":d("=>")}function X(){let G=a();if(G==="<"||G===">"||G==="+"||G==="-")return!1;if(G==="("||t[i]?.kind==="literal"&&e.charCodeAt(t[i].start)===96)return!0;if(!t[i]||f(t[i-1].end,t[i].start))return!0;if(["*","/","%","=","&","|","^","?",":",",",";",")","]","}","in","instanceof","as","satisfies"].includes(G))return!0;if(G==="!")return a(i+1)==="="&&t[i].end===t[i+1]?.start;return!l()&&t[i]?.kind!=="quoted"&&t[i]?.kind!=="literal"&&!["{","[","~","#","@"].includes(G)&&!/^[0-9]$/.test(G)}return(G,Z,ae)=>{let J=0,le=t.length;while(J<le){let Qe=J+le>>>1;if(t[Qe].start<G)J=Qe+1;else le=Qe}if(t[J]?.start!==G||a(J)!=="<")return;if(n!==Z){n=Z,o=void 0;let Qe=0,k=J;while(Qe<k){let z=Qe+k>>>1;if(t[z].start<Z)Qe=z+1;else k=z}if(i=Qe,qe())o=t[i-1].end}if(o!==void 0&&G<o)return{end:o,completeOperand:!1,parameters:!0};i=J;let ve=a(J-1),me=G===Z||["=","+","-","*","/","%","&","|","^","!","~","?",":","<",">","void","typeof","await","yield","delete"].includes(ve);if((ve==="function"||ve==="class"||ve==="*"&&a(J-2)==="function"||l(J-1)&&(a(J-2)==="function"||a(J-2)==="class"||a(J-2)==="*"&&a(J-3)==="function"))&&h(c))return{end:t[i-1].end,completeOperand:!1,parameters:!0};if(i=J,(me||ve==="async")&&h(c)){let Qe=t[i-1].end;if(h(D))return{end:Qe,completeOperand:!1,parameters:!0}}i=J;let W=ve==="."&&a(J-2)==="?"&&t[J-2].end===t[J-1].start;if((t[J-1]?.end??-1)>=Z&&(W||l(J-1)||ve===")"||ve==="]"||ve==="!"||ve===">"&&t[J-1].end===ae)&&h(A)&&X())return{end:t[i-1].end,completeOperand:!0};if(i=J,me&&u("<")&&re()&&u(">"))return{end:t[i-1].end,completeOperand:!1};return}}var Ss=ye(()=>{pt();Sn()});function rc(e,t){if(t.kind!=="punctuation")return 0;let i=e.slice(t.start,t.end);if("([{<".includes(i))return 1;if(")]}".includes(i)||i===">"&&e[t.start-1]!=="=")return-1;return 0}function En(e){if(!e.includes("?"))return e;let t=e.trim(),i=t.startsWith("(")&&t.endsWith(")"),r=e.indexOf(t)+(i?1:0),n=i?t.slice(1,-1):t,o=[[]],s=0;for(let h of ue(n)){if(h.kind==="punctuation"&&n[h.start]===","&&s===0)o.push([]);else o[o.length-1].push(h);s+=rc(n,h)}let a=o.map((h)=>{let p=0,m=-1;for(let[c,A]of h.entries()){if(p===0&&A.kind==="punctuation"&&n[A.start]===":"){m=c;break}p+=rc(n,A)}let g=m>0&&n[h[m-1].start]==="?"?h[m-1]:void 0,C=h[0]?n.slice(h[0].start,h[0].end):"",b=h[0]&&n.startsWith("...",h[0].start);return{tokens:h,colon:m,question:g,required:h.length>0&&!g&&!b&&C!=="this"}}),l=-1;for(let[h,p]of a.entries())if(p.required)l=h;let f=[];for(let[h,p]of a.entries()){if(h>=l||!p.question||p.colon<0)continue;let m=p.tokens[p.colon+1],g=p.tokens.at(-1);if(!m||!g)continue;f.push({start:r+p.question.start,end:r+p.question.end,text:""},{start:r+m.start,end:r+m.start,text:"("},{start:r+g.end,end:r+g.end,text:") | undefined"})}if(!f.length)return e;let u=[],d=0;for(let h of f)u.push(e.slice(d,h.start),h.text),d=h.end;return u.push(e.slice(d)),u.join("")}function nc(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function oc(e,t){if(t>=e.length||!nc(e.charCodeAt(t)))return t;let i=t+1;while(i<e.length&&(nc(e.charCodeAt(i))||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57))i++;return i}function Es(e,t){let i=t;while(i<e.length&&e.charCodeAt(i)<=32)i++;return i}function Sr(e,t){if(t.trim()!=="{}")return null;let i=e.trim();if(i.length<2||i[0]!=="{"||i[i.length-1]!=="}")return null;let r=i.slice(1,-1),n=[],o=0,s=0;for(let l=0;l<r.length;l++){let f=r.charCodeAt(l);if(f===34||f===39||f===96){l++;while(l<r.length&&r.charCodeAt(l)!==f){if(r.charCodeAt(l)===92)l++;l++}if(l>=r.length)return null;continue}if(f===47&&(r.charCodeAt(l+1)===47||r.charCodeAt(l+1)===42))return null;if(f===40||f===91||f===123)o++;else if(f===41||f===93||f===125){if(--o<0)return null}else if(f===44&&o===0)n.push(r.slice(s,l)),s=l+1}if(o!==0)return null;if(r.slice(s).trim()||n.length===0)n.push(r.slice(s));let a=[];for(let l of n){let f=l.trim(),u=oc(f,0);if(u===0)return null;let d=f.slice(0,u),h=d,p=Es(f,u);if(f.charCodeAt(p)===58){let g=Es(f,p+1),C=oc(f,g);if(C===g)return null;h=f.slice(g,C),p=Es(f,C)}if(f.charCodeAt(p)!==61||f.charCodeAt(p+1)===61||f.charCodeAt(p+1)===62)return null;let m=f.slice(p+1).trim();if(!m)return null;a.push({key:d,alias:h,value:m})}return a}function An(e,t){let i=e.map((n)=>n.key===n.alias?n.key:`${n.key}: ${n.alias}`).join(", "),r=e.map((n)=>{let o=t(n.value),s=o==="unknown"||o==="any"?o:`${o.includes("=>")?`(${o})`:o} | undefined`;return`${n.key}?: ${s}`}).join("; ");return`{ ${i} }?: { ${r} }`}var As=ye(()=>{pt()});function Kt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let r=e[0];if(r.length>0&&r.charCodeAt(0)>32&&r.charCodeAt(r.length-1)>32)return`${r}
|
|
34
|
+
`;break;case"r":t+="\r";break;case"t":t+="\t";break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="\v";break;case"0":if(/\d/.test(e[r+1]??""))return;t+="\x00";break;case"x":case"u":{let o=n==="u"&&e[r+1]==="{",s=r+(o?2:1),a=o?e.indexOf("}",s):s+(n==="x"?2:4),l=e.slice(s,a);if(a<s||a>i||!/^[\da-f]+$/i.test(l)||o&&l.length>6)return;let f=Number.parseInt(l,16);if(f>1114111)return;t+=String.fromCodePoint(f),r=o?a:a-1;break}default:if(/\d/.test(n))return;t+=n}}return t}function hi(e,t){let i=t;for(let r of e){let n=r.charCodeAt(0);if(r===t||r==="\\")i+=`\\${r}`;else if(n<32||n===8232||n===8233||r.length===1&&n>=55296&&n<=57343)i+=`\\u${n.toString(16).padStart(4,"0")}`;else i+=r}return i+t}function yn(e){let t=ue(e),i=(a)=>t[a]?e.slice(t[a].start,t[a].end):"";if(i(0)!=="import")return;let r=i(1)==="type"&&i(2)!=="=",n=r?2:1;if(t[n]?.kind!=="word"||i(n+1)!=="="||i(n+2)!=="require"||i(n+3)!=="("||t[n+4]?.kind!=="quoted"||i(n+5)!==")")return;let o=n+6;if(t.length!==o&&!(t.length===o+1&&i(o)===";"))return;let s=$t(i(n+4));if(s===void 0)return;return{name:i(n),source:s,isTypeOnly:r,end:t[t.length-1].end}}function Wt(e){let t=ue(e),i=[],r=new Set,n=(h)=>h>=0&&h<t.length?e.slice(t[h].start,t[h].end):"",o=(h)=>t[h]?.kind==="quoted",s=(h)=>t[h]?.kind==="word",a=[],l=!1,f=0;if(e.includes("declare")&&e.includes("module"))for(let h=0;h<t.length;h++){let p=n(h);if(f===0&&s(h)&&n(h-1)!=="."&&n(h-1)!=="#"){if(p==="export"||p==="import"&&n(h+1)!=="("&&n(h+1)!==".")l=!0;if(p==="declare"&&n(h+1)==="module"&&o(h+2)&&n(h+3)==="{")a.push(h+2)}if(p==="{"||p==="("||p==="[")f++;else if(p==="}"||p===")"||p==="]")f--}function u(h,p=!1){if(n(h)==="*"){if(n(h+1)==="as")return s(h+2)||p&&o(h+2)?h+3:-1;return p?h+1:-1}if(n(h)!=="{")return-1;let m=1;for(let g=h+1;g<t.length;g++)if(n(g)==="{")m++;else if(n(g)==="}"&&--m===0)return g+1;else if(t[g].kind==="literal"||n(g)===";")return-1;return-1}function d(h,p,m,g){let C=t[h];if(!C||C.kind!=="quoted"||r.has(C.start))return;let b=$t(e.slice(C.start,C.end));if(b===void 0)return;r.add(C.start),i.push({specifier:b,kind:p,isTypeOnly:m,category:g,start:C.start,end:C.end})}for(let h=0;h<t.length;h++){if(!s(h)||n(h-1)==="."||n(h-1)==="#")continue;let p=n(h),m=h+1;if(p==="export"){let g=n(m)==="type";if(g)m++;let C=n(m)==="*"?n(m+1)==="as"?"export-star-as":"export-star":"export-named",b=u(m,!0);if(b>=0&&n(b)==="from")d(b+1,C,g,"export")}else if(p==="import"){if(o(m)){d(m,"import",!1,"static-import");continue}if(n(m)==="("){if(n(m+2)===")"||n(m+2)===",")d(m+1,"import",!1,"import-type");continue}let g=n(m)==="type"&&n(m+1)!=="from"&&n(m+1)!=="="&&n(m+1)!==",";if(g)m++;if(s(m)){if(m++,n(m)==="="){if(n(m+1)==="require"&&n(m+2)==="("&&n(m+4)===")")d(m+3,"import",g,"static-import");continue}if(n(m)===",")m=u(m+1)}else m=u(m);if(m>=0&&n(m)==="from")d(m+1,"import",g,"static-import")}}if(l&&a.length){for(let h of a)d(h,"import",!0,"augmentation");i.sort((h,p)=>h.start-p.start)}return i}var _l,jl;var pt=ye(()=>{Bi();jl=[]});function Gl(e){let t=ue(e),i=(l)=>t[l]?e.slice(t[l].start,t[l].end):"",r=new Map,n=[];for(let l=0;l<t.length;l++)if(["(","[","{"].includes(i(l)))n.push(l);else if([")","]","}"].includes(i(l))){let f=n.pop();if(f===void 0||!["()","[]","{}"].includes(i(f)+i(l)))throw Error("Unbalanced binding pattern");r.set(f,l)}if(n.length)throw Error("Unbalanced binding pattern");for(let l=0;l<t.length;l++){if(i(l)!=="<")continue;let f=["=",",","(",":","?","[","{"].includes(i(l-1)),u=1;for(let d=l+1;d<t.length;d++){if(i(d)==="="&&i(d+1)!==">"&&u===1&&!f)break;if(i(d)==="<")u++;else if(i(d)===">"&&i(d-1)!=="="&&--u===0){if(d+1===t.length||["(","[",".",",","}","]",")","?",":",";","=",">"].includes(i(d+1)))r.set(l,d);break}let h=r.get(d);if(h!==void 0)d=h}}let o=(l,f)=>({text:l<f?e.slice(t[l].start,t[f-1].end):"",offset:t[l]?.start??e.length}),s=(l,f,u)=>{for(let d=l;d<f;d++){if(i(d)===u)return d;let h=r.get(d);if(h!==void 0)d=h}return},a=(l,f)=>{let u=s(l,f,"="),d=u===void 0?void 0:o(u+1,f);if(u!==void 0)f=u;if(l+1===f&&t[l]?.kind==="word")return{kind:"name",name:i(l),defaultValue:d};let h=i(l)==="{"?"object":i(l)==="["?"array":void 0;if(!h||r.get(l)!==f-1)throw Error(`Invalid binding target: ${o(l,f).text}`);let p=[],m=l+1;while(m<f-1){let g=s(m,f-1,","),C=g??f-1;if(m===C)p.push(void 0);else if(i(m)==="."&&i(m+1)==="."&&i(m+2)===".")p.push({rest:!0,target:a(m+3,C)});else if(h==="array")p.push({rest:!1,target:a(m,C)});else if(i(m)==="["){let b=r.get(m);if(b===void 0||i(b+1)!==":")throw Error("Computed binding needs a target");p.push({computed:o(m+1,b),rest:!1,target:a(b+2,C)})}else{let b=m+1;if(t[m].kind!=="word"&&t[m].kind!=="quoted")while(b<C&&i(b)!==":")b++;let c=i(b)===":";if(!c&&t[m].kind!=="word")throw Error("Invalid object binding key");p.push({key:o(m,c?b:m+1).text,rest:!1,target:a(c?b+1:m,C)})}if(g===void 0)break;m=g+1}return{kind:h,elements:p,defaultValue:d}};return a(0,t.length)}function Cs(e,t){if(e.kind==="name")t.push(e.name);else for(let i of e.elements)if(i)Cs(i.target,t)}function wn(e){let t=[];return Cs(Gl(e),t),t}function Vl(e){let t=Gl(e.pattern),i=[];if(Cs(t,i),!i.length)return[];let r=[e.root],n=!1,o={start:e.root.start,end:e.root.end},s=(l,f)=>{let u=e.allocateName();return r.push({kind:"variable",name:u,text:`declare ${f} ${u}: unknown;`,value:l.text,initializerStart:e.patternOffset+l.offset,modifiers:[f],isExported:!1,...o}),u},a=(l,f)=>{if(l.defaultValue){let c=s(l.defaultValue,e.kind),A=e.allocateName();f=`(${f}) extends infer ${A} ? ${A} extends undefined ? typeof ${c} : ${A} : never`}if(l.kind==="name"){let c=n?void 0:e.comments;n=!0,r.push({kind:"variable",name:l.name,text:`${e.exported?"export ":""}declare ${e.kind} ${l.name}: ${f};`,typeAnnotation:f,modifiers:[e.kind],isExported:e.exported,leadingComments:c,...o});return}let u=l.elements,d=[],h=[],p=[];for(let c of u){if(!c){d.push("");continue}let A=e.allocateName(),M=c.key;if(c.computed)M=`[${s(c.computed,"const")}]`;d.push(c.rest?`...${A}`:l.kind==="object"?`${M}: ${A}`:A),h.push({target:c.target,index:p.length}),p.push(`typeof ${A}`)}let m=e.allocateName(),g=e.allocateName(),C=e.allocateName(),b=l.kind==="object"?`{ ${d.join(", ")} }`:`[${d.join(", ")}]`;r.push({kind:"function",name:m,text:`declare function ${m}(${b}: ${f}): [${p.join(", ")}];`,isExported:!1,...o}),r.push({kind:"type",name:g,text:`type ${g} = (typeof ${m}) extends (...args: never[]) => infer ${C} ? ${C} : never;`,isExported:!1,...o});for(let c of h)a(c.target,`${g}[${c.index}]`)};return a(t,`typeof ${e.root.name}`),r}var Cn=ye(()=>{pt()});function vn(e,t){let i=ue(e),r=0,n=0;for(let o=0;o<i.length;o++){let s=i[o],a=e.slice(s.start,s.end),l=i[o+1];if(r===0&&a==="function"&&l?.kind==="word"&&e.slice(l.start,l.end)===t)n++;if(["{","(","["].includes(a))r++;else if(["}",")","]"].includes(a))r--}return n}var vs=ye(()=>{pt()});function Lt(e,t,i=0){if(i>=64)return;let r=e.trim(),n=ue(r);if(!n.length)return;if(n[0].start!==0||n[n.length-1].end!==r.length)return Lt(r.slice(n[0].start,n[n.length-1].end),t,i+1);if(n.length===1&&n[0].kind==="quoted")return $t(r);if(n.length===1&&n[0].kind==="word"){let u=t.get(r);return typeof u==="object"?void 0:u}if(Ul.exec(r)?.[0].length===r.length){let u=Number(r.replaceAll("_",""));return Number.isFinite(u)?u:void 0}let o=0,s;for(let u=0;u<n.length;u++){let d=n[u],h=r.slice(d.start,d.end);if(d.kind!=="punctuation")continue;if(["(","[","{"].includes(h)){o++;continue}if([")","]","}"].includes(h)){o--;continue}let p=Ul.exec(r.slice(d.start));if(p){while(n[u+1]?.start<d.start+p[0].length)u++;continue}if(o)continue;let m=np.find((b)=>r.startsWith(b,d.start));if(!m)continue;let g=n[u-1],C=g?r.slice(g.start,g.end):"";if(!(!g||g.kind==="punctuation"&&![")","]"].includes(C)&&!/\d/.test(C))&&(!s||bs[m]<s.priority||bs[m]===s.priority&&m!=="**"))s={start:d.start,operator:m,priority:bs[m]};while(n[u+1]?.start<d.start+m.length)u++}if(s){let u=Lt(r.slice(0,s.start),t,i+1),d=Lt(r.slice(s.start+s.operator.length),t,i+1);if(u===void 0||d===void 0)return;if(s.operator==="+"&&(typeof u==="string"||typeof d==="string"))return String(u)+String(d);if(typeof u!=="number"||typeof d!=="number")return;let h;switch(s.operator){case"+":h=u+d;break;case"-":h=u-d;break;case"*":h=u*d;break;case"/":h=u/d;break;case"%":h=u%d;break;case"**":h=u**d;break;case"<<":h=u<<d;break;case">>":h=u>>d;break;case">>>":h=u>>>d;break;case"|":h=u|d;break;case"^":h=u^d;break;case"&":h=u&d;break;default:return}return Number.isFinite(h)?h:void 0}if(r.startsWith("(")&&r.endsWith(")")){let u=0;if(n.every((d,h)=>{let p=r.slice(d.start,d.end);if(p==="(")u++;if(p===")")u--;return u!==0||h===n.length-1}))return Lt(r.slice(1,-1),t,i+1)}if(["+","-","~"].includes(r[0])){let u=Lt(r.slice(1),t,i+1);if(typeof u!=="number")return;return r[0]==="-"?-u:r[0]==="~"?~u:u}if(!r.startsWith("`")||!r.endsWith("`"))return;let a="",l=1;for(let u=1;u<r.length-1;u++){if(r[u]==="\\"){u++;continue}if(r[u]!=="$"||r[u+1]!=="{")continue;let d=$t(`\`${r.slice(l,u)}\``);if(d===void 0)return;a+=d;let h=0,p=n.find((g)=>{if(g.start<u+2||g.kind!=="punctuation")return!1;let C=r.slice(g.start,g.end);if(C==="{")h++;if(C!=="}")return!1;if(h===0)return!0;return h--,!1});if(!p)return;let m=Lt(r.slice(u+2,p.start),t,i+1);if(m===void 0)return;a+=String(m),u=p.start,l=u+1}let f=$t(`\`${r.slice(l,-1)}\``);return f===void 0?void 0:a+f}function zl(e,t){let i=[...new Set([...e,...t.values()])];if(!i.some((s)=>s.kind==="variable"&&typeof s.value==="string"&&/[\[{]/.test(s.value)))return;i.sort((s,a)=>(s.start??0)-(a.start??0));let r=new Map,n=new Map,o=i.some((s)=>s.name==="Symbol");for(let s of i){if(s.kind!=="variable"||typeof s.value!=="string")continue;if(s.value.includes("{")||s.value.includes("[")){let u=new Map(r);u.mutableBindingTypes=new Map(n),s.computedKeyConstants=u}let a=ue(s.value),l=a.length===1&&a[0].kind==="word"?r.get(s.value.slice(a[0].start,a[0].end)):void 0;if(s.typeAnnotation==="unique symbol"||s.typeAnnotation==="symbol"||typeof l==="object"||!o&&a[0]?.kind==="word"&&s.value.slice(a[0].start,a[0].end)==="Symbol"&&["(","."].includes(s.value.slice(a[1]?.start,a[1]?.end))){r.set(s.name,rp);continue}if(s.modifiers?.[0]!=="const"||s.typeAnnotation||s.modifiers.includes("const assertion"))continue;let f=Lt(s.value,r);if(f!==void 0){if(r.set(s.name,f),!(a.length===1&&a[0].kind==="word")||n.has(s.value.trim()))n.set(s.name,typeof f)}else if(s.value.trim()==="true"||s.value.trim()==="false")n.set(s.name,"boolean");else if(a.length===1&&a[0].kind==="word"){let u=n.get(s.value.trim());if(u)n.set(s.name,u)}}}function Kl(e,t){if(!e.trimStart().startsWith("[")||!e.includes("`"))return;let i=ue(e);if(e[i[0]?.start]!=="["||e[i[1]?.start]!=="`"||e[i.at(-1)?.start??-1]!=="]")return;let r=e.slice(i[0].end,i.at(-1).start).trim(),n=Lt(r,t??new Map);return typeof n==="string"?{name:hi(n,"'")}:{index:!0}}function Hl(e,t){if(!t||!e.trimStart().startsWith("["))return!1;let i=ue(e);return i.length===3&&e[i[0].start]==="["&&i[1].kind==="word"&&e[i[2].start]==="]"&&typeof t.get(e.slice(i[1].start,i[1].end))==="object"}function ql(e){if(!e.trimStart().startsWith("[")||!e.includes("`"))return!1;let t=ue(e);return e[t[1]?.start]==="`"&&t.some((i)=>i.kind==="punctuation"&&e[i.start]==="{")}var rp,Ul,bs,np;var bn=ye(()=>{pt();rp={kind:"symbol"},Ul=/^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:[\d_]+(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?)/,bs={"|":1,"^":2,"&":3,"<<":4,">>":4,">>>":4,"+":5,"-":5,"*":6,"/":6,"%":6,"**":7},np=[">>>","<<",">>","**","+","-","*","/","%","|","^","&"]});function $n(e){let t=ue(e);if(t.length!==1||t[0].kind!=="word")return;let i=e.slice(t[0].start,t[0].end);return["true","false","null","undefined","this","super"].includes(i)?void 0:i}function $s(e){let t=ue(e);if(t.length===0)return!0;let i=t[t.length-1],r=e.slice(i.start,i.end);if(i.kind==="word"&&(r==="is"||r==="extends"))return!0;if(r==="|"||r==="&")return!0;let n=t[t.length-2];return r===">"&&n!==void 0&&e.slice(n.start,n.end)==="="}function _i(e){return Yl(e,Mt(e))}function Jl(e){for(let t=1024;t<e.length;t*=8){let i=e.slice(0,t),r=Xl(i,ue(i),t);if(r!==void 0)return r}return Yl(e,ue(e))}function Yl(e,t){return Xl(e,t,1/0)??!1}function Xl(e,t,i){let r=0;for(let n=0;n<t.length;n++){let o=t[n];if(o.end>=i)return;if(o.kind==="punctuation"){let a=e.charCodeAt(o.start);if(a===123||a===40||a===91)r++;else if(a===125||a===41||a===93)r--;continue}if(r!==0||o.kind!=="word"||o.end-o.start!==6)continue;let s=e.slice(o.start,o.end);if(s==="export")return!0;if(s==="import"){let a=t[n+1];if(a===void 0?i!==1/0:a.end>=i)return;let l=a?e.slice(a.start,a.end):"";if(l!=="("&&l!==".")return!0}}return i===1/0?!1:void 0}function Zl(e){if(e.isExported)return!1;if(["function","variable","interface","type","class","enum","namespace"].includes(e.kind))return!0;return e.kind==="module"&&(e.moduleForm==="namespace"||e.moduleForm==="identifier")}function Ql(e,t,i){let r=e.text,n=ue(r),o=(C)=>n[C]?r.slice(n[C].start,n[C].end):"",s=(C)=>n[C]?.kind==="word",a=new Map,l=new Map,f=[];for(let C=0;C<n.length;C++){let b=o(C);if(b==="("||b==="["||b==="{"||b==="<")f.push(C);else if(b===")"||b==="]"||b==="}"||b===">"&&o(C-1)!=="="){let c=f.at(-1);if(c!==void 0&&(o(c)==="("&&b===")"||o(c)==="["&&b==="]"||o(c)==="{"&&b==="}"||o(c)==="<"&&b===">")){if(f.pop(),a.set(c,C),o(c)==="<")l.set(C,c)}}}let u=(C)=>{let b=C;while(["readonly","public","private","protected","static","abstract","override","declare","accessor","get","set","async"].includes(o(b))&&(s(b+1)||n[b+1]?.kind==="quoted"||o(b+1)==="["||/^[0-9]/.test(o(b+1))))b++;if(o(b)==="(")return o((a.get(b)??n.length)+1)===":";if(o(b)==="<")return o((a.get(b)??n.length)+1)==="(";let c=b+1;if(o(b)==="[")c=(a.get(b)??n.length)+1;else if(r.charCodeAt(n[b]?.start??r.length)>=48&&r.charCodeAt(n[b]?.start??r.length)<=57)while(c<n.length&&n[c-1].end===n[c].start&&/^[\da-fxob_e.+-]+$/i.test(o(c)))c++;else if(!s(b)&&n[b]?.kind!=="quoted"&&n[b]?.kind!=="literal")return!1;if(o(c)==="?")c++;if(o(c)==="<")c=(a.get(c)??n.length)+1;return o(c)===":"||o(c)==="("},d=[],h=[];for(let C=0;C<n.length;C++){if(o(C)!=="(")continue;let b=a.get(C);if(b===void 0||!(o(b+1)===":"||o(b+1)==="="&&o(b+2)===">"))continue;let c=new Set,A=C+1;while(A<b){let T=A;while(T<b&&o(T)!==","){let ee=a.get(T);if(ee!==void 0)T=ee+1;else T++}let N=A;while(N<T&&o(N)!==":"&&o(N)!=="="){let ee=a.get(N);if(ee!==void 0)N=ee+1;else N++}let B=A;while([".","public","private","protected","readonly","override"].includes(o(B)))B++;if(o(B)==="{"||o(B)==="[")for(let ee of wn(r.slice(n[B].start,n[N-1].end)))c.add(ee);else if(s(B))c.add(o(B));A=T+1}let M=b+(o(b+1)===":"?2:3);while(M<n.length){if(M>b+2&&r.slice(n[M-1].end,n[M].start).includes(`
|
|
35
|
+
`)&&!["|","&","?","extends","keyof","typeof","readonly","new","infer","is"].includes(o(M-1))&&u(M))break;if([";",",",")","]","}"].includes(o(M))||o(M)===">"&&o(M-1)!=="=")break;let T=a.get(M);if(T!==void 0)M=T+1;else M++}d.push({start:C,end:M,names:c});let S=l.get(C-1);if(i&&S!==void 0){let T=new Set,N=S+1;while(N<C-1){while(["const","in","out"].includes(o(N)))N++;if(s(N))T.add(o(N));while(N<C-1&&o(N)!==",")N=(a.get(N)??N)+1;N++}h.push({start:S,end:M,names:T})}}let p=i?new Set:void 0,m=(C)=>{if(!s(C))return;p?.add(n[C].start);let b=o(C);if(!d.some((c)=>C>=c.start&&C<c.end&&c.names.has(b)))t.add(b)},g=(C,b)=>{for(let c=C;c<b;c++){if(o(c)==="<"&&a.has(c)){c=a.get(c);continue}if(!s(c)||o(c-1)==="."||o(c+1)===":")continue;if(["true","false","null","undefined","new","this","super","as","satisfies","typeof","void","keyof"].includes(o(c)))continue;m(c)}};for(let C=0;C<n.length;C++){if(o(C)==="typeof")m(C+1);if(o(C)==="export"){let b=C+1;if(o(b)==="default"){if(!["function","class","abstract"].includes(o(b+1))){if(g(b+1,n.length),s(b+1)&&i?.candidates.has(o(b+1))&&(o(b+2)===";"||b+2===n.length))i.references.add(o(b+1))}continue}let c=o(b)==="type";if(c)b++;if(o(b)==="{"){let A=a.get(b);if(A===void 0||o(A+1)==="from")continue;for(let M=b+1;M<A;){let S=o(M)==="type"&&s(M+1)&&o(M+1)!=="as";if(S)M++;let T=i?.candidates.has(o(M));if(T)i.references.add(o(M));if(!T||!c&&!S)m(M);else p?.add(n[M].start);while(M<A&&o(M)!==",")M++;M++}}}if(o(C)==="["){let b=a.get(C);if(b!==void 0&&[":","?","("].includes(o(b+1))&&o(C+2)!==":"&&o(C+2)!=="in")g(C+1,b)}}if(e.kind==="class"){let C=-1;for(let b=0;b<n.length&&o(b)!=="{";b++)if(o(b)==="<"&&a.has(b))b=a.get(b);else if(o(b)==="extends"){C=b;break}if(C!==-1){let b=C+1;while(b<n.length&&o(b)!=="{"&&o(b)!=="implements"){let c=a.get(b);if(c!==void 0)b=c+1;else b++}g(C+1,b)}}if(i){let C=new Set,b=ue(e.generics??""),c=0,A=!1;for(let N of b){let B=(e.generics??"").slice(N.start,N.end);if(["<","(","[","{"].includes(B)){if(c++,B==="<"&&c===1)A=!0}else if([">",")","]","}"].includes(B)&&!(B===">"&&(e.generics??"").slice(N.start-1,N.start)==="="))c--;else if(B===","&&c===1)A=!0;else if(A&&c===1&&N.kind==="word"&&!["const","in","out"].includes(B))C.add(B),A=!1}let M=h.flatMap((N)=>[...N.names].flatMap((B)=>[{index:N.start,name:B,delta:1},{index:N.end,name:B,delta:-1}])).sort((N,B)=>N.index-B.index),S=new Map,T=0;for(let N=0;N<n.length;N++){while(T<M.length&&M[T].index<=N){let K=M[T++];S.set(K.name,(S.get(K.name)??0)+K.delta)}if(!s(N)||p?.has(n[N].start)||!i.candidates.has(o(N))||C.has(o(N))||(S.get(o(N))??0)>0)continue;let B=o(N-1),ee=o(N+1);if(B==="."||B==="as"&&e.kind==="export"||["const","let","var","function","class","interface","type","enum","namespace","module"].includes(B))continue;if(ee===":"&&B!=="?"||ee==="?"&&[":","("].includes(o(N+2))||ee==="("||ee==="<"&&o((a.get(N+1)??n.length)+1)==="(")continue;i.references.add(o(N))}}}var $r=ye(()=>{pt();Cn()});function xs(e){return typeof e==="string"?hi(e,"'"):String(e)}function op(e,t,i=new Map){let r=ue(e),n=new Map(i),o=new Map,s=[],a=1,l=0,f=0;for(let d=1;d<r.length;d++){let h=r[d],p=e.slice(h.start,h.end);if(h.kind==="punctuation"&&l===0&&(p===","||p==="}")){let m=r.slice(a,d),g=m[0];if(g){let C=g.kind==="quoted"?$t(e.slice(g.start,g.end)):e.slice(g.start,g.end),b=m.findIndex((A)=>A.kind==="punctuation"&&e[A.start]==="="),c=f;if(b>=0){let A=m.slice(b+1),M="",S=m[b].end;for(let T=0;T+2<A.length;T++){let[N,B,ee]=A.slice(T,T+3);if(N.kind!=="word"||ee.kind!=="word"||e.slice(B.start,B.end)!==".")continue;let K=n.get(`${e.slice(N.start,N.end)}.${e.slice(ee.start,ee.end)}`);if(K===void 0||typeof K==="object")continue;M+=e.slice(S,N.start)+xs(K),S=ee.end,T+=2}M+=e.slice(S,m.at(-1).end),c=Lt(M,n),s.push({start:m[b].start,end:m.at(-1).end,text:c===void 0?"":`= ${xs(c)}`})}else if(c!==void 0)s.push({start:g.end,end:g.end,text:` = ${xs(c)}`});if(f=typeof c==="number"?c+1:void 0,C!==void 0){if(n.delete(C),n.delete(`${t}.${C}`),c!==void 0)o.set(C,c),n.set(C,c),n.set(`${t}.${C}`,c)}}a=d+1}else if(h.kind==="punctuation"){if("([{".includes(p))l++;else if(")]}".includes(p))l--}}let u=e;for(let d of s.reverse())u=u.slice(0,d.start)+d.text+u.slice(d.end);return{body:u,members:o}}function ec(e,t){let i=[...new Set([...e,...t.values()])];if(!i.some((n)=>n.kind==="enum"))return;i.sort((n,o)=>(n.start??0)-(o.start??0));let r=new Map;for(let n of i)if(n.kind==="enum"){let o=n.text.indexOf("{");if(o<0)continue;if(ue(n.text.slice(0,o)).some((a)=>n.text.slice(a.start,a.end)==="declare"))continue;let s=op(n.text.slice(o),n.name,r);n.text=n.text.slice(0,o)+s.body;for(let[a,l]of s.members)r.set(`${n.name}.${a}`,l)}else if(n.kind==="variable"&&n.modifiers?.[0]==="const"&&!n.typeAnnotation&&!n.modifiers.includes("const assertion")&&typeof n.value==="string"){let o=Lt(n.value,r);if(o!==void 0)r.set(n.name,o)}}var tc=ye(()=>{pt();bn()});function ic(e,t){if(t===2)return e===48||e===49;if(t===8)return e>=48&&e<=55;if(t===10)return e>=48&&e<=57;return e>=48&&e<=57||e>=97&&e<=102||e>=65&&e<=70}function ji(e,t,i){let r=!1,n=!1;while(t.at<e.length){let o=e.charCodeAt(t.at);if(ic(o,i))r=!0,n=!1,t.at++;else if(o===95&&r&&!n&&t.at+1<e.length&&ic(e.charCodeAt(t.at+1),i))n=!0,t.at++;else break}return r&&!n}function rc(e,t){if(e.charCodeAt(t)!==48||t+1>=e.length)return 0;let i=e.charCodeAt(t+1)|32;return i===120?16:i===98?2:i===111?8:0}function zt(e){if(e.length===0)return!1;let t={at:0};if(e.charCodeAt(0)===45)t.at++;if(t.at>=e.length)return!1;let i=rc(e,t.at);if(i)return t.at+=2,ji(e,t,i)&&t.at===e.length;let r=ji(e,t,10);if(e.charCodeAt(t.at)===46){t.at++;let o=ji(e,t,10);if(!r&&!o)return!1}else if(!r)return!1;let n=e.charCodeAt(t.at);if(n===101||n===69){if(t.at++,e.charCodeAt(t.at)===43||e.charCodeAt(t.at)===45)t.at++;if(!ji(e,t,10))return!1}return t.at===e.length}function xn(e){if(e.length<2||e.charCodeAt(e.length-1)!==110)return!1;let t=e.slice(0,-1),i={at:0};if(t.charCodeAt(0)===45)i.at++;if(i.at>=t.length)return!1;let r=rc(t,i.at);if(r)return i.at+=2,ji(t,i,r)&&i.at===t.length;return ji(t,i,10)&&i.at===t.length}function xr(e){return e.includes("_")?e.replaceAll("_",""):e}var Sn=()=>{};function xi(e){let t=Mt(e),i=0,r,n,o,s=[new Map,new Map],a=(G=i)=>t[G]?e.slice(t[G].start,t[G].end):"",l=(G=i)=>t[G]?.kind==="word",f=(G,Z)=>/[\r\n]/.test(e.slice(G,Z));function u(G){if(a()!==G)return!1;return i++,!0}function d(G){let Z=i;for(let ae of G)if(!u(ae)||i>Z+1&&t[i-2].end!==t[i-1].start)return i=Z,!1;return!0}function h(G){let Z=i;if(G())return!0;return i=Z,!1}function p(){if(!l())return!1;return i++,!0}function m(){let G=i,Z=i;while(Z<t.length&&(Z===G||t[Z-1].end===t[Z].start)){let q=a(Z),le=(q==="+"||q==="-")&&/[eE]$/.test(a(Z-1));if(!l(Z)&&!/^[0-9.]$/.test(q)&&!le)break;Z++}if(Z===G)return!1;let ae=e.slice(t[G].start,t[Z-1].end);if(!zt(ae)&&!xn(ae))return!1;return i=Z,!0}function g(){if(!["(","[","{"].includes(a()))return!1;if(!r){r=new Map;let Z=[];for(let ae=0;ae<t.length;ae++){let q=a(ae);if(["(","[","{"].includes(q))Z.push(ae);else if([")","]","}"].includes(q)){let le=Z.pop();if(le!==void 0&&["()","[]","{}"].includes(a(le)+q))r.set(le,ae+1);else Z.length=0}}}let G=r.get(i);if(G===void 0)return!1;return i=G,!0}function C(){return p()||(a()==="{"||a()==="[")&&g()}function b(){if(!u("("))return!1;if(u(")"))return!0;do{if(d("..."),!C())return!1;if(u("?"),u(":")&&!re())return!1;if(a()===")")break}while(u(",")&&a()!==")");return u(")")}function c(){if(!u("<"))return!1;if(a()===">")return!1;do{if(a()==="const")i++;while((a()==="in"||a()==="out")&&l(i+1)&&a(i+1)!=="extends")i++;if(!p())return!1;if(u("extends")&&!re(!1))return!1;if(u("=")&&!re())return!1;if(a()===">")break}while(u(",")&&a()!==">");return u(">")}function A(){if(!u("<")||a()===">")return!1;do{if(!re())return!1;if(a()===">")break}while(u(",")&&a()!==">");return u(">")}function M(){if(u("abstract"),u("new"),a()==="<"&&!c())return!1;return b()&&d("=>")&&N()}function S(){if(t[i]?.kind!=="literal"||e.charCodeAt(t[i].start)!==96)return!1;for(;;){let G=t[i++];if(!G)return!1;if(e.charCodeAt(G.end-1)===96)return!0;if(e.charCodeAt(G.end-1)!==36||!u("{")||!re()||!u("}"))return!1;if(t[i]?.kind!=="literal")return!1}}function T(){if(!u("["))return!1;if(u("]"))return!0;do{d("...");let G=i;if(l()||t[i]?.kind==="quoted"){if(i++,u("?"),!u(":"))i=G}if(!re())return!1;if(u("?"),a()==="]")break}while(u(",")&&a()!=="]");return u("]")}function N(){if(u("asserts")){if(!p())return!1;return!u("is")||re()}if(l()&&a(i+1)==="is")return i+=2,re();return re()}function B(){if(a()==="<"&&!c())return!1;if(!b())return!1;return!u(":")||N()}function ee(){if(!u("["))return!1;if(l()&&(a(i+1)==="in"||a(i+1)===":")){i++;let G=u("in");if(!G&&!u(":"))return!1;if(!re())return!1;if(G&&u("as")&&!re())return!1}else{if(!p()&&!m()){if(t[i]?.kind!=="quoted")return!1;i++}while(u("."))if(!p())return!1}return u("]")}function K(){if(a()==="[")return ee();if(p()||m())return!0;if(t[i]?.kind!=="quoted")return!1;return i++,!0}function te(){if(a()!=="get"&&a()!=="set")return;let G=i++;i=K()&&a()==="("?G+1:G}function he(){if(!u("{"))return!1;while(!u("}")){if(i>=t.length)return!1;let G=i;if((a()==="+"||a()==="-")&&a(i+1)==="readonly")i++;if(a()==="readonly"&&a(i+1)!==":"&&a(i+1)!=="?"&&a(i+1)!=="("&&a(i+1)!==";"&&a(i+1)!=="}")i++;if(a()==="new"&&(a(i+1)==="("||a(i+1)==="<"))i++;if(a()==="("||a()==="<"){if(!B())return!1}else{if(te(),!K())return!1;if(a()==="+"||a()==="-"){if(i++,!u("?"))return!1}else u("?");if(u(":")){if(!re())return!1}else if(a()==="("||a()==="<"){if(!B())return!1}}if(i===G)return!1;if(u(";")||u(","))continue;if(a()!=="}"&&!f(t[i-1].end,t[i]?.start??e.length))return!1}return!0}function Ae(){if(h(M))return!0;if(u("("))return re()&&u(")");if(a()==="{")return he();if(a()==="[")return T();if(h(S))return!0;if(t[i]?.kind==="quoted")return i++,!0;if(u("-"))return m();if(h(m))return!0;if(u("typeof")){if(a()==="import")return Ae();if(!p())return!1;while(u("."))if(!p())return!1;if(a()==="<"&&!A())return!1;return!0}if(u("import")){if(!u("(")||!re())return!1;if(u(",")&&!he())return!1;return u(")")}if(["export","function","class","const","let","var","return","throw","default","new","abstract"].includes(a()))return!1;return p()}function Se(){if(a()==="keyof"||a()==="readonly"||a()==="unique")return i++,Se();if(u("infer")){if(!p())return!1;if(u("extends")&&!re(!1))return!1;return!0}if(!Ae())return!1;for(;;)if(u(".")){if(!p())return!1}else if(a()==="<"){if(f(t[i-1].end,t[i].start))return!0;if(!A())return!1}else if(a()==="["){if(f(t[i-1].end,t[i].start))return!0;if(i++,!u("]")&&!(re()&&u("]")))return!1}else return!0}function fe(){if(u("&"),!Se())return!1;while(u("&"))if(!Se())return!1;return!0}function re(G=!0){let Z=i,ae=s[G?1:0],q=ae.get(Z);if(q!==void 0){if(q<0)return!1;return i=q,!0}let le=pe(G);if(ae.set(Z,le?i:-1),!le)i=Z;return le}function pe(G){if(u("|"),!fe())return!1;while(u("|"))if(!fe())return!1;if(G&&a()==="extends"&&!f(t[i-1].end,t[i].start))return i++,re(!1)&&u("?")&&re()&&u(":")&&re();return!0}function D(){if(a()!=="("||!g())return!1;if(u(":")&&!N())return!1;return d("=>")}function qe(){u("async");let G=u("function");if(G){if(u("*"),l())i++}if(a()==="<"&&!c())return!1;if(a()!=="("||!g())return!1;if(u(":")&&!N())return!1;return G?a()==="{":d("=>")}function X(){let G=a();if(G==="<"||G===">"||G==="+"||G==="-")return!1;if(G==="("||t[i]?.kind==="literal"&&e.charCodeAt(t[i].start)===96)return!0;if(!t[i]||f(t[i-1].end,t[i].start))return!0;if(["*","/","%","=","&","|","^","?",":",",",";",")","]","}","in","instanceof","as","satisfies"].includes(G))return!0;if(G==="!")return a(i+1)==="="&&t[i].end===t[i+1]?.start;return!l()&&t[i]?.kind!=="quoted"&&t[i]?.kind!=="literal"&&!["{","[","~","#","@"].includes(G)&&!/^[0-9]$/.test(G)}return(G,Z,ae)=>{let q=0,le=t.length;while(q<le){let Qe=q+le>>>1;if(t[Qe].start<G)q=Qe+1;else le=Qe}if(t[q]?.start!==G||a(q)!=="<")return;if(n!==Z){n=Z,o=void 0;let Qe=0,O=q;while(Qe<O){let z=Qe+O>>>1;if(t[z].start<Z)Qe=z+1;else O=z}if(i=Qe,qe())o=t[i-1].end}if(o!==void 0&&G<o)return{end:o,completeOperand:!1,parameters:!0};i=q;let ve=a(q-1),me=G===Z||["=","+","-","*","/","%","&","|","^","!","~","?",":","<",">","void","typeof","await","yield","delete"].includes(ve);if((ve==="function"||ve==="class"||ve==="*"&&a(q-2)==="function"||l(q-1)&&(a(q-2)==="function"||a(q-2)==="class"||a(q-2)==="*"&&a(q-3)==="function"))&&h(c))return{end:t[i-1].end,completeOperand:!1,parameters:!0};if(i=q,(me||ve==="async")&&h(c)){let Qe=t[i-1].end;if(h(D))return{end:Qe,completeOperand:!1,parameters:!0}}i=q;let W=ve==="."&&a(q-2)==="?"&&t[q-2].end===t[q-1].start;if((t[q-1]?.end??-1)>=Z&&(W||l(q-1)||ve===")"||ve==="]"||ve==="!"||ve===">"&&t[q-1].end===ae)&&h(A)&&X())return{end:t[i-1].end,completeOperand:!0};if(i=q,me&&u("<")&&re()&&u(">"))return{end:t[i-1].end,completeOperand:!1};return}}var Ss=ye(()=>{pt();Sn()});function nc(e,t){if(t.kind!=="punctuation")return 0;let i=e.slice(t.start,t.end);if("([{<".includes(i))return 1;if(")]}".includes(i)||i===">"&&e[t.start-1]!=="=")return-1;return 0}function En(e){if(!e.includes("?"))return e;let t=e.trim(),i=t.startsWith("(")&&t.endsWith(")"),r=e.indexOf(t)+(i?1:0),n=i?t.slice(1,-1):t,o=[[]],s=0;for(let h of ue(n)){if(h.kind==="punctuation"&&n[h.start]===","&&s===0)o.push([]);else o[o.length-1].push(h);s+=nc(n,h)}let a=o.map((h)=>{let p=0,m=-1;for(let[c,A]of h.entries()){if(p===0&&A.kind==="punctuation"&&n[A.start]===":"){m=c;break}p+=nc(n,A)}let g=m>0&&n[h[m-1].start]==="?"?h[m-1]:void 0,C=h[0]?n.slice(h[0].start,h[0].end):"",b=h[0]&&n.startsWith("...",h[0].start);return{tokens:h,colon:m,question:g,required:h.length>0&&!g&&!b&&C!=="this"}}),l=-1;for(let[h,p]of a.entries())if(p.required)l=h;let f=[];for(let[h,p]of a.entries()){if(h>=l||!p.question||p.colon<0)continue;let m=p.tokens[p.colon+1],g=p.tokens.at(-1);if(!m||!g)continue;f.push({start:r+p.question.start,end:r+p.question.end,text:""},{start:r+m.start,end:r+m.start,text:"("},{start:r+g.end,end:r+g.end,text:") | undefined"})}if(!f.length)return e;let u=[],d=0;for(let h of f)u.push(e.slice(d,h.start),h.text),d=h.end;return u.push(e.slice(d)),u.join("")}function oc(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function sc(e,t){if(t>=e.length||!oc(e.charCodeAt(t)))return t;let i=t+1;while(i<e.length&&(oc(e.charCodeAt(i))||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57))i++;return i}function Es(e,t){let i=t;while(i<e.length&&e.charCodeAt(i)<=32)i++;return i}function Sr(e,t){if(t.trim()!=="{}")return null;let i=e.trim();if(i.length<2||i[0]!=="{"||i[i.length-1]!=="}")return null;let r=i.slice(1,-1),n=[],o=0,s=0;for(let l=0;l<r.length;l++){let f=r.charCodeAt(l);if(f===34||f===39||f===96){l++;while(l<r.length&&r.charCodeAt(l)!==f){if(r.charCodeAt(l)===92)l++;l++}if(l>=r.length)return null;continue}if(f===47&&(r.charCodeAt(l+1)===47||r.charCodeAt(l+1)===42))return null;if(f===40||f===91||f===123)o++;else if(f===41||f===93||f===125){if(--o<0)return null}else if(f===44&&o===0)n.push(r.slice(s,l)),s=l+1}if(o!==0)return null;if(r.slice(s).trim()||n.length===0)n.push(r.slice(s));let a=[];for(let l of n){let f=l.trim(),u=sc(f,0);if(u===0)return null;let d=f.slice(0,u),h=d,p=Es(f,u);if(f.charCodeAt(p)===58){let g=Es(f,p+1),C=sc(f,g);if(C===g)return null;h=f.slice(g,C),p=Es(f,C)}if(f.charCodeAt(p)!==61||f.charCodeAt(p+1)===61||f.charCodeAt(p+1)===62)return null;let m=f.slice(p+1).trim();if(!m)return null;a.push({key:d,alias:h,value:m})}return a}function An(e,t){let i=e.map((n)=>n.key===n.alias?n.key:`${n.key}: ${n.alias}`).join(", "),r=e.map((n)=>{let o=t(n.value),s=o==="unknown"||o==="any"?o:`${o.includes("=>")?`(${o})`:o} | undefined`;return`${n.key}?: ${s}`}).join("; ");return`{ ${i} }?: { ${r} }`}var As=ye(()=>{pt()});function Kt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let r=e[0];if(r.length>0&&r.charCodeAt(0)>32&&r.charCodeAt(r.length-1)>32)return`${r}
|
|
36
36
|
`;return`${r.trim()}
|
|
37
37
|
`}let i="";for(let r=0;r<e.length;r++){if(r>0)i+=`
|
|
38
38
|
`;i+=e[r].trim()}return`${i}
|
|
39
|
-
`}function Er(e){return e.replaceAll("*/","*\\/")}var kn=()=>{};function Ts(e){return
|
|
40
|
-
`)||o.includes("\r"))return"string";return o}if(o.charCodeAt(0)===39||o.charCodeAt(0)===34){let l=
|
|
41
|
-
`;if(i==="t")return"\t";if(i==="r")return"\r";if(i==="0")return"\x00";return i})}function
|
|
42
|
-
`,r+2);r=o===-1?e.length:o;continue}if(e[r+1]==="*"){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+1;continue}if(kt(e,r)){r=bt(e,r)-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(n===60){i??=xi(e);let o=i(r,0);if(o){r=o.end-1;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)===n){while(e.charCodeAt(r+1)===n)r++;continue}if((n===62||n===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function
|
|
39
|
+
`}function Er(e){return e.replaceAll("*/","*\\/")}var kn=()=>{};function Ts(e){return mc(e).replace(/\n[ \t]*(?=\n)/g,"")}function mc(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],i=0,r=0,n=e.length;while(r<n)if(e.charCodeAt(r)===47&&r+1<n&&e.charCodeAt(r+1)===42){if(r>i)t.push(e.substring(i,r));r+=2;while(r<n-1){if(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47){r+=2;break}r++}i=r}else r++;if(i<n)t.push(e.substring(i));return t.join("").trim()}function Is(){Nn=!0,yt=null}function Ns(){Nn=!1;let e=yt;return yt=null,e}function ks(e,t){let i=0,r=0;while((r=e.indexOf(t,r))!==-1)i++,r+=t.length;return i}function ac(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 On(e){let t=e.trim();if(t.length<3||t.charCodeAt(0)!==60)return!1;if(t.startsWith("<>"))return t.endsWith("</>");let i=t.charCodeAt(1);if(!(i>=65&&i<=90||i>=97&&i<=122||i===36||i===95))return!1;let r=2;while(r<t.length&&ac(t.charCodeAt(r)))r++;let n=t.slice(1,r),o=t.charCodeAt(r);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&&ac(t.charCodeAt(a)))a++;return t.slice(s+2,a)===n&&t.charCodeAt(a)===62&&a===t.length-1}function Rn(e){let t=e.length,i=!1;for(let s=1;s<t;s++)if(e.charCodeAt(s)<=32&&e.charCodeAt(s-1)<=32){i=!0;break}if(!i)for(let s=0;s<t;s++){let a=e.charCodeAt(s);if(a===10||a===13||a===9){i=!0;break}}if(!i)return e;let r=[],n=-1,o=!1;for(let s=0;s<t;s++)if(e.charCodeAt(s)<=32){if(!o){if(n>=0)r.push(e.substring(n,s));r.push(" "),o=!0,n=-1}}else{if(o||n<0)n=s;o=!1}if(n>=0)r.push(e.substring(n));return r.join("")}function Te(e,t=!1,i=!1,r=0,n){if(!e||typeof e!=="string")return"unknown";if(r>=In)return"unknown";let o=e.trim();if(On(o))return"JSX.Element";let s=Cc(o);if(s)return s;if(o.startsWith("BigInt("))return"bigint";if(o.startsWith("Symbol.for("))return"symbol";if(!(o.startsWith("[")&&o.endsWith("]")||o.startsWith("{")&&o.endsWith("}"))&&(o.includes(".raw`")||o.includes("String.raw`")))return"string";if(o.startsWith("`")&&o.endsWith("`")){if(!t||o.includes("${")||o.includes(`
|
|
40
|
+
`)||o.includes("\r"))return"string";return o}if(o.charCodeAt(0)===39||o.charCodeAt(0)===34){let l=sp(o);if(l!==null){if(l==="string"||!t)return"string";return l}}if(zt(o)){if(!t)return"number";return xr(o)}if(o==="true"||o==="false"){if(!t)return"boolean";return o}if(o==="null")return"null";if(o==="undefined")return"undefined";if(o.startsWith("[")&&o.endsWith("]"))return Rs(o,t,r+1,n);if(o.startsWith("{")&&o.endsWith("}"))return Ec(o,t,r+1,n);if(o.startsWith("class ")||o.startsWith("class{"))return Sp(o);if(o.startsWith("new "))return Fs(o);if(o.endsWith("as const")){let l=o.slice(0,-8).trim();if(l.startsWith("[")&&l.endsWith("]")){let f=l.slice(1,-1).trim();if(!f)return"readonly []";let u=kr(f),d=[];for(let h=0;h<u.length;h++){let p=u[h].trim();if(p.startsWith("...")){let m=p.slice(3).trim();if(Ei(m))d.push(`...typeof ${m}`);else{let g=Te(m,!0,!1,r+1,n);d.push(g.startsWith("readonly [")||g.endsWith("[]")?`...${g}`:"...unknown[]")}}else d.push(Te(p,!0,!1,r+1,n))}return`readonly [${d.join(", ")}]`}return Te(l,!0,i,r+1,n)}if(Ai(o)!==-1||o.startsWith("function")||o.startsWith("async"))return kc(o,i,r,t);if(o.startsWith("`")&&o.endsWith("`"))return xp(o,t);if(o.startsWith("Promise."))return $c(o,t,r,n);if(o.startsWith("await "))return"unknown";if(o.startsWith("typeof ")&&Tn(o.slice(7)))return"string";if(o.startsWith("void ")&&Tn(o.slice(5)))return"undefined";if(o.startsWith("delete ")&&Tn(o.slice(7)))return"boolean";if(xn(o)){if(t)return xr(o);return"bigint"}if(o.startsWith("Symbol(")||o==="Symbol.for")return"symbol";let a=ki(o);if(a!==null)return a;if(gc(o))return"boolean";if(fp(o))return"number";return"unknown"}function lc(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return qt(e,0,t)===e.length}function sp(e){if(lc(e))return e;let t=ap(e);if(t.length<2)return null;let i=!1,r=!0,n="";for(let o of t){let s=o.trim();if(lc(s))i=!0,n+=lp(s);else r=!1}if(r)return cp(n);if(i)return"string";return null}function ap(e){let t=[],i=0,r=0,n=0;while(n<e.length){let o=e.charCodeAt(n);if(o===39||o===34||o===96){n=qt(e,n,o);continue}if(o===40||o===91||o===123)i++;else if(o===41||o===93||o===125)i--;else if(o===43&&i===0)t.push(e.slice(r,n)),r=n+1;n++}return t.push(e.slice(r)),t}function lp(e){return e.slice(1,-1).replace(/\\(.)/g,(t,i)=>{if(i==="n")return`
|
|
41
|
+
`;if(i==="t")return"\t";if(i==="r")return"\r";if(i==="0")return"\x00";return i})}function cp(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function fp(e){if(e==="")return!1;let t=!1,i=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=48&&n<=57){t=!0;continue}if(n===43||n===45||n===42||n===47||n===37){i=!0;continue}if(n===60||n===62){let o=r+1;while(o<e.length&&e.charCodeAt(o)===n)o++;let s=o-r;if(s!==2&&!(n===62&&s===3))return!1;i=!0,r=o-1;continue}if(n===46||n===40||n===41||n<=32)continue;return!1}return t&&i}function gc(e){let t=0,i;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=qt(e,r,n)-1;continue}if(n===47){if(e[r+1]==="/"){let o=e.indexOf(`
|
|
42
|
+
`,r+2);r=o===-1?e.length:o;continue}if(e[r+1]==="*"){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+1;continue}if(kt(e,r)){r=bt(e,r)-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(n===60){i??=xi(e);let o=i(r,0);if(o){r=o.end-1;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)===n){while(e.charCodeAt(r+1)===n)r++;continue}if((n===62||n===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function up(e,t=!1,i=0,r){return Te(e,t,!0,i,r)}function Qt(e,t=!1,i="",r,n){let o=Os(i,r),s=[],a=!1,l=0;while(l<e.length){let u=e.charCodeAt(l);if(u===34||u===39||u===96){l=qt(e,l,u);continue}if(u===47&&e.charCodeAt(l+1)===47){l+=2;while(l<e.length&&e.charCodeAt(l)!==10&&e.charCodeAt(l)!==13)l++;continue}if(u===47&&e.charCodeAt(l+1)===42){let d=e.indexOf("*/",l+2);l=d===-1?e.length:d+2;continue}if(e.startsWith("function",l)&&Ar(e,l,8)||e.startsWith("class",l)&&Ar(e,l,5)){let d=$p(e,l);if(d!==-1){l=Mn(e,d);continue}}if(u===61&&e.charCodeAt(l+1)===62){let d=bc(e,l+2);if(e.charCodeAt(d)===123){l=Mn(e,d);continue}}if(e.startsWith("return",l)&&(l===0||!Ht(e.charCodeAt(l-1)))&&!Ht(e.charCodeAt(l+6))){l+=6;let d=!1;while(l<e.length&&e.charCodeAt(l)<=32){let c=e.charCodeAt(l);if(c===10||c===13)d=!0;l++}if(d||l>=e.length||e.charCodeAt(l)===59||e.charCodeAt(l)===125){a=!0;continue}let h=l,p=0,m=0,g=0;while(l<e.length){let c=e.charCodeAt(l);if(c===34||c===39||c===96){l=qt(e,l,c);continue}if(c===47&&e.charCodeAt(l+1)===47){if(p===0&&m===0&&g===0)break;while(l<e.length&&e.charCodeAt(l)!==10&&e.charCodeAt(l)!==13)l++;continue}if(c===47&&e.charCodeAt(l+1)===42){let A=e.indexOf("*/",l+2);l=A===-1?e.length:A+2;continue}if(c===40)p++;else if(c===41)p--;else if(c===91)m++;else if(c===93)m--;else if(c===123)g++;else if(c===125){if(g===0&&p===0&&m===0)break;g--}else if(c===59&&p===0&&m===0&&g===0)break;else if((c===10||c===13)&&p===0&&m===0&&g===0){let A=l+1;while(A<e.length&&e.charCodeAt(A)<=32)A++;if(e.startsWith("return",A)&&!Ht(e.charCodeAt(A+6)))break}l++}let C=e.slice(h,l).trim(),b=Ts(Dt(C,o,r,n,h));if(!s.includes(b))s.push(b);continue}l++}if(a&&!s.includes("undefined"))s.push("undefined");let f=s.includes("unknown")?"unknown":s.length===0?"void":wc(s);return t&&!f.startsWith("Promise<")?`Promise<${f}>`:f}function Os(e,t){let i=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,n=ue(r),o=0,s=0,a=[];for(let l of n){let f=r.slice(l.start,l.end);if(f===","&&s===0)a.push(r.slice(o,l.start)),o=l.end;if(["(","[","{","<"].includes(f))s++;else if([")","]","}"].includes(f)||f===">"&&r[l.start-1]!=="=")s--}a.push(r.slice(o));for(let l of a){let f=ue(l),u=-1,d=-1,h=0;for(let C of f){let b=l.slice(C.start,C.end);if(h===0&&b===":"&&u===-1)u=C.start;if(h===0&&b==="="&&l[C.end]!==">"){d=C.start;break}if(["(","[","{","<"].includes(b))h++;else if([")","]","}"].includes(b)||b===">"&&l[C.start-1]!=="=")h--}let p=l.slice(0,u!==-1?u:d!==-1?d:void 0).trim().replace(/^\.\.\./,"").replace(/\?$/,""),m=u===-1&&d!==-1&&!l.trim().startsWith("...")?Sr(p,l.slice(d+1)):null;if(m){for(let C of m)i.set(C.alias,t?.(C.value)??Te(C.value,!1));continue}if(!Gi(p)){if(p.startsWith("{")||p.startsWith("["))for(let C of wn(p))i.set(C,"unknown");continue}let g=u!==-1?l.slice(u+1,d!==-1?d:void 0).trim():"";if(!g&&d!==-1){let C=l.slice(d+1).trim();g=t?.(C)??Te(C,!1)}if(g){if(d===-1&&l.slice(0,u).trim().endsWith("?"))g=`(${g}) | undefined`;i.set(p,g)}else i.set(p,"unknown")}return i}function dp(e,t){let i=Object.hasOwn(cc,e)?cc[e]:void 0;return i&&Object.hasOwn(i,t)?i[t]:void 0}function Zt(e){return e.includes(`
|
|
43
43
|
`)?e.replaceAll(`
|
|
44
44
|
`,`
|
|
45
|
-
`):e}function
|
|
45
|
+
`):e}function hp(e,t){if(e=e.trim(),!e.startsWith("{")||!e.endsWith("}"))return;let i=e.slice(1,-1),r=ue(i),n=0,o=0;for(let s=0;s<=r.length;s++){let a=r[s],l=a?i.slice(a.start,a.end):";";if(o===0&&(l===";"||l===",")){let f=i.slice(n,a?.start).trim(),u=f.indexOf(":");if(u!==-1&&f.slice(0,u).trim()===t)return f.slice(u+1).trim();n=a?.end??i.length}if(["(","[","{","<"].includes(l))o++;else if([")","]","}"].includes(l)||l===">"&&a&&i[a.start-1]!=="=")o--}return}function Dt(e,t,i,r,n=0,o=0){if(o>=In)return"unknown";let s=e.trim();while(Fn(s))s=s.slice(1,-1).trim();let a=i?.(s);if(a)return a;if(On(s))return"JSX.Element";if(s.startsWith("await ")){let c=Dt(s.slice(6),t,i,r,n,o+1);return c.startsWith("Promise<")&&c.endsWith(">")?c.slice(8,-1):c}if(t.has(s))return t.get(s);let l=/^([\w$]+)\.([\w$]+(?:\.[\w$]+)*)$/.exec(s),f;if(l){let c=t.get(l[1]),A=c&&hp(c,l[2]);if(A)return A;if(c)f=`typeof ${s}`}if(s.startsWith("!"))return"boolean";if(s.startsWith("fetch("))return"Promise<Response>";if(bp(s))return Te(s,!1);let u=vc(s);if(u){let c=Dt(u.whenTrue,t,i,r,n,o+1),A=Dt(u.whenFalse,t,i,r,n,o+1);return c===A?c:wc([c,A])}for(let c of["??","||","&&"]){let A=yc(s,c);if(A!==-1){let M=Dt(s.slice(0,A),t,i,r,n,o+1),S=Dt(s.slice(A+c.length),t,i,r,n,o+1);return wp(M,S,c)}}let d=pp(s);if(d&&r)return r(d,n);let h=Cc(s);if(h)return r?r(h,n):h;if(gc(s))return"boolean";let p=0;for(let c=s.length-1;c>=0;c--){let A=s.charCodeAt(c);if(A===41||A===93||A===125)p++;else if(A===40||A===91||A===123)p--;else if(p===0&&(A===43||A===45||A===42||A===47||A===37)){let M=Dt(s.slice(0,c),t,i,r,n,o+1),S=Dt(s.slice(c+1),t,i,r,n,o+1);if(A===43&&(M==="string"||S==="string"))return"string";if(M==="number"&&S==="number")return"number";break}}if(s.startsWith("[")&&s.endsWith("]")){let c=kr(s.slice(1,-1));if(c.some((A)=>A.trim().startsWith("..."))){let A=c.map((M)=>{let S=M.trim();if(!S)return"undefined";let T=S.startsWith("..."),N=Dt(T?S.slice(3):S,t,i,r,n,o+1);return T?`(NonNullable<${N}> extends Iterable<infer Element> ? Element : never)`:N});return`(${[...new Set(A)].join(" | ")||"never"})[]`}}let m=f??(s.startsWith("{")&&s.endsWith("}")?Ec(s,!1,o+1,void 0,(c)=>Dt(c,t,i,r,n,o+1)):Te(s,!1));if(m==="unknown"&&Gi(s)&&r)return r(`typeof ${s}`,n);let g=ue(m),C="",b=0;for(let c=0;c<g.length;c++){let A=g[c];if(A.kind!=="word"||m.slice(A.start,A.end)!=="typeof")continue;let M=g[c+1];if(!M||M.kind!=="word")continue;let S=t.get(m.slice(M.start,M.end)),T=S,N=!S,B=A.start,ee=M.end,K=c,te=[];c++;while(g[c+1]&&m.slice(g[c+1].start,g[c+1].end)==="."&&g[c+2]?.kind==="word"){let fe=g[c+2];if(te.push(m.slice(fe.start,fe.end)),!N)S=`(${S})["${m.slice(fe.start,fe.end)}"]`;ee=fe.end,c+=2}let he=g[c+1];if(he&&m.slice(he.start,he.end)==="<"){let fe=rt(m,he.start,"<",">");if(fe!==-1){ee=fe+1;while(g[c+1]&&g[c+1].start<=fe)c++;S=void 0,T=void 0,N=!0}}let Ae=K>=2&&m.slice(g[K-2].start,g[K-2].end)==="ReturnType"&&m.slice(g[K-1].start,g[K-1].end)==="<"&&g[c+1]&&m.slice(g[c+1].start,g[c+1].end)===">",Se=T&&Ae&&te.length===1?dp(T.trim(),te[0]):void 0;if(Se){B=g[K-2].start,ee=g[++c].end;let fe=B===0&&ee===m.length;C+=m.slice(b,B)+(fe||!Se.includes("|")?Se:`(${Se})`),b=ee;continue}if(N&&Ae)B=g[K-2].start,ee=g[++c].end;C+=m.slice(b,B)+(S??"unknown"),b=ee}return C+m.slice(b)}function pp(e){let t=ue(e),i=0,r=-1;for(let o=0;o<t.length;o++){let s=t[o],a=e.slice(s.start,s.end);if(s.kind!=="punctuation"&&s.kind!=="word")continue;if(["(","[","{"].includes(a))i++;else if([")","]","}"].includes(a))i--;else if(!i&&a==="as"&&o>0&&e.slice(t[o-1].start,t[o-1].end)!==".")r=o}if(r===-1||r+1===t.length)return;let n=e.slice(t[r].end).trim();if(n==="const")return;i=0;for(let o of t.slice(r+1)){if(o.kind!=="punctuation")continue;let s=e.slice(o.start,o.end);if(!i&&["??","||","&&"].some((a)=>e.startsWith(a,o.start)))return;if(["(","[","{","<"].includes(s))i++;else if([")","]","}",">"].includes(s))i--;else if(!i&&["+","-","*","/","%","=","!",";"].includes(s))return}return n}function yc(e,t){let i=0;for(let r of ue(e)){if(r.kind!=="punctuation")continue;let n=e.slice(r.start,r.end);if(["(","[","{"].includes(n))i++;else if([")","]","}"].includes(n))i--;if(!i&&e.startsWith(t,r.start))return r.start}return-1}function mp(e){if(e.includes("=>"))return null;let t=[],i=0,r=0;for(let n=0;n<=e.length;n++){let o=n===e.length?"|":e[n];if(o==="'"||o==='"'||o==="`"){n++;while(n<e.length&&e[n]!==o)n+=e[n]==="\\"?2:1;if(n>=e.length)return null}else if(o==="("||o==="["||o==="{"||o==="<")i++;else if(o===")"||o==="]"||o==="}"||o===">")i--;else if(o==="|"&&i===0){let s=e.slice(r,n).trim();if(s)t.push(s);r=n+1}if(i<0)return null}return i===0?t:null}function gp(e,t){let i=mp(t);if(!i)return`${e} | ${t}`;let r=[];for(let f of[e,...i]){if(f==="unknown")return"unknown";if(!r.includes(f))r.push(f)}let n=r.includes("boolean")||r.includes("true")&&r.includes("false"),o=r.includes("string"),s=r.includes("number"),a=[],l=!1;for(let f of r)if(n&&(f==="true"||f==="false"||f==="boolean")){if(!l)a.push("boolean");l=!0}else if(o&&yp(f))continue;else if(s&&/^-?\d+(?:\.\d+)?$/.test(f))continue;else a.push(f);return a.join(" | ")}function yp(e){let t=e[0];return e.length>=2&&(t==="'"||t==='"')&&e.endsWith(t)&&!e.slice(1,-1).includes(t)}function wp(e,t,i){let r=Ai(t)!==-1?`(${t.trim()})`:t;if(e.trim()==="unknown")return i==="&&"||r.trim()==="unknown"?"unknown":`{} | ${r}`;let n=e.trim();if(n==="boolean"||n==="string"||n==="number"){if(i==="??")return n;return gp(i==="||"?n==="boolean"?"true":n:n==="boolean"?"false":n==="string"?"''":"0",r)}let o="false | 0 | 0n | '' | null | undefined";if(i==="??")return`([${e}] extends [NonNullable<${e}>] ? ${e} : NonNullable<${e}> | ${r})`;if(i==="||")return`([${e}] extends [object] ? ${e} : [Exclude<${e}, object> & (${o})] extends [never] ? ${e} : Exclude<NonNullable<${e}>, ${o}> | ${r})`;return`([${e}] extends [object] ? ${r} : [${e}] extends [${o}] ? ${e} : unknown extends (${e}) ? ${e} : (Exclude<${e}, object> & (${o})) | ${r})`}function Cp(e){let t=`(NonNullable<${e}> extends infer __dtsx_spread_value ? { -readonly [__dtsx_spread_key in keyof __dtsx_spread_value]: __dtsx_spread_value[__dtsx_spread_key] } : never)`,i=`(NonNullable<${e}> extends infer __dtsx_spread_value ? { -readonly [__dtsx_spread_key in keyof __dtsx_spread_value]?: __dtsx_spread_value[__dtsx_spread_key] } : never)`;return`([${e}] extends [null | undefined] ? {} : [${e}] extends [NonNullable<${e}>] ? ${t} : ${i})`}function vp(e,t){let i=e.trim();while(Fn(i))i=i.slice(1,-1).trim();let r=yc(i,"??");if(r!==-1&&i.slice(r+2).trim()==="{}")return Cp(t(i.slice(0,r)));let n=vc(i);if(n){if(n.whenFalse.trim()==="{}")return`Partial<${t(n.whenTrue)}>`;if(n.whenTrue.trim()==="{}")return`Partial<${t(n.whenFalse)}>`}return t(i)}function wc(e){return e.map((t)=>e.length>1&&Ai(t)!==-1?`(${t})`:t).join(" | ")}function Pn(e){let t=0;while(t<e.length){let n=e.charCodeAt(t);if(n<=32)t++;else if(n===47&&e.charCodeAt(t+1)===47){t+=2;while(t<e.length&&e.charCodeAt(t)!==10&&e.charCodeAt(t)!==13)t++}else if(n===47&&e.charCodeAt(t+1)===42){let o=e.indexOf("*/",t+2);t=o===-1?e.length:o+2}else break}let i=t,r=t;while(r<e.length){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=qt(e,r,n),i=r;continue}if(n===92){r=Math.min(r+2,e.length),i=r;continue}if(n===47&&e.charCodeAt(r+1)===47){while(r<e.length&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13)r++;continue}if(n===47&&e.charCodeAt(r+1)===42){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+2;continue}if(r++,n>32)i=r}return e.slice(t,i)}function Cc(e){if(!e.startsWith("<"))return;let t=xi(e)(0,0);if(!t||t.parameters||t.completeOperand||!e.slice(t.end).trim()||!Tn(e.slice(t.end).trim()))return;return e.slice(1,t.end-1).trim()}function Tn(e){e=Pn(e);let t=0,i;for(let r=0;r<e.length;r++){let n=e[r];if(n==="'"||n==='"'||n==="`"){let o=r+1;while(o<e.length&&e[o]!==n){if(e[o]==="\\")o++;o++}r=o;continue}if(n==="/"){if(e[r+1]==="/"){let o=e.indexOf(`
|
|
46
46
|
`,r+2);r=o===-1?e.length:o;continue}if(e[r+1]==="*"){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+1;continue}if(kt(e,r)){r=bt(e,r)-1;continue}}if(n==="<"&&t===0){i??=xi(e);let o=i(r,0);if(o){r=o.end-1;continue}}if(n==="("||n==="["||n==="{")t++;else if(n===")"||n==="]"||n==="}")t--;else if(t!==0)continue;else if(n==="?"){if(e[r+1]!==".")return!1}else if("=!<>&|+-*/%,:".includes(n))return!1;else if(n===" "||n==="\t"||n===`
|
|
47
|
-
`||n==="\r"){let o=e.slice(r).trimStart(),s=/[A-Za-z]+$/.exec(Pn(e.slice(0,r)))?.[0];if(r=e.length-o.length-1,s&&["new","void","typeof","delete","await","yield"].includes(s))continue;if(o&&o[0]!=="."&&o[0]!=="?"&&o[0]!=="("&&o[0]!=="[")return!1}}return!0}function
|
|
48
|
-
`)||e.includes("\r"))return"string";return e}function Fs(e,t){let i=ue(e),r=(l)=>i[l]?e.slice(i[l].start,i[l].end):"";if(r(0)!=="new"||i[1]?.kind!=="word"||["class","function","new","super"].includes(r(1)))return"unknown";let n=2,o=[r(1)];while(r(n)==="."&&i[n+1]?.kind==="word")o.push(r(n+1)),n+=2;let s=o.join(".");if(!t&&(s.charCodeAt(0)<65||s.charCodeAt(0)>90))return"unknown";let a="";if(r(n)==="<"){let l=i[n].start,f=xi(e)(l,0);if(!f||!f.completeOperand||f.parameters)return"unknown";a=e.slice(l,f.end);while(n<i.length&&i[n].start<f.end)n++}if(n<i.length){if(r(n)!=="(")return"unknown";let l=0,f=!1;for(;n<i.length;n++)if(r(n)==="(")l++;else if(r(n)===")"&&--l===0){f=n===i.length-1;break}if(!f)return"unknown"}if(t)return t(s)?s+a:`InstanceType<typeof ${s}${a}>`;if(a)return s+a;switch(s){case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"Array":return"any[]";case"Object":return"object";case"Promise":return"Promise<any>";default:return s}}function
|
|
47
|
+
`||n==="\r"){let o=e.slice(r).trimStart(),s=/[A-Za-z]+$/.exec(Pn(e.slice(0,r)))?.[0];if(r=e.length-o.length-1,s&&["new","void","typeof","delete","await","yield"].includes(s))continue;if(o&&o[0]!=="."&&o[0]!=="?"&&o[0]!=="("&&o[0]!=="[")return!1}}return!0}function bp(e){if(e.startsWith("function")&&Ar(e,0,8))return!0;let t=Ai(e);if(t===-1)return!1;let i=e.slice(0,t).trim();if(i.startsWith("async")&&Ar(i,0,5))i=i.slice(5).trim();if(i.startsWith("<")){let n=rt(i,0,"<",">");if(n===-1)return!1;i=i.slice(n+1).trim()}if(i.startsWith("(")){let n=rt(i,0,"(",")");if(n===-1)return!1;let o=i.slice(n+1).trim();if(o&&!o.startsWith(":"))return!1}let r=Ds(i);return Fn(r.params)||Gi(r.params)}function Fn(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r===40)t++;else if(r===41&&--t===0)return i===e.length-1}return!1}function vc(e){let t=0,i=-1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=qt(e,r,n)-1;continue}if(n===47&&(e.charCodeAt(r+1)===47||e.charCodeAt(r+1)===42)){if(e.charCodeAt(r+1)===47)while(r+1<e.length&&e.charCodeAt(r+1)!==10&&e.charCodeAt(r+1)!==13)r++;else{let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+1}continue}if(n===40||n===91||n===123)t++;else if(n===41||n===93||n===125)t--;else if(n===63&&t===0&&e.charCodeAt(r+1)!==63)i=r;else if(n===58&&t===0&&i!==-1)return{whenTrue:Pn(e.slice(i+1,r)),whenFalse:Pn(e.slice(r+1))}}return null}function Ar(e,t,i){return(t===0||!Ht(e.charCodeAt(t-1)))&&!Ht(e.charCodeAt(t+i))}function bc(e,t){let i=t;while(i<e.length){if(e.charCodeAt(i)<=32){i++;continue}if(e.startsWith("//",i)){while(i<e.length&&e.charCodeAt(i)!==10&&e.charCodeAt(i)!==13)i++;continue}if(e.startsWith("/*",i)){let r=e.indexOf("*/",i+2);i=r<0?e.length:r+2;continue}break}return i}function $p(e,t){let i=0,r=0,n=0,o=!1,s=!1;for(let a=t;a<e.length;a++){if(a=bc(e,a),a>=e.length)break;let l=e.charCodeAt(a);if(l===34||l===39||l===96){a=qt(e,a,l)-1,s=!1;continue}if(Ht(l)||l>=128){let f=a;while(a+1<e.length&&(Ht(e.charCodeAt(a+1))||e.charCodeAt(a+1)>=128))a++;s=o&&["keyof","typeof","readonly","unique","new","abstract","infer","extends"].includes(e.slice(f,a+1));continue}if(l===61&&e.charCodeAt(a+1)===62){a++,s=o;continue}if(l===40)i++;else if(l===41)i--,s=!1;else if(l===91)r++;else if(l===93)r--,s=!1;else if(l===60&&i===0&&r===0)n++;else if(l===62&&n>0&&i===0&&r===0)n--,s=!1;else if(l===123)if(i||r||n||o&&s)a=Mn(e,a)-1,s=!1;else return a;else if(i===0&&r===0&&n===0){if(l===58)o=!0,s=!0;else if(o&&[124,38,63].includes(l))s=!0;else if(l===59)return-1}}return-1}function Mn(e,t){let i=1,r=t+1;while(r<e.length&&i>0){let n=e.charCodeAt(r);if(n===34||n===39||n===96){r=qt(e,r,n);continue}if(n===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13)r++;continue}if(n===47&&e.charCodeAt(r+1)===42){let o=e.indexOf("*/",r+2);r=o===-1?e.length:o+2;continue}if(n===123)i++;else if(n===125)i--;r++}return r}function qt(e,t,i){let r=t+1;while(r<e.length){let n=e.charCodeAt(r);if(n===92){r+=2;continue}if(i===96&&n===36&&e.charCodeAt(r+1)===123){r=Mn(e,r+1);continue}if(r++,n===i)break}return r}function xp(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
|
|
48
|
+
`)||e.includes("\r"))return"string";return e}function Fs(e,t){let i=ue(e),r=(l)=>i[l]?e.slice(i[l].start,i[l].end):"";if(r(0)!=="new"||i[1]?.kind!=="word"||["class","function","new","super"].includes(r(1)))return"unknown";let n=2,o=[r(1)];while(r(n)==="."&&i[n+1]?.kind==="word")o.push(r(n+1)),n+=2;let s=o.join(".");if(!t&&(s.charCodeAt(0)<65||s.charCodeAt(0)>90))return"unknown";let a="";if(r(n)==="<"){let l=i[n].start,f=xi(e)(l,0);if(!f||!f.completeOperand||f.parameters)return"unknown";a=e.slice(l,f.end);while(n<i.length&&i[n].start<f.end)n++}if(n<i.length){if(r(n)!=="(")return"unknown";let l=0,f=!1;for(;n<i.length;n++)if(r(n)==="(")l++;else if(r(n)===")"&&--l===0){f=n===i.length-1;break}if(!f)return"unknown"}if(t)return t(s)?s+a:`InstanceType<typeof ${s}${a}>`;if(a)return s+a;switch(s){case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"Array":return"any[]";case"Object":return"object";case"Promise":return"Promise<any>";default:return s}}function Sp(e){return"{ new (...args: any[]): any }"}function $c(e,t,i=0,r){if(e.startsWith("Promise.resolve(")){let n=e.indexOf(")",16);if(n!==-1){let o=e.slice(16,n).trim();if(o)return`Promise<${Te(o,t,!1,i+1,r)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let n=e.indexOf("[",12),o=e.lastIndexOf("]");if(n!==-1&&o>n){let s=e.slice(n+1,o).trim(),a=kr(s),l=[];for(let f=0;f<a.length;f++){let u=a[f].trim();if(u.startsWith("Promise.resolve(")){let d=$c(u,t,i+1,r),h=d.indexOf("<"),p=d.lastIndexOf(">");l.push(h!==-1&&p>h?d.slice(h+1,p):"unknown")}else l.push(Te(u,t,!1,i+1,r))}return`Promise<[${l.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Rs(e,t,i=0,r){let n=e.slice(1,-1).trim();if(!n)return"never[]";if(i>=In)return"unknown[]";let o=kr(n),s=!1;for(let p=0;p<o.length;p++){let m=o[p],g=m.length;while(g>0&&m.charCodeAt(g-1)<=32)g--;if(g>=8&&m.slice(g-8,g)==="as const"){s=!0;break}}if(s){let p=[];for(let m=0;m<o.length;m++){let g=o[m].trim();if(g.endsWith("as const")){let C=g.slice(0,-8).trim();if(C.startsWith("[")&&C.endsWith("]")){let b=C.slice(1,-1).trim(),c=kr(b),A=[];for(let M=0;M<c.length;M++)A.push(Te(c[M].trim(),!0,!1,i+1,r));p.push(`readonly [${A.join(", ")}]`)}else p.push(Te(C,!0,!1,i+1,r))}else if(g.startsWith("[")&&g.endsWith("]"))p.push(Rs(g,!0,i+1,r));else p.push(Te(g,!0,!1,i+1,r))}return`readonly [
|
|
49
49
|
${p.join(` |
|
|
50
50
|
`)}
|
|
51
|
-
]`}let a=Nn&&!t,l=[],f=[];for(let p of o){let m=p.trim(),g=yt;if(yt=null,m.startsWith("...")){let C=m.slice(3).trim(),b=Te(C,!1,!1,i+1,r);if(b.endsWith("[]"))l.push(b.slice(0,-2));else if(b.startsWith("readonly [")&&b.endsWith("]"))l.push(b.slice(10,-1));else if(Ei(C))l.push(`(typeof ${C})[number]`);else l.push("unknown")}else if(m.startsWith("[")&&m.endsWith("]"))l.push(Rs(m,t,i+1,r));else l.push(
|
|
52
|
-
`,a+2);a=(f===-1?e.length:f)-1;continue}if(l===47&&e.charCodeAt(a+1)===42){let f=e.indexOf("*/",a+2);a=(f===-1?e.length:f+2)-1;continue}if(l===32||l===9||l===10||l===13)continue;if(l===44&&i===0){if(o!==-1)t.push(e.slice(o,s));o=-1;continue}if(l===34||l===39||l===96)r=!0,n=l;else if(l===91||l===123||l===40)i++;else if(l===93||l===125||l===41)i--;if(o===-1)o=a;s=a+1}if(o!==-1)t.push(e.slice(o,s));return t}function Dn(e){if(zt(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function
|
|
51
|
+
]`}let a=Nn&&!t,l=[],f=[];for(let p of o){let m=p.trim(),g=yt;if(yt=null,m.startsWith("...")){let C=m.slice(3).trim(),b=Te(C,!1,!1,i+1,r);if(b.endsWith("[]"))l.push(b.slice(0,-2));else if(b.startsWith("readonly [")&&b.endsWith("]"))l.push(b.slice(10,-1));else if(Ei(C))l.push(`(typeof ${C})[number]`);else l.push("unknown")}else if(m.startsWith("[")&&m.endsWith("]"))l.push(Rs(m,t,i+1,r));else l.push(up(m,t,i+1,r));if(a)f.push(yt);yt=g}if(a)if(Ps(e))yt=Rn(e);else{let p=[];for(let m=0;m<o.length;m++){let g=o[m].trim();if(g.endsWith("as const"))continue;if(Dn(g)||g==="null"||g==="undefined")p.push(g);else if(g.startsWith("[")&&Ps(g))p.push(Rn(g));else if(g.startsWith("{")){if(f[m])p.push(f[m])}else{let C=Te(g,!1,!1,0,r);if(C!=="unknown")p.push(C)}}if(p.length>0)yt=`[${p.join(", ")}]`}if(t)return`readonly [${l.join(", ")}]`;let u=new Set,d=[],h=!0;for(let p of l){if(!u.has(p))u.add(p),d.push(p);if(h){if(!(zt(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))h=!1}}if(h&&l.length<=10)return`readonly [${l.join(", ")}]`;if(d.length===1)return`${d[0]}[]`;return`(${d.join(" | ")})[]`}function kr(e){let t=[],i=0,r=!1,n=0,o=-1,s=0;for(let a=0;a<e.length;a++){let l=e.charCodeAt(a);if(r){if(l===92)a++;else if(l===n)r=!1;s=a+1;continue}if(l===47&&e.charCodeAt(a+1)===47){let f=e.indexOf(`
|
|
52
|
+
`,a+2);a=(f===-1?e.length:f)-1;continue}if(l===47&&e.charCodeAt(a+1)===42){let f=e.indexOf("*/",a+2);a=(f===-1?e.length:f+2)-1;continue}if(l===32||l===9||l===10||l===13)continue;if(l===44&&i===0){if(o!==-1)t.push(e.slice(o,s));o=-1;continue}if(l===34||l===39||l===96)r=!0,n=l;else if(l===91||l===123||l===40)i++;else if(l===93||l===125||l===41)i--;if(o===-1)o=a;s=a+1}if(o!==-1)t.push(e.slice(o,s));return t}function Dn(e){if(zt(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function xc(e){return e==="number"||e==="string"||e==="boolean"}function Sc(e){let t=[],i=0;while(i<e.length){while(i<e.length&&e.charCodeAt(i)<=32)i++;if(e.startsWith("/*",i)){let r=e.indexOf("*/",i+2);if(r===-1)break;t.push(e.slice(i,r+2)),i=r+2}else if(e.startsWith("//",i)){let r=i;while(r<e.length&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13)r++;t.push(e.slice(i,r).trimEnd()),i=r}else break}return t}function Ws(e,t,i){let r=t.trim();if(!xc(i)||!Dn(r))return"";let n=(e??[]).map((s)=>s.trim()).filter((s)=>s.startsWith("/**")||s.startsWith("//")).join(`
|
|
53
53
|
`),o;if(n.includes("@defaultValue"))o=n;else{let s=`@defaultValue ${Er(r)}`;if(!n)o=`/** ${s} */`;else{let a=n.lastIndexOf("*/");if(a!==-1){let l=n.slice(0,a).trimEnd();if(l.startsWith("/** ")&&!l.includes(`
|
|
54
54
|
`))l=`/**
|
|
55
55
|
* ${l.slice(4)}`;o=`${l}
|
|
@@ -60,36 +60,36 @@ defineProps<${i}>()`,null)}function Qh(e){return fs(e)}function Fl(e){let t=ls(e
|
|
|
60
60
|
*/`}}return o.split(`
|
|
61
61
|
`).map((s)=>{let a=s.trim();if(!a)return"";return a.startsWith("*")?` ${a}`:` ${a}`}).join(`
|
|
62
62
|
`)+`
|
|
63
|
-
`}function Ps(e){let t=!1,i=0,r=e.length;for(let n=0;n<r;n++){let o=e.charCodeAt(n);if(t){if(o===92){n++;continue}if(o===i)t=!1;continue}if(o===34||o===39||o===96){t=!0,i=o;continue}if(o===61&&n+1<r&&e.charCodeAt(n+1)===62)return!1;if(o===47&&(e.charCodeAt(n+1)===47||e.charCodeAt(n+1)===42))return!1;if(o>=97&&o<=122){let s=n;while(n<r&&(e.charCodeAt(n)>=97&&e.charCodeAt(n)<=122||e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90||e.charCodeAt(n)>=48&&e.charCodeAt(n)<=57||e.charCodeAt(n)===95||e.charCodeAt(n)===36))n++;let a=e.slice(s,n);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let l=n;while(l<r&&e.charCodeAt(l)<=32)l++;if(l<r&&e.charCodeAt(l)===40)return!1;n--}}return!0}function
|
|
64
|
-
`:"",
|
|
65
|
-
${N}: ${Zt(K)}`);else l.push(`${S}${t?"readonly ":""}${N}: ${Zt(K)}`)}if(h){let re=
|
|
63
|
+
`}function Ps(e){let t=!1,i=0,r=e.length;for(let n=0;n<r;n++){let o=e.charCodeAt(n);if(t){if(o===92){n++;continue}if(o===i)t=!1;continue}if(o===34||o===39||o===96){t=!0,i=o;continue}if(o===61&&n+1<r&&e.charCodeAt(n+1)===62)return!1;if(o===47&&(e.charCodeAt(n+1)===47||e.charCodeAt(n+1)===42))return!1;if(o>=97&&o<=122){let s=n;while(n<r&&(e.charCodeAt(n)>=97&&e.charCodeAt(n)<=122||e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90||e.charCodeAt(n)>=48&&e.charCodeAt(n)<=57||e.charCodeAt(n)===95||e.charCodeAt(n)===36))n++;let a=e.slice(s,n);if(a==="new"||a==="async"||a==="await"||a==="function"||a==="yield"||a==="console"||a==="process")return!1;let l=n;while(l<r&&e.charCodeAt(l)<=32)l++;if(l<r&&e.charCodeAt(l)===40)return!1;n--}}return!0}function Ec(e,t,i=0,r,n){let o=e.slice(1,-1).trim();if(!o)return"{}";if(i>=In)return"Record<string, unknown>";let s=Tp(o),a=new Set(s.flatMap(([b])=>{let c=hc(Ms(b).key);return c?.kind==="get"?[c.name]:[]})),l=[],f=[],u=[],d=!1,h=Nn&&!t,p=[],m=0;for(let[b,c]of s){let{comments:A,key:M}=Ms(b),S=A?`${A}
|
|
64
|
+
`:"",T=hc(M);if(T&&ql(T.name))continue;let N=M,B=!1;if(M==="..."){let re=c.trim(),pe=n?vp(re,n):Ei(re)?`typeof ${re}`:Te(re,t,!1,i+1,r);if(pe!=="unknown")f.push(pe);if(h&&(Ei(re)||re.startsWith("{")))p.push(`...${Rn(re)}`);continue}let ee=yt;yt=null;let K,te=c.trim();if(te===M&&Gi(te))K=n?.(c)??(t?void 0:r?.mutableBindingTypes?.get(te))??`typeof ${te}`;else if(Pp(te)){B=!0;let re=Mp(M);if(re){N=re.name;let pe="";if(te.startsWith("async "))pe="async ";if(te.charCodeAt(pe.length)===42)pe+="*";K=pc(re.name,pe+re.typeParams+te.slice(pe.length))}else K=pc(M,te)}else{if(K=n?.(c)??Te(c,t,!1,i+1,r),K==="unknown"&&Ei(te))K=(t?void 0:r?.mutableBindingTypes?.get(te))??`typeof ${te}`;if(K.includes("=>")||K.includes("function")||K.includes("async"))K=fc(K)}let he=yt;yt=ee;let Ae=N,Se=c.trim(),fe=Kl(N,r);if(!Hl(T?.name??N,r)&&!(T?.kind==="set"&&a.has(T.name)))u.push(T?Rp(T.kind,K):K);if(fe&&"index"in fe)d=!0;else{if(fe&&"name"in fe)N=fe.name;if(T){let re=Op(T.kind,T.name,K);if(re){l.push(`${S}${Zt(re)}`);continue}}if(!t&&xc(K)&&Dn(Se))l.push(`${S}/** @defaultValue ${Er(Se)} */
|
|
65
|
+
${N}: ${Zt(K)}`);else l.push(`${S}${t?"readonly ":""}${N}: ${Zt(K)}`)}if(h){let re=mc(Ae);if(Se.endsWith("as const"));else if(Dn(Se))p.push(`${re}: ${Se}`);else if(Se.startsWith("[")&&Ps(Se))p.push(`${re}: ${Rn(Se)}`);else if(Se.startsWith("{")){if(he)p.push(`${re}: ${he}`)}else if(B)p.push(`${re}: ${Ts(fc(K))}`),m++;else if(!Se.startsWith("[")&&(Se.includes("=>")||Se.startsWith("function")||Se.startsWith("async"))){let pe=kc(Se,!1,0,!0);p.push(`${re}: ${Ts(pe)}`),m++}}}if(h&&p.length>m){let b=i>0?(i-1)/2:0,c=`{ ${p.join(", ")} }`;if(c.length<=80)yt=c;else{let A=" ".repeat((b+1)*2),M=" ".repeat(b*2);yt=`{
|
|
66
66
|
${A}${p.join(`,
|
|
67
67
|
${A}`)}
|
|
68
68
|
${M}}`}}if(d&&f.length===0){let b=[...new Set(u)].map((c)=>c.includes("=>")||c.includes(" & ")?`(${c})`:c);l.unshift(`${t?"readonly ":""}[x: string]: ${Zt(b.join(" | "))}`)}let g=l.length>0?`{
|
|
69
69
|
${l.join(`;
|
|
70
70
|
`)}
|
|
71
|
-
}`:"{}";if(f.length===0)return g;let C=f[0];for(let b=1;b<f.length;b++)C=`Omit<${C}, keyof ${f[b]}> & ${f[b]}`;return l.length>0?`Omit<${C}, keyof ${g}> & ${g}`:C}function Gi(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 i=1;i<e.length;i++)if(!Ht(e.charCodeAt(i)))return!1;return!0}function Ei(e){let t=e.split(".");return t.length>0&&t.every(Gi)}function
|
|
72
|
-
`).map((f)=>
|
|
73
|
-
`),i=t.indexOf("async");if(i!==-1){let f=i>0?t.charCodeAt(i-1):32,u=i+5<t.length?t.charCodeAt(i+5):32;if(!Ht(f)&&!Ht(u))t=(t.slice(0,i)+t.slice(i+5)).trim()}let r=t.indexOf("(");if(r!==-1){let f=rt(t,r,"(",")");if(f!==-1){let u=t.slice(r,f+1),d=Si(u);t=t.slice(0,r)+d+t.slice(f+1)}}let n=t.length,o="",s=[],a=!1,l=!1;for(let f=0;f<n;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)l=!0;continue}if(a&&o.length>0){let d=(s.length>0?s[s.length-1]:0)===123;if(l&&d){let h=o.charCodeAt(o.length-1),p=h===59||h===44||h===123||u===125,m=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!p&&!m)o+="; ";else o+=" "}else o+=" "}a=!1,l=!1,o+=t[f]}return o.trim()}function Ht(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Si(e){let t=e.trim(),i,r=!1;if(t.startsWith("(")&&t.endsWith(")"))i=t.slice(1,-1),r=!0;else i=t;let n=i.trim();if(!n)return r?"()":"";let o=!1;{let m=0;for(let g=0;g<n.length;g++){let C=n.charCodeAt(g);if(C===40||C===60||C===91||C===123)m++;else if(C===41||C===93||C===125||C===62&&n.charCodeAt(g-1)!==61)m--;else if(m===0&&C===61){let b=g>0?n.charCodeAt(g-1):0,c=g+1<n.length?n.charCodeAt(g+1):0;if(b!==61&&b!==33&&b!==60&&b!==62&&c!==61&&c!==62){o=!0;break}}}}if(!o)return t;let s=[],a=[],l=0,f=0,u=!1,d=0;for(let m=0;m<=n.length;m++){if(m===n.length){s.push(n.slice(l));break}let g=n.charCodeAt(m);if(u){if(g===92){m++;continue}if(g===d)u=!1;continue}if(g===47&&m+1<n.length){let C=n.charCodeAt(m+1);if(C===42){m+=2;while(m+1<n.length&&!(n.charCodeAt(m)===42&&n.charCodeAt(m+1)===47))m++;m++;continue}if(C===47){while(m<n.length&&n.charCodeAt(m)!==10)m++;continue}}if(g===39||g===34||g===96){u=!0,d=g;continue}if(g===40||g===60||g===91||g===123)f++;else if(g===41||g===93||g===125||g===62&&n.charCodeAt(m-1)!==61)f--;else if(g===44&&f===0){s.push(n.slice(l,m));let C=",",b=m+1;while(b<n.length&&n.charCodeAt(b)<=32)C+=n[b],b++;a.push(C),l=b}}let h=[];for(let m of s){let g=m.trim();if(!g){h.push(m);continue}if(g.startsWith("//"))continue;let C=
|
|
74
|
-
`),key:e.slice(i).trim()}}function
|
|
75
|
-
`))
|
|
76
|
-
${r}`:r,r]);else if(r.startsWith("...")&&r.length>3)e.push(["...",r.slice(3).trim()])}function dc(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let i=t.slice(4).trim();if(i)return{kind:"get",name:i}}if(t.startsWith("set ")&&t.length>4){let i=t.slice(4).trim();if(i)return{kind:"set",name:i}}return null}function Tp(e,t,i){let r=i.trim();if(r.charCodeAt(0)!==40)return null;let n=rt(r,0,"(",")");if(n===-1)return null;let o=r.slice(1,n).trim(),s=r.slice(n+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 Op(e,t){let i=t.trim(),r=rt(i,0,"(",")");if(!i.startsWith("(")||r===-1)return"unknown";if(e==="get"){let a=i.slice(r+1).trim();return a.startsWith("=>")?a.slice(2).trim():"unknown"}let n=i.slice(1,r).trim(),o=n.startsWith("{")?rt(n,0,"{","}"):n.startsWith("[")?rt(n,0,"[","]"):0,s=n.indexOf(":",Math.max(0,o));return s===-1?"unknown":n.slice(s+1).trim()}function Rp(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 i=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n===40)i++;else if(n===41){if(i--,i===0){let o=t.slice(r+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=Ls(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function Pp(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let i=0,r=-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;i++}else if(s===60){if(i--,i===0){r=o;break}}}if(r===-1)return null;let n=t.slice(0,r).trimEnd();if(!n)return null;return{name:n,typeParams:t.slice(r)}}function hc(e,t){let i=t.trimStart(),r=!1,n=!1;if(i.startsWith("async ")||i.startsWith("async\t"))r=!0,i=i.slice(5).trimStart();if(i.startsWith("*"))n=!0,i=i.slice(1).trimStart();let o="";if(i.charCodeAt(0)===60){let h=0,p=-1;for(let m=0;m<i.length;m++)if(i.charCodeAt(m)===60)h++;else if(i.charCodeAt(m)===62&&!(m>0&&i.charCodeAt(m-1)===61)){if(h--,h===0){p=m;break}}if(p!==-1)o=i.slice(0,p+1),i=i.slice(p+1).trimStart()}let s=i.indexOf("("),a=rt(i,s,"(",")");if(s===-1||a===-1)return"() => unknown";let l=i.slice(s,a+1),f="unknown",u=i.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let h=u.slice(1),p=Ls(h,0);if(p)f=h.slice(0,p.index).trim();else f=h.trim()}if(f==="unknown"&&!n&&u.charCodeAt(0)===123){let h=rt(u,0,"{","}");if(h!==-1){let p=Qt(u.slice(1,h),r,l);if(p!=="unknown"&&p!=="Promise<unknown>")f=r&&p.startsWith("Promise<")?p.slice(8,-1):p;else if(r)f="Promise<unknown>"}}if(f==="unknown"){if(r&&n)f="AsyncGenerator<unknown, void, unknown>";else if(n)f="Generator<unknown, void, unknown>";else if(r)f="Promise<void>"}else if(r&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let d=Si(l);return`${o}${d} => ${f}`}function Ls(e,t){let i=0,r=0,n=0,o=0,s=!1,a=0;for(let l=t;l<e.length;l++){let f=e.charCodeAt(l);if(s){if(f===92)l++;else if(f===a)s=!1;continue}if(f===34||f===39||f===96){s=!0,a=f;continue}if(f===40)i++;else if(f===41&&i>0)i--;else if(f===91)r++;else if(f===93&&r>0)r--;else if(f===60)n++;else if(f===62&&n>0&&e.charCodeAt(l-1)!==61)n--;else if(f===125&&o>0)o--;else if(f===123){let u=i>0||r>0||n>0||o>0,d=e.slice(t,l).trimEnd(),h=d.charCodeAt(d.length-1),p=d.length===0||h===38||h===124||h===40||h===44||h===58||h===61||h===91;if(u||p)o++;else return{index:l,kind:"body"}}else if(f===61&&l+1<e.length&&e.charCodeAt(l+1)===62&&i===0&&r===0&&n===0&&o===0)return{index:l,kind:"arrow"}}return null}function rt(e,t,i,r){let n=0;for(let o=t;o<e.length;o++)if(e[o]===i)n++;else if(e[o]===r){if(r===">"&&o>0&&e[o-1]==="=")continue;if(n--,n===0)return o}return-1}function Ai(e){let t=0,i=0,r=!1,n="";for(let o=0;o<e.length-1;o++){let s=e[o],a=e[o+1],l=o>0?e[o-1]:"";if(!r&&(s==='"'||s==="'"||s==="`"))r=!0,n=s;else if(r&&s===n&&l!=="\\")r=!1;if(!r){if(s==="<"){let f=rt(e,o,"<",">");if(f!==-1){o=f;continue}}if(s==="(")t++;else if(s===")")t--;else if(s==="[")i++;else if(s==="]")i--;if(s==="="&&a===">"&&t===0&&i===0)return o}}return-1}function Ac(e,t=!1,i=0,r=!0){let n=e.trim();if(n.length>200&&ks(n,"=>")>2&&ks(n,"<")>5&&!n.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(n.startsWith("async ")&&n.includes("=>")){let s=n.slice(5).trim(),a=Ai(s);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let l=s.substring(0,a).trim(),f=s.substring(a+2).trim(),u=Ds(l),{params:d,returnType:h}=u;if(d=Si(d),d==="()"||d==="")d="()";else if(!d.startsWith("("))d=`(${d})`;let p=h;if(p);else if(f.startsWith("{"))p=Qt(f.slice(1,f.endsWith("}")?-1:void 0),!0,u.params);else p=Dt(f,Os(u.params));let m=`${d} => ${h||p.startsWith("Promise<")?p:`Promise<${p}>`}`;return t?`(${m})`:m}if(n.includes("=>")){let s="",a=n;if(n.startsWith("<")){let C=rt(n,0,"<",">");if(C!==-1)s=n.substring(0,C+1),a=n.substring(C+1).trim()}let l=Ai(a);if(l===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,l).trim(),u=a.substring(l+2).trim(),d=Ds(f),{params:h,returnType:p}=d;if(h=Si(h),h==="()"||h==="")h="()";else if(!h.startsWith("("))h=`(${h})`;let m="unknown";if(p)m=p;else if(u.startsWith("{"))m=Qt(u.slice(1,u.endsWith("}")?-1:void 0),!1,d.params);else if(On(u)||Fn(u)&&On(u.slice(1,-1).trim()))m="JSX.Element";else if(u.includes("=>")){let C=u.trimStart(),b=C.indexOf("("),c=b!==-1?rt(C,b,"(",")"):-1,A=c!==-1?C.indexOf("=>",c):-1;if(b===0&&c!==-1&&A!==-1){let M=C.substring(b+1,c).trim(),S=Si(M);if(s.includes("T")&&S.includes("T"))m=`(${S}) => T`;else m=`(${S}) => any`}else m="any"}else m=Dt(u,Os(d.params));let g=`${s}${h} => ${m}`;return t?`(${g})`:g}if(n.startsWith("function")){let s=8,a=n.length;while(s<a&&n.charCodeAt(s)<=32)s++;let l=!1;if(s<a&&n.charCodeAt(s)===42){l=!0,s++;while(s<a&&n.charCodeAt(s)<=32)s++}let f="";if(s<a&&n.charCodeAt(s)===60){let h=s,p=1;s++;while(s<a&&p>0){let m=n.charCodeAt(s);if(m===60)p++;else if(m===62&&n.charCodeAt(s-1)!==61)p--;s++}f=n.substring(h,s);while(s<a&&n.charCodeAt(s)<=32)s++}let u=n.indexOf("(",s);if(u!==-1){let h=1,p=u+1;while(p<a&&h>0){let A=n.charCodeAt(p);if(A===40)h++;else if(A===41)h--;p++}let m=n.substring(u+1,p-1).trim(),g=m?Si(`(${m})`):"()";if(l){let A=n.substring(p).trim(),M=A.indexOf("Generator<");if(M!==-1){let O=M+10,N=A.indexOf(">",O);if(N!==-1){let B=A.substring(O,N),ee=`${f}${g} => Generator<${B}>`;return t?`(${ee})`:ee}}let S=`${f}${g} => Generator<any, any, any>`;return t?`(${S})`:S}let C="unknown",b=n.substring(p).trimStart();if(b.charCodeAt(0)===58){let A=b.slice(1),M=Ls(A,0),S=(M?A.slice(0,M.index):A).trim();if(S)C=S}let c=`${f}${g} => ${C}`;return t?`(${c})`:c}let d="(...args: any[]) => unknown";return t?`(${d})`:d}if(n.includes("=>")&&n.includes("(")&&n.includes(")")){if(n.length>100||ks(n,"=>")>2){let s="";if(n.charCodeAt(0)===60){let d=rt(n,0,"<",">");if(d!==-1)s=n.substring(0,d+1)}let a=n.indexOf("("),l=a!==-1?rt(n,a,"(",")"):-1,f=a!==-1&&l!==-1?n.substring(a,l+1):"(...args: any[])";f=Si(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${n})`:n}let o="() => unknown";return t?`(${o})`:o}function Ds(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let i=rt(t,0,"(",")");if(i===-1)return{params:t,returnType:""};let r=t.slice(i+1).trim();return{params:t.slice(0,i+1),returnType:r.startsWith(":")?r.slice(1).trim():""}}function kc(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 Wn(e){let t=-1,i=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o===34||o===39||o===96){n=qt(e,n,o)-1;continue}if(o===47&&e.charCodeAt(n+1)===47){while(n<e.length&&e.charCodeAt(n)!==10)n++;continue}if(o===47&&e.charCodeAt(n+1)===42){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+1;continue}if(o===47){let s=n-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let a=!1;for(n++;n<e.length;n++){let l=e.charCodeAt(n);if(l===92)n++;else if(l===91)a=!0;else if(l===93)a=!1;else if(l===47&&!a)break}continue}}if(o===40||o===91||o===123)i++;else if(o===41||o===93||o===125)i--;else if(i===0&&e.startsWith("satisfies",n)&&Ar(e,n,9)&&e[n-1]!==".")t=n}if(t===-1)return null;let r=e.slice(t+9).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var In=20,Nn=!1,yt=null,lc;var Tr=ye(()=>{Bi();pt();Cn();bn();Sn();Ss();As();kn();lc={string:{at:"string | undefined",charAt:"string",charCodeAt:"number",codePointAt:"number | undefined",concat:"string",endsWith:"boolean",includes:"boolean",indexOf:"number",lastIndexOf:"number",localeCompare:"number",normalize:"string",padEnd:"string",padStart:"string",repeat:"string",replace:"string",replaceAll:"string",search:"number",slice:"string",split:"string[]",startsWith:"boolean",substring:"string",toLocaleLowerCase:"string",toLocaleUpperCase:"string",toLowerCase:"string",toString:"string",toUpperCase:"string",trim:"string",trimEnd:"string",trimStart:"string",valueOf:"string"},number:{toExponential:"string",toFixed:"string",toLocaleString:"string",toPrecision:"string",toString:"string",valueOf:"number"},bigint:{toLocaleString:"string",toString:"string",valueOf:"bigint"},boolean:{toString:"string",valueOf:"boolean"}}});function Tc(e,t,i,r){let n=new Map,o=new Map;for(let h of[...t,...i.values(),...[...r.values()].flat()])if(n.set(h.name,h),h.kind==="function"&&!o.has(h.name))o.set(h.name,h);for(let[h,p]of r)if(p.length)o.set(h,p[0]);if(!o.size)return;let s=new Set;for(let[h,p]of r)if(p.length>1)s.add(h);let a=new Map;for(let h of t)if(h.kind==="function"){let p=(a.get(h.name)??0)+1;if(a.set(h.name,p),p>1)s.add(h.name)}let l=Mt(e),f=(h)=>l[h]?e.slice(l[h].start,l[h].end):"",u=new Map,d=0;for(let h=0;h<l.length;h++){let p=l[h];if(p.kind==="punctuation"){let O=e.charCodeAt(p.start);if(O===40||O===91||O===123)d++;else if(O===41||O===93||O===125)d--;continue}if(d||l[h+2]?.kind!=="word"||f(h+1)!=="."||f(h+3)!=="=")continue;let m=f(h);if(!o.has(m))continue;let g=f(h+2),C=h+4,b=C,c=0;for(;b<l.length;b++){let O=f(b);if(!c&&O===";")break;if(!c&&b>C&&/[\r\n]/.test(e.slice(l[b-1].end,l[b].start))&&(["export","const","let","var","function","class"].includes(O)||o.has(O)&&f(b+1)==="."))break;if(["(","[","{"].includes(O))c++;else if([")","]","}"].includes(O))c--}if(b===C)continue;let A=Oc(e.slice(l[C].start,l[b-1].end),n,s),M=u.get(m);if(!M)u.set(m,M=new Map);let S=M.get(g);if(!S)M.set(g,S=[]);if(!S.includes(A))S.push(A);h=b-1}for(let[h,p]of u){let m=o.get(h),g=[...p].map(([b,c])=>` let ${b}: ${c.map((A)=>A.includes("=>")&&c.length>1?`(${A})`:A).join(" | ")};`).join(`
|
|
71
|
+
}`:"{}";if(f.length===0)return g;let C=f[0];for(let b=1;b<f.length;b++)C=`Omit<${C}, keyof ${f[b]}> & ${f[b]}`;return l.length>0?`Omit<${C}, keyof ${g}> & ${g}`:C}function Gi(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 i=1;i<e.length;i++)if(!Ht(e.charCodeAt(i)))return!1;return!0}function Ei(e){let t=e.split(".");return t.length>0&&t.every(Gi)}function Ep(e){let t=!1,i="";for(let r=0;r<e.length;r++){let n=e[r];if(t){if(n==="\\")r++;else if(n===i)t=!1;continue}if(n==='"'||n==="'"||n==="`"){t=!0,i=n;continue}if(n==="(")return r;if(n==="<"){let o=rt(e,r,"<",">");if(o!==-1)r=o}}return-1}function ki(e){if(e.length<3||!e.endsWith(")"))return null;let t=Ep(e);if(t===-1||rt(e,t,"(",")")!==e.length-1)return null;let i=e.slice(0,t).trim(),r=!1;if(i.endsWith("?."))r=!0,i=i.slice(0,-2).trim();let n=i,o=!1,s=i.indexOf("<");if(s!==-1){if(rt(i,s,"<",">")!==i.length-1)return null;n=i.slice(0,s).trim(),o=!0}if(n.endsWith("?.")){r=!0;let p=i.slice(n.length);n=n.slice(0,-2).trim(),i=n+p}if(!Ei(n))return null;let a=e.slice(t+1,-1).trim(),l=Ai(a)!==-1||a.startsWith("function")||a.startsWith("async function"),f=Ei(a),u=!l&&a.endsWith(")")&&ki(a)!==null,d=n.indexOf(".");if(d!==-1){if(n.indexOf(".",d+1)!==-1)return null}else if(!o&&!r&&!l&&!f&&!u)return null;let h=`ReturnType<typeof ${i}>`;return r?`ReturnType<NonNullable<typeof ${i}>> | (null extends typeof ${n} ? undefined : undefined extends typeof ${n} ? undefined : never)`:h}function fc(e){let t=e.split(`
|
|
72
|
+
`).map((f)=>Ac(f)).join(`
|
|
73
|
+
`),i=t.indexOf("async");if(i!==-1){let f=i>0?t.charCodeAt(i-1):32,u=i+5<t.length?t.charCodeAt(i+5):32;if(!Ht(f)&&!Ht(u))t=(t.slice(0,i)+t.slice(i+5)).trim()}let r=t.indexOf("(");if(r!==-1){let f=rt(t,r,"(",")");if(f!==-1){let u=t.slice(r,f+1),d=Si(u);t=t.slice(0,r)+d+t.slice(f+1)}}let n=t.length,o="",s=[],a=!1,l=!1;for(let f=0;f<n;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)l=!0;continue}if(a&&o.length>0){let d=(s.length>0?s[s.length-1]:0)===123;if(l&&d){let h=o.charCodeAt(o.length-1),p=h===59||h===44||h===123||u===125,m=o.length>=2&&o.charCodeAt(o.length-1)===47&&o.charCodeAt(o.length-2)===42;if(!p&&!m)o+="; ";else o+=" "}else o+=" "}a=!1,l=!1,o+=t[f]}return o.trim()}function Ht(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Si(e){let t=e.trim(),i,r=!1;if(t.startsWith("(")&&t.endsWith(")"))i=t.slice(1,-1),r=!0;else i=t;let n=i.trim();if(!n)return r?"()":"";let o=!1;{let m=0;for(let g=0;g<n.length;g++){let C=n.charCodeAt(g);if(C===40||C===60||C===91||C===123)m++;else if(C===41||C===93||C===125||C===62&&n.charCodeAt(g-1)!==61)m--;else if(m===0&&C===61){let b=g>0?n.charCodeAt(g-1):0,c=g+1<n.length?n.charCodeAt(g+1):0;if(b!==61&&b!==33&&b!==60&&b!==62&&c!==61&&c!==62){o=!0;break}}}}if(!o)return t;let s=[],a=[],l=0,f=0,u=!1,d=0;for(let m=0;m<=n.length;m++){if(m===n.length){s.push(n.slice(l));break}let g=n.charCodeAt(m);if(u){if(g===92){m++;continue}if(g===d)u=!1;continue}if(g===47&&m+1<n.length){let C=n.charCodeAt(m+1);if(C===42){m+=2;while(m+1<n.length&&!(n.charCodeAt(m)===42&&n.charCodeAt(m+1)===47))m++;m++;continue}if(C===47){while(m<n.length&&n.charCodeAt(m)!==10)m++;continue}}if(g===39||g===34||g===96){u=!0,d=g;continue}if(g===40||g===60||g===91||g===123)f++;else if(g===41||g===93||g===125||g===62&&n.charCodeAt(m-1)!==61)f--;else if(g===44&&f===0){s.push(n.slice(l,m));let C=",",b=m+1;while(b<n.length&&n.charCodeAt(b)<=32)C+=n[b],b++;a.push(C),l=b}}let h=[];for(let m of s){let g=m.trim();if(!g){h.push(m);continue}if(g.startsWith("//"))continue;let C=Ac(g),b=m.slice(0,m.length-m.trimStart().length);h.push(b+Ap(C))}let p=h[0]||"";for(let m=1;m<h.length;m++)p+=(a[m-1]||", ")+h[m];return En(r?`(${p})`:p)}function Ac(e){let t=!1,i=0;for(let r=0;r<e.length-1;r++){let n=e.charCodeAt(r);if(t){if(n===92){r++;continue}if(n===i)t=!1;continue}if(n===39||n===34||n===96){t=!0,i=n;continue}if(n===47&&e.charCodeAt(r+1)===47)return e.slice(0,r).trimEnd()}return e}function Ap(e){if(e.startsWith("..."))return e;let t=-1,i=-1,r=0,n=!1,o=0;for(let a=0;a<e.length;a++){let l=e.charCodeAt(a);if(n){if(l===92){a++;continue}if(l===o)n=!1;continue}if(l===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(l===39||l===34||l===96){n=!0,o=l;continue}if(l===40||l===60||l===91||l===123)r++;else if(l===41||l===93||l===125||l===62&&e.charCodeAt(a-1)!==61)r--;else if(r===0){if(l===58&&t===-1)t=a;else if(l===61&&i===-1&&(a===0||e.charCodeAt(a-1)!==61)&&(a+1>=e.length||e.charCodeAt(a+1)!==61&&e.charCodeAt(a+1)!==62))i=a}}let s=i!==-1;if(t!==-1&&(i===-1||t<i)){let a=e.slice(0,t).trim(),l=i!==-1?e.slice(t+1,i).trim():e.slice(t+1).trim(),f=s&&!a.endsWith("?")?"?":"";return`${a}${f}: ${l}`}else if(i!==-1){let a=e.slice(0,i).trim(),l=Sr(a,e.slice(i+1));if(l)return An(l,uc);let f=!a.endsWith("?")?"?":"";return`${a}${f}: ${uc(e.slice(i+1))}`}return e}function uc(e){let t=e.trim();if(t==="true"||t==="false")return"boolean";if(zt(t))return"number";if(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))return"string";if(t.startsWith("["))return"unknown[]";if(t.startsWith("{"))return"Record<string, unknown>";return"unknown"}function kp(e){let t=0,i=e.length;while(t<i){while(t<i&&(e.charCodeAt(t)===32||e.charCodeAt(t)===9||e.charCodeAt(t)===10||e.charCodeAt(t)===13))t++;if(t+1<i&&e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42){t+=2;while(t+1<i&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t+=2;continue}break}return t}function Ms(e){let t=[],i=0,r=e.length;while(i<r){while(i<r&&e.charCodeAt(i)<=32)i++;if(i+1>=r||e.charCodeAt(i)!==47||e.charCodeAt(i+1)!==42)break;let n=i;i+=2;while(i+1<r&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))i++;i=Math.min(i+2,r),t.push(e.slice(n,i).trim())}return{comments:t.join(`
|
|
74
|
+
`),key:e.slice(i).trim()}}function Tp(e){let t=[],i="",r="",n=0,o=!1,s="",a=!0,l=!1,f=0,u=!1,d=!1,h=0,p=!1,m=!1;for(let g=0;g<e.length;g++){let C=e.charCodeAt(g),b=g>0?e.charCodeAt(g-1):0,c=g<e.length-1?e.charCodeAt(g+1):0;if(!o&&!l&&C===47&&c===47){i=i.replace(/[ \t]+$/,""),g+=2;while(g<e.length&&e.charCodeAt(g)!==10)g++;g--;continue}if(!o&&!l&&C===47&&c===42){l=!0,f=1,i+="/*",g++;continue}else if(l&&C===42&&c===47){if(f--,i+="*/",g++,f===0)l=!1;continue}else if(l&&C===47&&c===42){f++,i+="/*",g++;continue}let A=e[g];if(!o&&!l&&(C===34||C===39||C===96))o=!0,s=A,i+=A;else if(o&&A===s&&b!==92)o=!1,i+=A;else if(!o&&!l)if(C===46&&c===46&&e.charCodeAt(g+2)===46&&n===0&&a)r=`${i.trim()}...`,i="",a=!1,p=!1,g+=2;else if(C===40&&n===0&&a&&h===0){r=i.trim();let M=kp(r),S=M>0?r.slice(0,M):"",T=r.slice(M),N="";if(T.startsWith("async ")||T.startsWith("async\t")||T.startsWith(`async
|
|
75
|
+
`))T=T.slice(6).trimStart(),N="async ";if(T.startsWith("*"))T=T.slice(1).trimStart(),N+="*";r=S+T,i=N+A,a=!1,p=!0,m=!1,n=1}else if(C===123||C===91||C===40){if(n++,i+=A,m&&C===123)m=!1}else if(C===125||C===93||C===41){if(n--,i+=A,C===41&&n===0&&!a&&!p)u=!0;if(p){if(C===41&&n===0&&!m)m=!0;else if(C===125&&n===0)p=!1,m=!1}}else if(C===58&&n===0&&a&&h===0)r=i.trim(),i="",a=!1;else if(C===58&&n===0&&u)d=!0,i+=A;else if(C===60&&d)h++,i+=A;else if(C===60&&a&&n===0)h++,i+=A;else if(C===62&&h>0&&b!==61)h--,i+=A;else if(C===61&&c===62&&d&&h===0)d=!1,u=!1,i+=A;else if(C===44&&n===0&&h===0&&!m){if(r&&i.trim()){let M=i.trim();t.push([r,M])}else if(a&&i.trim())dc(t,i.trim());i="",r="",a=!0,u=!1,d=!1,h=0}else i+=A;else i+=A}if(r&&i.trim()){let g=i.trim();t.push([r,g])}else if(a&&i.trim())dc(t,i.trim());return t}function dc(e,t){let{comments:i,key:r}=Ms(t);if(Gi(r))e.push([i?`${i}
|
|
76
|
+
${r}`:r,r]);else if(r.startsWith("...")&&r.length>3)e.push(["...",r.slice(3).trim()])}function hc(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let i=t.slice(4).trim();if(i)return{kind:"get",name:i}}if(t.startsWith("set ")&&t.length>4){let i=t.slice(4).trim();if(i)return{kind:"set",name:i}}return null}function Op(e,t,i){let r=i.trim();if(r.charCodeAt(0)!==40)return null;let n=rt(r,0,"(",")");if(n===-1)return null;let o=r.slice(1,n).trim(),s=r.slice(n+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 Rp(e,t){let i=t.trim(),r=rt(i,0,"(",")");if(!i.startsWith("(")||r===-1)return"unknown";if(e==="get"){let a=i.slice(r+1).trim();return a.startsWith("=>")?a.slice(2).trim():"unknown"}let n=i.slice(1,r).trim(),o=n.startsWith("{")?rt(n,0,"{","}"):n.startsWith("[")?rt(n,0,"[","]"):0,s=n.indexOf(":",Math.max(0,o));return s===-1?"unknown":n.slice(s+1).trim()}function Pp(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 i=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n===40)i++;else if(n===41){if(i--,i===0){let o=t.slice(r+1).trimStart();if(o.startsWith("{"))return!0;if(o.startsWith(":")){let s=Ls(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function Mp(e){let t=e.trimEnd();if(!t.endsWith(">"))return null;let i=0,r=-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;i++}else if(s===60){if(i--,i===0){r=o;break}}}if(r===-1)return null;let n=t.slice(0,r).trimEnd();if(!n)return null;return{name:n,typeParams:t.slice(r)}}function pc(e,t){let i=t.trimStart(),r=!1,n=!1;if(i.startsWith("async ")||i.startsWith("async\t"))r=!0,i=i.slice(5).trimStart();if(i.startsWith("*"))n=!0,i=i.slice(1).trimStart();let o="";if(i.charCodeAt(0)===60){let h=0,p=-1;for(let m=0;m<i.length;m++)if(i.charCodeAt(m)===60)h++;else if(i.charCodeAt(m)===62&&!(m>0&&i.charCodeAt(m-1)===61)){if(h--,h===0){p=m;break}}if(p!==-1)o=i.slice(0,p+1),i=i.slice(p+1).trimStart()}let s=i.indexOf("("),a=rt(i,s,"(",")");if(s===-1||a===-1)return"() => unknown";let l=i.slice(s,a+1),f="unknown",u=i.slice(a+1).trimStart();if(u.charCodeAt(0)===58){let h=u.slice(1),p=Ls(h,0);if(p)f=h.slice(0,p.index).trim();else f=h.trim()}if(f==="unknown"&&!n&&u.charCodeAt(0)===123){let h=rt(u,0,"{","}");if(h!==-1){let p=Qt(u.slice(1,h),r,l);if(p!=="unknown"&&p!=="Promise<unknown>")f=r&&p.startsWith("Promise<")?p.slice(8,-1):p;else if(r)f="Promise<unknown>"}}if(f==="unknown"){if(r&&n)f="AsyncGenerator<unknown, void, unknown>";else if(n)f="Generator<unknown, void, unknown>";else if(r)f="Promise<void>"}else if(r&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let d=Si(l);return`${o}${d} => ${f}`}function Ls(e,t){let i=0,r=0,n=0,o=0,s=!1,a=0;for(let l=t;l<e.length;l++){let f=e.charCodeAt(l);if(s){if(f===92)l++;else if(f===a)s=!1;continue}if(f===34||f===39||f===96){s=!0,a=f;continue}if(f===40)i++;else if(f===41&&i>0)i--;else if(f===91)r++;else if(f===93&&r>0)r--;else if(f===60)n++;else if(f===62&&n>0&&e.charCodeAt(l-1)!==61)n--;else if(f===125&&o>0)o--;else if(f===123){let u=i>0||r>0||n>0||o>0,d=e.slice(t,l).trimEnd(),h=d.charCodeAt(d.length-1),p=d.length===0||h===38||h===124||h===40||h===44||h===58||h===61||h===91;if(u||p)o++;else return{index:l,kind:"body"}}else if(f===61&&l+1<e.length&&e.charCodeAt(l+1)===62&&i===0&&r===0&&n===0&&o===0)return{index:l,kind:"arrow"}}return null}function rt(e,t,i,r){let n=0;for(let o=t;o<e.length;o++)if(e[o]===i)n++;else if(e[o]===r){if(r===">"&&o>0&&e[o-1]==="=")continue;if(n--,n===0)return o}return-1}function Ai(e){let t=0,i=0,r=!1,n="";for(let o=0;o<e.length-1;o++){let s=e[o],a=e[o+1],l=o>0?e[o-1]:"";if(!r&&(s==='"'||s==="'"||s==="`"))r=!0,n=s;else if(r&&s===n&&l!=="\\")r=!1;if(!r){if(s==="<"){let f=rt(e,o,"<",">");if(f!==-1){o=f;continue}}if(s==="(")t++;else if(s===")")t--;else if(s==="[")i++;else if(s==="]")i--;if(s==="="&&a===">"&&t===0&&i===0)return o}}return-1}function kc(e,t=!1,i=0,r=!0){let n=e.trim();if(n.length>200&&ks(n,"=>")>2&&ks(n,"<")>5&&!n.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(n.startsWith("async ")&&n.includes("=>")){let s=n.slice(5).trim(),a=Ai(s);if(a===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let l=s.substring(0,a).trim(),f=s.substring(a+2).trim(),u=Ds(l),{params:d,returnType:h}=u;if(d=Si(d),d==="()"||d==="")d="()";else if(!d.startsWith("("))d=`(${d})`;let p=h;if(p);else if(f.startsWith("{"))p=Qt(f.slice(1,f.endsWith("}")?-1:void 0),!0,u.params);else p=Dt(f,Os(u.params));let m=`${d} => ${h||p.startsWith("Promise<")?p:`Promise<${p}>`}`;return t?`(${m})`:m}if(n.includes("=>")){let s="",a=n;if(n.startsWith("<")){let C=rt(n,0,"<",">");if(C!==-1)s=n.substring(0,C+1),a=n.substring(C+1).trim()}let l=Ai(a);if(l===-1)return t?"(() => unknown)":"() => unknown";let f=a.substring(0,l).trim(),u=a.substring(l+2).trim(),d=Ds(f),{params:h,returnType:p}=d;if(h=Si(h),h==="()"||h==="")h="()";else if(!h.startsWith("("))h=`(${h})`;let m="unknown";if(p)m=p;else if(u.startsWith("{"))m=Qt(u.slice(1,u.endsWith("}")?-1:void 0),!1,d.params);else if(On(u)||Fn(u)&&On(u.slice(1,-1).trim()))m="JSX.Element";else if(u.includes("=>")){let C=u.trimStart(),b=C.indexOf("("),c=b!==-1?rt(C,b,"(",")"):-1,A=c!==-1?C.indexOf("=>",c):-1;if(b===0&&c!==-1&&A!==-1){let M=C.substring(b+1,c).trim(),S=Si(M);if(s.includes("T")&&S.includes("T"))m=`(${S}) => T`;else m=`(${S}) => any`}else m="any"}else m=Dt(u,Os(d.params));let g=`${s}${h} => ${m}`;return t?`(${g})`:g}if(n.startsWith("function")){let s=8,a=n.length;while(s<a&&n.charCodeAt(s)<=32)s++;let l=!1;if(s<a&&n.charCodeAt(s)===42){l=!0,s++;while(s<a&&n.charCodeAt(s)<=32)s++}let f="";if(s<a&&n.charCodeAt(s)===60){let h=s,p=1;s++;while(s<a&&p>0){let m=n.charCodeAt(s);if(m===60)p++;else if(m===62&&n.charCodeAt(s-1)!==61)p--;s++}f=n.substring(h,s);while(s<a&&n.charCodeAt(s)<=32)s++}let u=n.indexOf("(",s);if(u!==-1){let h=1,p=u+1;while(p<a&&h>0){let A=n.charCodeAt(p);if(A===40)h++;else if(A===41)h--;p++}let m=n.substring(u+1,p-1).trim(),g=m?Si(`(${m})`):"()";if(l){let A=n.substring(p).trim(),M=A.indexOf("Generator<");if(M!==-1){let T=M+10,N=A.indexOf(">",T);if(N!==-1){let B=A.substring(T,N),ee=`${f}${g} => Generator<${B}>`;return t?`(${ee})`:ee}}let S=`${f}${g} => Generator<any, any, any>`;return t?`(${S})`:S}let C="unknown",b=n.substring(p).trimStart();if(b.charCodeAt(0)===58){let A=b.slice(1),M=Ls(A,0),S=(M?A.slice(0,M.index):A).trim();if(S)C=S}let c=`${f}${g} => ${C}`;return t?`(${c})`:c}let d="(...args: any[]) => unknown";return t?`(${d})`:d}if(n.includes("=>")&&n.includes("(")&&n.includes(")")){if(n.length>100||ks(n,"=>")>2){let s="";if(n.charCodeAt(0)===60){let d=rt(n,0,"<",">");if(d!==-1)s=n.substring(0,d+1)}let a=n.indexOf("("),l=a!==-1?rt(n,a,"(",")"):-1,f=a!==-1&&l!==-1?n.substring(a,l+1):"(...args: any[])";f=Si(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${n})`:n}let o="() => unknown";return t?`(${o})`:o}function Ds(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let i=rt(t,0,"(",")");if(i===-1)return{params:t,returnType:""};let r=t.slice(i+1).trim();return{params:t.slice(0,i+1),returnType:r.startsWith(":")?r.slice(1).trim():""}}function Tc(e){let t=e.trim();if(t==="any"||t==="object"||t==="unknown")return!0;if(t.startsWith("Record<")&&t.endsWith(">"))return!0;if(t.startsWith("Array<")&&t.endsWith(">"))return!0;if(/^\{\s*\[[^\]]*\]:\s*(any|string|number|unknown)\s*\}$/.test(t))return!0;return!1}function Wn(e){let t=-1,i=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o===34||o===39||o===96){n=qt(e,n,o)-1;continue}if(o===47&&e.charCodeAt(n+1)===47){while(n<e.length&&e.charCodeAt(n)!==10)n++;continue}if(o===47&&e.charCodeAt(n+1)===42){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+1;continue}if(o===47){let s=n-1;while(s>=0&&e.charCodeAt(s)<=32)s--;if(s<0||"([{:;,=!?&|+*-~>".includes(e[s])){let a=!1;for(n++;n<e.length;n++){let l=e.charCodeAt(n);if(l===92)n++;else if(l===91)a=!0;else if(l===93)a=!1;else if(l===47&&!a)break}continue}}if(o===40||o===91||o===123)i++;else if(o===41||o===93||o===125)i--;else if(i===0&&e.startsWith("satisfies",n)&&Ar(e,n,9)&&e[n-1]!==".")t=n}if(t===-1)return null;let r=e.slice(t+9).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var In=20,Nn=!1,yt=null,cc;var Tr=ye(()=>{Bi();pt();Cn();bn();Sn();Ss();As();kn();cc={string:{at:"string | undefined",charAt:"string",charCodeAt:"number",codePointAt:"number | undefined",concat:"string",endsWith:"boolean",includes:"boolean",indexOf:"number",lastIndexOf:"number",localeCompare:"number",normalize:"string",padEnd:"string",padStart:"string",repeat:"string",replace:"string",replaceAll:"string",search:"number",slice:"string",split:"string[]",startsWith:"boolean",substring:"string",toLocaleLowerCase:"string",toLocaleUpperCase:"string",toLowerCase:"string",toString:"string",toUpperCase:"string",trim:"string",trimEnd:"string",trimStart:"string",valueOf:"string"},number:{toExponential:"string",toFixed:"string",toLocaleString:"string",toPrecision:"string",toString:"string",valueOf:"number"},bigint:{toLocaleString:"string",toString:"string",valueOf:"bigint"},boolean:{toString:"string",valueOf:"boolean"}}});function Oc(e,t,i,r){let n=new Map,o=new Map;for(let h of[...t,...i.values(),...[...r.values()].flat()])if(n.set(h.name,h),h.kind==="function"&&!o.has(h.name))o.set(h.name,h);for(let[h,p]of r)if(p.length)o.set(h,p[0]);if(!o.size)return;let s=new Set;for(let[h,p]of r)if(p.length>1)s.add(h);let a=new Map;for(let h of t)if(h.kind==="function"){let p=(a.get(h.name)??0)+1;if(a.set(h.name,p),p>1)s.add(h.name)}let l=Mt(e),f=(h)=>l[h]?e.slice(l[h].start,l[h].end):"",u=new Map,d=0;for(let h=0;h<l.length;h++){let p=l[h];if(p.kind==="punctuation"){let T=e.charCodeAt(p.start);if(T===40||T===91||T===123)d++;else if(T===41||T===93||T===125)d--;continue}if(d||l[h+2]?.kind!=="word"||f(h+1)!=="."||f(h+3)!=="=")continue;let m=f(h);if(!o.has(m))continue;let g=f(h+2),C=h+4,b=C,c=0;for(;b<l.length;b++){let T=f(b);if(!c&&T===";")break;if(!c&&b>C&&/[\r\n]/.test(e.slice(l[b-1].end,l[b].start))&&(["export","const","let","var","function","class"].includes(T)||o.has(T)&&f(b+1)==="."))break;if(["(","[","{"].includes(T))c++;else if([")","]","}"].includes(T))c--}if(b===C)continue;let A=Rc(e.slice(l[C].start,l[b-1].end),n,s),M=u.get(m);if(!M)u.set(m,M=new Map);let S=M.get(g);if(!S)M.set(g,S=[]);if(!S.includes(A))S.push(A);h=b-1}for(let[h,p]of u){let m=o.get(h),g=[...p].map(([b,c])=>` let ${b}: ${c.map((A)=>A.includes("=>")&&c.length>1?`(${A})`:A).join(" | ")};`).join(`
|
|
77
77
|
`),C=m.isExported&&!m.isDefault?"export ":"";if(m.isDefault)m.text=m.text.replace("export default function ","declare function ");if(m.text+=`
|
|
78
78
|
${C}declare namespace ${h} {
|
|
79
79
|
${g}
|
|
80
80
|
}`,m.isDefault)m.text+=`
|
|
81
|
-
export default ${h};`}}function
|
|
81
|
+
export default ${h};`}}function Rc(e,t,i,r=0){let n=e.trim(),o=t.get(n);if(o?.kind==="variable"&&r<64){if(o.typeAnnotation)return o.typeAnnotation==="unique symbol"?`typeof ${n}`:o.typeAnnotation;if(typeof o.value==="string")return Rc(o.value,t,i,r+1)}let s=Te(n,!1);if(s!=="unknown")return s;let a=ue(n);if(a[0]?.kind==="word"&&a[1]&&n.slice(a[1].start,a[1].end)==="("&&n.endsWith(")")){let l=0,f=-1;for(let h=1;h<a.length;h++){let p=n.slice(a[h].start,a[h].end);if(p==="(")l++;else if(p===")"&&--l===0){f=h;break}}if(f!==a.length-1)return s;let u=n.slice(a[0].start,a[0].end),d=t.get(u);if(d?.kind==="function"&&!d.generics&&!i.has(u))return`ReturnType<typeof ${u}>`}if(/^[$A-Z_a-z][$\w]*(?:\.[$A-Z_a-z][$\w]*)*$/.test(n))return`typeof ${n}`;return s}var Pc=ye(()=>{pt();Tr()});function Dp(e){if(e.includes(`
|
|
82
82
|
`))return`/**
|
|
83
83
|
* ${e}
|
|
84
84
|
*/
|
|
85
85
|
`;return`/** ${e} */
|
|
86
|
-
`}function
|
|
86
|
+
`}function Ip(e){let t=e.indexOf("{");if(t===-1)return-1;let i=e.indexOf("<");if(i===-1||i>t)return t;let r=0,n=!1,o="";for(let s=0;s<e.length;s++){let a=e[s],l=s>0?e[s-1]:"";if(!n&&(a==='"'||a==="'"||a==="`"))n=!0,o=a;else if(n&&a===o&&l!=="\\")n=!1;if(!n){if(a==="<")r++;else if(a===">")r--;else if(a==="{"&&r===0)return s}}return-1}function Mc(e,t=!0){return Kt(e.leadingComments,t)+e.text}function Vi(e,t=!0){if(e.inferenceError)throw Object.assign(Error(`Cannot infer alias '${e.name}': unsupported source value flow`),{code:e.inferenceError});let i=Kt(e.leadingComments,t);if(!e.typeAnnotation&&e.inferredType)return i+e.text;if(e.typeAnnotation&&!e.value)return i+e.text;let r="";if(e.isExported)r+="export ";r+="declare ";let n=e.modifiers?.[0]||"const";r+=`${n} `,r+=e.name;let{typeAnnotation:o,value:s}=e,a=!o&&s?Wn(s):null;if(a)o=a;else if(!o&&s&&s.trim().endsWith("as const"))o=Te(s,!0,!1,0,e.computedKeyConstants);else if(!o&&s&&n==="const"){let f=s.trim(),u=f.startsWith("{")||f.startsWith("[");if(u)Is();o=Te(s,!u,!1,0,e.computedKeyConstants)}else if(!o&&s)o=Te(s,n==="const",!1,0,e.computedKeyConstants);if(!o)o="unknown";let l="";if(t&&s&&!e.typeAnnotation&&!s.trim().endsWith("as const")){let f=s.trim();if(n!=="const"){if((o==="string"||o==="number"||o==="boolean")&&f.length>0)l=`@defaultValue ${f}`}else if(f.startsWith("{")||f.startsWith("[")){let u=Ns();if(u)if(u.includes(`
|
|
87
87
|
`))l=`@defaultValue
|
|
88
88
|
* \`\`\`ts
|
|
89
89
|
${u.split(`
|
|
90
90
|
`).map((d)=>` * ${d}`).join(`
|
|
91
91
|
`)}
|
|
92
|
-
* \`\`\``;else l=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&
|
|
92
|
+
* \`\`\``;else l=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&Tc(e.typeAnnotation)){Is();let f=s.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Te(u,!1,!1,0,e.computedKeyConstants);let d=Ns();if(d)if(d.includes(`
|
|
93
93
|
`))l=`@defaultValue
|
|
94
94
|
* \`\`\`ts
|
|
95
95
|
${d.split(`
|
|
@@ -104,57 +104,57 @@ ${d.split(`
|
|
|
104
104
|
* ${f.replace(/^\/\/\s*/,"")}
|
|
105
105
|
* ${l}
|
|
106
106
|
*/
|
|
107
|
-
${r}`}if(l)return`${Mp(l)}${r}`;return i+r}function Mc(e,t=!0){let i=Kt(e.leadingComments,t),r=e.text;if(r.startsWith("export declare interface")||r.startsWith("declare interface"))return i+r;let n="";if(e.isExported)n+="export ";if(n+="declare interface ",n+=e.name,e.generics)n+=e.generics;if(e.extends)n+=` extends ${e.extends}`;let o=Dp(e.text);if(o!==-1)n+=` ${e.text.slice(o)}`;else n+=" {}";return i+n}function Dc(e,t=!0){let i=Kt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return i+e.text;let r="";if(e.isExported)r+="export ";if(!e.isExported&&!e.text.includes(" from "))r+="declare ";let n=e.text.indexOf("type ");if(n!==-1){let s=e.text.slice(n),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);r+=s}else{if(r+=`type ${e.name}`,e.generics)r+=e.generics;r+=" = any"}let o=r.trimEnd();if(!o.endsWith(";")&&!o.endsWith("}"))r+=";";return i+r}function Ic(e,t=!0){return Kt(e.leadingComments,t)+e.text}function Nc(e,t=!0){let i=Kt(e.leadingComments,t),r="";if(e.isExported)r+="export ";if(r+="declare ",e.modifiers?.includes("const"))r+="const ";r+="enum ",r+=e.name;let n=e.text.indexOf("{");if(n!==-1)r+=` ${e.text.slice(n)}`;else r+=" {}";return i+r}function Fc(e,t=!0){let i=Kt(e.leadingComments,t);if(e.text.startsWith("declare global"))return i+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 i+o}let r="";if(e.isExported)r+="export ";if(!e.modifiers?.includes("declare"))r+="declare ";r+="namespace ",r+=e.name;let n=e.text.indexOf("{");if(n!==-1)r+=` ${e.text.slice(n)}`;else r+=" {}";return i+r}var Ln=ye(()=>{kn();Tr()});function Wc(e){let t=Ti.get(e);if(t)return Ti.delete(e),Ti.set(e,t),t;return null}function Lc(e,t){if(Ti.set(e,t),Ti.size>200){let i=0;for(let r of Ti.keys()){if(i++>=20)break;Ti.delete(r)}}}var Ti;var Bc=ye(()=>{Ti=new Map});function Bs(e){return Wt(e).find((t)=>t.category==="static-import")}function Ip(e){return ue(e).map((t)=>e.slice(t.start,t.end)).join(" ")}function Np(e){let t=Bs(e);return t?e.lastIndexOf(" from ",t.start):-1}function Bn(e){let t=Bs(e);return t?hi(t.specifier,"'"):void 0}function Oi(e){let t=Wc(e);if(t)return t;let i=Ri(e),r=i?[i.defaultName,i.namespaceName,...i.namedItems.map((n)=>n.name)].filter((n)=>n!==null):[];return Lc(e,r),r}function Fp(e){let t=[],i=0;for(let n of ue(e)){if(n.kind!=="punctuation"||e.slice(n.start,n.end)!==",")continue;let o=e.slice(i,n.start).trim();if(o)t.push(o);i=n.end}let r=e.slice(i).trim();if(r)t.push(r);return t}function Ri(e){e=Ip(e);let t=yn(e);if(t)return{defaultName:t.name,namedItems:[],source:t.source,isTypeOnly:t.isTypeOnly,isNamespace:!1,namespaceName:null,isImportEquals:!0};let i=Np(e);if(i===-1)return null;let r=Bs(e);if(!r)return null;let n=r.specifier,o=e.slice(0,i).trim(),s=r.isTypeOnly;if(o.startsWith("import "))o=o.slice(7).trim();if(s&&o.startsWith("type "))o=o.slice(5).trim();let a=null,l=[],f=!1,u=null,d=o.includes("{")?-1:o.indexOf("* as ");if(d!==-1)return f=!0,u=o.slice(d+5).trim(),a=o.slice(0,d).trim().replace(/,$/,"").trim()||null,{defaultName:a,namedItems:[],source:n,isTypeOnly:s,isNamespace:f,namespaceName:u};let h=o.indexOf("{"),p=o.lastIndexOf("}");if(h!==-1&&p!==-1){let m=o.slice(0,h).trim();if(m.endsWith(","))a=m.slice(0,-1).trim()||null;let g=o.slice(h+1,p),C=Fp(g);for(let b of C){let c=Wp(b),A=c?b.slice(5).trim():b,M=A.lastIndexOf(" as "),S,O;if(M!==-1)O=A.slice(0,M).trim(),S=A.slice(M+4).trim();else S=A,O=A;l.push({name:S,originalName:O,isTypeOnly:s||c,isDefault:!1})}}else a=o.trim()||null;return{defaultName:a,namedItems:l,source:n,isTypeOnly:s,isNamespace:f,namespaceName:u}}function Wp(e){let t=ue(e),i=t[0];if(!i||i.kind!=="word"||e.slice(i.start,i.end)!=="type"||t.length<2)return!1;return!(t.length===3&&e.slice(t[1].start,t[1].end)==="as")}var Pi=ye(()=>{pt();Bc()});function _s(e,t){let i=(r)=>ue(r).map((n)=>r.slice(n.start,n.end)).join("");return i(e)===i(t)}function jc(e){if(["number","string","boolean","bigint","symbol","undefined","null"].includes(e))return e;let t=Te(e,!1);return["number","string","boolean","bigint","undefined","null"].includes(t)?t:void 0}function _c(e,t){if(_s(e,t))return e;let i=jc(t);if(!i)return;let r=ue(e),n=0,o=0,s=[];for(let l of r){let f=e.slice(l.start,l.end);if(f==="("||f==="["||f==="{"||f==="<")n++;else if(f===")"||f==="]"||f==="}"||f===">")n--;else if(f==="|"&&n===0)s.push(e.slice(o,l.start).trim()),o=l.end}s.push(e.slice(o).trim());let a=s.find((l)=>_s(l,t));if(a)return a;if(s.includes(i))return i==="boolean"&&(t==="true"||t==="false")?t:i;return}function Gc(e,t,i,r=new Set){let n=new Map,o=[],s=new Set;for(let k of[...t,...i.values()]){if(s.has(k))continue;if(s.add(k),o.push(k),k.kind==="import")for(let z of Oi(k.text))n.set(z,{declared:`typeof ${z}`,flow:`typeof ${z}`,unresolved:!1});else if(["function","class","enum"].includes(k.kind))n.set(k.name,{declared:`typeof ${k.name}`,flow:`typeof ${k.name}`,unresolved:!1});else if(k.kind==="variable")n.set(k.name,{declared:k.typeAnnotation,unresolved:!1})}o.sort((k,z)=>(k.start??0)-(z.start??0));let a=new Set(o.filter((k)=>k.kind==="function"&&!k.generics).map((k)=>k.name));for(let k of r)a.add(k);let l=new Map,f=(k)=>{if(k=k.trimStart(),l.has(k))return l.get(k);if(l.set(k,void 0),!ht(k.charCodeAt(0)))return;let z=1;while(je(k.charCodeAt(z)))z++;if(!a.has(k.slice(0,z)))return;let _=ue(k);if(_[0]?.kind!=="word"||!_[1]||k.slice(_[1].start,_[1].end)!=="(")return;let H=1;for(let q=2;q<_.length;q++){let ce=k.slice(_[q].start,_[q].end);if(ce==="(")H++;else if(ce===")"&&--H===0){let ge=q===_.length-1?k.slice(_[0].start,_[0].end):void 0;return l.set(k,ge),ge}}return},u=new Set(o.filter((k)=>k.kind==="variable"&&!k.typeAnnotation&&typeof k.value==="string").map((k)=>f(k.value)).filter((k)=>k!==void 0)).size?Mt(e):void 0,d=new Map;if(u){let k=0;for(let z=0;z<u.length;z++){let _=e.slice(u[z].start,u[z].end);if(k===0&&_==="function"){let H=u[z+1],q=H&&e.slice(H.start,H.end)==="*"?u[z+2]:H;if(q?.kind==="word"){let ce=e.slice(q.start,q.end);d.set(ce,(d.get(ce)??0)+1)}}if(["{","(","["].includes(_))k++;else if(["}",")","]"].includes(_))k--}}let h=new Map;for(let k of o)if(k.kind==="function"&&!k.generics&&d.get(k.name)===1)h.set(k.name,k);for(let k of r){let z=o.find((_)=>_.kind==="import"&&Oi(_.text).includes(k));if(z)h.set(k,z)}let p="__dtsx_call_result";while(e.includes(p))p+="_";let m=(k)=>`(typeof ${k}) extends (...args: never[]) => infer ${p} ? ${p} : never`,g=new Map,C=!1;for(let k of o){if(k.kind!=="variable"||k.typeAnnotation||typeof k.value!=="string")continue;let z=ki(k.value);if(z&&Te(k.value,!1)===z)k.inferredType=z,k.text=`${k.isExported?"export ":""}declare ${k.modifiers?.[0]??"const"} ${k.name}: ${z};`;let _=f(k.value);if(_&&h.has(_))g.set(k,m(_)),n.get(k.name).active=!0,n.get(_).active=!0,C=!0;if(k.modifiers?.[0]!=="const")continue;let H=$n(k.value);if(!H||H===k.name||!n.has(H))continue;n.get(H).active=!0,n.get(k.name).active=!0,C=!0}if(!C)return;let b=u??Mt(e),c=(k)=>b[k]?e.slice(b[k].start,b[k].end):"",A=new Map,M=new Map,S=new Set,O=new Set,N=new Set,B=new Map,ee=[];for(let k=0;k<b.length;k++){let z=c(k),_=ee.at(-1);if(_!==void 0)M.set(k,_);if(z==="{"&&["=","(","[",",",":","?","return","yield"].includes(c(k-1)))S.add(k);if(["(","[","{"].includes(z))ee.push(k);else if([")","]","}"].includes(z)){let H=ee.at(-1);if(H!==void 0&&["()","[]","{}"].includes(c(H)+z))ee.pop(),A.set(H,k)}}let K=new Map;for(let k=0;k<b.length;){if(b[k].kind!=="punctuation"){k++;continue}let z=[">>>=","**=","&&=","||=","??=","<<=",">>=","===","!==",">>>","**","&&","||","??","<<",">>","=>","==","!=","<=",">=","++","--","+=","-=","*=","/=","%=","&=","|=","^=","="].find((H)=>e.startsWith(H,b[k].start))??c(k);K.set(k,z);let _=b[k].start+z.length;do k++;while(k<b.length&&b[k].start<_)}for(let k=0;k<b.length;k++){let z=re(k);if(z!==void 0)O.add(z)}for(let k of O)J(k);let te=0;function he(k){let z=$n(k);if(z){let ce=n.get(z);return{type:ce?.flow,unresolved:ce?.unresolved??!1}}let _=f(k),H=_?h.get(_):void 0;if(H)return{type:H.returnType&&jc(H.returnType)?H.returnType:m(_),unresolved:!1};let q=Te(k,!0);return{type:q==="unknown"?void 0:q,unresolved:!1}}function Ae(k){return K.get(k)??""}function Se(k){if(b[k]?.kind!=="word"||N.has(k)||c(k-1)==="."||c(k-1)==="#"&&c(k-2)===".")return;let z=n.get(c(k));if(!z?.active)return;let _=Ae(k+1);if(["=","+=","-=","*=","/=","%=","**=","<<=",">>=",">>>=","&=","|=","^=","&&=","||=","??="].includes(_))return{binding:z,operator:_};if(["++","--"].includes(_)&&!/[\r\n]/.test(e.slice(b[k].end,b[k+1].start)))return{binding:z,operator:_};if(k>=2&&["++","--"].includes(Ae(k-2))){let H=b[k-3],q=H&&(H.kind==="word"||H.kind==="quoted"||[")","]"].includes(c(k-3)));if(!H||!q||/[\r\n;]/.test(e.slice(H.end,b[k-2].start)))return{binding:z,operator:Ae(k-2)}}return}function fe(k){let z=Se(k);return z?.operator==="="?z.binding:void 0}function re(k){if(b[k]?.kind!=="word"||c(k)!=="class"||c(k-1)==="."||["(",":","="].includes(c(k+1)))return;let z=k+1,_=0;while(z<b.length){let H=c(z);if(H==="{"&&_===0)return z;if(H==="class"){let q=re(z);if(q!==void 0){z=(A.get(q)??q)+1;continue}}if(H==="function"){let q=me(z,b.length);if(q){z=q.end;continue}}if(H==="<")_++;else if(H===">"&&Ae(z-1)!=="=>"&&_>0)_--;if(H===";")break;z=(A.get(z)??z)+1}return}function pe(k,z,_){let H=k,q=!1,ce=_?["public","protected","private","static","abstract","override","declare","readonly","accessor","async","get","set"]:["async","get","set"];while(ce.includes(c(H))&&!["(","<","?","!",":","=",";","}"].includes(c(H+1))){if(c(H)==="static")q=!0;H++}if(c(H)==="*")H++;if(_&&c(H)==="#")H++;if(c(H)==="["){let Oe=A.get(H);return Oe===void 0?void 0:{next:Oe+1,isStatic:q}}if(b[H]?.kind==="word"||b[H]?.kind==="quoted")return{next:H+1,isStatic:q};let ge=H+1;while(ge<z&&b[ge-1].end===b[ge].start&&!["(","<","?","!",":","=",";","}","[","{",","].includes(c(ge)))ge++;if(H<z&&Te(e.slice(b[H].start,b[ge-1].end),!1)==="number")return{next:ge,isStatic:q};return}function D(k,z,_){let H=pe(k,z,_);if(!H)return;let q=H.next;if(_&&["?","!"].includes(c(q)))q++;if(c(q)==="<"){let ce=1;q++;while(q<z&&ce>0){if(c(q)==="<")ce++;else if(c(q)===">"&&Ae(q-1)!=="=>")ce--;q=(A.get(q)??q)+1}if(ce!==0)return}return q}function qe(k,z,_){return D(k,z,_)===z}function X(k,z){let _=0,H=-1;for(let q=k;q<z;q=(A.get(q)??q)+1)if(c(q)==="<"&&(_>0||q>k&&(b[q-1].kind==="word"||[")","]"].includes(c(q-1))))){if(_===0)H=q;_++}else if(c(q)===">"&&Ae(q-1)!=="=>"&&_>0){if(_--,q===z-1&&_===0)return H<q-1}return!1}function G(k,z){if(c(k)==="static"&&c(k+1)==="{")return!0;let _=D(k,z,!0);return _!==void 0&&(_===z||["(",":","=",";","}"].includes(c(_)))}function Z(k,z,_=!1){let H=A.get(z)??b.length,q=k;while(q<H){if(c(q)===";"||_&&Ae(q)==="=")return q;if(q>k&&M.get(q)===z&&/[\r\n]/.test(e.slice(b[q-1].end,b[q].start))){let ce=c(q-1),ge=!(ce===">"&&X(k,q)&&G(q,H))&&["+","-","*","/","%","=","<",">","&","|","^","!","~","?",":",",",".","(","[","{","as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","yield","void"].includes(ce),Oe=[".","?",":",")","]","}",",","+","-","*","/","%","<",">","=","&","|","^","`","(","[","as","satisfies","instanceof","in"].includes(c(q));if(!ge&&!Oe)return q}q=(A.get(q)??q)+1}return H}function ae(k,z){for(let _=k;_<z;_++){if(c(_)==="["&&A.has(_)){_=A.get(_);continue}if(b[_].kind==="word")N.add(_)}}function J(k){let z=A.get(k)??b.length,_=k+1;while(_<z){if(c(_)===";"){_++;continue}if(c(_)==="static"&&c(_+1)==="{"){_=(A.get(_+1)??_+1)+1;continue}let H=pe(_,z,!0);if(!H){_++;continue}let q=D(_,z,!0);if(q===void 0){_++;continue}if(ae(_,q),c(q)==="("){let ge=A.get(q),Oe=ge===void 0?void 0:ve(ge,z);if(Oe!==void 0){_=(A.get(Oe)??Oe)+1;continue}}let ce=q;if(c(ce)===":")ce=Z(ce+1,k,!0);if(Ae(ce)==="="){ae(_,ce+1);let ge=ce+1,Oe=Z(ge,k);if(!H.isStatic&&Oe>ge)B.set(ge,Oe);_=Oe}else{let ge=Z(q,k);ae(_,ge),_=Math.max(_+1,ge)}}}function le(k){let z=M.get(k);if(z===void 0)return!1;let _=O.has(z);if(!_&&!S.has(z))return!1;if(qe(z+1,k,_))return!0;for(let H=z+1;H<k;H++){let q=M.get(H),ce=M.get(H)===z&&(c(H)===","||_&&c(H)===";"),ge=_&&c(H)==="}"&&q!==void 0&&M.get(q)===z,Oe=_&&M.get(H+1)===z&&/[\r\n]/.test(e.slice(b[H].end,b[H+1].start));if((ce||ge||Oe)&&qe(H+1,k,_))return!0}return!1}function ve(k,z){let _=k+1,H=c(_)===":"?_+1:void 0;while(_<z){if(c(_)==="{"&&(H===void 0||!$s(e.slice(b[H].start,b[_].start))))return _;if(H===void 0)return;_=(A.get(_)??_)+1}return}function me(k,z){let _=-1;if(c(k)==="("){let q=A.get(k);if(q!==void 0&&le(k))_=ve(q,z)??-1;else if(q!==void 0&&Ae(q+1)==="=>")_=q+3;else if(q!==void 0&&c(q+1)===":"){let ce=q+2;while(ce<z&&c(ce)!==";"){if(Ae(ce)==="=>"){_=ce+2;break}ce=(A.get(ce)??ce)+1}}}else if(b[k]?.kind==="word"&&Ae(k+1)==="=>")_=k+3;else if(c(k)==="function"){let q=k+1;while(q<z&&c(q)!=="(")q=(A.get(q)??q)+1;let ce=A.get(q);if(ce===void 0)return;_=ce+1;let ge=c(_)===":"?_+1:void 0;while(_<z){if(c(_)==="{"&&(ge===void 0||!$s(e.slice(b[ge].start,b[_].start))))break;_=(A.get(_)??_)+1}}if(_<0||_>=z)return;if(c(_)==="{")return{start:k,end:(A.get(_)??z-1)+1};let H=_;while(H<z&&![",",";",")","]","}"].includes(c(H)))H=(A.get(H)??H)+1;return{start:k,end:H}}function W(k,z,_=!0){for(let H=k;H<z;H++){let q=B.get(H);if(q!==void 0){H=Math.min(q,z)-1;continue}let ce=_?me(H,z):void 0;if(ce){let Oe=ce.end;while(c(Oe)===")")Oe++;if(c(Oe)==="("||c(Oe)==="."&&["call","apply"].includes(c(Oe+1))&&c(Oe+2)==="(")W(ce.start,ce.end,!1);H=ce.end-1;continue}let ge=Se(H);if(ge)ge.binding.flow=void 0,ge.binding.unresolved=!0}}function Qe(k){let z=!1;while(te<b.length&&b[te].start<k){let _=c(te);if(["if","else","for","while","do","switch","try","catch","finally","with"].includes(_))z=!0;if(_===";")z=!1;if(_==="("||_==="{"||_==="["){let ce=A.get(te)??te+1;while(ce<b.length&&b[ce].start>=k)ce--;if(W(te+1,ce),te=ce+1,_==="{")z=!1;continue}let H=fe(te);if(H){let ce=te+2,ge=ce,Oe=[];while(ge<b.length&&b[ge].start<k){let xt=c(ge);if(Oe.length===0&&(xt===";"||ge>ce&&/[\r\n]/.test(e.slice(b[ge-1].end,b[ge].start))&&(fe(ge)||["if","for","while","switch","try","do","return","throw"].includes(xt))))break;if(xt==="("||xt==="{"||xt==="[")Oe.push(xt==="("?")":xt==="{"?"}":"]");else if(xt===Oe.at(-1))Oe.pop();ge++}let Gt=ge>ce?e.slice(b[ce].start,b[ge-1].end):"";W(ce,ge);let ci=he(Gt);H.flow=!z&&ci.type?H.declared?_c(H.declared,ci.type):ci.type:void 0,H.unresolved=z||ci.unresolved||!H.flow,te=ge;continue}let q=Se(te);if(q)q.binding.flow=void 0,q.binding.unresolved=!0;te++}}for(let k of o){Qe(k.start??0);let z=te;while(te<b.length&&b[te].start<(k.end??0))te++;if(k.kind!=="variable")continue;if(k.initializerStart!==void 0){let Gt=z;while(Gt<te&&b[Gt].start<k.initializerStart)Gt++;W(Gt,te)}let _=n.get(k.name);if(!_.active)continue;let H=typeof k.value==="string"?k.value:"";if(!H){_.flow=_.declared;continue}let q=he(H),ce=$n(H),ge=ce?n.get(ce):void 0,Oe=g.get(k);if(Oe)k.inferredType=Oe;else if(!k.typeAnnotation&&k.modifiers?.[0]==="const"&&ce&&ce!==k.name&&ge){if(q.unresolved)k.inferenceError="DTSX_UNSUPPORTED_VALUE_FLOW";else if(q.type)k.inferredType=ge.declared&&_s(ge.declared,q.type)?`typeof ${ce}`:q.type}if(k.inferredType)k.text=`${k.isExported?"export ":""}declare ${k.modifiers?.[0]??"const"} ${k.name}: ${k.inferredType};`;if(k.typeAnnotation)_.flow=q.type?_c(k.typeAnnotation,q.type)??k.typeAnnotation:k.typeAnnotation;else if(k.inferredType)_.declared=k.inferredType,_.flow=k.inferredType;else{let Gt=k.modifiers?.[0]==="const",ci=H.trim().startsWith("{")||H.trim().startsWith("["),xt=Te(H,Gt&&!ci);_.declared=xt==="unknown"?void 0:xt,_.flow=_.declared}_.unresolved=q.unresolved}}var Vc=ye(()=>{Bi();pt();$r();Pi();Tr()});function Lp(e,t,i,r,n=""){let o=new Map,s={start:0,end:e.length,header:0,name:"",children:[],results:new Map},a=ue(e),l=[],f=[],u=[],d=new Map;for(let g=0;g<a.length;g++){let C=a[g];if(C.kind!=="punctuation")continue;let b=e.slice(C.start,C.end);if(b==="(")u.push(g);else if(b===")"){let c=u.pop();if(c!==void 0)d.set(g,c)}else if(b==="{")f.push(g);else if(b==="}"){let c=f.pop();if(c===void 0)continue;let A=a[c].start,M=c-1,S=M>=0?e.slice(a[M].start,a[M].end):"";if(S===")"){let O=d.get(M);if(O!==void 0&&O>0&&["if","for","while","switch","catch","with"].includes(e.slice(a[O-1].start,a[O-1].end)))A=a[O-1].start}else if(["else","try","finally","do"].includes(S))A=a[M].start;l.push({open:a[c].start,close:C.start,header:A})}}let h=0,p=(g,C=new Set)=>{let b=new Set(C),c=ue(e.slice(g.start,g.end)),A=0;for(let K=0;K+1<c.length;K++){let te=e.slice(g.start+c[K].start,g.start+c[K].end);if(te==="{")A++;else if(te==="}")A--;else if(!A&&["type","interface"].includes(te))b.add(e.slice(g.start+c[K+1].start,g.start+c[K+1].end))}let M="",S=g.start,O=[...g.results].map(([K,te])=>({type:K,name:te}));for(let K of g.children.sort((te,he)=>te.header-he.header)){let te=p(K,b);M+=e.slice(S,K.header)+`
|
|
107
|
+
${r}`}if(l)return`${Dp(l)}${r}`;return i+r}function Dc(e,t=!0){let i=Kt(e.leadingComments,t),r=e.text;if(r.startsWith("export declare interface")||r.startsWith("declare interface"))return i+r;let n="";if(e.isExported)n+="export ";if(n+="declare interface ",n+=e.name,e.generics)n+=e.generics;if(e.extends)n+=` extends ${e.extends}`;let o=Ip(e.text);if(o!==-1)n+=` ${e.text.slice(o)}`;else n+=" {}";return i+n}function Ic(e,t=!0){let i=Kt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return i+e.text;let r="";if(e.isExported)r+="export ";if(!e.isExported&&!e.text.includes(" from "))r+="declare ";let n=e.text.indexOf("type ");if(n!==-1){let s=e.text.slice(n),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);r+=s}else{if(r+=`type ${e.name}`,e.generics)r+=e.generics;r+=" = any"}let o=r.trimEnd();if(!o.endsWith(";")&&!o.endsWith("}"))r+=";";return i+r}function Nc(e,t=!0){return Kt(e.leadingComments,t)+e.text}function Fc(e,t=!0){let i=Kt(e.leadingComments,t),r="";if(e.isExported)r+="export ";if(r+="declare ",e.modifiers?.includes("const"))r+="const ";r+="enum ",r+=e.name;let n=e.text.indexOf("{");if(n!==-1)r+=` ${e.text.slice(n)}`;else r+=" {}";return i+r}function Wc(e,t=!0){let i=Kt(e.leadingComments,t);if(e.text.startsWith("declare global"))return i+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 i+o}let r="";if(e.isExported)r+="export ";if(!e.modifiers?.includes("declare"))r+="declare ";r+="namespace ",r+=e.name;let n=e.text.indexOf("{");if(n!==-1)r+=` ${e.text.slice(n)}`;else r+=" {}";return i+r}var Ln=ye(()=>{kn();Tr()});function Lc(e){let t=Ti.get(e);if(t)return Ti.delete(e),Ti.set(e,t),t;return null}function Bc(e,t){if(Ti.set(e,t),Ti.size>200){let i=0;for(let r of Ti.keys()){if(i++>=20)break;Ti.delete(r)}}}var Ti;var _c=ye(()=>{Ti=new Map});function Bs(e){return Wt(e).find((t)=>t.category==="static-import")}function Np(e){return ue(e).map((t)=>e.slice(t.start,t.end)).join(" ")}function Fp(e){let t=Bs(e);return t?e.lastIndexOf(" from ",t.start):-1}function Bn(e){let t=Bs(e);return t?hi(t.specifier,"'"):void 0}function Oi(e){let t=Lc(e);if(t)return t;let i=Ri(e),r=i?[i.defaultName,i.namespaceName,...i.namedItems.map((n)=>n.name)].filter((n)=>n!==null):[];return Bc(e,r),r}function Wp(e){let t=[],i=0;for(let n of ue(e)){if(n.kind!=="punctuation"||e.slice(n.start,n.end)!==",")continue;let o=e.slice(i,n.start).trim();if(o)t.push(o);i=n.end}let r=e.slice(i).trim();if(r)t.push(r);return t}function Ri(e){e=Np(e);let t=yn(e);if(t)return{defaultName:t.name,namedItems:[],source:t.source,isTypeOnly:t.isTypeOnly,isNamespace:!1,namespaceName:null,isImportEquals:!0};let i=Fp(e);if(i===-1)return null;let r=Bs(e);if(!r)return null;let n=r.specifier,o=e.slice(0,i).trim(),s=r.isTypeOnly;if(o.startsWith("import "))o=o.slice(7).trim();if(s&&o.startsWith("type "))o=o.slice(5).trim();let a=null,l=[],f=!1,u=null,d=o.includes("{")?-1:o.indexOf("* as ");if(d!==-1)return f=!0,u=o.slice(d+5).trim(),a=o.slice(0,d).trim().replace(/,$/,"").trim()||null,{defaultName:a,namedItems:[],source:n,isTypeOnly:s,isNamespace:f,namespaceName:u};let h=o.indexOf("{"),p=o.lastIndexOf("}");if(h!==-1&&p!==-1){let m=o.slice(0,h).trim();if(m.endsWith(","))a=m.slice(0,-1).trim()||null;let g=o.slice(h+1,p),C=Wp(g);for(let b of C){let c=Lp(b),A=c?b.slice(5).trim():b,M=A.lastIndexOf(" as "),S,T;if(M!==-1)T=A.slice(0,M).trim(),S=A.slice(M+4).trim();else S=A,T=A;l.push({name:S,originalName:T,isTypeOnly:s||c,isDefault:!1})}}else a=o.trim()||null;return{defaultName:a,namedItems:l,source:n,isTypeOnly:s,isNamespace:f,namespaceName:u}}function Lp(e){let t=ue(e),i=t[0];if(!i||i.kind!=="word"||e.slice(i.start,i.end)!=="type"||t.length<2)return!1;return!(t.length===3&&e.slice(t[1].start,t[1].end)==="as")}var Pi=ye(()=>{pt();_c()});function _s(e,t){let i=(r)=>ue(r).map((n)=>r.slice(n.start,n.end)).join("");return i(e)===i(t)}function Gc(e){if(["number","string","boolean","bigint","symbol","undefined","null"].includes(e))return e;let t=Te(e,!1);return["number","string","boolean","bigint","undefined","null"].includes(t)?t:void 0}function jc(e,t){if(_s(e,t))return e;let i=Gc(t);if(!i)return;let r=ue(e),n=0,o=0,s=[];for(let l of r){let f=e.slice(l.start,l.end);if(f==="("||f==="["||f==="{"||f==="<")n++;else if(f===")"||f==="]"||f==="}"||f===">")n--;else if(f==="|"&&n===0)s.push(e.slice(o,l.start).trim()),o=l.end}s.push(e.slice(o).trim());let a=s.find((l)=>_s(l,t));if(a)return a;if(s.includes(i))return i==="boolean"&&(t==="true"||t==="false")?t:i;return}function js(e){for(let t of e){if(t.kind!=="variable"||t.typeAnnotation||typeof t.value!=="string")continue;let i=ki(t.value);if(i&&Te(t.value,!1)===i)t.inferredType=i,t.text=`${t.isExported?"export ":""}declare ${t.modifiers?.[0]??"const"} ${t.name}: ${i};`}}function Vc(e,t,i,r=new Set){js([...t,...i.values()]);let n=new Map,o=[],s=new Set;for(let O of[...t,...i.values()]){if(s.has(O))continue;if(s.add(O),o.push(O),O.kind==="import")for(let z of Oi(O.text))n.set(z,{declared:`typeof ${z}`,flow:`typeof ${z}`,unresolved:!1});else if(["function","class","enum"].includes(O.kind))n.set(O.name,{declared:`typeof ${O.name}`,flow:`typeof ${O.name}`,unresolved:!1});else if(O.kind==="variable")n.set(O.name,{declared:O.typeAnnotation,unresolved:!1})}o.sort((O,z)=>(O.start??0)-(z.start??0));let a=new Set(o.filter((O)=>O.kind==="function"&&!O.generics).map((O)=>O.name));for(let O of r)a.add(O);let l=new Map,f=(O)=>{if(O=O.trimStart(),l.has(O))return l.get(O);if(l.set(O,void 0),!ht(O.charCodeAt(0)))return;let z=1;while(je(O.charCodeAt(z)))z++;if(!a.has(O.slice(0,z)))return;let _=ue(O);if(_[0]?.kind!=="word"||!_[1]||O.slice(_[1].start,_[1].end)!=="(")return;let Y=1;for(let H=2;H<_.length;H++){let ce=O.slice(_[H].start,_[H].end);if(ce==="(")Y++;else if(ce===")"&&--Y===0){let ge=H===_.length-1?O.slice(_[0].start,_[0].end):void 0;return l.set(O,ge),ge}}return},u=new Set(o.filter((O)=>O.kind==="variable"&&!O.typeAnnotation&&typeof O.value==="string").map((O)=>f(O.value)).filter((O)=>O!==void 0)).size?Mt(e):void 0,d=new Map;if(u){let O=0;for(let z=0;z<u.length;z++){let _=e.slice(u[z].start,u[z].end);if(O===0&&_==="function"){let Y=u[z+1],H=Y&&e.slice(Y.start,Y.end)==="*"?u[z+2]:Y;if(H?.kind==="word"){let ce=e.slice(H.start,H.end);d.set(ce,(d.get(ce)??0)+1)}}if(["{","(","["].includes(_))O++;else if(["}",")","]"].includes(_))O--}}let h=new Map;for(let O of o)if(O.kind==="function"&&!O.generics&&d.get(O.name)===1)h.set(O.name,O);for(let O of r){let z=o.find((_)=>_.kind==="import"&&Oi(_.text).includes(O));if(z)h.set(O,z)}let p="__dtsx_call_result";while(e.includes(p))p+="_";let m=(O)=>`(typeof ${O}) extends (...args: never[]) => infer ${p} ? ${p} : never`,g=new Map,C=!1;for(let O of o){if(O.kind!=="variable"||O.typeAnnotation||typeof O.value!=="string")continue;let z=f(O.value);if(z&&h.has(z))g.set(O,m(z)),n.get(O.name).active=!0,n.get(z).active=!0,C=!0;if(O.modifiers?.[0]!=="const")continue;let _=$n(O.value);if(!_||_===O.name||!n.has(_))continue;n.get(_).active=!0,n.get(O.name).active=!0,C=!0}if(!C)return;let b=u??Mt(e),c=(O)=>b[O]?e.slice(b[O].start,b[O].end):"",A=new Map,M=new Map,S=new Set,T=new Set,N=new Set,B=new Map,ee=[];for(let O=0;O<b.length;O++){let z=c(O),_=ee.at(-1);if(_!==void 0)M.set(O,_);if(z==="{"&&["=","(","[",",",":","?","return","yield"].includes(c(O-1)))S.add(O);if(["(","[","{"].includes(z))ee.push(O);else if([")","]","}"].includes(z)){let Y=ee.at(-1);if(Y!==void 0&&["()","[]","{}"].includes(c(Y)+z))ee.pop(),A.set(Y,O)}}let K=new Map;for(let O=0;O<b.length;){if(b[O].kind!=="punctuation"){O++;continue}let z=[">>>=","**=","&&=","||=","??=","<<=",">>=","===","!==",">>>","**","&&","||","??","<<",">>","=>","==","!=","<=",">=","++","--","+=","-=","*=","/=","%=","&=","|=","^=","="].find((Y)=>e.startsWith(Y,b[O].start))??c(O);K.set(O,z);let _=b[O].start+z.length;do O++;while(O<b.length&&b[O].start<_)}for(let O=0;O<b.length;O++){let z=re(O);if(z!==void 0)T.add(z)}for(let O of T)q(O);let te=0;function he(O){let z=$n(O);if(z){let ce=n.get(z);return{type:ce?.flow,unresolved:ce?.unresolved??!1}}let _=f(O),Y=_?h.get(_):void 0;if(Y)return{type:Y.returnType&&Gc(Y.returnType)?Y.returnType:m(_),unresolved:!1};let H=Te(O,!0);return{type:H==="unknown"?void 0:H,unresolved:!1}}function Ae(O){return K.get(O)??""}function Se(O){if(b[O]?.kind!=="word"||N.has(O)||c(O-1)==="."||c(O-1)==="#"&&c(O-2)===".")return;let z=n.get(c(O));if(!z?.active)return;let _=Ae(O+1);if(["=","+=","-=","*=","/=","%=","**=","<<=",">>=",">>>=","&=","|=","^=","&&=","||=","??="].includes(_))return{binding:z,operator:_};if(["++","--"].includes(_)&&!/[\r\n]/.test(e.slice(b[O].end,b[O+1].start)))return{binding:z,operator:_};if(O>=2&&["++","--"].includes(Ae(O-2))){let Y=b[O-3],H=Y&&(Y.kind==="word"||Y.kind==="quoted"||[")","]"].includes(c(O-3)));if(!Y||!H||/[\r\n;]/.test(e.slice(Y.end,b[O-2].start)))return{binding:z,operator:Ae(O-2)}}return}function fe(O){let z=Se(O);return z?.operator==="="?z.binding:void 0}function re(O){if(b[O]?.kind!=="word"||c(O)!=="class"||c(O-1)==="."||["(",":","="].includes(c(O+1)))return;let z=O+1,_=0;while(z<b.length){let Y=c(z);if(Y==="{"&&_===0)return z;if(Y==="class"){let H=re(z);if(H!==void 0){z=(A.get(H)??H)+1;continue}}if(Y==="function"){let H=me(z,b.length);if(H){z=H.end;continue}}if(Y==="<")_++;else if(Y===">"&&Ae(z-1)!=="=>"&&_>0)_--;if(Y===";")break;z=(A.get(z)??z)+1}return}function pe(O,z,_){let Y=O,H=!1,ce=_?["public","protected","private","static","abstract","override","declare","readonly","accessor","async","get","set"]:["async","get","set"];while(ce.includes(c(Y))&&!["(","<","?","!",":","=",";","}"].includes(c(Y+1))){if(c(Y)==="static")H=!0;Y++}if(c(Y)==="*")Y++;if(_&&c(Y)==="#")Y++;if(c(Y)==="["){let Oe=A.get(Y);return Oe===void 0?void 0:{next:Oe+1,isStatic:H}}if(b[Y]?.kind==="word"||b[Y]?.kind==="quoted")return{next:Y+1,isStatic:H};let ge=Y+1;while(ge<z&&b[ge-1].end===b[ge].start&&!["(","<","?","!",":","=",";","}","[","{",","].includes(c(ge)))ge++;if(Y<z&&Te(e.slice(b[Y].start,b[ge-1].end),!1)==="number")return{next:ge,isStatic:H};return}function D(O,z,_){let Y=pe(O,z,_);if(!Y)return;let H=Y.next;if(_&&["?","!"].includes(c(H)))H++;if(c(H)==="<"){let ce=1;H++;while(H<z&&ce>0){if(c(H)==="<")ce++;else if(c(H)===">"&&Ae(H-1)!=="=>")ce--;H=(A.get(H)??H)+1}if(ce!==0)return}return H}function qe(O,z,_){return D(O,z,_)===z}function X(O,z){let _=0,Y=-1;for(let H=O;H<z;H=(A.get(H)??H)+1)if(c(H)==="<"&&(_>0||H>O&&(b[H-1].kind==="word"||[")","]"].includes(c(H-1))))){if(_===0)Y=H;_++}else if(c(H)===">"&&Ae(H-1)!=="=>"&&_>0){if(_--,H===z-1&&_===0)return Y<H-1}return!1}function G(O,z){if(c(O)==="static"&&c(O+1)==="{")return!0;let _=D(O,z,!0);return _!==void 0&&(_===z||["(",":","=",";","}"].includes(c(_)))}function Z(O,z,_=!1){let Y=A.get(z)??b.length,H=O;while(H<Y){if(c(H)===";"||_&&Ae(H)==="=")return H;if(H>O&&M.get(H)===z&&/[\r\n]/.test(e.slice(b[H-1].end,b[H].start))){let ce=c(H-1),ge=!(ce===">"&&X(O,H)&&G(H,Y))&&["+","-","*","/","%","=","<",">","&","|","^","!","~","?",":",",",".","(","[","{","as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","yield","void"].includes(ce),Oe=[".","?",":",")","]","}",",","+","-","*","/","%","<",">","=","&","|","^","`","(","[","as","satisfies","instanceof","in"].includes(c(H));if(!ge&&!Oe)return H}H=(A.get(H)??H)+1}return Y}function ae(O,z){for(let _=O;_<z;_++){if(c(_)==="["&&A.has(_)){_=A.get(_);continue}if(b[_].kind==="word")N.add(_)}}function q(O){let z=A.get(O)??b.length,_=O+1;while(_<z){if(c(_)===";"){_++;continue}if(c(_)==="static"&&c(_+1)==="{"){_=(A.get(_+1)??_+1)+1;continue}let Y=pe(_,z,!0);if(!Y){_++;continue}let H=D(_,z,!0);if(H===void 0){_++;continue}if(ae(_,H),c(H)==="("){let ge=A.get(H),Oe=ge===void 0?void 0:ve(ge,z);if(Oe!==void 0){_=(A.get(Oe)??Oe)+1;continue}}let ce=H;if(c(ce)===":")ce=Z(ce+1,O,!0);if(Ae(ce)==="="){ae(_,ce+1);let ge=ce+1,Oe=Z(ge,O);if(!Y.isStatic&&Oe>ge)B.set(ge,Oe);_=Oe}else{let ge=Z(H,O);ae(_,ge),_=Math.max(_+1,ge)}}}function le(O){let z=M.get(O);if(z===void 0)return!1;let _=T.has(z);if(!_&&!S.has(z))return!1;if(qe(z+1,O,_))return!0;for(let Y=z+1;Y<O;Y++){let H=M.get(Y),ce=M.get(Y)===z&&(c(Y)===","||_&&c(Y)===";"),ge=_&&c(Y)==="}"&&H!==void 0&&M.get(H)===z,Oe=_&&M.get(Y+1)===z&&/[\r\n]/.test(e.slice(b[Y].end,b[Y+1].start));if((ce||ge||Oe)&&qe(Y+1,O,_))return!0}return!1}function ve(O,z){let _=O+1,Y=c(_)===":"?_+1:void 0;while(_<z){if(c(_)==="{"&&(Y===void 0||!$s(e.slice(b[Y].start,b[_].start))))return _;if(Y===void 0)return;_=(A.get(_)??_)+1}return}function me(O,z){let _=-1;if(c(O)==="("){let H=A.get(O);if(H!==void 0&&le(O))_=ve(H,z)??-1;else if(H!==void 0&&Ae(H+1)==="=>")_=H+3;else if(H!==void 0&&c(H+1)===":"){let ce=H+2;while(ce<z&&c(ce)!==";"){if(Ae(ce)==="=>"){_=ce+2;break}ce=(A.get(ce)??ce)+1}}}else if(b[O]?.kind==="word"&&Ae(O+1)==="=>")_=O+3;else if(c(O)==="function"){let H=O+1;while(H<z&&c(H)!=="(")H=(A.get(H)??H)+1;let ce=A.get(H);if(ce===void 0)return;_=ce+1;let ge=c(_)===":"?_+1:void 0;while(_<z){if(c(_)==="{"&&(ge===void 0||!$s(e.slice(b[ge].start,b[_].start))))break;_=(A.get(_)??_)+1}}if(_<0||_>=z)return;if(c(_)==="{")return{start:O,end:(A.get(_)??z-1)+1};let Y=_;while(Y<z&&![",",";",")","]","}"].includes(c(Y)))Y=(A.get(Y)??Y)+1;return{start:O,end:Y}}function W(O,z,_=!0){for(let Y=O;Y<z;Y++){let H=B.get(Y);if(H!==void 0){Y=Math.min(H,z)-1;continue}let ce=_?me(Y,z):void 0;if(ce){let Oe=ce.end;while(c(Oe)===")")Oe++;if(c(Oe)==="("||c(Oe)==="."&&["call","apply"].includes(c(Oe+1))&&c(Oe+2)==="(")W(ce.start,ce.end,!1);Y=ce.end-1;continue}let ge=Se(Y);if(ge)ge.binding.flow=void 0,ge.binding.unresolved=!0}}function Qe(O){let z=!1;while(te<b.length&&b[te].start<O){let _=c(te);if(["if","else","for","while","do","switch","try","catch","finally","with"].includes(_))z=!0;if(_===";")z=!1;if(_==="("||_==="{"||_==="["){let ce=A.get(te)??te+1;while(ce<b.length&&b[ce].start>=O)ce--;if(W(te+1,ce),te=ce+1,_==="{")z=!1;continue}let Y=fe(te);if(Y){let ce=te+2,ge=ce,Oe=[];while(ge<b.length&&b[ge].start<O){let xt=c(ge);if(Oe.length===0&&(xt===";"||ge>ce&&/[\r\n]/.test(e.slice(b[ge-1].end,b[ge].start))&&(fe(ge)||["if","for","while","switch","try","do","return","throw"].includes(xt))))break;if(xt==="("||xt==="{"||xt==="[")Oe.push(xt==="("?")":xt==="{"?"}":"]");else if(xt===Oe.at(-1))Oe.pop();ge++}let Gt=ge>ce?e.slice(b[ce].start,b[ge-1].end):"";W(ce,ge);let ci=he(Gt);Y.flow=!z&&ci.type?Y.declared?jc(Y.declared,ci.type):ci.type:void 0,Y.unresolved=z||ci.unresolved||!Y.flow,te=ge;continue}let H=Se(te);if(H)H.binding.flow=void 0,H.binding.unresolved=!0;te++}}for(let O of o){Qe(O.start??0);let z=te;while(te<b.length&&b[te].start<(O.end??0))te++;if(O.kind!=="variable")continue;if(O.initializerStart!==void 0){let Gt=z;while(Gt<te&&b[Gt].start<O.initializerStart)Gt++;W(Gt,te)}let _=n.get(O.name);if(!_.active)continue;let Y=typeof O.value==="string"?O.value:"";if(!Y){_.flow=_.declared;continue}let H=he(Y),ce=$n(Y),ge=ce?n.get(ce):void 0,Oe=g.get(O);if(Oe)O.inferredType=Oe;else if(!O.typeAnnotation&&O.modifiers?.[0]==="const"&&ce&&ce!==O.name&&ge){if(H.unresolved)O.inferenceError="DTSX_UNSUPPORTED_VALUE_FLOW";else if(H.type)O.inferredType=ge.declared&&_s(ge.declared,H.type)?`typeof ${ce}`:H.type}if(O.inferredType)O.text=`${O.isExported?"export ":""}declare ${O.modifiers?.[0]??"const"} ${O.name}: ${O.inferredType};`;if(O.typeAnnotation)_.flow=H.type?jc(O.typeAnnotation,H.type)??O.typeAnnotation:O.typeAnnotation;else if(O.inferredType)_.declared=O.inferredType,_.flow=O.inferredType;else{let Gt=O.modifiers?.[0]==="const",ci=Y.trim().startsWith("{")||Y.trim().startsWith("["),xt=Te(Y,Gt&&!ci);_.declared=xt==="unknown"?void 0:xt,_.flow=_.declared}_.unresolved=H.unresolved}}var Uc=ye(()=>{Bi();pt();$r();Pi();Tr()});function Bp(e,t,i,r,n=""){let o=new Map,s={start:0,end:e.length,header:0,name:"",children:[],results:new Map},a=ue(e),l=[],f=[],u=[],d=new Map;for(let g=0;g<a.length;g++){let C=a[g];if(C.kind!=="punctuation")continue;let b=e.slice(C.start,C.end);if(b==="(")u.push(g);else if(b===")"){let c=u.pop();if(c!==void 0)d.set(g,c)}else if(b==="{")f.push(g);else if(b==="}"){let c=f.pop();if(c===void 0)continue;let A=a[c].start,M=c-1,S=M>=0?e.slice(a[M].start,a[M].end):"";if(S===")"){let T=d.get(M);if(T!==void 0&&T>0&&["if","for","while","switch","catch","with"].includes(e.slice(a[T-1].start,a[T-1].end)))A=a[T-1].start}else if(["else","try","finally","do"].includes(S))A=a[M].start;l.push({open:a[c].start,close:C.start,header:A})}}let h=0,p=(g,C=new Set)=>{let b=new Set(C),c=ue(e.slice(g.start,g.end)),A=0;for(let K=0;K+1<c.length;K++){let te=e.slice(g.start+c[K].start,g.start+c[K].end);if(te==="{")A++;else if(te==="}")A--;else if(!A&&["type","interface"].includes(te))b.add(e.slice(g.start+c[K+1].start,g.start+c[K+1].end))}let M="",S=g.start,T=[...g.results].map(([K,te])=>({type:K,name:te}));for(let K of g.children.sort((te,he)=>te.header-he.header)){let te=p(K,b);M+=e.slice(S,K.header)+`
|
|
108
108
|
declare namespace ${K.name} {
|
|
109
109
|
${te.text}
|
|
110
110
|
}
|
|
111
|
-
`,S=K.end+1;for(let he of te.exports)
|
|
111
|
+
`,S=K.end+1;for(let he of te.exports)T.push({type:`${K.name}.${he.name}`,name:he.name})}M+=`${e.slice(S,g.end)}
|
|
112
112
|
;
|
|
113
|
-
${
|
|
114
|
-
`)}`;let N=jn(M,t,!1);for(let K of
|
|
115
|
-
`);return{declarations:N,text:ee,exports:
|
|
113
|
+
${T.map((K)=>`export type ${K.name} = ${K.type};`).join(`
|
|
114
|
+
`)}`;let N=jn(M,t,!1);for(let K of T)b.add(K.name);let B=n?Vs(n).map((K,te)=>[K,`${m}_capture_${te}`]):[],ee=N.map((K)=>n&&["type","interface"].includes(K.kind)?_p(K,n,B,b):(K.kind==="variable"?Vi(K,!1):K.text).replace(/^export\s+/,"").replace(/^declare\s+/,"")).join(`
|
|
115
|
+
`);return{declarations:N,text:ee,exports:T}},m;return{resolve(g,C){m??=i();let b=s;for(let A of l.filter((M)=>M.open<C&&C<M.close).sort((M,S)=>M.open-S.open)){let M=b.children.find((S)=>S.start===A.open+1);if(!M)M={start:A.open+1,end:A.close,header:A.header,name:`${m}_scope_${h++}`,children:[],results:new Map},b.children.push(M);b=M}let c=b.results.get(g);if(!c)c=`${m}_result_${o.size}`,b.results.set(g,c),o.set(c,g);return`${m}.${c}`},finish(g){if(!m)return g;let C=p(s),b=C.declarations,c=new Set(o.keys());if(b.every((M)=>c.has(M.name))){let M=new Map(o),S=ue(g),T="",N=0;for(let B=0;B+2<S.length;B++){if(g.slice(S[B].start,S[B].end)!==m||g.slice(S[B+1].start,S[B+1].end)!==".")continue;let ee=M.get(g.slice(S[B+2].start,S[B+2].end));if(!ee)continue;T+=g.slice(N,S[B].start)+`(${ee})`,N=S[B+2].end,B+=2}return T+g.slice(N)}if(n){let M=Vs(n).join(", "),S=ue(g),T="",N=0;for(let B=0;B+2<S.length;B++){if(g.slice(S[B].start,S[B].end)!==m||g.slice(S[B+1].start,S[B+1].end)!=="."||!c.has(g.slice(S[B+2].start,S[B+2].end)))continue;T+=`${g.slice(N,S[B+2].end)}<${M}>`,N=S[B+2].end,B+=2}g=T+g.slice(N)}let A=C.text;return r({kind:"module",name:m,text:`declare namespace ${m} {
|
|
116
116
|
${A}
|
|
117
|
-
}`,moduleForm:"namespace",isExported:!1}),g}}}function
|
|
117
|
+
}`,moduleForm:"namespace",isExported:!1}),g}}}function Vs(e){let t=ue(e),i=[],r=0,n=0,o=!1;for(let s of t){let a=e.slice(s.start,s.end);if(a==="<"){if(r++,r===1)o=!0}else if(a===">"&&e[s.start-1]!=="=")r--;else if(["(","[","{"].includes(a))n++;else if([")","]","}"].includes(a))n--;else if(a===","&&r===1&&!n)o=!0;else if(o&&s.kind==="word"&&!["const","in","out"].includes(a))i.push(a),o=!1}return i}function _p(e,t,i,r){let n=new Set(Vs(e.generics||"")),o=(p,m,g)=>{let C=ue(p),b="",c=0;for(let A=0;A<C.length;A++){let M=C[A],S=p.slice(M.start,M.end),T=C[A+1]&&p.slice(C[A+1].start,C[A+1].end),N=C[A+2]&&p.slice(C[A+2].start,C[A+2].end),B=C[A-1]&&p.slice(C[A-1].start,C[A-1].end);if(M.kind!=="word"||T===":"||T==="?"&&N===":")continue;let ee=!g.has(S)&&B!=="."&&i.find(([K])=>K===S)?.[1];if(ee)b+=p.slice(c,M.start)+ee,c=M.end;else if(m&&r.has(S)&&!g.has(S)){let K=i.map(([,te])=>te).join(", ");b+=`${p.slice(c,M.end)}<${K}${T==="<"?", ":">"}`,c=T==="<"?C[++A].end:M.end}}return b+p.slice(c)},s=ue(e.text),a=s.findIndex((p)=>["type","interface"].includes(e.text.slice(p.start,p.end))),l=s[a+1],f=e.generics||"",u=f?e.text.indexOf(f,l.end)+f.length:l.end,d=o(jp(t),!1,new Set),h=f?`, ${o(f.slice(1,-1),!0,n)}`:"";return`${e.text.slice(0,l.end)}<${d}${h}>${o(e.text.slice(u),!0,n)}`.replace(/^export\s+/,"").replace(/^declare\s+/,"")}function jp(e){let t=e.slice(1,-1),i=ue(t),r=0,n=0,o=!1,s="";for(let a=0;a<i.length;a++){let l=i[a],f=t.slice(l.start,l.end);if(["(","[","{","<"].includes(f))r++;else if([")","]","}"].includes(f)||f===">"&&t[l.start-1]!=="=")r--;else if(!r&&f==="const")s+=t.slice(n,l.start),n=l.end;else if(!r&&f==="="&&t.slice(i[a+1]?.start,i[a+1]?.end)!==">")s+=t.slice(n,l.start),o=!0;else if(!r&&f===","&&o)n=l.start,o=!1}return s+(o?"":t.slice(n))}function it(e){return e===lt||e===ct||e===Fe||e===ze}function Kc(e){let t=!0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r===Ui){if(t)return!1;t=!0}else if(t){if(!ht(r))return!1;t=!1}else if(!je(r))return!1}return e.length>0&&!t}function Or(e,t,i){let r=t+1;while(r<e.length){let n=e.charCodeAt(r);if(n===Tt){r+=2;continue}if(r++,n===i)break}return r}function Up(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===se&&e.includes("[")&&e.includes("]:")}function Rr(e,t,i=!0){return zs(e,t,i,!0)}function jn(e,t,i=!0,r){return zs(e,t,i,!1,!1,r)}function Us(e,t,i=!0){return zs(e,t,i,!0,!0)}function zs(e,t,i,r,n=!1,o){let s=e,a=i,l=r,f=s.length,u=gn(s),d=_i(s),h=[],p=new Map,m=new Map;function g(y,v){let w=v.kind==="interface"||v.kind==="type";if(w){let E=m.get(y);if(E)E.push(v);else m.set(y,[v])}let x=p.get(y);if(!w||!x||x.kind!=="variable"&&x.kind!=="function")p.set(y,v)}let C=new Map,b=new Set,c=0,A,M=0,S=[],T=[],N=[],B=[],ee;function K(y,v=!1){let w=`__dtsx_constructor_field_${B.length}__`;ee??=new Set(Mt(s).filter((x)=>x.kind==="word").map((x)=>s.slice(x.start,x.end)).filter((x)=>x.startsWith("__dtsx_constructor_field_")));while(ee.has(w))w+="_";return B.push({marker:w,initializer:y,classes:S.map((x)=>x.name),namespaces:[...N],binding:v}),w}function te(y){let v=/^this\.([\w$]+)$/.exec(y);if(v){let F=S.at(-1);return F?.fields.get(`${F.isStatic?"static:":""}${v[1]}`)}let w=/^([\w$]+)\s*\(/.exec(y);if(!w||!y.endsWith(")"))return;let x=ue(y),E=0;for(let F=1;F<x.length;F++){let P=y.slice(x[F].start,x[F].end);if(P==="(")E++;else if(P===")"&&--E===0&&F!==x.length-1)return}let k=[...h,...p.values()].filter((F)=>F.kind==="function"&&F.name===w[1]);if(k.length!==1||k[0].generics||vn(s,w[1])!==1)return;return k[0].returnType}function he(y){let v=y.trim(),w=te(v);if(w)return w;if(!v.startsWith("class"))return;let x=ue(v);if(x[0]?.kind!=="word"||v.slice(x[0].start,x[0].end)!=="class")return;let E;do E=`__dtsx_class_${M++}`;while(s.includes(E));let k=x[1],F=k?v.slice(k.start,k.end):"",P=k?.kind==="word"&&!["extends","implements"].includes(F),I=P?F:`${E}_value`,R=P?`export ${v}`:`export class ${I} ${v.slice(5)}`,L=jn(R,t,a),J=L.find((Q)=>Q.kind==="class");if(!J)throw Error("Cannot extract the class expression declaration");if(ue(R.slice(J.end??R.length)).some((Q)=>R.slice((J.end??0)+Q.start,(J.end??0)+Q.end)!==";"))return;let U=L.map((Q)=>Q.text.replace(/^export\s+/,"").replace(/^declare\s+/,"")).join(`
|
|
118
118
|
`);return g(E,{kind:"module",name:E,text:`declare namespace ${E} {
|
|
119
119
|
${U}
|
|
120
|
-
}`,moduleForm:"namespace",isExported:!1,start:c,end:c}),`typeof ${E}.${I}`}function Ae(y,v){let w=/^this\.([\w$]+)$/.exec(y);if(w)return S.at(-1)?.fields.get(`${v?"static:":""}${w[1]}`);return he(y)}function Se(y){let v=C.get(y.name);if(v)v.push(y);else C.set(y.name,[y]);g(y.name,y)}if(c<f&&s.charCodeAt(c)===65279)c++;function fe(y,v){if(y<v){let w=s.charCodeAt(y),x=s.charCodeAt(v-1);if(w!==lt&&w!==ct&&w!==Fe&&w!==ze&&x!==lt&&x!==ct&&x!==Fe&&x!==ze)return s.slice(y,v)}while(y<v&&it(s.charCodeAt(y)))y++;while(v>y&&it(s.charCodeAt(v-1)))v--;return s.slice(y,v)}let re=/[\r\n]/g;function pe(y){return re.lastIndex=y,re.exec(s)?.index??f}function D(){if(c>=f)return;let y=s.charCodeAt(c);if(y!==lt&&y!==ct&&y!==Fe&&y!==ze&&y!==we)return;while(c<f){let v=s.charCodeAt(c);if(v===lt||v===ct||v===Fe||v===ze){c++;continue}if(v===we&&c+1<f){let w=s.charCodeAt(c+1);if(w===we){c=pe(c+2);continue}if(w===Ie){let x=s.indexOf("*/",c+2);c=x===-1?f:x+2;continue}}break}}function qe(y){if(y.indexOf("//")===-1&&y.indexOf("/*")===-1)return y;let v=0,w=0;while(w<y.length){let x=y.charCodeAt(w);if(x===De||x===Ne||x===Xe){w=Or(y,w,x),v=w;continue}if(x===Tt){w+=2,v=Math.min(w,y.length);continue}if(x===we&&y.charCodeAt(w+1)===we){while(w<y.length&&y.charCodeAt(w)!==Fe&&y.charCodeAt(w)!==ze)w++;continue}if(x===we&&y.charCodeAt(w+1)===Ie){let E=y.indexOf("*/",w+2);w=E===-1?y.length:E+2;continue}if(w++,x>32)v=w}return v<y.length?y.slice(0,v).trimEnd():y}function X(y){let v=y.length,w=0,x=v;for(let E=0;E<v;E++){let
|
|
121
|
-
`,c),v=y===-1?f:y,w=s.indexOf(";",c);if(w!==-1&&w<v){let x=w-1;while(x>=c&&(s.charCodeAt(x)===lt||s.charCodeAt(x)===ct))x--;let E=s.charCodeAt(c),
|
|
122
|
-
`));continue}break}if(w.length===0)return;return w.reverse(),w}function
|
|
123
|
-
`),x=[],E=[],
|
|
124
|
-
`);let I=P-2,R=Array(x.length);for(let L=0;L<x.length;L++){let
|
|
120
|
+
}`,moduleForm:"namespace",isExported:!1,start:c,end:c}),`typeof ${E}.${I}`}function Ae(y,v){let w=/^this\.([\w$]+)$/.exec(y);if(w)return S.at(-1)?.fields.get(`${v?"static:":""}${w[1]}`);return he(y)}function Se(y){let v=C.get(y.name);if(v)v.push(y);else C.set(y.name,[y]);g(y.name,y)}if(c<f&&s.charCodeAt(c)===65279)c++;function fe(y,v){if(y<v){let w=s.charCodeAt(y),x=s.charCodeAt(v-1);if(w!==lt&&w!==ct&&w!==Fe&&w!==ze&&x!==lt&&x!==ct&&x!==Fe&&x!==ze)return s.slice(y,v)}while(y<v&&it(s.charCodeAt(y)))y++;while(v>y&&it(s.charCodeAt(v-1)))v--;return s.slice(y,v)}let re=/[\r\n]/g;function pe(y){return re.lastIndex=y,re.exec(s)?.index??f}function D(){if(c>=f)return;let y=s.charCodeAt(c);if(y!==lt&&y!==ct&&y!==Fe&&y!==ze&&y!==we)return;while(c<f){let v=s.charCodeAt(c);if(v===lt||v===ct||v===Fe||v===ze){c++;continue}if(v===we&&c+1<f){let w=s.charCodeAt(c+1);if(w===we){c=pe(c+2);continue}if(w===Ie){let x=s.indexOf("*/",c+2);c=x===-1?f:x+2;continue}}break}}function qe(y){if(y.indexOf("//")===-1&&y.indexOf("/*")===-1)return y;let v=0,w=0;while(w<y.length){let x=y.charCodeAt(w);if(x===De||x===Ne||x===Xe){w=Or(y,w,x),v=w;continue}if(x===Tt){w+=2,v=Math.min(w,y.length);continue}if(x===we&&y.charCodeAt(w+1)===we){while(w<y.length&&y.charCodeAt(w)!==Fe&&y.charCodeAt(w)!==ze)w++;continue}if(x===we&&y.charCodeAt(w+1)===Ie){let E=y.indexOf("*/",w+2);w=E===-1?y.length:E+2;continue}if(w++,x>32)v=w}return v<y.length?y.slice(0,v).trimEnd():y}function X(y){let v=y.length,w=0,x=v;for(let E=0;E<v;E++){let k=y.charCodeAt(E);if(w){if(k===Tt){E++;continue}if(k===w)w=0;continue}if(k===De||k===Ne||k===Xe){w=k;continue}if(k===we&&E+1<v){let F=y.charCodeAt(E+1);if(F===we){x=E;while(x>0&&(y.charCodeAt(x-1)===lt||y.charCodeAt(x-1)===ct))x--;return y.slice(0,x)}if(F===Ie){let P=y.indexOf("*/",E+2);if(P!==-1){y=`${y.slice(0,E)} ${y.slice(P+2)}`,E--;continue}}}}x=v;while(x>0&&(y.charCodeAt(x-1)===lt||y.charCodeAt(x-1)===ct||y.charCodeAt(x-1)===ze))x--;return x<v?y.slice(0,x):y}function G(y){c++;let v=y===De?"'":'"';while(c<f){let w=s.indexOf(v,c);if(w===-1){c=f;return}let x=0,E=w-1;while(E>=0&&s.charCodeAt(E)===Tt)x++,E--;if(x%2===0){c=w+1;return}c=w+1}}function Z(){c++;let y=[];while(c<f){let v=s.charCodeAt(c);if(y.length===0){if(v===Tt){c+=2;continue}if(v===Xe){c++;return}if(v===Vp&&c+1<f&&s.charCodeAt(c+1)===se){c+=2,y.push(0);continue}c++;continue}if(v===De||v===Ne){G(v);continue}if(v===Xe){Z();continue}if(v===we&&c+1<f){let w=s.charCodeAt(c+1);if(w===we){c=pe(c+2);continue}if(w===Ie){let x=s.indexOf("*/",c+2);c=x===-1?f:x+2;continue}if(le()){ve();continue}c++;continue}if(v===se){y[y.length-1]++,c++;continue}if(v===Ce){let w=y[y.length-1];if(w===0){y.pop(),c++;continue}y[y.length-1]=w-1,c++;continue}c++}}let ae=!1;function q(){ae=!1;let y=s.charCodeAt(c);if(y===De||y===Ne)return G(y),!0;if(y===Xe)return Z(),!0;if(y===we&&c+1<f){let v=s.charCodeAt(c+1);if(v===we)return c=pe(c+2),!0;if(v===Ie){let w=s.indexOf("*/",c+2);return ae=pe(c+2)<(w===-1?f:w),c=w===-1?f:w+2,!0}if(le())return ve(),!0}return!1}function le(){return kt(s,c)}function ve(){c=bt(s,c)}function me(){let y=c;while(c<f&&je(s.charCodeAt(c)))c++;return s.slice(y,c)}function W(y){if(c+y.length>f)return!1;for(let v=0;v<y.length;v++)if(s.charCodeAt(c+v)!==y.charCodeAt(v))return!1;if(c+y.length<f&&je(s.charCodeAt(c+y.length)))return!1;return!0}function Qe(y){let v=c+y;while(v<f){let w=s.charCodeAt(v);if(w===lt||w===ct||w===Fe||w===ze){v++;continue}return w!==Ui&&w!==Ue}return!1}function O(){if(!ae)return!1;let y=c;D();let v=c>=f||z()||s.charCodeAt(c)===Ce;return c=y,v}function z(){if(c>=f)return!1;switch(s.charCodeAt(c)){case 101:return W("export")||W("enum");case 105:return W("import")||W("interface");case 102:return W("function");case 99:return W("class")||W("const");case 116:return W("type");case 108:return W("let");case 118:return W("var");case 100:return W("declare")||W("default");case 109:return W("module");case 110:return W("namespace");case 97:return W("abstract")||W("async");default:return!1}}function _(){let y=s.charCodeAt(c);if(y!==Fe&&y!==ze)return!1;let v=c;if(c++,y===ze&&c<f&&s.charCodeAt(c)===Fe)c++;while(c<f){let x=s.charCodeAt(c);if(x===lt||x===ct||x===ze||x===Fe){c++;continue}if(x===we&&c+1<f){let E=s.charCodeAt(c+1);if(E===we){c=pe(c+2);continue}if(E===Ie){let k=s.indexOf("*/",c+2);c=k===-1?f:k+2;continue}}break}let w=c>=f||z()||s.charCodeAt(c)===Ce;return c=v,w}function Y(y){let v=y-1;while(v>=0){let I=s.charCodeAt(v);if(I===lt||I===ct||I===ze||I===Fe){v--;continue}break}if(v<0)return!0;let w=s[v];if("+-*/%=<>&|^!~?:,.([{".includes(w))return!0;let x=v;while(x>0&&s.charCodeAt(x-1)!==Fe)x--;let E=s.slice(x,v+1),k=E.lastIndexOf("<");if(k!==-1&&/^<[A-Za-z]/.test(E.slice(k))&&!E.slice(k).includes(">"))return!0;let F=v;while(F>=0&&/[a-z]/i.test(s[F]))F--;let P=s.slice(F+1,v+1);return["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(P)}function H(y,v){let w=s.charCodeAt(c);if(w!==Fe&&w!==ze&&!(w===we&&(s[c+1]==="/"||s[c+1]==="*")))return!1;let x=Mt(s),E=0,k=x.length;while(E<k){let L=E+k>>>1;if(x[L].start<c)E=L+1;else k=L}let F=x[E-1],P=x[E];if(!F||F.start<y||!/[\r\n]/.test(s.slice(c,P?.start??f)))return!1;let I=s.slice(F.start,F.end);if(F.end!==v&&F.kind==="punctuation"&&"+-*/%=<>&|^!~?:,.([{".includes(I))return!1;if(F.kind==="word"&&["as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","return","yield","void"].includes(I))return!1;if(!P)return!0;let R=s.slice(P.start,P.end);return!(".?:)]},+-*/%<>=&|^`([".includes(R)||P.kind==="literal"&&s.charCodeAt(P.start)===Xe||["as","satisfies","instanceof","in"].includes(R))}function ce(){let y=s.charCodeAt(c);if(y!==Fe&&y!==ze)return!1;if(Y(c))return!1;let v=c;c++;while(c<f){let E=s.charCodeAt(c);if(E===lt||E===ct||E===ze||E===Fe){c++;continue}if(E===we&&c+1<f){let k=s.charCodeAt(c+1);if(k===we){c=pe(c+2);continue}if(k===Ie){let F=s.indexOf("*/",c+2);c=F===-1?f:F+2;continue}}break}let w=c<f?s[c]:"",x=w==="|"||w==="&"||w==="["||w==="."||w==="?"||w===":"||w===">"||w===")"||w===","||W("extends");return c=v,!x}function ge(){let y=s.charCodeAt(c);if(y!==Fe&&y!==ze)return!1;let v=c;if(c++,y===ze&&c<f&&s.charCodeAt(c)===Fe)c++;while(c<f){let x=s.charCodeAt(c);if(x===lt||x===ct||x===ze||x===Fe){c++;continue}if(x===we&&c+1<f&&s.charCodeAt(c+1)===we){c=pe(c+2);continue}break}if(c>=f)return c=v,!0;let w=s.charCodeAt(c);if(w===124||w===38||w===Ui||w===_n||w===It)return c=v,!1;if(W("extends")||W("keyof")||W("typeof")||W("infer")||W("is")||W("as")||W("in"))return c=v,!1;return c=v,!0}let Oe=/[{}'"`\/]/g,Gt=/[()'"`\/]/g,ci=/[[\]'"`\/]/g,xt=/[<>'"`\/]/g;function et(y,v){let w=1;c++;let x=y===se?Oe:y===Ee?Gt:y===Ge?ci:xt;x.lastIndex=c;let E;while((E=x.exec(s))!==null){let k=E.index,F=s.charCodeAt(k);if(F===De||F===Ne){c=k,G(F),x.lastIndex=c;continue}if(F===Xe){c=k,Z(),x.lastIndex=c;continue}if(F===we){if(c=k,q()){x.lastIndex=c;continue}x.lastIndex=k+1;continue}if(F===y)w++;else if(F===v){if(v===Ve&&k>0&&s.charCodeAt(k-1)===Ue){x.lastIndex=k+1;continue}if(w--,w===0)return c=k+1,c}x.lastIndex=k+1}return c=f,c}function St(){return c>0&&s.charCodeAt(c-1)===Ue}function Vo(){return c+1<f&&s.charCodeAt(c+1)===Ve}let gt=/[<{};'"`\/\n\r()[\]]/g;function tt(y=!1){let v=0,w=0,x=0,E=0,k=s.charCodeAt(c)===se;gt.lastIndex=c;let F;while((F=gt.exec(s))!==null){let P=F.index,I=s.charCodeAt(P);if(I===De||I===Ne){c=P,G(I),gt.lastIndex=c;continue}if(I===Xe){c=P,Z(),gt.lastIndex=c;continue}if(I===we){if(P>0&&s.charCodeAt(P-1)===_e){gt.lastIndex=P+1;continue}if(c=P,q()){if(v===0&&w===0&&x===0&&E===0&&O())return;gt.lastIndex=c;continue}gt.lastIndex=P+1;continue}if(I===_e){let R=u(P)?.delta??null;if(R!==null)E=Math.max(0,E+R);gt.lastIndex=P+1;continue}if(I===Ee){w++,gt.lastIndex=P+1;continue}if(I===Me){w--,gt.lastIndex=P+1;continue}if(I===Ge){x++,gt.lastIndex=P+1;continue}if(I===Je){x--,gt.lastIndex=P+1;continue}if(I===se){v++,gt.lastIndex=P+1;continue}if(I===Ce){let R=v>0;if(!R&&y&&w===0&&x===0&&E===0){c=P;return}if(R)v--;if((!R||k)&&v===0&&w===0&&x===0&&E===0){c=P+1;return}if(R&&v===0&&w===0&&x===0&&E===0){c=P+1;let L=c;D();let J=z();if(c=L,J)return}gt.lastIndex=P+1;continue}if(I===xe&&v===0&&w===0&&x===0&&E===0){c=P+1;return}if((I===Fe||I===ze)&&v===0&&w===0&&x===0&&E===0){if(c=P,_())return}gt.lastIndex=P+1}c=f}function lh(){c++;while(c<f&&(s.charCodeAt(c)===lt||s.charCodeAt(c)===ct))c++;let y=s.indexOf(`
|
|
121
|
+
`,c),v=y===-1?f:y,w=s.indexOf(";",c);if(w!==-1&&w<v){let x=w-1;while(x>=c&&(s.charCodeAt(x)===lt||s.charCodeAt(x)===ct))x--;let E=s.charCodeAt(c),k=s.charCodeAt(x);if(E===se&&k===Ce||E===Ge&&k===Je||E===De&&k===De||E===Ne&&k===Ne||E===Xe&&k===Xe){c=w+1;return}}tt()}function fl(){et(se,Ce);while(c<f&&it(s.charCodeAt(c)))c++;if(W("from")){c+=4;while(c<f&&it(s.charCodeAt(c)))c++;if(c<f){let y=s.charCodeAt(c);if(y===De||y===Ne)G(y)}}while(c<f&&(s.charCodeAt(c)===lt||s.charCodeAt(c)===ct))c++;if(c<f&&s.charCodeAt(c)===xe)c++}function ul(){c++;while(c<f&&it(s.charCodeAt(c)))c++;if(W("as")){c+=2;while(c<f&&it(s.charCodeAt(c)))c++;me();while(c<f&&it(s.charCodeAt(c)))c++}if(W("from")){c+=4;while(c<f&&it(s.charCodeAt(c)))c++;if(c<f){let y=s.charCodeAt(c);if(y===De||y===Ne)G(y)}}while(c<f&&(s.charCodeAt(c)===lt||s.charCodeAt(c)===ct))c++;if(c<f&&s.charCodeAt(c)===xe)c++}function Jr(y){let v=y.indexOf("from ");if(v===-1)return;let w=v+5;while(w<y.length&&(y.charCodeAt(w)===32||y.charCodeAt(w)===9))w++;if(w>=y.length)return;let x=y.charCodeAt(w);if(x!==39&&x!==34)return;let E=y.indexOf(y[w],w+1);if(E===-1)return;return y.slice(w+1,E)}function vt(y){if(!a)return;let v=y-1;while(v>=0&&it(s.charCodeAt(v)))v--;if(v<0)return;let w=[],x=!1;while(v>=0){if(v>=1&&s.charCodeAt(v)===we&&s.charCodeAt(v-1)===Ie){let F=s.lastIndexOf("/*",v-2);if(F>=0){w.push(s.slice(F,v+1)),x=!0,v=F-1;while(v>=0&&it(s.charCodeAt(v)))v--;continue}break}let E=v;while(E>0&&s.charCodeAt(E-1)!==Fe)E--;let k=fe(E,v+1);if(k.startsWith("//")){if(x)break;let F=[k];v=E-1;while(v>=0&&(s.charCodeAt(v)===Fe||s.charCodeAt(v)===ze))v--;while(v>=0){let P=v;while(P>0&&s.charCodeAt(P-1)!==Fe)P--;let I=fe(P,v+1);if(I.startsWith("//")){F.push(I),v=P-1;while(v>=0&&(s.charCodeAt(v)===Fe||s.charCodeAt(v)===ze))v--}else if(I===""){v=P-1;while(v>=0&&(s.charCodeAt(v)===Fe||s.charCodeAt(v)===ze))v--}else break}F.reverse(),w.push(F.join(`
|
|
122
|
+
`));continue}break}if(w.length===0)return;return w.reverse(),w}function ch(y){let v=y,w=!1,x=0,E;while(c<f){let U=s.charCodeAt(c);if(U===we&&(s.charCodeAt(c+1)===we||s.charCodeAt(c+1)===Ie)){D();continue}if(U===xe){c++;break}if(U===se)x++;else if(U===Ce&&x>0)x--;if(U===De||U===Ne){if(G(U),x>0)continue;w=!0;let Q=c;if(D(),s.charCodeAt(c)===Me){let j=c+1;E=yn(s.slice(v,j)),c=E?j:Q}else c=Q;while(c<f&&(s.charCodeAt(c)===lt||s.charCodeAt(c)===ct))c++;if(c<f&&s.charCodeAt(c)===xe)c++;break}if(U===Fe&&w)break;c++}let k=fe(v,c),F=Wt(k).find((U)=>U.category==="static-import"),P=ue(k),I=E?.isTypeOnly??F?.isTypeOnly??!1,R=P[1]?.kind==="quoted",L=E?.source??F?.specifier??"",J=vt(v);return{kind:"import",name:"",text:k,isExported:!1,isTypeOnly:I,isSideEffect:R,source:L,leadingComments:J,start:v,end:c}}function Uo(){let y=c;return et(se,Ce),s.slice(y,c)}function dl(y){let v=y.indexOf("(");if(v===-1)return y;let w=y.slice(v);if(w.indexOf("=")===-1)return y;let x=!1;for(let I=0;I<w.length;I++)if(w.charCodeAt(I)===61){let R=I>0?w.charCodeAt(I-1):0,L=I+1<w.length?w.charCodeAt(I+1):0;if(R!==61&&R!==33&&R!==60&&R!==62&&L!==61&&L!==62){x=!0;break}}if(!x)return y;let E=0,k=-1;for(let I=v;I<y.length;I++){let R=y.charCodeAt(I);if(R===40)E++;else if(R===41){if(E--,E===0){k=I;break}}}if(k===-1)return y;let F=y.slice(v,k+1),P=Ni(F);return y.slice(0,v)+P+y.slice(k+1)}function hl(y){let v=y.indexOf("//")!==-1||y.indexOf("/*")!==-1,w=y.split(`
|
|
123
|
+
`),x=[],E=[],k=[],F=!1,P=1/0;for(let L=0;L<w.length;L++){let J=w[L];if(v){if(F){if(J.includes("*/"))F=!1;continue}let U=J.trim();if(U.length===0)continue;let Q=U.charCodeAt(0);if(Q===we){let be=U.charCodeAt(1);if(be===we)continue;if(be===Ie){if(!U.includes("*/"))F=!0;continue}}if(Q===Ie)continue;let j=X(J);if(j.charCodeAt(j.length-1)===xe)j=j.slice(0,-1);j=dl(j);let V=j.trim();if(!V)continue;x.push(j),E.push(V);let ie=0;while(ie<j.length&&it(j.charCodeAt(ie)))ie++;if(V!=="{"&&V!=="}"){if(ie<P)P=ie}k.push(ie)}else{let U=J.length;while(U>0&&(J.charCodeAt(U-1)===lt||J.charCodeAt(U-1)===ct||J.charCodeAt(U-1)===ze))U--;if(U===0)continue;let Q=U<J.length?J.slice(0,U):J;if(Q.charCodeAt(Q.length-1)===xe)Q=Q.slice(0,-1);Q=dl(Q);let j=Q.trim();if(!j)continue;x.push(Q),E.push(j);let V=0;while(V<Q.length&&it(Q.charCodeAt(V)))V++;if(j!=="{"&&j!=="}"){if(V<P)P=V}k.push(V)}}if(x.length===0)return"{}";if(P===1/0||P<=2)return x.join(`
|
|
124
|
+
`);let I=P-2,R=Array(x.length);for(let L=0;L<x.length;L++){let J=E[L];if(J==="{"){R[L]=J;continue}let U=k[L];if(U>P)R[L]=x[L];else if(U===P&&(J.charCodeAt(0)===Ce||J.charCodeAt(0)===Je||J.charCodeAt(0)===Me))R[L]=x[L];else{let Q=Math.max(0,U-I);R[L]=" ".repeat(Q)+J}}return R.join(`
|
|
125
125
|
`)}function Vt(){if(c>=f||s.charCodeAt(c)!==_e)return"";let y=c;et(_e,Ve);let v=s.slice(y,c);if(v.includes(`
|
|
126
|
-
`)){let w="",x=!1;for(let E=0;E<v.length;E++){let
|
|
126
|
+
`)){let w="",x=!1;for(let E=0;E<v.length;E++){let k=v.charCodeAt(E);if(k===32||k===9||k===10||k===13){if(!x&&w.length>0)w+=" ",x=!0}else w+=v[E],x=!1}if(w.charCodeAt(1)===32)w=`<${w.slice(2)}`;if(w.charCodeAt(w.length-2)===32)w=`${w.slice(0,-2)}>`;return w}return v}function fi(){if(c>=f||s.charCodeAt(c)!==Ee)return"()";let y=c;return et(Ee,Me),s.slice(y,c)}function Yr(y){if(y.indexOf("/")===-1)return y;let v="",w=!1,x=0;for(let E=0;E<y.length;E++){let k=y.charCodeAt(E);if(w){if(v+=y[E],k===Tt&&E+1<y.length){v+=y[++E];continue}if(k===x)w=!1;continue}if(k===De||k===Ne||k===Xe){w=!0,x=k,v+=y[E];continue}if(k===we&&E+1<y.length){let F=y.charCodeAt(E+1);if(F===Ie){let P=y.indexOf("*/",E+2);E=P===-1?y.length:P+1,v+=" ";continue}if(F===we){let P=y.indexOf(`
|
|
127
127
|
`,E+2);E=P===-1?y.length:P-1;continue}if(kt(y,E)){let P=bt(y,E);v+=y.slice(E,P),E=P-1;continue}}v+=y[E]}return v.trim()}function Ni(y){let v=y.slice(1,-1).trim();if(!v)return"()";if(y.indexOf(`
|
|
128
|
-
`)===-1&&v.indexOf(":")!==-1&&v.indexOf("{")===-1&&v.indexOf("[")===-1&&v.indexOf("=")===-1&&v.indexOf("@")===-1&&v.indexOf("...")===-1){let I=0,R=0,L=0;for(let
|
|
129
|
-
`,V);if(be===-1){L=L.slice(0,j).trimEnd();break}let ne=L.slice(0,j),oe=L.slice(be+1);L=`${ne}${oe}`,V=j-1}}}if(!L.trim())continue;P.push(
|
|
128
|
+
`)===-1&&v.indexOf(":")!==-1&&v.indexOf("{")===-1&&v.indexOf("[")===-1&&v.indexOf("=")===-1&&v.indexOf("@")===-1&&v.indexOf("...")===-1){let I=0,R=0,L=0;for(let J=0;J<v.length;J++){let U=v.charCodeAt(J);if(U===Ee||U===_e||U===se)L++;else if(U===Me||U===Ve||U===Ce)L--;else if(L===0){if(U===It)I++;else if(U===Bt)R++}}if(I>=R+1){let J=!1;for(let U=0;U<Gs.length;U++){let Q=Gs[U],j=v.indexOf(Q);if(j!==-1){let V=j+Q.length;if((j===0||!je(v.charCodeAt(j-1)))&&(V>=v.length||!je(v.charCodeAt(V)))){J=!0;break}}}if(!J)return y}}let w=[],x=0,E=0,k=!1,F=0;for(let I=0;I<=v.length;I++){if(I===v.length){w.push(Yr(v.slice(x).trim()));break}let R=v.charCodeAt(I);if(k){if(R===Tt){I++;continue}if(R===F)k=!1;continue}if(R===we&&I+1<v.length){let L=v.charCodeAt(I+1);if(L===Ie){I+=2;while(I+1<v.length&&!(v.charCodeAt(I)===Ie&&v.charCodeAt(I+1)===we))I++;I++;continue}if(L===we){while(I<v.length&&v.charCodeAt(I)!==10)I++;continue}if(kt(v,I)){I=bt(v,I)-1;continue}}if(R===De||R===Ne||R===Xe){k=!0,F=R;continue}if(R===Ee||R===se||R===Ge||R===_e)E++;else if(R===Me||R===Ce||R===Je||R===Ve&&!(I>0&&v.charCodeAt(I-1)===Ue))E--;else if(R===Bt&&E===0)w.push(Yr(v.slice(x,I).trim())),x=I+1}let P=[];for(let I of w){if(!I)continue;let R=I.trim();if(R.startsWith("//")||R.startsWith("/*"))continue;let L=I;{let J=!1,U=0,Q=0,j=0;for(let V=0;V<L.length-1;V++){let ie=L.charCodeAt(V);if(ie===Fe){j=V+1;continue}if(J){if(ie===Tt){V++;continue}if(ie===U)J=!1;continue}if(ie===De||ie===Ne||ie===Xe){J=!0,U=ie;continue}if(ie===se||ie===Ge||ie===Ee||ie===_e){Q++;continue}if(ie===Ce||ie===Je||ie===Me||ie===Ve){if(Q>0)Q--;continue}if(ie===we&&kt(L,V)){V=bt(L,V)-1;continue}if(ie===we&&L.charCodeAt(V+1)===we){if(Q===0){L=L.slice(0,V).trimEnd();break}let be=L.indexOf(`
|
|
129
|
+
`,V);if(be===-1){L=L.slice(0,j).trimEnd();break}let ne=L.slice(0,j),oe=L.slice(be+1);L=`${ne}${oe}`,V=j-1}}}if(!L.trim())continue;P.push(pl(L))}return En(`(${P.join(", ")})`)}function fh(y){if(!y.startsWith("{")&&!y.startsWith("["))return y;let v="",w=0,x=0,E=!1,k=0;while(w<y.length){let F=y.charCodeAt(w);if(E){if(F===Tt&&w+1<y.length){v+=y[w]+y[w+1],w+=2;continue}if(F===k)E=!1;v+=y[w],w++;continue}if(F===we&&w+1<y.length){let P=y.charCodeAt(w+1);if(P===Ie){let I=w;w+=2;while(w+1<y.length&&!(y.charCodeAt(w)===Ie&&y.charCodeAt(w+1)===we))w++;w=Math.min(w+2,y.length),v+=y.slice(I,w);continue}if(P===we){let I=w;while(w<y.length&&y.charCodeAt(w)!==10)w++;v+=y.slice(I,w);continue}}if(F===De||F===Ne||F===Xe){E=!0,k=F,v+=y[w],w++;continue}if(F===se||F===Ge||F===Ee)x++;else if(F===Ce||F===Je||F===Me)x--;if(x>=1&&F===Ue&&(w+1>=y.length||y.charCodeAt(w+1)!==Ue&&y.charCodeAt(w+1)!==Ve)){while(v.length>0&&(v[v.length-1]===" "||v[v.length-1]==="\t"||v[v.length-1]===`
|
|
130
130
|
`))v=v.slice(0,-1);w++;let P=0;while(w<y.length){let I=y.charCodeAt(w);if(I===we){if(y.charCodeAt(w+1)===we){let R=y.indexOf(`
|
|
131
|
-
`,w+2);w=R===-1?y.length:R+1;continue}if(y.charCodeAt(w+1)===Ie){let R=y.indexOf("*/",w+2);w=R===-1?y.length:R+2;continue}if(kt(y,w)){w=bt(y,w);continue}}if(I===De||I===Ne||I===Xe){let R=I;w++;while(w<y.length){if(y.charCodeAt(w)===Tt){w+=2;continue}if(y.charCodeAt(w)===R){w++;break}w++}continue}if(I===se||I===Ge||I===Ee)P++;else if(I===Ce||I===Je||I===Me){if(P===0)break;P--}else if(I===Bt&&P===0)break;w++}continue}v+=y[w],w++}return v}function
|
|
131
|
+
`,w+2);w=R===-1?y.length:R+1;continue}if(y.charCodeAt(w+1)===Ie){let R=y.indexOf("*/",w+2);w=R===-1?y.length:R+2;continue}if(kt(y,w)){w=bt(y,w);continue}}if(I===De||I===Ne||I===Xe){let R=I;w++;while(w<y.length){if(y.charCodeAt(w)===Tt){w+=2;continue}if(y.charCodeAt(w)===R){w++;break}w++}continue}if(I===se||I===Ge||I===Ee)P++;else if(I===Ce||I===Je||I===Me){if(P===0)break;P--}else if(I===Bt&&P===0)break;w++}continue}v+=y[w],w++}return v}function pl(y){let v=y.trim(),w=v.startsWith("...");if(w)v=v.slice(3).trim();while(v.startsWith("@")){let j=1;while(j<v.length&&je(v.charCodeAt(j)))j++;if(j<v.length&&v.charCodeAt(j)===Ee){let V=1;j++;while(j<v.length&&V>0){if(v.charCodeAt(j)===Ee)V++;else if(v.charCodeAt(j)===Me)V--;j++}}v=v.slice(j).trim()}let x=!0;while(x){x=!1;for(let j of Gs)if(v.startsWith(j)&&v.length>j.length&&!je(v.charCodeAt(j.length))){let V=v.slice(j.length).trim();if(V.charCodeAt(0)===It||V.charCodeAt(0)===_n&&V.length>1&&V.charCodeAt(1)===It)break;v=V,x=!0;break}}let E=-1,k=-1,F=0,P=!1,I=0;for(let j=0;j<v.length;j++){let V=v.charCodeAt(j);if(P){if(V===Tt){j++;continue}if(V===I)P=!1;continue}if(V===we&&j+1<v.length){let ie=v.charCodeAt(j+1);if(ie===Ie){j+=2;while(j+1<v.length&&!(v.charCodeAt(j)===Ie&&v.charCodeAt(j+1)===we))j++;j++;continue}if(ie===we){while(j<v.length&&v.charCodeAt(j)!==10)j++;continue}if(kt(v,j)){j=bt(v,j)-1;continue}}if(V===De||V===Ne||V===Xe){P=!0,I=V;continue}if(V===Ee||V===se||V===Ge||V===_e)F++;else if(V===Me||V===Ce||V===Je||V===Ve&&!(j>0&&v.charCodeAt(j-1)===Ue))F--;else if(F===0){if(V===It&&E===-1)E=j;else if(V===Ue&&k===-1&&(j===0||v.charCodeAt(j-1)!==Ue)&&(j+1>=v.length||v.charCodeAt(j+1)!==Ue&&v.charCodeAt(j+1)!==Ve))k=j}}let R,L,J=k!==-1;if(E!==-1&&(k===-1||E<k))if(R=v.slice(0,E).trim(),k!==-1)L=v.slice(E+1,k).trim();else L=v.slice(E+1).trim();else if(k!==-1){R=v.slice(0,k).trim();let j=w?null:Sr(R,v.slice(k+1));if(j)return An(j,hr);L=hr(v.slice(k+1).trim())}else R=v,L="unknown";if(R=fh(R),(R.startsWith("{")||R.startsWith("["))&&R.includes(`
|
|
132
132
|
`)){let j=R.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(j.length<=40)R=j;else R=R.split(`
|
|
133
133
|
`).map((V)=>{let ie=V.trim();if(!ie)return"";if(ie==="{"||ie==="}"||ie==="["||ie==="]"||ie.startsWith("}")||ie.startsWith("]"))return ie;return` ${ie}`}).join(`
|
|
134
|
-
`)}let U=R.endsWith("?")||
|
|
135
|
-
`,
|
|
136
|
-
`;if(w==="t")return"\t";if(w==="r")return"\r";if(w==="0")return"\x00";return w})}function
|
|
134
|
+
`)}let U=R.endsWith("?")||J;if(R.endsWith("?"))R=R.slice(0,-1).trim();let Q=U&&!w?"?":"";if(w)return`...${R}: ${L}`;return`${R}${Q}: ${L}`}function hr(y){let v=y.trim(),w=te(v);if(w)return w;if(v==="true"||v==="false")return"boolean";if(zt(v))return"number";if(v.startsWith("'")&&v.endsWith("'")||v.startsWith('"')&&v.endsWith('"'))return"string";if(v.startsWith("["))return"unknown[]";if(v.startsWith("{"))return"Record<string, unknown>";return ki(v)??"unknown"}function zo(y){let v=y.trim();if(v.endsWith("as const"))v=v.slice(0,-8).trim();if(v==="true"||v==="false")return v;if(zt(v))return xr(v);let w=uh(v);if(w!==null)return w;return ki(v)??"unknown"}function uh(y){if(y==="")return null;if(y.charCodeAt(0)===De||y.charCodeAt(0)===Ne){if(Or(y,0,y.charCodeAt(0))===y.length)return y}let v=dh(y,"+");if(v.length>1){let w=!1,x=!0,E=[];for(let k of v){let F=k.trim(),P=F.charCodeAt(0);if((P===De||P===Ne)&&Or(F,0,P)===F.length)w=!0,E.push(hh(F));else x=!1}if(x)return ph(E.join(""));if(w)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(y)&&/\d/.test(y)&&/[+*/%\-\s]/.test(y))return"number";return null}function dh(y,v){let w=[],x=0,E="",k=0;while(k<y.length){let F=y.charCodeAt(k);if(F===De||F===Ne||F===Xe){let P=Or(y,k,F);E+=y.slice(k,P),k=P;continue}if(F===we&&(y.charCodeAt(k+1)===we||y.charCodeAt(k+1)===42)){if(y.charCodeAt(k+1)===we){let R=y.indexOf(`
|
|
135
|
+
`,k+2),L=R===-1?y.length:R;E+=y.slice(k,L),k=L;continue}let P=y.indexOf("*/",k+2),I=P===-1?y.length:P+2;E+=y.slice(k,I),k=I;continue}if(F===Ee||F===Ge||F===se)x++;else if(F===Me||F===Je||F===Ce)x--;if(y[k]===v&&x===0){w.push(E),E="",k++;continue}E+=y[k],k++}return w.push(E),w}function hh(y){return y.slice(1,-1).replace(/\\(.)/g,(v,w)=>{if(w==="n")return`
|
|
136
|
+
`;if(w==="t")return"\t";if(w==="r")return"\r";if(w==="0")return"\x00";return w})}function ph(y){return`'${y.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function Xr(y){if(y.endsWith("as const"))return null;let v=0,w=-1;for(let x=0;x<y.length;x++){let E=y.charCodeAt(x);if(E===De||E===Ne||E===Xe)x=Or(y,x,E)-1;else if(E===123||E===91||E===40)v++;else if(E===125||E===93||E===41)v--;else if(v===0&&E===32&&x+4<=y.length&&y.substring(x,x+4)===" as ")w=x}if(w===-1)return null;return y.slice(w+4).trim()||null}function pr(){if(D(),c<f&&s.charCodeAt(c)===It){let y=function(){let E=fe(v,x),k=(F)=>{let P=E.length-F.length;return P>=0&&E.endsWith(F)&&(P===0||!je(E.charCodeAt(P-1)))};return E.length===0||E.endsWith("=>")||E.endsWith("|")||E.endsWith("&")||k("is")||k("extends")};c++,D();let v=c,w=0,x=v;while(c<f){let E=c;if(q()){if(s.charCodeAt(E)!==we)x=c;continue}let k=s.charCodeAt(c);if(k===Ee||k===Ge||k===_e)w++;else if(k===Me||k===Je||k===Ve&&!St())w--;else if(k===se)if(w>0)w++;else if(y())w++;else break;else if(k===Ce){if(w===0)break;w--}else if(w===0&&k===xe)break;if(w===0&&ge()&&!y())break;if(!it(k))x=c+1;c++}return fe(v,c)}return""}function ui(y,v,w,x){c+=8,D();let E=c<f&&s.charCodeAt(c)===Ie;if(E)c++,D();let k=me();if(!k&&!x)return null;D();let F=Vt();D();let P=fi();D();let I=pr(),R=I.length>0;if(!I)if(w&&E)I="AsyncGenerator<unknown, void, unknown>";else if(E)I="Generator<unknown, void, unknown>";else if(w)I="Promise<void>";else I="void";D();let L=!1;if(c<f&&s.charCodeAt(c)===se){L=!0;let V=c+1;if(et(se,Ce),!R&&!E){let ie=s.slice(V,c-1),be=Bp(ie,t??"stdin.ts",()=>{let ne;do ne=`__dtsx_return_${M++}`;while(s.includes(ne));return ne},(ne)=>g(ne.name,{...ne,start:c,end:c}),F);I=be.finish(Qt(ie,w,P,he,be.resolve))}}else if(c<f&&s.charCodeAt(c)===xe)c++;let J=Ni(P),U=`${v?x?"export default function ":"export declare function ":"declare function "}${k||(x?"":"default")}${F}${J}: ${I};`,Q=vt(y),j={kind:"function",name:k||"default",text:U,isExported:v,isDefault:x,isAsync:w,isGenerator:E,returnType:I,generics:F||void 0,leadingComments:Q,start:y,end:c};if(L)b.add(j);return j}let Ko,mh=0;function ml(){Ko??=new Set(ue(s).filter((y)=>y.kind==="word").map((y)=>s.slice(y.start,y.end)));for(;;){let y=`__dtsx_binding_${mh++}`;if(Ko.has(y))continue;return Ko.add(y),y}}function bi(y,v,w){c+=v.length,D();let x=[];do{if(D(),c>=f)break;let E=s.charCodeAt(c),k,F=c;if(E===se||E===Ge)et(E,E===se?Ce:Je),k=s.slice(F,c);let P=k?ml():me();if(!P)return tt(),x;D();let I,R,L,J=!1;if(c<f&&s.charCodeAt(c)===It){c++,D();let be=c,ne=0;while(c<f){if(q()){if(ne===0&&O())break;continue}let oe=s.charCodeAt(c);if(oe===Ee||oe===se||oe===Ge||oe===_e)ne++;else if(oe===Me||oe===Ce||oe===Je||oe===Ve&&!St())ne--;else if(ne===0&&(oe===xe||oe===Bt))break;else if(ne===0&&oe===Ue&&!Vo())break;if(ne===0&&(_()||ce()))break;c++}I=fe(be,c)}if(c<f&&s.charCodeAt(c)===Ue)if(l&&I&&(!a||!Up(I)))lh();else{c++,D();let be=c;L=be;let ne=0,oe=0,ke;while(c<f){if(ne===0&&oe===0&&H(be,ke))break;if(q())continue;let $e=s.charCodeAt(c);if($e===Ee||$e===se||$e===Ge)ne++;else if($e===Me||$e===Ce||$e===Je)ne--;else if($e===_e){A??=xi(s);let Ye=ne===0&&oe===0?A(c,be,ke):void 0;if(Ye?.parameters||Ye?.completeOperand||Ye&&t!==void 0&&!/\.[jt]sx$/.test(t)){c=Ye.end,ke=Ye.completeOperand?Ye.end:void 0;continue}let $i=oe>0||s[c+1]!=="/"&&br(s,c)?u(c):null;if($i){if(oe=Math.max(0,oe+$i.delta),c=$i.end+1,oe===0)ke=c;continue}else if(oe===0){if(Ye){c=Ye.end,ke=Ye.completeOperand?Ye.end:void 0;continue}}}else if(ne===0&&oe===0&&($e===xe||$e===Bt))break;c++}if(R=qe(fe(be,c)),R.endsWith(" as const")||R==="const"){if(J=!0,!I){let $e=R.endsWith(" as const")?R.slice(0,-9).trim():R,Ye=zo($e);I=Ye!=="unknown"?Ye:void 0}}else if(!I){let $e=Wn(R)??Xr(R)??he(R);if($e)I=$e}}let U=x.length===0?vt(y):void 0,Q=k?"const":v,j=k?!1:w,V=`${j?"export ":""}declare ${Q} ${P}: ${I||"unknown"};`,ie={kind:"variable",name:P,text:V,isExported:j,typeAnnotation:I,value:R,initializerStart:L,modifiers:J?[Q,"const assertion"]:[Q],leadingComments:k?void 0:U,start:y,end:c};if(k)x.push(...Vl({pattern:k,patternOffset:F,root:ie,kind:v,exported:w,comments:U,allocateName:ml}));else x.push(ie);if(s.charCodeAt(c)===Bt){c++;continue}if(s.charCodeAt(c)===xe)c++;break}while(c<f);return x}function Ho(y,v){c+=9,D();let w=me();D();let x=Vt();D();let E="";if(W("extends")){c+=7,D();let R=c,L=0;while(c<f){if(q())continue;let J=s.charCodeAt(c);if(J===_e)L++;else if(J===Ve&&!St())L--;else if(J===se&&L===0)break;c++}E=fe(R,c)}D();let k=c<f&&s.charCodeAt(c)===se?Uo():"{}",F=hl(k),P=`${v?"export ":""}declare interface ${w}${x}${E?` extends ${E}`:""} ${F}`,I=vt(y);return{kind:"interface",name:w,text:P,isExported:v,extends:E||void 0,generics:x||void 0,leadingComments:I,start:y,end:c}}function qo(y,v){c+=4,D();let w=me();D();let x=Vt();if(D(),c<f&&s.charCodeAt(c)===Ue)c++;D();let E=c,k=0;while(c<f){if(q())continue;let R=s.charCodeAt(c);if(R===Ee||R===se||R===Ge||R===_e)k++;else if(R===Me||R===Ce||R===Je||R===Ve&&!St())k--;else if(k===0&&R===xe)break;if(k===0&&(_()||ce()))break;c++}let F=fe(E,c);if(c<f&&s.charCodeAt(c)===xe)c++;let P=`${v?"export ":""}type ${w}${x} = ${F}`,I=vt(y);return{kind:"type",name:w,text:P,isExported:v,generics:x||void 0,leadingComments:I,start:y,end:c}}function Fi(y,v,w){c+=4,D();let x=me();D();let E=c;if(c<f&&s.charCodeAt(c)===se)et(se,Ce);let k=fe(y,c),F=vt(y);return{kind:"enum",name:x,text:k,isExported:v,modifiers:w?["const"]:void 0,leadingComments:F,start:y,end:c}}function di(y,v,w,x=!1){c+=5,D();let E=me()||"AnonymousClass";D();let k=Vt();D();let F="";if(W("extends")){c+=7,D();let J=c,U=0;while(c<f){if(q())continue;let Q=s.charCodeAt(c);if(Q===_e)U++;else if(Q===Ve&&!St())U--;else if(U===0&&(Q===se||W("implements")))break;c++}F=fe(J,c)}let P;if(W("implements")){c+=10,D();let J=c,U=0;while(c<f){if(q())continue;let j=s.charCodeAt(c);if(j===_e)U++;else if(j===Ve&&!St())U--;else if(U===0&&j===se)break;c++}let Q=fe(J,c);if(Q)P=Q.split(",").map((j)=>j.trim())}D();let I=Yo(E),R=`${v?x?"export default ":"export declare ":"declare "}${w?"abstract ":""}class ${E}${k}${F?` extends ${F}`:""}${P&&P.length>0?` implements ${P.join(", ")}`:""} ${I}`,L=vt(y);return{kind:"class",name:E,text:R,isExported:v,isDefault:x,extends:F||void 0,implements:P,generics:k||void 0,modifiers:w?["abstract"]:void 0,leadingComments:L,start:y,end:c}}let Jo;function Yo(y){if(c>=f||s.charCodeAt(c)!==se)return"{}";c++;let v={name:y,fields:new Map,pending:[],isStatic:!1};S.push(v);let w=[],x=new Set;while(c<f){if(D(),c>=f)break;if(s.charCodeAt(c)===Ce){c++;break}if(s.charCodeAt(c)===xe){c++;continue}if(Jo=vt(c),W("static")&&Qr("static")===se){c+=6,D(),et(se,Ce);continue}let E=!1,k=!1,F=!1,P=!1,I=!1,R=!1,L=!1,J=!1,U=!0;while(U){D();let ne=c,oe=me();if(c=ne,oe){let ke=Qr(oe);if(ke===Ee||ke===_e||ke===_n||ke===33||ke===It||ke===Ue||ke===xe||ke===Ce)break}if(W("private")){E=!0,c+=7;continue}if(W("protected")){k=!0,c+=9;continue}if(W("public")){c+=6;continue}if(W("static")){F=!0,c+=6;continue}if(W("abstract")){P=!0,c+=8;continue}if(W("readonly")){I=!0,c+=8;continue}if(W("override")){R=!0,c+=8;continue}if(W("accessor")){L=!0,c+=8;continue}if(W("async")){J=!0,c+=5;continue}if(W("declare")){c+=7;continue}break}if(D(),c>=f||s.charCodeAt(c)===Ce)break;let Q=c;if(v.isStatic=F,(W("get")||W("set"))&&Xo(Qr(s.slice(c,c+3))))c+=3,D();if(s.charCodeAt(c)===Ie)c++,D();let j=Zr();c=Q;let V=j.startsWith("#");if(V)E=!0;if(E&&j&&j!=="constructor"){let ne=V?F?" static #private_static;":" #private;":` private ${F?"static ":""}${j};`,oe=j[0]==="'"||j[0]==='"'?$t(j)??j:j,ke=V?`${F?"static":"instance"}#`:`${F?"static:":"instance:"}${oe}`;if(!x.has(ke))x.add(ke),w.push(ne)}let ie=E?[]:w,be=" ";if(k)be+="protected ";if(F)be+="static ";if(P)be+="abstract ";if(I)be+="readonly ";if(W("constructor")){c+=11,D();let ne=fi();if(D(),yh(ne,w),c<f&&s.charCodeAt(c)===se)et(se,Ce);else if(c<f&&s.charCodeAt(c)===xe)c++;let oe=Ni(ne);w.push(E?" private constructor();":` ${k?"protected ":""}constructor${oe};`)}else if(W("get"))if(c+=3,D(),c<f&&Xo(s.charCodeAt(c))){let ne=Zr();if(ne.startsWith("#")){if(D(),c<f&&s.charCodeAt(c)===Ee)fi();if(D(),pr(),D(),c<f&&s.charCodeAt(c)===se)et(se,Ce);else if(c<f&&s.charCodeAt(c)===xe)c++;continue}D(),fi(),D();let oe=pr(),ke;if(D(),c<f&&s.charCodeAt(c)===se){let Ye=c+1;if(et(se,Ce),!oe&&!l)ke=s.slice(Ye,c-1),oe=Qt(ke,!1,"()",($i)=>Ae($i,F))}else if(c<f&&s.charCodeAt(c)===xe)c++;let $e=ie.length;if(ie.push(`${be}get ${ne}(): ${ke?Zt(oe):oe||"unknown"};`),ke)v.pending.push(()=>{let Ye=Qt(ke,!1,"()",($i)=>Ae($i,F));ie[$e]=`${be}get ${ne}(): ${Zt(Ye)};`})}else yl("get",be,F,I,J,ie);else if(W("set"))if(c+=3,D(),c<f&&Xo(s.charCodeAt(c))){let ne=Zr();if(ne.startsWith("#")){if(D(),c<f&&s.charCodeAt(c)===Ee)fi();if(D(),c<f&&s.charCodeAt(c)===se)et(se,Ce);else if(c<f&&s.charCodeAt(c)===xe)c++;continue}D();let oe=fi();if(D(),c<f&&s.charCodeAt(c)===se)et(se,Ce);else if(c<f&&s.charCodeAt(c)===xe)c++;let ke=Ni(oe);ie.push(`${be}set ${ne}${ke};`)}else yl("set",be,F,I,J,ie);else{let ne=s.charCodeAt(c)===Ie;if(ne)c++,D();let oe=Zr();if(!oe){gl();continue}wl(oe,be,F,I,ne,P,J,ie)}}for(let E of v.pending)E();return S.pop(),`{
|
|
137
137
|
${w.join(`
|
|
138
138
|
`)}
|
|
139
|
-
}`}function Xo(y){return ht(y)||y===Ge||y===
|
|
140
|
-
${
|
|
139
|
+
}`}function Xo(y){return ht(y)||y===Ge||y===zc||y===De||y===Ne}function Zr(){if(c>=f)return"";let y=s.charCodeAt(c);if(y===Ge){let v=c;return et(Ge,Je),s.slice(v,c)}if(y===zc)return c++,`#${me()}`;if(y===De||y===Ne){let v=c;return G(y),s.slice(v,c)}return me()}function Qr(y){let v=c;c+=y.length,D();let w=c<f?s.charCodeAt(c):0;return c=v,w}function gl(){let y=0;while(c<f){if(q())continue;let v=s.charCodeAt(c);if(v===se||v===Ee)y++;else if(v===Ce||v===Me){if(y===0)return;y--}else if(v===xe&&y===0){c++;return}if(y===0&&ge())return;c++}}function yl(y,v,w,x,E,k){wl(y,v,w,x,!1,!1,E,k)}function wl(y,v,w,x,E,k,F,P){let I=Jo;if(Jo=void 0,D(),c>=f)return;let R=s.charCodeAt(c),L=!1;if(R===_n)L=!0,c++,D();if(c<f&&s.charCodeAt(c)===33)c++,D();let J=c<f?s.charCodeAt(c):0;if(J===Ee||J===_e){let U=J===_e?Vt():"";D();let Q=fi();D();let j=pr(),V,ie=j.length>0;if(!j)if(F&&E)j="AsyncGenerator<unknown, void, unknown>";else if(E)j="Generator<unknown, void, unknown>";else if(F)j="Promise<void>";else j="void";if(D(),c<f&&s.charCodeAt(c)===se){let ke=c+1;if(et(se,Ce),!ie&&!E)V=s.slice(ke,c-1),j=Qt(V,F,Q,($e)=>Ae($e,w))}else if(c<f&&s.charCodeAt(c)===xe)c++;let be=Ni(Q),ne=L?"?":"",oe=P.length;if(P.push(`${v}${y}${ne}${U}${be}: ${V?Zt(j):j};`),V)S.at(-1)?.pending.push(()=>{let ke=Qt(V,F,Q,($e)=>Ae($e,w));P[oe]=`${v}${y}${ne}${U}${be}: ${Zt(ke)};`})}else if(J===It||J===Ue||J===xe||J===Ce||J===Fe||J===ze){let U="";if(J===It){c++,D();let be=c,ne=0;while(c<f){if(q())continue;let oe=s.charCodeAt(c);if(oe===Ee||oe===se||oe===Ge||oe===_e)ne++;else if(oe===Me||oe===Ce||oe===Je||oe===Ve&&!St()){if(ne===0)break;ne--}else if(ne===0&&(oe===xe||oe===Bt))break;else if(ne===0&&oe===Ue&&!Vo())break;if(ne===0&&ge())break;c++}U=fe(be,c)}let Q="";if(c<f&&s.charCodeAt(c)===Ue)if(l&&U){c++;let be=0;while(c<f){if(q())continue;let ne=s.charCodeAt(c);if(ne===Ee||ne===se||ne===Ge)be++;else if(ne===Me||ne===Ce||ne===Je){if(be===0&&ne===Ce)break;be--}else if(be===0&&ne===xe)break;if(be===0&&ge())break;c++}}else{c++,D();let be=c,ne=0;while(c<f){if(q())continue;let oe=s.charCodeAt(c);if(oe===Ee||oe===se||oe===Ge)ne++;else if(oe===Me||oe===Ce||oe===Je){if(ne===0&&oe===Ce)break;ne--}else if(ne===0&&oe===xe)break;if(ne===0&&ge())break;c++}Q=fe(be,c)}if(c<f&&s.charCodeAt(c)===xe)c++;let j=U.length>0;if(!U)if(Q){let be=Xr(Q);if(be)U=be;else if(Q.startsWith("new "))U=K(Q);else if(U=Q.endsWith("as const")||w&&x?zo(Q):hr(Q),U==="unknown"&&Kc(Q)&&!Q.includes("."))U=K(Q,!0)}else U="unknown";let V=L?"?":"";S.at(-1)?.fields.set(`${w?"static:":""}${y}`,L?`(${U}) | undefined`:U);let ie=a&&!j&&Q?Ws(I,Q,U):"";P.push(`${ie}${v}${y}${V}: ${U};`)}else gl()}function gh(y){let v=0;for(let w=0;w<y.length;w++){let x=y.charCodeAt(w);if(x===Ee||x===se||x===Ge||x===_e)v++;else if(x===Me||x===Ce||x===Je||x===Ve&&y.charCodeAt(w-1)!==Ue)v--;else if(x===Ue&&v===0&&y.charCodeAt(w+1)!==Ve&&y.charCodeAt(w+1)!==Ue)return!0}return!1}function yh(y,v){let w=y.slice(1,-1).trim();if(!w)return;let x=[],E=0,k=0,F=!1,P=0,I=[];for(let R=0;R<=w.length;R++){if(R===w.length){I.push(w.slice(E)),x.push(Yr(w.slice(E).trim()));break}let L=w.charCodeAt(R);if(F){if(L===Tt){R++;continue}if(L===P)F=!1;continue}if(L===we&&R+1<w.length){let J=w.charCodeAt(R+1);if(J===Ie){R+=2;while(R+1<w.length&&!(w.charCodeAt(R)===Ie&&w.charCodeAt(R+1)===we))R++;R++;continue}if(J===we){while(R<w.length&&w.charCodeAt(R)!==10)R++;continue}}if(L===De||L===Ne||L===Xe){F=!0,P=L;continue}if(L===Ee||L===se||L===Ge||L===_e)k++;else if(L===Me||L===Ce||L===Je||L===Ve&&!(R>0&&w.charCodeAt(R-1)===Ue))k--;else if(L===Bt&&k===0)I.push(w.slice(E,R)),x.push(Yr(w.slice(E,R).trim())),E=R+1}for(let[R,L]of x.entries()){let J=L.startsWith("public ")||L.startsWith("public\t"),U=L.startsWith("protected ")||L.startsWith("protected\t"),Q=L.startsWith("private ")||L.startsWith("private\t"),j=L.includes("readonly ");if(!J&&!U&&!Q&&!j)continue;let V=L,ie=[];if(Q){let $e=7;while($e<V.length&&it(V.charCodeAt($e)))$e++;V=V.slice($e),ie.push("private")}if(J){let $e=6;while($e<V.length&&it(V.charCodeAt($e)))$e++;V=V.slice($e),ie.push("public")}if(U){let $e=9;while($e<V.length&&it(V.charCodeAt($e)))$e++;V=V.slice($e),ie.push("protected")}if(j){let $e=V.indexOf("readonly ");if($e!==-1){let Ye=$e+8;while(Ye<V.length&&it(V.charCodeAt(Ye)))Ye++;V=V.slice(0,$e)+V.slice(Ye)}ie.push("readonly")}let be=ie.length>0?`${ie.join(" ")} `:"",ne=pl(V),oe=V.search(/[?:=]/);if(oe!==-1&&V.charCodeAt(oe)!==63&&gh(V))ne=ne.replace(/^([\w$]+)\?:/,"$1:");let ke="";if(a&&!Q&&oe!==-1&&V.charCodeAt(oe)===Ue){let $e=V.slice(oe+1);ke=Ws(Sc(I[R]),$e,hr($e))}v.push(Q?` private ${ne.split(/[?:]/,1)[0]};`:`${ke} ${be}${ne};`)}}function Zo(y=" ",v="",w=!1){if(c>=f||s.charCodeAt(c)!==se)return"{}";c++;let x=N.at(-1)?.path,E={path:x?`${x}.${v}`:v,bindings:new Map,exports:new Set,annotatedValues:new Set,ambient:w||N.at(-1)?.ambient===!0};T.push(E),N.push(E);let k=[];while(c<f){if(D(),c>=f)break;if(s.charCodeAt(c)===Ce){c++;break}if(s.charCodeAt(c)===xe){c++;continue}let F=!1;if(W("export"))F=!0,c+=6,D();let P=!1;if(W("declare"))P=!0,c+=7,D();let I=F?"export ":"";if(W("function")||W("async")&&wh("async","function")){let R=!1;if(W("async"))R=!0,c+=5,D();if(c+=8,D(),c<f&&s.charCodeAt(c)===Ie)c++,D();let L=me();D();let J=Vt();D();let U=fi();D();let Q=pr();if(!Q)Q=R?"Promise<void>":"void";if(D(),c<f&&s.charCodeAt(c)===se)et(se,Ce);else if(c<f&&s.charCodeAt(c)===xe)c++;let j=Ni(U);k.push(`${y}${I}function ${L}${J}${j}: ${Q};`)}else if(W("const")||W("let")||W("var")){let R=W("const")?"const":W("let")?"let":"var";c+=R.length,D();let L=me();if(E.bindings.set(L,"value"),F||E.ambient)E.exports.add(L);if(!L){tt(!0);continue}D();let J="";if(c<f&&s.charCodeAt(c)===It){c++,D();let Q=c,j=0;while(c<f){if(q())continue;let V=s.charCodeAt(c);if(V===Ee||V===se||V===Ge||V===_e)j++;else if(V===Ce&&j===0)break;else if(V===Me||V===Ce||V===Je||V===Ve&&!St())j--;else if(j===0&&(V===xe||V===Bt))break;else if(j===0&&V===Ue&&!Vo())break;if(j===0&&_())break;c++}J=fe(Q,c)}if(J)E.annotatedValues.add(L);let U="";if(c<f&&s.charCodeAt(c)===Ue){c++,D();let Q=c,j=0;while(c<f){if(q())continue;let V=s.charCodeAt(c);if(V===Ee||V===se||V===Ge||V===_e)j++;else if(V===Ce&&j===0)break;else if(V===Me||V===Ce||V===Je||V===Ve&&!St())j--;else if(j===0&&(V===xe||V===Bt))break;if(j===0&&_())break;c++}U=fe(Q,c)}if(c<f&&s.charCodeAt(c)===xe)c++;if(!J&&U){let Q=Xr(U);if(Q)J=Q;else if(R==="const")J=zo(U);else J=hr(U)}if(!J)J="unknown";k.push(`${y}${I}${R} ${L}: ${J};`)}else if(W("interface")){c+=9,D();let R=me();D();let L=Vt();D();let J="";if(W("extends")){c+=7,D();let Q=c,j=0;while(c<f){if(q())continue;let V=s.charCodeAt(c);if(V===_e)j++;else if(V===Ve&&!St())j--;else if(V===se&&j===0)break;c++}J=fe(Q,c)}let U=hl(Uo());k.push(`${y}${I}interface ${R}${L}${J?` extends ${J}`:""} ${U}`)}else if(W("type")){c+=4,D();let R=me();D();let L=Vt();if(D(),c<f&&s.charCodeAt(c)===Ue){c++,D();let J=c,U=0;while(c<f){if(q())continue;let j=s.charCodeAt(c);if(j===Ee||j===se||j===Ge||j===_e)U++;else if(j===Ce&&U===0)break;else if(j===Me||j===Ce||j===Je||j===Ve&&!St())U--;else if(U===0&&j===xe)break;if(U===0&&_())break;c++}let Q=fe(J,c);if(c<f&&s.charCodeAt(c)===xe)c++;k.push(`${y}${I}type ${R}${L} = ${Q}`)}}else if(W("class")){c+=5,D();let R=me();D();let L=Vt();D();let J=c,U=0;while(c<f){if(q())continue;let ie=s.charCodeAt(c);if(ie===_e)U++;else if(ie===Ve&&!St())U--;else if(ie===se&&U===0)break;c++}let Q=fe(J,c),j=Q?` ${Q}`:"";if(E.bindings.set(R,"class"),F||E.ambient)E.exports.add(R);let V=Yo(R);k.push(`${y}${I}class ${R}${L}${j} ${V}`)}else if(W("enum")){c+=4,D();let R=me();D();let L=Uo();k.push(`${y}${I}enum ${R} ${L}`)}else if(W("namespace")||W("module")){let R=W("namespace")?"namespace":"module";c+=R.length,D();let L=me();if(!E.bindings.has(L))E.bindings.set(L,"namespace");if(F||E.ambient)E.exports.add(L);D();let J=Zo(y,L,P);k.push(`${y}${I}${R} ${L} ${J}`)}else if(W("abstract"))if(c+=8,D(),W("class")){c+=5,D();let R=me();D();let L=Vt();D();let J=c,U=0;while(c<f){if(q())continue;let ie=s.charCodeAt(c);if(ie===_e)U++;else if(ie===Ve&&!St())U--;else if(ie===se&&U===0)break;c++}let Q=fe(J,c),j=Q?` ${Q}`:"";if(E.bindings.set(R,"class"),F||E.ambient)E.exports.add(R);let V=Yo(R);k.push(`${y}${I}abstract class ${R}${L}${j} ${V}`)}else tt(!0);else if(F&&W("default")){c+=7,D();let R=c;tt(!0);let L=fe(R,c);if(L.charCodeAt(L.length-1)===xe)L=L.slice(0,-1);if(L)k.push(`${y}export default ${L};`)}else if(!F&&(s.charCodeAt(c)===De||s.charCodeAt(c)===Ne||s.charCodeAt(c)===Xe))tt(!0);else tt(!0)}if(N.pop(),k.length===0)return"{}";return`{
|
|
140
|
+
${k.join(`
|
|
141
141
|
`)}
|
|
142
|
-
}`}function yh(y,v){let w=c+y.length;while(w<f&&it(s.charCodeAt(w)))w++;for(let x=0;x<v.length;x++)if(w+x>=f||s.charCodeAt(w+x)!==v.charCodeAt(x))return!1;return w+v.length>=f||!je(s.charCodeAt(w+v.length))}function Wi(y,v,w){c+=w.length,D();let x="",E=s.charCodeAt(c);if(E===De||E===Ne){let U=c;G(E),x=s.slice(U,c)}else{x=me();while(c<f&&s.charCodeAt(c)===Ui)c++,x+=`.${me()}`}D();let T=ue(s.slice(y,c)),F=T.findIndex((U)=>U.kind==="word"&&["namespace","module"].includes(s.slice(y+U.start,y+U.end))),P=T.slice(0,F).some((U)=>U.kind==="word"&&s.slice(y+U.start,y+U.end)==="declare"),I=c<f&&s.charCodeAt(c)===se?Zo(" ",x,P):"{}",R=`${v?"export ":""}declare ${w} ${x} ${I}`,L=vt(y),Y=x.startsWith("'")||x.startsWith('"');return{kind:"module",name:x,text:R,isExported:v,moduleForm:Y?"quoted":w==="namespace"?"namespace":"identifier",source:Y?x.slice(1,-1):void 0,leadingComments:L,start:y,end:c}}function wl(y,v){tt();let w=fe(v,c);if(w.charCodeAt(w.length-1)===xe)w=w.slice(0,-1).trimEnd();if(!w)return;let x=ht(w.charCodeAt(0));for(let R=1;x&&R<w.length;R++)x=je(w.charCodeAt(R));let E=vt(y);if(x){h.push({kind:"export",name:"default",text:`export default ${w};`,isExported:!0,isTypeOnly:!1,leadingComments:E,start:y,end:c});return}let T="__dtsx_default_export__",F=1;while(s.includes(T))T=`__dtsx_default_export_${F++}__`;let P=Xr(w)||he(w)||Te(w,!1),I=P==="unknown"&&zc(w)?`typeof ${w}`:P;h.push({kind:"variable",name:T,text:`declare const ${T}: ${I};`,isExported:!1,typeAnnotation:I,modifiers:["const"],start:y,end:c}),h.push({kind:"export",name:"default",text:`export default ${T};`,isExported:!0,isTypeOnly:!1,leadingComments:E,start:y,end:c})}function Cl(){if(s.charCodeAt(c)===se)return et(se,Ce),!0;let y=W("if"),v=W("do"),w=W("try"),x=W("for");if(!y&&!v&&!w&&!x&&!W("while")&&!W("switch")&&!W("with"))return!1;if(me(),D(),x&&W("await"))c+=5,D();if(!v&&!w&&s.charCodeAt(c)===Ee)et(Ee,Me);if(en(),D(),y&&W("else"))c+=4,en();else if(v&&W("while")){if(c+=5,D(),s.charCodeAt(c)===Ee)et(Ee,Me);if(D(),s.charCodeAt(c)===xe)c++}else if(w){if(W("catch")){if(c+=5,D(),s.charCodeAt(c)===Ee)et(Ee,Me);en(),D()}if(W("finally"))c+=7,en()}return!0}function en(){if(D(),!Cl())tt()}while(c<f){if(D(),c>=f)break;if(Cl())continue;let y=c,v=s.charCodeAt(c);if(v===105&&W("import"))h.push(lh(y));else if(v===101&&W("export")){c+=6,D();let w=s.charCodeAt(c);if(w===100&&W("default")){c+=7,D();let x=c,E=s.charCodeAt(c);if(E===102&&W("function")){let T=ui(y,!0,!1,!0);if(T)h.push(T)}else if(E===97&&W("async")&&Qr("async")!==xe)if(c+=5,D(),W("function")){let T=ui(y,!0,!0,!0);if(T)h.push(T)}else wl(y,x);else if(E===99&&W("class")){let T=di(y,!0,!1,!0);h.push(T)}else if(E===97&&W("abstract")){if(c+=8,D(),W("class")){let T=di(y,!0,!0,!0);h.push(T)}}else wl(y,x)}else if(w===116&&W("type")){let x=c;if(c+=4,D(),c<f&&s.charCodeAt(c)===se){cl();let E=fe(y,c),T=vt(y);h.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:!0,source:Jr(E),leadingComments:T,start:y,end:c})}else if(c<f&&s.charCodeAt(c)===Ie){fl();let E=fe(y,c);h.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:!0,source:Jr(E),start:y,end:c})}else{c=x;let E=qo(y,!0);h.push(E)}}else if(w===105&&W("interface")){let x=Ho(y,!0);h.push(x)}else if(w===102&&W("function")){let x=ui(y,!0,!1,!1);if(x)h.push(x)}else if(w===97&&W("async"))if(c+=5,D(),W("function")){let x=ui(y,!0,!0,!1);if(x)h.push(x)}else tt();else if(w===99)if(W("class")){let x=di(y,!0,!1);h.push(x)}else if(W("const")){let x=c;if(c+=5,D(),W("enum")){c=x+5,D();let E=Fi(y,!0,!0);h.push(E)}else{c=x;let E=bi(y,"const",!0);for(let T=0;T<E.length;T++)h.push(E[T])}}else tt();else if(w===97&&W("abstract")){if(c+=8,D(),W("class")){let x=di(y,!0,!0);h.push(x)}}else if(w===108&&W("let")){let x=bi(y,"let",!0);for(let E=0;E<x.length;E++)h.push(x[E])}else if(w===118&&W("var")){let x=bi(y,"var",!0);for(let E=0;E<x.length;E++)h.push(x[E])}else if(w===101&&W("enum")){let x=Fi(y,!0,!1);h.push(x)}else if(w===100&&W("declare"))c+=7,D(),bl(y,!0);else if(w===110&&W("namespace")&&Qe(9)){let x=Wi(y,!0,"namespace");h.push(x)}else if(w===109&&W("module")&&Qe(6)){let x=Wi(y,!0,"module");h.push(x)}else if(w===se){cl();let x=fe(y,c),E=x.includes("export type"),T=vt(y);h.push({kind:"export",name:"",text:x,isExported:!0,isTypeOnly:E,source:Jr(x),leadingComments:T,start:y,end:c})}else if(w===Ie){fl();let x=fe(y,c),E=vt(y);h.push({kind:"export",name:"",text:x,isExported:!0,isTypeOnly:!1,source:Jr(x),leadingComments:E,start:y,end:c})}else{tt();let x=fe(y,c);if(x)h.push({kind:"export",name:"",text:x,isExported:!0,start:y,end:c})}}else if(v===100&&W("declare"))c+=7,D(),bl(y,!1);else if(v===105&&W("interface")){let w=Ho(y,!1);g(w.name,w)}else if(v===116&&W("type")){let w=qo(y,!1);g(w.name,w),h.push(w)}else if(v===102&&W("function")){let w=ui(y,!1,!1,!1);if(w)Se(w);else tt()}else if(v===97)if(W("async")){let w=c;if(c+=5,D(),W("function")){let x=ui(y,!1,!0,!1);if(x)Se(x);else c=w,tt()}else c=w,tt()}else if(W("abstract"))if(c+=8,D(),W("class")){let w=di(y,!1,!1);g(w.name,w),h.push(w)}else tt();else c++,tt();else if(v===99)if(W("class")){let w=di(y,!1,!1);g(w.name,w),h.push(w)}else if(W("const")){let w=c;if(c+=5,D(),W("enum")){c=w+5,D();let x=Fi(y,!1,!0);g(x.name,x),h.push(x)}else{c=w;let x=bi(y,"const",!1);for(let E=0;E<x.length;E++)g(x[E].name,x[E])}}else c++,tt();else if(v===101&&W("enum")){let w=Fi(y,!1,!1);g(w.name,w),h.push(w)}else if(v===108&&W("let")||v===118&&W("var")){let w=W("let")?"let":"var",x=bi(y,w,!1);for(let E=0;E<x.length;E++)g(x[E].name,x[E])}else if(v===109&&W("module")&&Qe(6)){let w=Wi(y,!1,"module");h.push(w)}else if(v===110&&W("namespace")&&Qe(9)){let w=Wi(y,!1,"namespace");h.push(w)}else{let w=s.charCodeAt(c);if(w===xe)c++;else if(w===De||w===Ne){if(G(w),c<f&&s.charCodeAt(c)===xe)c++}else if(w===Xe){if(Z(),c<f&&s.charCodeAt(c)===xe)c++}else if(w===jp){if(c++,me(),D(),c<f&&s.charCodeAt(c)===Ui)c++,me(),D();if(c<f&&s.charCodeAt(c)===Ee)et(Ee,Me)}else c++,tt()}}if(B.length){let y=new Set([...h,...p.values()]),v=new Set([...y].filter((P)=>P.kind==="class").map((P)=>P.name)),w=new Set([...y].filter((P)=>P.kind==="variable"&&!!P.typeAnnotation).map((P)=>P.name)),x=new Set,E=new Map;for(let P of O)for(let[I,R]of P.bindings){let L=P.path?`${P.path}.${I}`:I;if(P.exports.has(I)&&(R!=="namespace"||!E.has(L)))E.set(L,R);if(P.exports.has(I)&&P.annotatedValues.has(I))x.add(L)}let T=new Map;for(let P of B){if(P.binding){let I=w.has(P.initializer);for(let R=P.namespaces.length-1;R>=0;R--){let L=P.namespaces[R],Y=L.path?`${L.path}.${P.initializer}`:P.initializer;if(L.bindings.has(P.initializer)||E.has(Y)){I=L.bindings.has(P.initializer)?L.annotatedValues.has(P.initializer):x.has(Y);break}}T.set(P.marker,I?`typeof ${P.initializer}`:"unknown");continue}T.set(P.marker,Fs(P.initializer,(I)=>{if(P.classes.includes(I))return!0;for(let R=P.namespaces.length-1;R>=0;R--){let L=P.namespaces[R],Y=L.path?`${L.path}.${I}`:I,U=I.split(".")[0],Q=L.bindings.get(U);if(Q){if(I===U&&Q!=="namespace")return Q==="class";return E.get(Y)==="class"}let j=L.path?`${L.path}.${U}`:U;if(E.has(j))return E.get(Y)==="class"}return E.has(I)?E.get(I)==="class":v.has(I)}))}let F=(P)=>{if(!P.includes("__dtsx_constructor_field_"))return P;let I="",R=0;for(let L of ue(P)){if(L.kind!=="word")continue;let Y=T.get(P.slice(L.start,L.end));if(!Y)continue;I+=P.slice(R,L.start)+Y,R=L.end}return I+P.slice(R)};for(let P of y){P.text=F(P.text);for(let I of["typeAnnotation","inferredType","returnType"])if(P[I])P[I]=F(P[I])}}if(b.size>0){vl(h);for(let y of C.values())vl(y)}if(Tc(s,h,p,C),Ql(h,p),Ul(h,p),!l)Gc(s,h,p,o);if(n){let y=new Set(h);for(let v of[...p.values(),...[...C.values()].flat(),...[...m.values()].flat()])if(!y.has(v))h.push(v),y.add(v);return h.sort((v,w)=>(v.start??0)-(w.start??0))}if(p.size>0)Up(h,p,C,m,d);return h;function vl(y){let v=new Map;for(let x of y)if(x.kind==="function")v.set(x.name,(v.get(x.name)||0)+1);let w=new Set;for(let[x,E]of v)if(E>1)w.add(x);if(w.size>0){let x=new Set;for(let E of w)for(let T=y.length-1;T>=0;T--)if(y[T].kind==="function"&&y[T].name===E&&b.has(y[T])){x.add(T);break}if(x.size>0){let E=[...x].sort((T,F)=>F-T);for(let T of E)y.splice(T,1)}}}function bl(y,v){if(W("function")){let w=ui(y,v,!1,!1);if(w)h.push(w)}else if(W("async")){if(c+=5,D(),W("function")){let w=ui(y,v,!0,!1);if(w)h.push(w)}}else if(W("class")){let w=di(y,v,!1);h.push(w)}else if(W("abstract")){if(c+=8,D(),W("class")){let w=di(y,v,!0);h.push(w)}}else if(W("interface")){let w=Ho(y,v);h.push(w)}else if(W("type")){let w=qo(y,v);h.push(w)}else if(W("enum")){let w=Fi(y,v,!1);h.push(w)}else if(W("const")){let w=c;if(c+=5,D(),W("enum")){c=w+5,D();let x=Fi(y,v,!0);h.push(x)}else{c=w;let x=bi(y,"const",v);for(let E=0;E<x.length;E++)if(v||!d)h.push(x[E]);else g(x[E].name,x[E])}}else if(W("let")||W("var")){let w=W("let")?"let":"var",x=bi(y,w,v);for(let E=0;E<x.length;E++)if(v||!d)h.push(x[E]);else g(x[E].name,x[E])}else if(W("module")){let w=Wi(y,v,"module");h.push(w)}else if(W("namespace")){let w=Wi(y,v,"namespace");h.push(w)}else if(W("global")){c+=6,D();let w=`declare global ${c<f&&s.charCodeAt(c)===se?Zo(" ","",!0):"{}"}`,x=vt(y);h.push({kind:"module",name:"global",text:w,isExported:!1,moduleForm:"global",leadingComments:x,start:y,end:c})}else tt()}}class Hc{names;lengths=new Uint8Array(65);firstUnits=new Uint8Array(65536);size;constructor(e){this.names=e;for(let t of e.keys()){if(!t)continue;this.lengths[Math.min(t.length,64)]=1,this.firstUnits[t.charCodeAt(0)]=1}this.size=e.size}scan(e,t){if(this.size===0)return!1;let i=!1,r=0,n=e.length;while(r<n){let o=e.charCodeAt(r);if(o>=65&&o<=90||o>=97&&o<=122||o===95||o===36||o>127){let s=r;r++;while(r<n){let a=e.charCodeAt(r);if(a>=65&&a<=90||a>=97&&a<=122||a>=48&&a<=57||a===95||a===36||a>127)r++;else break}if(this.firstUnits[o]===1&&this.lengths[Math.min(r-s,64)]===1){let a=e.substring(s,r),l=this.names.get(a);if(l!==void 0){if(t.add(a),l.kind==="function"||l.kind==="variable")i=!0}}}else r++}return i}}function Kc(e,t){let i=0;while(i<e.length){let r=e.charCodeAt(i);if(r===De||r===Ne||r===Xe){let u=r;i++;while(i<e.length)if(e.charCodeAt(i)===Tt)i+=2;else if(e.charCodeAt(i++)===u)break;continue}if(r===we&&e.charCodeAt(i+1)===we){i+=2;while(i<e.length&&e.charCodeAt(i)!==Fe&&e.charCodeAt(i)!==ze)i++;continue}if(r===we&&e.charCodeAt(i+1)===Ie){let u=e.indexOf("*/",i+2);i=u===-1?e.length:u+2;continue}if(!ht(r)){i++;continue}let n=i++;while(i<e.length&&je(e.charCodeAt(i)))i++;let o=n-1,s=i;while(o>=0&&it(e.charCodeAt(o)))o--;while(s<e.length&&it(e.charCodeAt(s)))s++;let a=o>=0?e.charCodeAt(o):0,l=s<e.length?e.charCodeAt(s):0,f=n>=3&&e.slice(n-3,n)==="...";if(l===It||a===Ui&&!f)continue;if(l===Ee&&(a===se||a===Bt))continue;t.add(e.slice(n,i))}}function Up(e,t,i,r,n){let o=new Map;if(n){let c=0;for(let A of e)if(A.kind==="class"&&!A.isExported){if(o.set(A.name,A),!t.has(A.name))t.set(A.name,A)}else if(!A.isExported&&(A.kind==="type"||A.kind==="interface")&&["variable","function"].includes(t.get(A.name)?.kind??""));else e[c++]=A;e.length=c}let s=new Set(e),a=new Set,l=new Set,f=new Set;for(let c of e)if(l.add(c.name),c.kind!=="type"&&c.kind!=="interface")f.add(c.name);let u=new Hc(t),d=new Map;for(let[c,A]of r){let M=t.get(c);if(M?.kind==="variable"||M?.kind==="function")d.set(c,A[0])}let h=new Set,p=new Set,m=new Set,g=new Set,C=(c)=>{if(u.scan(c.text,m))Zl(c,g,d.size?{candidates:d,references:h}:void 0)},b=new Set;for(let c=0;c<e.length;c++){let A=e[c];if(A.kind!=="import"){if(C(A),typeof A.value==="string")Kc(A.value,b)}}for(;;){let c=[];for(let[S,O]of t){if(a.has(S))continue;if((O.kind==="function"||O.kind==="variable"?g:m).has(S)||O.kind!=="function"&&b.has(S)){let N=o.get(S);if(N){for(let B of[N,O])if(!s.has(B))c.push(B),s.add(B);l.add(S)}else if(!(O.kind==="function"||O.kind==="variable"?f:l).has(S)){let B=O.kind==="function"?i.get(S):void 0;if(B)for(let ee of B)c.push(ee);else c.push(O);if(l.add(S),O.kind==="function"||O.kind==="variable")f.add(S)}a.add(S)}}for(let[S,O]of r){if(!d.has(S)||p.has(S)||!h.has(S))continue;for(let N of O)if(!s.has(N))c.push(N),s.add(N);p.add(S)}if(c.length===0)break;c.sort((S,O)=>(S.start??1/0)-(O.start??1/0));let A=[],M=0;for(let S=0;S<e.length;S++){let O=e[S].start??1/0;while(M<c.length&&(c[M].start??1/0)<=O)A.push(c[M++]);A.push(e[S])}while(M<c.length)A.push(c[M++]);e.length=0;for(let S=0;S<A.length;S++)e.push(A[S]);for(let S of c)if(S.kind!=="import"){if(C(S),typeof S.value==="string")Kc(S.value,b)}}}var lt=32,ct=9,Fe=10,ze=13,we=47,Ie=42,De=39,Ne=34,Xe=96,Tt=92,se=123,Ce=125,Ee=40,Me=41,Ge=91,Je=93,_e=60,Ve=62,xe=59,It=58,Ue=61,Bt=44,Ui=46,_n=63,Uc=35,jp=64,Gp=36,js;var Gn=ye(()=>{Bi();pt();Cn();vs();bn();$r();ec();Sn();Ss();As();Tr();Rc();Ln();Vc();js=["public","protected","private","readonly","override"]});function Jc(e,t,i=!0,r=!1,n){if(cn(t??""))e=dn(e);else if(pn(t??""))e=mn(e);let o=mr(e),s=JSON.stringify([t,i,r,[...n??[]].sort()]),a=zi.get(s);if(a&&a.contentHash===o)return a.lastAccess=++qc,a.declarations;let l=r?Rr(e,t,i):jn(e,t,i,n);if(zi.set(s,{declarations:l,contentHash:o,lastAccess:++qc}),zi.size>zp){let f=Math.max(1,Math.ceil(zi.size*0.1)),u=[];for(let[d,h]of zi)u.push([d,h.lastAccess]);u.sort((d,h)=>d[1]-h[1]);for(let d=0;d<f&&d<u.length;d++)zi.delete(u[d][0])}return l}var zp=100,qc=0,zi;var Yc=ye(()=>{hn();ms();ts();Gn();zi=new Map});function Vn(e,t,i=!0,r=!1,n){return Jc(e,t,i,r,n)}var zs=ye(()=>{Yc()});function Un(e){let t=new Set,i=[];for(let o of e)if(o.kind==="import")for(let s of Oi(o.text))t.add(s);else if(o.kind!=="unknown"){if(i.push(o.text),o.kind==="variable"){if(o.typeAnnotation)i.push(o.typeAnnotation);else if(o.value)i.push(Vi(o,!1))}}let r=i.join(`
|
|
143
|
-
`),n=new Set;for(let o=0;o<r.length;){if(!ht(r.charCodeAt(o))){o++;continue}let s=o++;while(o<r.length&&je(r.charCodeAt(o)))o++;let a=r.slice(s,o);if(t.has(a))n.add(a)}return{usedItems:n,referenceText:r}}var
|
|
144
|
-
`;i++}i=Math.min(i+2,e.length);continue}if(n===44){let o=i+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){i++;continue}}t+=e[i++]}return t}var
|
|
142
|
+
}`}function wh(y,v){let w=c+y.length;while(w<f&&it(s.charCodeAt(w)))w++;for(let x=0;x<v.length;x++)if(w+x>=f||s.charCodeAt(w+x)!==v.charCodeAt(x))return!1;return w+v.length>=f||!je(s.charCodeAt(w+v.length))}function Wi(y,v,w){c+=w.length,D();let x="",E=s.charCodeAt(c);if(E===De||E===Ne){let U=c;G(E),x=s.slice(U,c)}else{x=me();while(c<f&&s.charCodeAt(c)===Ui)c++,x+=`.${me()}`}D();let k=ue(s.slice(y,c)),F=k.findIndex((U)=>U.kind==="word"&&["namespace","module"].includes(s.slice(y+U.start,y+U.end))),P=k.slice(0,F).some((U)=>U.kind==="word"&&s.slice(y+U.start,y+U.end)==="declare"),I=c<f&&s.charCodeAt(c)===se?Zo(" ",x,P):"{}",R=`${v?"export ":""}declare ${w} ${x} ${I}`,L=vt(y),J=x.startsWith("'")||x.startsWith('"');return{kind:"module",name:x,text:R,isExported:v,moduleForm:J?"quoted":w==="namespace"?"namespace":"identifier",source:J?x.slice(1,-1):void 0,leadingComments:L,start:y,end:c}}function Cl(y,v){tt();let w=fe(v,c);if(w.charCodeAt(w.length-1)===xe)w=w.slice(0,-1).trimEnd();if(!w)return;let x=ht(w.charCodeAt(0));for(let R=1;x&&R<w.length;R++)x=je(w.charCodeAt(R));let E=vt(y);if(x){h.push({kind:"export",name:"default",text:`export default ${w};`,isExported:!0,isTypeOnly:!1,leadingComments:E,start:y,end:c});return}let k="__dtsx_default_export__",F=1;while(s.includes(k))k=`__dtsx_default_export_${F++}__`;let P=Xr(w)||he(w)||Te(w,!1),I=P==="unknown"&&Kc(w)?`typeof ${w}`:P;h.push({kind:"variable",name:k,text:`declare const ${k}: ${I};`,isExported:!1,typeAnnotation:I,modifiers:["const"],start:y,end:c}),h.push({kind:"export",name:"default",text:`export default ${k};`,isExported:!0,isTypeOnly:!1,leadingComments:E,start:y,end:c})}function vl(){if(s.charCodeAt(c)===se)return et(se,Ce),!0;let y=W("if"),v=W("do"),w=W("try"),x=W("for");if(!y&&!v&&!w&&!x&&!W("while")&&!W("switch")&&!W("with"))return!1;if(me(),D(),x&&W("await"))c+=5,D();if(!v&&!w&&s.charCodeAt(c)===Ee)et(Ee,Me);if(en(),D(),y&&W("else"))c+=4,en();else if(v&&W("while")){if(c+=5,D(),s.charCodeAt(c)===Ee)et(Ee,Me);if(D(),s.charCodeAt(c)===xe)c++}else if(w){if(W("catch")){if(c+=5,D(),s.charCodeAt(c)===Ee)et(Ee,Me);en(),D()}if(W("finally"))c+=7,en()}return!0}function en(){if(D(),!vl())tt()}while(c<f){if(D(),c>=f)break;if(vl())continue;let y=c,v=s.charCodeAt(c);if(v===105&&W("import"))h.push(ch(y));else if(v===101&&W("export")){c+=6,D();let w=s.charCodeAt(c);if(w===100&&W("default")){c+=7,D();let x=c,E=s.charCodeAt(c);if(E===102&&W("function")){let k=ui(y,!0,!1,!0);if(k)h.push(k)}else if(E===97&&W("async")&&Qr("async")!==xe)if(c+=5,D(),W("function")){let k=ui(y,!0,!0,!0);if(k)h.push(k)}else Cl(y,x);else if(E===99&&W("class")){let k=di(y,!0,!1,!0);h.push(k)}else if(E===97&&W("abstract")){if(c+=8,D(),W("class")){let k=di(y,!0,!0,!0);h.push(k)}}else Cl(y,x)}else if(w===116&&W("type")){let x=c;if(c+=4,D(),c<f&&s.charCodeAt(c)===se){fl();let E=fe(y,c),k=vt(y);h.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:!0,source:Jr(E),leadingComments:k,start:y,end:c})}else if(c<f&&s.charCodeAt(c)===Ie){ul();let E=fe(y,c);h.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:!0,source:Jr(E),start:y,end:c})}else{c=x;let E=qo(y,!0);h.push(E)}}else if(w===105&&W("interface")){let x=Ho(y,!0);h.push(x)}else if(w===102&&W("function")){let x=ui(y,!0,!1,!1);if(x)h.push(x)}else if(w===97&&W("async"))if(c+=5,D(),W("function")){let x=ui(y,!0,!0,!1);if(x)h.push(x)}else tt();else if(w===99)if(W("class")){let x=di(y,!0,!1);h.push(x)}else if(W("const")){let x=c;if(c+=5,D(),W("enum")){c=x+5,D();let E=Fi(y,!0,!0);h.push(E)}else{c=x;let E=bi(y,"const",!0);for(let k=0;k<E.length;k++)h.push(E[k])}}else tt();else if(w===97&&W("abstract")){if(c+=8,D(),W("class")){let x=di(y,!0,!0);h.push(x)}}else if(w===108&&W("let")){let x=bi(y,"let",!0);for(let E=0;E<x.length;E++)h.push(x[E])}else if(w===118&&W("var")){let x=bi(y,"var",!0);for(let E=0;E<x.length;E++)h.push(x[E])}else if(w===101&&W("enum")){let x=Fi(y,!0,!1);h.push(x)}else if(w===100&&W("declare"))c+=7,D(),$l(y,!0);else if(w===110&&W("namespace")&&Qe(9)){let x=Wi(y,!0,"namespace");h.push(x)}else if(w===109&&W("module")&&Qe(6)){let x=Wi(y,!0,"module");h.push(x)}else if(w===se){fl();let x=fe(y,c),E=x.includes("export type"),k=vt(y);h.push({kind:"export",name:"",text:x,isExported:!0,isTypeOnly:E,source:Jr(x),leadingComments:k,start:y,end:c})}else if(w===Ie){ul();let x=fe(y,c),E=vt(y);h.push({kind:"export",name:"",text:x,isExported:!0,isTypeOnly:!1,source:Jr(x),leadingComments:E,start:y,end:c})}else{tt();let x=fe(y,c);if(x)h.push({kind:"export",name:"",text:x,isExported:!0,start:y,end:c})}}else if(v===100&&W("declare"))c+=7,D(),$l(y,!1);else if(v===105&&W("interface")){let w=Ho(y,!1);g(w.name,w)}else if(v===116&&W("type")){let w=qo(y,!1);g(w.name,w),h.push(w)}else if(v===102&&W("function")){let w=ui(y,!1,!1,!1);if(w)Se(w);else tt()}else if(v===97)if(W("async")){let w=c;if(c+=5,D(),W("function")){let x=ui(y,!1,!0,!1);if(x)Se(x);else c=w,tt()}else c=w,tt()}else if(W("abstract"))if(c+=8,D(),W("class")){let w=di(y,!1,!1);g(w.name,w),h.push(w)}else tt();else c++,tt();else if(v===99)if(W("class")){let w=di(y,!1,!1);g(w.name,w),h.push(w)}else if(W("const")){let w=c;if(c+=5,D(),W("enum")){c=w+5,D();let x=Fi(y,!1,!0);g(x.name,x),h.push(x)}else{c=w;let x=bi(y,"const",!1);for(let E=0;E<x.length;E++)g(x[E].name,x[E])}}else c++,tt();else if(v===101&&W("enum")){let w=Fi(y,!1,!1);g(w.name,w),h.push(w)}else if(v===108&&W("let")||v===118&&W("var")){let w=W("let")?"let":"var",x=bi(y,w,!1);for(let E=0;E<x.length;E++)g(x[E].name,x[E])}else if(v===109&&W("module")&&Qe(6)){let w=Wi(y,!1,"module");h.push(w)}else if(v===110&&W("namespace")&&Qe(9)){let w=Wi(y,!1,"namespace");h.push(w)}else{let w=s.charCodeAt(c);if(w===xe)c++;else if(w===De||w===Ne){if(G(w),c<f&&s.charCodeAt(c)===xe)c++}else if(w===Xe){if(Z(),c<f&&s.charCodeAt(c)===xe)c++}else if(w===Gp){if(c++,me(),D(),c<f&&s.charCodeAt(c)===Ui)c++,me(),D();if(c<f&&s.charCodeAt(c)===Ee)et(Ee,Me)}else c++,tt()}}if(B.length){let y=new Set([...h,...p.values()]),v=new Set([...y].filter((P)=>P.kind==="class").map((P)=>P.name)),w=new Set([...y].filter((P)=>P.kind==="variable"&&!!P.typeAnnotation).map((P)=>P.name)),x=new Set,E=new Map;for(let P of T)for(let[I,R]of P.bindings){let L=P.path?`${P.path}.${I}`:I;if(P.exports.has(I)&&(R!=="namespace"||!E.has(L)))E.set(L,R);if(P.exports.has(I)&&P.annotatedValues.has(I))x.add(L)}let k=new Map;for(let P of B){if(P.binding){let I=w.has(P.initializer);for(let R=P.namespaces.length-1;R>=0;R--){let L=P.namespaces[R],J=L.path?`${L.path}.${P.initializer}`:P.initializer;if(L.bindings.has(P.initializer)||E.has(J)){I=L.bindings.has(P.initializer)?L.annotatedValues.has(P.initializer):x.has(J);break}}k.set(P.marker,I?`typeof ${P.initializer}`:"unknown");continue}k.set(P.marker,Fs(P.initializer,(I)=>{if(P.classes.includes(I))return!0;for(let R=P.namespaces.length-1;R>=0;R--){let L=P.namespaces[R],J=L.path?`${L.path}.${I}`:I,U=I.split(".")[0],Q=L.bindings.get(U);if(Q){if(I===U&&Q!=="namespace")return Q==="class";return E.get(J)==="class"}let j=L.path?`${L.path}.${U}`:U;if(E.has(j))return E.get(J)==="class"}return E.has(I)?E.get(I)==="class":v.has(I)}))}let F=(P)=>{if(!P.includes("__dtsx_constructor_field_"))return P;let I="",R=0;for(let L of ue(P)){if(L.kind!=="word")continue;let J=k.get(P.slice(L.start,L.end));if(!J)continue;I+=P.slice(R,L.start)+J,R=L.end}return I+P.slice(R)};for(let P of y){P.text=F(P.text);for(let I of["typeAnnotation","inferredType","returnType"])if(P[I])P[I]=F(P[I])}}if(b.size>0){bl(h);for(let y of C.values())bl(y)}if(Oc(s,h,p,C),ec(h,p),zl(h,p),l)js([...h,...p.values()]);else Vc(s,h,p,o);if(n){let y=new Set(h);for(let v of[...p.values(),...[...C.values()].flat(),...[...m.values()].flat()])if(!y.has(v))h.push(v),y.add(v);return h.sort((v,w)=>(v.start??0)-(w.start??0))}if(p.size>0)zp(h,p,C,m,d);return h;function bl(y){let v=new Map;for(let x of y)if(x.kind==="function")v.set(x.name,(v.get(x.name)||0)+1);let w=new Set;for(let[x,E]of v)if(E>1)w.add(x);if(w.size>0){let x=new Set;for(let E of w)for(let k=y.length-1;k>=0;k--)if(y[k].kind==="function"&&y[k].name===E&&b.has(y[k])){x.add(k);break}if(x.size>0){let E=[...x].sort((k,F)=>F-k);for(let k of E)y.splice(k,1)}}}function $l(y,v){if(W("function")){let w=ui(y,v,!1,!1);if(w)h.push(w)}else if(W("async")){if(c+=5,D(),W("function")){let w=ui(y,v,!0,!1);if(w)h.push(w)}}else if(W("class")){let w=di(y,v,!1);h.push(w)}else if(W("abstract")){if(c+=8,D(),W("class")){let w=di(y,v,!0);h.push(w)}}else if(W("interface")){let w=Ho(y,v);h.push(w)}else if(W("type")){let w=qo(y,v);h.push(w)}else if(W("enum")){let w=Fi(y,v,!1);h.push(w)}else if(W("const")){let w=c;if(c+=5,D(),W("enum")){c=w+5,D();let x=Fi(y,v,!0);h.push(x)}else{c=w;let x=bi(y,"const",v);for(let E=0;E<x.length;E++)if(v||!d)h.push(x[E]);else g(x[E].name,x[E])}}else if(W("let")||W("var")){let w=W("let")?"let":"var",x=bi(y,w,v);for(let E=0;E<x.length;E++)if(v||!d)h.push(x[E]);else g(x[E].name,x[E])}else if(W("module")){let w=Wi(y,v,"module");h.push(w)}else if(W("namespace")){let w=Wi(y,v,"namespace");h.push(w)}else if(W("global")){c+=6,D();let w=`declare global ${c<f&&s.charCodeAt(c)===se?Zo(" ","",!0):"{}"}`,x=vt(y);h.push({kind:"module",name:"global",text:w,isExported:!1,moduleForm:"global",leadingComments:x,start:y,end:c})}else tt()}}class qc{names;lengths=new Uint8Array(65);firstUnits=new Uint8Array(65536);size;constructor(e){this.names=e;for(let t of e.keys()){if(!t)continue;this.lengths[Math.min(t.length,64)]=1,this.firstUnits[t.charCodeAt(0)]=1}this.size=e.size}scan(e,t){if(this.size===0)return!1;let i=!1,r=0,n=e.length;while(r<n){let o=e.charCodeAt(r);if(o>=65&&o<=90||o>=97&&o<=122||o===95||o===36||o>127){let s=r;r++;while(r<n){let a=e.charCodeAt(r);if(a>=65&&a<=90||a>=97&&a<=122||a>=48&&a<=57||a===95||a===36||a>127)r++;else break}if(this.firstUnits[o]===1&&this.lengths[Math.min(r-s,64)]===1){let a=e.substring(s,r),l=this.names.get(a);if(l!==void 0){if(t.add(a),l.kind==="function"||l.kind==="variable")i=!0}}}else r++}return i}}function Hc(e,t){let i=0;while(i<e.length){let r=e.charCodeAt(i);if(r===De||r===Ne||r===Xe){let u=r;i++;while(i<e.length)if(e.charCodeAt(i)===Tt)i+=2;else if(e.charCodeAt(i++)===u)break;continue}if(r===we&&e.charCodeAt(i+1)===we){i+=2;while(i<e.length&&e.charCodeAt(i)!==Fe&&e.charCodeAt(i)!==ze)i++;continue}if(r===we&&e.charCodeAt(i+1)===Ie){let u=e.indexOf("*/",i+2);i=u===-1?e.length:u+2;continue}if(!ht(r)){i++;continue}let n=i++;while(i<e.length&&je(e.charCodeAt(i)))i++;let o=n-1,s=i;while(o>=0&&it(e.charCodeAt(o)))o--;while(s<e.length&&it(e.charCodeAt(s)))s++;let a=o>=0?e.charCodeAt(o):0,l=s<e.length?e.charCodeAt(s):0,f=n>=3&&e.slice(n-3,n)==="...";if(l===It||a===Ui&&!f)continue;if(l===Ee&&(a===se||a===Bt))continue;t.add(e.slice(n,i))}}function zp(e,t,i,r,n){let o=new Map;if(n){let c=0;for(let A of e)if(A.kind==="class"&&!A.isExported){if(o.set(A.name,A),!t.has(A.name))t.set(A.name,A)}else if(!A.isExported&&(A.kind==="type"||A.kind==="interface")&&["variable","function"].includes(t.get(A.name)?.kind??""));else e[c++]=A;e.length=c}let s=new Set(e),a=new Set,l=new Set,f=new Set;for(let c of e)if(l.add(c.name),c.kind!=="type"&&c.kind!=="interface")f.add(c.name);let u=new qc(t),d=new Map;for(let[c,A]of r){let M=t.get(c);if(M?.kind==="variable"||M?.kind==="function")d.set(c,A[0])}let h=new Set,p=new Set,m=new Set,g=new Set,C=(c)=>{if(u.scan(c.text,m))Ql(c,g,d.size?{candidates:d,references:h}:void 0)},b=new Set;for(let c=0;c<e.length;c++){let A=e[c];if(A.kind!=="import"){if(C(A),typeof A.value==="string")Hc(A.value,b)}}for(;;){let c=[];for(let[S,T]of t){if(a.has(S))continue;if((T.kind==="function"||T.kind==="variable"?g:m).has(S)||T.kind!=="function"&&b.has(S)){let N=o.get(S);if(N){for(let B of[N,T])if(!s.has(B))c.push(B),s.add(B);l.add(S)}else if(!(T.kind==="function"||T.kind==="variable"?f:l).has(S)){let B=T.kind==="function"?i.get(S):void 0;if(B)for(let ee of B)c.push(ee);else c.push(T);if(l.add(S),T.kind==="function"||T.kind==="variable")f.add(S)}a.add(S)}}for(let[S,T]of r){if(!d.has(S)||p.has(S)||!h.has(S))continue;for(let N of T)if(!s.has(N))c.push(N),s.add(N);p.add(S)}if(c.length===0)break;c.sort((S,T)=>(S.start??1/0)-(T.start??1/0));let A=[],M=0;for(let S=0;S<e.length;S++){let T=e[S].start??1/0;while(M<c.length&&(c[M].start??1/0)<=T)A.push(c[M++]);A.push(e[S])}while(M<c.length)A.push(c[M++]);e.length=0;for(let S=0;S<A.length;S++)e.push(A[S]);for(let S of c)if(S.kind!=="import"){if(C(S),typeof S.value==="string")Hc(S.value,b)}}}var lt=32,ct=9,Fe=10,ze=13,we=47,Ie=42,De=39,Ne=34,Xe=96,Tt=92,se=123,Ce=125,Ee=40,Me=41,Ge=91,Je=93,_e=60,Ve=62,xe=59,It=58,Ue=61,Bt=44,Ui=46,_n=63,zc=35,Gp=64,Vp=36,Gs;var Gn=ye(()=>{Bi();pt();Cn();vs();bn();$r();tc();Sn();Ss();As();Tr();Pc();Ln();Uc();Gs=["public","protected","private","readonly","override"]});function Yc(e,t,i=!0,r=!1,n){if(cn(t??""))e=dn(e);else if(pn(t??""))e=mn(e);let o=mr(e),s=JSON.stringify([t,i,r,[...n??[]].sort()]),a=zi.get(s);if(a&&a.contentHash===o)return a.lastAccess=++Jc,a.declarations;let l=r?Rr(e,t,i):jn(e,t,i,n);if(zi.set(s,{declarations:l,contentHash:o,lastAccess:++Jc}),zi.size>Kp){let f=Math.max(1,Math.ceil(zi.size*0.1)),u=[];for(let[d,h]of zi)u.push([d,h.lastAccess]);u.sort((d,h)=>d[1]-h[1]);for(let d=0;d<f&&d<u.length;d++)zi.delete(u[d][0])}return l}var Kp=100,Jc=0,zi;var Xc=ye(()=>{hn();ms();ts();Gn();zi=new Map});function Vn(e,t,i=!0,r=!1,n){return Yc(e,t,i,r,n)}var Ks=ye(()=>{Xc()});function Un(e){let t=new Set,i=[];for(let o of e)if(o.kind==="import")for(let s of Oi(o.text))t.add(s);else if(o.kind!=="unknown"){if(i.push(o.text),o.kind==="variable"){if(o.typeAnnotation)i.push(o.typeAnnotation);else if(o.value)i.push(Vi(o,!1))}}let r=i.join(`
|
|
143
|
+
`),n=new Set;for(let o=0;o<r.length;){if(!ht(r.charCodeAt(o))){o++;continue}let s=o++;while(o<r.length&&je(r.charCodeAt(o)))o++;let a=r.slice(s,o);if(t.has(a))n.add(a)}return{usedItems:n,referenceText:r}}var Hs=ye(()=>{Bi();Ln();Pi()});function Hp(e){if(!e.includes("declare")||!e.includes("module"))return[];return Wt(e).filter((t)=>t.category==="augmentation").map((t)=>t.specifier)}function qp(e,t){let i=new Set([e]);for(let r of i)for(let n of t(r))i.add(n);return i}async function Zc(e,t,i=!1,r){let n=new Map,o=new Map;for(let u of e){let d=r?.get(u)??await Et(u);n.set(u,d);let h=Hp(d);if(h.length)o.set(u,h)}let s=new Map;if(o.size===0)return s;let a=new Map,l=(u,d)=>{let h=t(u,d);if(h.resolved)return h.resolved;if(!h.isRelative&&!h.isAlias)return`external:${u}`;return};for(let[u,d]of n){let h=Vn(d,u,!1,i),p=Un(h),m={edges:[],declarations:new Set,augmentations:new Set},g=(C,b,c)=>{let A=l(C.specifier,u);if(!A)return;if(n.has(A))m.edges.push({specifier:C.specifier,target:A,import:b});if(c)m.declarations.add(A)};for(let C of h){if(C.kind!=="import")continue;let b=C.isSideEffect||Oi(C.text).some((c)=>p.usedItems.has(c));for(let c of Wt(C.text))g(c,!0,!!b)}for(let C of Wt(p.referenceText))g(C,!1,!0);for(let C of o.get(u)??[]){let b=l(C,u);if(b)m.augmentations.add(b),m.declarations.add(b)}a.set(u,m)}let f=!0;while(f){f=!1;for(let[u,d]of a){let h=qp(u,(p)=>a.get(p)?.declarations??[]);for(let[p,m]of a){if(h.has(p)||!m.augmentations.size||![...m.augmentations].some((c)=>h.has(c)))continue;let g=[u],C=new Map,b=new Set([u]);for(let c of g){if(c===p)break;for(let A of a.get(c).edges){if(b.has(A.target))continue;b.add(A.target),C.set(A.target,{from:c,edge:A}),g.push(A.target)}}if(!C.has(p))continue;for(let c=p;c!==u;){let{from:A,edge:M}=C.get(c),S=a.get(A);if(M.import){let T=s.get(A);if(!T)T=new Set,s.set(A,T);T.add(M.specifier)}if(!S.declarations.has(c))S.declarations.add(c),f=!0;c=A}}}}return s}var Qc=ye(()=>{gr();pt();Pi();Ks();Hs()});function Ki(e){return ef[e]>=ef[zn]}function Xp(){if(!Yp)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Zp(e,t){let i=Xp();if(e||i)return[`${i}${e}`,...t];return t}function Hi(e,t,i){let r=Zp(t,i);if(tf){tf(e,...r);return}switch(e){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break}}function rf(e){return{debug:(...t)=>{if(Ki("debug"))Hi("debug",e,t)},info:(...t)=>{if(Ki("info"))Hi("info",e,t)},warn:(...t)=>{if(Ki("warn"))Hi("warn",e,t)},error:(...t)=>{if(Ki("error"))Hi("error",e,t)},setLevel:(t)=>{zn=t},getLevel:()=>zn,child:(t)=>{let i=e?`${e}:${t}`:`[${t}]`;return rf(i)},time:(t)=>{let i=performance.now();return()=>{let r=performance.now()-i;if(Ki("debug"))Hi("debug",e,[`${t}: ${r.toFixed(2)}ms`])}},progress:(t)=>{if(Ki("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Hi("info",e,[t])}}}function qs(e){zn=e}var ef,zn="info",Jp="[dtsx]",Yp=!1,tf=null,de;var Kn=ye(()=>{ef={debug:0,info:1,warn:2,error:3,silent:4};de=rf(Jp)});function nf(e){let t="",i=0,r=0;while(i<e.length){let n=e.charCodeAt(i);if(r){if(t+=e[i],n===92&&i+1<e.length){t+=e[i+1],i+=2;continue}if(n===r)r=0;i++;continue}if(n===34){r=n,t+=e[i++];continue}if(n===47&&e.charCodeAt(i+1)===47){i+=2;while(i<e.length&&e.charCodeAt(i)!==10&&e.charCodeAt(i)!==13)i++;continue}if(n===47&&e.charCodeAt(i+1)===42){i+=2;while(i+1<e.length&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47)){if(e.charCodeAt(i)===10)t+=`
|
|
144
|
+
`;i++}i=Math.min(i+2,e.length);continue}if(n===44){let o=i+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){i++;continue}}t+=e[i++]}return t}var of=()=>{};import{readFileSync as Qp,statSync as em}from"fs";import{readFile as tm}from"fs/promises";import{createRequire as im}from"module";import{dirname as Pr,isAbsolute as rm,join as Js,resolve as Ys}from"path";function qi(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Js(e,"tsconfig.json"));for(let i of t)try{if(em(i).isFile())return i}catch{}return null}function nm(e,t){if(rm(e)||e.startsWith("."))return qi(Ys(Pr(t),e));let i=im(t),r=e.startsWith("@")?/^@[^/]+\/[^/]+/.exec(e)?.[0]:e.split("/")[0];if(r)for(let n of i.resolve.paths(r)??[]){let o=qi(Js(n,r,"package.json"));if(!o)continue;let s=JSON.parse(Qp(o,"utf8"));if(e===r){if(s.tsconfig!==void 0){if(typeof s.tsconfig!=="string")throw Error(`Invalid tsconfig field in ${o}`);let l=qi(Ys(Pr(o),s.tsconfig));if(!l)throw Error(`Cannot resolve tsconfig ${JSON.stringify(s.tsconfig)} from ${o}`);return l}let a=qi(Js(Pr(o),"tsconfig.json"));if(a)return a}break}for(let n of[`${e}/tsconfig.json`,e])try{let o=i.resolve(n),s=o.endsWith(".json")?qi(o):null;if(s)return s}catch{}return null}async function Mr(e,t={},i=new Set){let r=qi(e);if(!r)return;if(i.has(r)){if(t.allowCircular)return;throw Error(`Circular tsconfig extends: ${r}`)}let n=new Set(i).add(r),o=JSON.parse(nf(await tm(r,"utf8"))),s=typeof o.extends==="string"?[o.extends]:o.extends??[];if(!Array.isArray(s)||s.some((f)=>typeof f!=="string"))throw Error(`Invalid tsconfig extends in ${r}`);let a={};for(let f of s){let u=nm(f,r);if(!u)throw Error(`Cannot resolve tsconfig extends ${JSON.stringify(f)} from ${r}`);a={...a,...await Mr(u,t,n)}}let l=o.compilerOptions??{};if(l.isolatedDeclarations!==void 0)a.isolatedDeclarations=l.isolatedDeclarations;if(l.baseUrl!==void 0){if(typeof l.baseUrl!=="string")throw Error(`Invalid baseUrl in ${r}`);a.baseUrl=Ys(Pr(r),l.baseUrl)}if(l.paths!==void 0){if(!l.paths||typeof l.paths!=="object"||Array.isArray(l.paths))throw Error(`Invalid paths in ${r}`);for(let[f,u]of Object.entries(l.paths))if(f.split("*").length>2||!Array.isArray(u)||u.length===0||u.some((d)=>typeof d!=="string"||d.split("*").length>2))throw Error(`Invalid path mapping ${JSON.stringify(f)} in ${r}`);a.paths=l.paths,a.pathsBasePath=Pr(r)}return a}var Xs=ye(()=>{of()});import{existsSync as ea,readFileSync as Zs,realpathSync as Dr,statSync as om}from"fs";import{builtinModules as sm}from"module";import{dirname as ta,extname as am,isAbsolute as ia,join as lf,relative as cf,resolve as Ji}from"path";function Hn(e){try{return om(e).isFile()}catch{return!1}}function Yi(e,t){let i=e.replace(/[?#].*$/,"");if(!(i.startsWith("./")||i.startsWith("../")||i==="."||i==="..")&&!ia(i))return{resolved:null,isRelative:!1};let r=ta(t),n=Ji(r,i);if(Hn(n))return{resolved:n,isRelative:!0};let o=am(n),s=lm[o];if(s){let a=n.slice(0,-o.length);for(let l of s){let f=a+l;if(Hn(f))return{resolved:f,isRelative:!0}}}for(let a of sf){let l=n+a;if(Hn(l))return{resolved:l,isRelative:!0}}if(ea(n))for(let a of sf){let l=lf(n,`index${a}`);if(Hn(l))return{resolved:l,isRelative:!0}}return{resolved:null,isRelative:!0}}function ff(e,t){let i=e.indexOf("*");return i===-1?t===e:t.startsWith(e.slice(0,i))&&t.endsWith(e.slice(i+1))&&t.length>=e.length-1}function uf(e,t){if(Object.hasOwn(e,t))return e[t]!==null;let i=Object.keys(e).filter((r)=>r.includes("*")&&ff(r,t)).sort((r,n)=>n.indexOf("*")-r.indexOf("*")||n.length-r.length)[0];return i!==void 0&&e[i]!==null}function af(e,t){if(!e.name||t!==e.name&&!t.startsWith(`${e.name}/`))return!1;if(e.exports===void 0)return!0;let i=t===e.name?".":`.${t.slice(e.name.length)}`;if(typeof e.exports==="string"||Array.isArray(e.exports))return i===".";if(!e.exports||typeof e.exports!=="object")return!1;let r=e.exports;if(!Object.keys(r).some((n)=>n.startsWith(".")))return i===".";return uf(r,i)}function Qs(e,t){let i=cf(e,t);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!ia(i)}async function qn(e){let t=await Mr(Ji(e.cwd,e.tsconfigPath||"tsconfig.json")),i=Object.entries(t?.paths??{});if(i.length===0){let f=(u,d)=>Yi(u,d);return f.cacheKey=(u)=>JSON.stringify(u.map((d)=>({file:d,references:Mi(Zs(d,"utf8"),{includeImports:!0}).map((h)=>({specifier:h.specifier,resolution:f(h.specifier,d)}))}))),f}let r=t?.baseUrl??t?.pathsBasePath??e.cwd,n=Ji(e.cwd,e.root),o=new Map,s=new Set([...sm,"bun"]),a=(f)=>{let u=ta(f),d=[];while(!0){if(o.has(u)){let m=o.get(u);for(let g of d)o.set(g,m);return m}d.push(u);let h=lf(u,"package.json");if(ea(h)){let m={...JSON.parse(Zs(h,"utf8")),directory:Dr(u)};for(let g of d)o.set(g,m);return m}let p=ta(u);if(p===u)return;u=p}},l=(f,u)=>{if(f.startsWith(".")||ia(f))return Yi(f,u);if(f.startsWith("node:")||f.startsWith("bun:")||s.has(f))return{resolved:null,isRelative:!1};let d=a(u),h=f.startsWith("@")?/^@[^/]+\/[^/]+/.exec(f)?.[0]:f.split("/")[0];if(d&&(af(d,f)||uf(d.imports??{},f)||h&&[d.dependencies,d.devDependencies,d.peerDependencies,d.optionalDependencies].some((c)=>Object.hasOwn(c??{},h))))return{resolved:null,isRelative:!1};let p=i.filter(([c])=>ff(c,f)).sort(([c],[A])=>{if(!c.includes("*"))return-1;if(!A.includes("*"))return 1;return A.indexOf("*")-c.indexOf("*")})[0];if(!p)return{resolved:null,isRelative:!1};let[m,g]=p,C=m.indexOf("*"),b=C===-1?"":f.slice(C,f.length-(m.length-C-1));for(let c of g){let A=Ji(r,c.replace("*",b)),M=a(A);if(M&&af(M,f)&&!M.private&&M.directory!==d?.directory)return{resolved:null,isRelative:!1};let S=Yi(A,u);if(!S.resolved)continue;let T=Dr(S.resolved),N=e.outputStructure==="flat"||ea(n)&&Qs(Dr(n),T);if(!d||!Qs(d.directory,T)||!N||a(T)?.directory!==d.directory||/\.d\.(?:ts|mts|cts)$/.test(T))throw Error(`Local alias ${JSON.stringify(f)} from ${u} resolves outside its emitted package source: ${T}`);return de.debug(`Resolved local declaration alias ${f} from ${u} to ${T}`),{resolved:e.outputStructure==="flat"?S.resolved:Ji(n,cf(Dr(n),T)),isRelative:!0,isAlias:!0,suffix:A.match(/[?#].*$/)?.[0]??""}}throw Error(`Cannot resolve local alias ${JSON.stringify(f)} from ${u} using ${e.tsconfigPath||"tsconfig.json"} (${JSON.stringify(m)})`)};return l.isPackageLocal=(f,u)=>{let d=a(f);return!!d&&a(u)?.directory===d.directory&&Qs(d.directory,Dr(u))},l.cacheKey=(f)=>{let u=f.map((h)=>({file:h,references:Mi(Zs(h,"utf8"),{includeImports:!0}).map((p)=>({specifier:p.specifier,resolution:l(p.specifier,h)}))})),d=[...new Set(o.values())].filter((h)=>h!==void 0).sort((h,p)=>h.directory.localeCompare(p.directory));return JSON.stringify({root:n,compilerOptions:t,packages:d,edges:u})},l}function Mi(e,t={}){let i=Wt(e);return(t.includeImports?["export","static-import","import-type","augmentation"]:["export"]).flatMap((r)=>i.filter((n)=>n.category===r).map(({specifier:n,kind:o,isTypeOnly:s})=>({specifier:n,kind:o,isTypeOnly:s})))}function df(e,t){let i=[];for(let n of Wt(e)){let o=t(n.specifier);if(o!==n.specifier)i.push({start:n.start,end:n.end,value:hi(o,e[n.start])})}let r=e;for(let n of i.reverse())r=r.slice(0,n.start)+n.value+r.slice(n.end);return r}async function Ir(e,t={}){let i=new Set,r=new Map,n=[],o=new Map,s=[];for(let a of e){let l=Ji(a);if(!i.has(l))i.add(l),s.push(l)}while(s.length>0){let a=s.shift(),l;try{l=await Et(a)}catch{continue}o.set(a,l);let f=Mi(l,t);r.set(a,f);for(let u of f){let d=(t.resolveSpecifier??Yi)(u.specifier,a);if(!d.isRelative)continue;if(d.resolved){if(!i.has(d.resolved))i.add(d.resolved),s.push(d.resolved)}else n.push({from:a,specifier:u.specifier,isTypeOnly:u.isTypeOnly})}}return{reachable:i,reExports:r,unresolved:n,sources:o}}var sf,lm;var Jn=ye(()=>{gr();Kn();pt();Xs();sf=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],lm={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]}});import{relative as Di}from"path";function ra(e){let t=ue(e),i=(a)=>t[a]?e.slice(t[a].start,t[a].end):"",r=i(0)==="export"?1:0;if(i(r++)!=="declare")return;let n;if(i(r)==="module"&&t[r+1]?.kind==="quoted"){if(n=$t(i(r+1)),n===void 0)return;r+=2}else if(i(r++)!=="global")return;if(i(r)!=="{")return;let o=t[r].end,s=1;for(r++;r<t.length;r++)if(i(r)==="{")s++;else if(i(r)==="}"&&--s===0)return{specifier:n,body:e.slice(o,t[r].start),start:o,end:t[r].start};return}function fm(e){let t=[],i=[],r=0,n=0,o=[],s=!1,a=0,l=e.length,f=(u)=>{let d=e.slice(r,u).trim();if(r=u,!d)return;if(um(d)){i.push(d);return}t.push({text:d,comments:i}),i=[]};while(a<l){let u=e[a];if(s){if(u==="\\"){a+=2;continue}if(u==="`"){s=!1,a++;continue}if(u==="$"&&e[a+1]==="{"){o.push(n),n++,s=!1,a+=2;continue}a++;continue}if(u==="/"&&e[a+1]==="*"){let d=e.indexOf("*/",a+2);a=d===-1?l:d+2;continue}if(u==="/"&&e[a+1]==="/"){let d=e.indexOf(`
|
|
145
145
|
`,a);a=d===-1?l:d;continue}if(u==="'"||u==='"'){a++;while(a<l&&e[a]!==u&&e[a]!==`
|
|
146
146
|
`){if(e[a]==="\\")a++;a++}a++;continue}if(u==="`"){s=!0,a++;continue}if(u==="("||u==="["||u==="{"){n++,a++;continue}if(u===")"||u==="]"||u==="}"){if(n--,o.length>0&&u==="}"&&n===o[o.length-1])o.pop(),s=!0;a++;continue}if(n===0&&u===";"){f(a+1),a++;continue}if(n===0&&u===`
|
|
147
|
-
`){let d=e[a+1];if(d!==void 0&&/[\w$@/]/.test(d))f(a+1);a++;continue}a++}return f(l),t}function
|
|
148
|
-
`,t);t=i===-1?e.length:i;continue}if(e.startsWith("/*",t)){let i=e.indexOf("*/",t+2);if(i===-1)return!0;t=i+2;continue}return!1}return!0}function
|
|
149
|
-
`).map((h)=>h.trim()).filter((h)=>h.startsWith("///"))),!1;return!0});let s=o.text.replace(/;\s*$/,"").trim(),a=s.startsWith("import")?Ri(s):null;if(a&&!a.isImportEquals){let d=a.source;if(a.defaultName)r.imports.set(a.defaultName,{specifier:d,imported:"default"});if(a.namespaceName)r.imports.set(a.namespaceName,{specifier:d,imported:"*"});for(let h of a.namedItems)r.imports.set(h.name,{specifier:d,imported:/^['"]/.test(h.originalName)?$t(h.originalName):h.originalName});continue}if(/^import\s+['"]/.test(s)){r.verbatim.push(o);continue}let l=s.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/);if(l){r.namespaceReExports.push({specifier:l[3],exported:l[1]});continue}if(l=s.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),l){r.starReExports.push(l[2]);continue}if(l=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),l){for(let d of
|
|
147
|
+
`){let d=e[a+1];if(d!==void 0&&/[\w$@/]/.test(d))f(a+1);a++;continue}a++}return f(l),t}function um(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 i=e.indexOf(`
|
|
148
|
+
`,t);t=i===-1?e.length:i;continue}if(e.startsWith("/*",t)){let i=e.indexOf("*/",t+2);if(i===-1)return!0;t=i+2;continue}return!1}return!0}function hf(e){let t=[];for(let i of e.split(",")){let r=i.replace(/\/\*[\s\S]*?\*\//g,"").trim().replace(/^type\s+/,"");if(!r)continue;let n=r.match(/^([\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!n)continue;t.push({local:n[1],exported:n[2]??n[1]})}return t}function hm(e,t){let i=e.replace(/^export\s+/,""),r=/^default\s+/.test(i);if(i=i.replace(/^default\s+/,""),r)i=i.replace(/^((?:declare\s+)?(?:abstract\s+)?(?:class|function\s*\*?|async\s+function\s*\*?))\s*(?=[(<{])/,(n,o)=>`${o.trimEnd()} ${t}`);if(/^(?:interface|type)\b/.test(i)||/^declare\b/.test(i))return i;return`declare ${i}`}function Yn(e,t,i=!1){let r={file:e,declarations:[],declared:new Set,imports:new Map,localExports:new Map,namedReExports:[],starReExports:[],namespaceReExports:[],verbatim:[],augmentations:[],directives:[]},n=i?Us(t,e).map((o)=>({text:o.text,comments:[...o.leadingComments??[]]})):fm(t);for(let o of n){o.comments=o.comments.filter((d)=>{if(/^\/\/\/\s*</.test(d))return r.directives.push(...d.split(`
|
|
149
|
+
`).map((h)=>h.trim()).filter((h)=>h.startsWith("///"))),!1;return!0});let s=o.text.replace(/;\s*$/,"").trim(),a=s.startsWith("import")?Ri(s):null;if(a&&!a.isImportEquals){let d=a.source;if(a.defaultName)r.imports.set(a.defaultName,{specifier:d,imported:"default"});if(a.namespaceName)r.imports.set(a.namespaceName,{specifier:d,imported:"*"});for(let h of a.namedItems)r.imports.set(h.name,{specifier:d,imported:/^['"]/.test(h.originalName)?$t(h.originalName):h.originalName});continue}if(/^import\s+['"]/.test(s)){r.verbatim.push(o);continue}let l=s.match(/^export\s+(?:type\s+)?\*\s+as\s+([\w$]+)\s+from\s+(['"])([^'"]+)\2/);if(l){r.namespaceReExports.push({specifier:l[3],exported:l[1]});continue}if(l=s.match(/^export\s+(?:type\s+)?\*\s+from\s+(['"])([^'"]+)\1/),l){r.starReExports.push(l[2]);continue}if(l=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}\s+from\s+(['"])([^'"]+)\2/),l){for(let d of hf(l[1]))r.namedReExports.push({specifier:l[3],imported:d.local,exported:d.exported});continue}if(l=s.match(/^export\s+(?:type\s+)?\{([\s\S]*)\}$/),l){for(let d of hf(l[1]))r.localExports.set(d.exported,d.local);continue}if(l=s.match(/^export\s+default\s+([\w$]+)$/),l&&cm.test(l[1])){r.localExports.set("default",l[1]);continue}let f=ra(s);if(f?.specifier!==void 0&&_i(t)){r.augmentations.push({statement:o,specifier:f.specifier,body:f.body});continue}if(/^export\s+as\s+namespace\b/.test(s)||f){r.verbatim.push(o);continue}let u=s.match(dm);if(u){let d=!!u[1],h=u[4]??(d?"_default":null);if(h){if(r.declared.add(h),/^export\s/.test(s))r.localExports.set(d?"default":h,h);r.declarations.push({statement:o,name:h,emit:hm(o.text,h)});continue}}r.declarations.push({statement:o,name:null,emit:o.text})}return r}function Nr(e,t){if(t.size===0)return e;let i=ue(e),r=new Map(i.filter((p)=>p.kind==="literal").map((p)=>[p.start,p.end])),n=(p)=>i[p]?e.slice(i[p].start,i[p].end):"",o=new Map,s=[];for(let p=0;p<i.length;p++){let m=n(p);if(["(","[","{","<"].includes(m))s.push(p);else if([")","]","}",">"].includes(m)&&!(m===">"&&n(p-1)==="=")){let g=s.at(-1);if(g!==void 0&&["()","[]","{}","<>"].includes(n(g)+m))s.pop(),o.set(g,p)}}let a=(p)=>{for(let m=p;m<i.length;m++){if([";",",",")","]","}"].includes(n(m))||n(m)===">"&&n(m-1)!=="=")return m;let g=o.get(m);if(g!==void 0)m=g}return i.length},l=new Set;for(let p=0;p<i.length;p++){let m=o.get(p);if(n(p)!=="<"||m===void 0)continue;let g=["class","interface","type"].includes(n(p-2));if(!g&&n(m+1)!=="(")continue;let C=new Set;for(let c=p+1;c<m;c++){if(c===p+1||n(c-1)===","){while(["const","in","out"].includes(n(c)))c++;if(i[c]?.kind==="word")C.add(n(c))}let A=o.get(c);if(A!==void 0)c=A}let b=a(m+1);if(g&&n(p-2)!=="type")for(let c=m+1;c<i.length;c++){if(n(c)==="{"){b=o.get(c)??b;break}let A=o.get(c);if(A!==void 0)c=A}for(let c=p+1;c<b;c++){let A=n(p-2)==="class"&&c>m&&n(c-1)==="extends";if(C.has(n(c))&&n(c-1)!=="typeof"&&!A)l.add(i[c].start)}}for(let p=0;p<i.length;p++){if(!["namespace","module"].includes(n(p))||i[p+1]?.kind!=="word"||n(p+2)!=="{")continue;let m=o.get(p+2);if(m===void 0)continue;let g=Us(e.slice(i[p+2].end,i[m].start),"bundle-namespace.ts"),C=new Set(g.filter((c)=>["class","interface","type","enum","module","namespace"].includes(c.kind)).map((c)=>c.name)),b=new Set(g.filter((c)=>["class","variable","function","enum","module","namespace"].includes(c.kind)).map((c)=>c.name));for(let c=p+3;c<m;c++)if((n(c-1)==="typeof"?b:C).has(n(c)))l.add(i[c].start)}let f="",u=0,d=e.length,h=`
|
|
150
150
|
`;while(u<d){let p=r.get(u);if(p!==void 0){f+=e.slice(u,p),u=p,h="`";continue}let m=e[u];if(m==="/"&&e[u+1]==="*"){let g=e.indexOf("*/",u+2),C=g===-1?d:g+2;f+=e.slice(u,C),u=C;continue}if(m==="/"&&e[u+1]==="/"){let g=e.indexOf(`
|
|
151
151
|
`,u),C=g===-1?d:g;f+=e.slice(u,C),u=C;continue}if(m==="'"||m==='"'){let g=u+1;while(g<d&&e[g]!==m&&e[g]!==`
|
|
152
152
|
`){if(e[g]==="\\")g++;g++}f+=e.slice(u,g+1),u=g+1,h=m;continue}if(/[A-Z_$]/i.test(m)){let g=u+1;while(g<d&&/[\w$]/.test(e[g]))g++;let C=e.slice(u,g),b=t.get(C);if(b!==void 0&&h!=="."&&!l.has(u)){let c=g;while(c<d&&(e[c]===" "||e[c]==="\t"))c++;let A=(e[c]===":"||e[c]==="?"&&e[c+1]===":")&&/[{;,(\n]/.test(h);f+=A?C:b}else f+=C;h="a",u=g;continue}if(f+=m,m===`
|
|
153
|
-
`||!/\s/.test(m))h=m;u++}return f}function
|
|
154
|
-
export { ${
|
|
155
|
-
}`),ae}let K=[],te=[],he=new Set;for(let[X,G]of o){for(let
|
|
153
|
+
`||!/\s/.test(m))h=m;u++}return f}function pf(e,t,i,r){let n=[],o=new Map,s=[e,...t.filter((X)=>X!==e)];for(let X of s){let G=i.get(X);if(G===void 0){n.push(`No declarations were generated for ${Di(r.cwd,X)}; it is left out of the bundle`);continue}o.set(X,Yn(X,G))}let a=(X,G)=>{if(!X.startsWith(".")&&!X.startsWith("/"))return null;let Z=Yi(X,G).resolved;return Z&&o.has(Z)?Z:null},l=(X)=>X.startsWith(".")||X.startsWith("/"),f=new Set,u=(X)=>{let G=X;for(let Z=1;f.has(G);Z++)G=`${X}_${Z}`;return f.add(G),G},d=new Map;for(let[X,G]of o){let Z=new Map;for(let ae of G.declared)Z.set(ae,u(ae));d.set(X,Z)}let h=new Map,p=(X,G,Z)=>{let ae=`${X}\x00${G}`,q=h.get(ae);if(!q)q=u(Z),h.set(ae,q);return q},m=new Map,g=new Map,C=new Set,b=new Map,c=!0,A=(X,G,Z)=>{let ae=a(G,X.file);if(ae){if(Z==="*")return{kind:"namespace",file:ae};let q=S(ae).get(Z);if(!q&&!c)n.push(`${Di(r.cwd,X.file)}: '${Z}' is not exported by '${G}'`);return q??null}if(l(G))return n.push(`${Di(r.cwd,X.file)}: '${G}' is not part of the bundle`),null;return Z==="*"?{kind:"external-namespace",source:G}:{kind:"external",source:G,imported:Z}},M=(X,G)=>{if(X.declared.has(G))return{kind:"local",name:d.get(X.file).get(G)};let Z=X.imports.get(G);if(Z)return A(X,Z.specifier,Z.imported);return n.push(`${Di(r.cwd,X.file)}: cannot resolve exported name '${G}'`),null};function S(X){let G=m.get(X);if(G)return G;let Z=new Map,ae=o.get(X);if(!ae||C.has(X))return Z;C.add(X);let q=new Set;for(let[le,ve]of ae.localExports){let me=M(ae,ve);if(me)Z.set(le,me)}for(let le of ae.namedReExports){let ve=A(ae,le.specifier,le.imported);if(ve)Z.set(le.exported,ve)}for(let le of ae.namespaceReExports){let ve=A(ae,le.specifier,"*");if(ve)Z.set(le.exported,ve)}for(let le of ae.starReExports){let ve=a(le,X);if(ve){for(let[me,W]of S(ve))if(me!=="default"&&!Z.has(me))Z.set(me,W);for(let me of g.get(ve)??[])q.add(me)}else if(l(le))n.push(`${Di(r.cwd,X)}: '${le}' is not part of the bundle`);else q.add(le)}for(let[le,ve]of b.get(X)??[])Z.set(le,ve);return C.delete(X),m.set(X,Z),g.set(X,q),Z}for(let[X,G]of o)for(let Z of G.augmentations){let ae=a(Z.specifier,X);if(!ae)continue;for(let q of Yn(X,Z.body,!0).declared){if(S(ae).has(q))continue;let le=b.get(ae);if(!le)le=new Map,b.set(ae,le);le.set(q,{kind:"local",name:u(q)}),m.clear()}}c=!1,m.clear(),g.clear();let T=new Map,N=[],B=(X,G)=>{switch(X.kind){case"local":return X.name;case"external":return p(X.source,X.imported,X.imported==="default"?G:X.imported);case"external-namespace":return p(X.source,"*",G);case"namespace":return ee(X.file,G)}};function ee(X,G){let Z=T.get(X);if(Z)return Z;let ae=u(G);T.set(X,ae);let q=[];for(let[le,ve]of S(X)){if(le==="default")continue;let me=B(ve,le);q.push(me===le?le:`${me} as ${le}`)}if(g.get(X)?.size)n.push(`${Di(r.cwd,X)}: 'export * from' an external module cannot be expressed inside namespace '${ae}'`);return N.push(`declare namespace ${ae} {
|
|
154
|
+
export { ${q.join(", ")} };
|
|
155
|
+
}`),ae}let K=[],te=[],he=new Set;for(let[X,G]of o){for(let q of G.directives)he.add(q);let Z=new Map;for(let[q,le]of d.get(X))if(q!==le)Z.set(q,le);for(let[q,le]of G.imports){if(G.declared.has(q))continue;let ve=A(G,le.specifier,le.imported);if(!ve)continue;let me=B(ve,q);if(me!==q)Z.set(q,me)}let ae=[];for(let q of G.declarations){if(r.keepComments)ae.push(...q.statement.comments);let le=Nr(q.emit,Z);if(!/[;}]$/.test(le))le+=";";ae.push(le)}for(let q of G.verbatim){if(r.keepComments)te.push(...q.comments);let le=ra(q.text);if(le){let ve=new Map(Z);for(let me of Yn(X,le.body,!0).declared)ve.delete(me);te.push(q.text.slice(0,le.start)+Nr(le.body,ve)+q.text.slice(le.end))}else{let ve=ue(q.text),me=ve[1]?.kind==="quoted"?$t(q.text.slice(ve[1].start,ve[1].end)):void 0;if(me===void 0||!a(me,X))te.push(Nr(q.text,Z))}}for(let q of G.augmentations){let le=a(q.specifier,X),ve=Yn(X,q.body,!0),me=new Map(Z);if(!le){for(let Qe of ve.declared)me.delete(Qe);let W=ra(q.statement.text);if(r.keepComments)te.push(...q.statement.comments);te.push(q.statement.text.slice(0,W.start)+Nr(W.body,me)+q.statement.text.slice(W.end));continue}for(let[W,Qe]of S(le))me.set(W,B(Qe,W));if(r.keepComments)ae.push(...q.statement.comments);for(let W of ve.declarations){if(!W.name||!S(le).has(W.name))throw Error(`Cannot link augmentation '${q.specifier}' member '${W.name??W.emit}'`);if(r.keepComments)ae.push(...W.statement.comments);ae.push(Nr(W.emit,me))}}if(ae.length>0)K.push(`// From: ${Di(r.cwd,X)}
|
|
156
156
|
${ae.join(`
|
|
157
|
-
`)}`)}let Ae=S(e),Se=[],fe=[];for(let[X,G]of Ae){if(G.kind==="external"){fe.push(`export { ${G.imported===X?X:`${G.imported} as ${X}`} } from '${G.source}';`);continue}if(G.kind==="external-namespace"){fe.push(`export * as ${X} from '${G.source}';`);continue}let Z=B(G,X==="default"?"_default":X);Se.push(Z===X?X:`${Z} as ${X}`)}for(let X of g.get(e)??[])fe.push(`export * from '${X}';`);let re=new Map;for(let[X,G]of h){let[Z,ae]=X.split("\x00"),
|
|
157
|
+
`)}`)}let Ae=S(e),Se=[],fe=[];for(let[X,G]of Ae){if(G.kind==="external"){fe.push(`export { ${G.imported===X?X:`${G.imported} as ${X}`} } from '${G.source}';`);continue}if(G.kind==="external-namespace"){fe.push(`export * as ${X} from '${G.source}';`);continue}let Z=B(G,X==="default"?"_default":X);Se.push(Z===X?X:`${Z} as ${X}`)}for(let X of g.get(e)??[])fe.push(`export * from '${X}';`);let re=new Map;for(let[X,G]of h){let[Z,ae]=X.split("\x00"),q=re.get(Z)??{named:[],defaults:[],namespaces:[]};if(re.set(Z,q),ae==="*")q.namespaces.push(G);else if(ae==="default")q.defaults.push(G);else q.named.push(ae===G?G:`${ae} as ${G}`)}let pe=[];for(let[X,G]of[...re].sort(([Z],[ae])=>Z.localeCompare(ae))){for(let Z of G.defaults)pe.push(`import ${Z} from '${X}';`);for(let Z of G.namespaces)pe.push(`import * as ${Z} from '${X}';`);if(G.named.length>0)pe.push(`import { ${G.named.join(", ")} } from '${X}';`)}let D=[];if(he.size>0)D.push([...he].join(`
|
|
158
158
|
`));if(D.push(`/**
|
|
159
159
|
* Bundled TypeScript declarations
|
|
160
160
|
* Generated from ${o.size} source files
|
|
@@ -165,24 +165,24 @@ ${ae.join(`
|
|
|
165
165
|
`)),{content:`${D.join(`
|
|
166
166
|
|
|
167
167
|
`)}
|
|
168
|
-
`,files:[...o.keys()],exportCount:Ae.size,warnings:n}}var lm,um;var pf=ye(()=>{pt();$r();Gn();Pi();Jn();lm=/^[A-Z_$][\w$]*$/i;um=/^(?: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$]+)?/});import hm from"process";import{existsSync as mf,statSync as gf}from"fs";import{resolve as Wr}from"path";import pm from"process";import{existsSync as AC,mkdirSync as kC,readdirSync as TC,readFileSync as mm,writeFileSync as OC}from"fs";import{homedir as Xi}from"os";import{dirname as MC,resolve as Jt}from"path";import Oo from"process";import{existsSync as yf,statSync as wf}from"fs";import{existsSync as xa,mkdirSync as gm,readdirSync as ym,writeFileSync as wm}from"fs";import{homedir as Zi}from"os";import{dirname as Cf,resolve as Ct}from"path";import Ii from"process";import{join as Cm,relative as vm,resolve as vf}from"path";import go from"process";import{existsSync as ru,mkdirSync as GC,readdirSync as VC,writeFileSync as UC}from"fs";import{homedir as ra}from"os";import{dirname as HC,resolve as wt}from"path";import _r from"process";import{join as bm,relative as $m,resolve as bf}from"path";import yo from"process";import{existsSync as nu,mkdirSync as ZC,readdirSync as QC,writeFileSync as ev}from"fs";import{dirname as iv,resolve as wo}from"path";import Sa from"process";import{Buffer as pi}from"buffer";import{createCipheriv as xm,createDecipheriv as Sm,randomBytes as na}from"crypto";import{closeSync as oa,createReadStream as $f,createWriteStream as Em,existsSync as sa,fsyncSync as xf,openSync as Sf,writeFileSync as Am}from"fs";import{access as km,constants as Ef,mkdir as Tm,readdir as Xn,rename as Af,stat as Qi,unlink as Zn,writeFile as aa}from"fs/promises";import{join as er}from"path";import ft from"process";import{pipeline as Om}from"stream/promises";import{createGzip as kf}from"zlib";import tr from"process";import ri from"process";import{Buffer as ei}from"buffer";import{createCipheriv as Rm,createDecipheriv as Pm,randomBytes as la}from"crypto";import{closeSync as ca,createReadStream as Tf,createWriteStream as Mm,existsSync as Qn,fsyncSync as Of,openSync as Rf,writeFileSync as Dm}from"fs";import{access as Im,constants as Pf,mkdir as Nm,readdir as eo,rename as Mf,stat as ir,unlink as to,writeFile as fa}from"fs/promises";import{isAbsolute as Fm,join as rr,resolve as Wm}from"path";import We from"process";import{pipeline as Lm}from"stream/promises";import{createGzip as Df}from"zlib";import nr from"process";import ni from"process";import io from"process";import{existsSync as ro}from"fs";import{resolve as ua}from"path";import{existsSync as Bm}from"fs";import{existsSync as _m,readdirSync as jm}from"fs";import{extname as da,resolve as If}from"path";import Gm from"process";import{join as Vm,relative as Um,resolve as Nf}from"path";import Co from"process";import{Buffer as ti}from"buffer";import{createCipheriv as zm,createDecipheriv as Km,randomBytes as ha}from"crypto";import{closeSync as pa,createReadStream as Ff,createWriteStream as Hm,existsSync as no,fsyncSync as Wf,openSync as Lf,writeFileSync as qm}from"fs";import{access as Jm,constants as Bf,mkdir as Ym,readdir as oo,rename as _f,stat as or,unlink as so,writeFile as ma}from"fs/promises";import{isAbsolute as Xm,join as sr,resolve as Zm}from"path";import Le from"process";import{pipeline as Qm}from"stream/promises";import{createGzip as jf}from"zlib";import ar from"process";import oi from"process";import ao from"process";import{readFileSync as eg,realpathSync as tg}from"fs";import{createRequire as ig}from"module";import{pathToFileURL as rg}from"url";import{existsSync as ga,statSync as ng}from"fs";import{resolve as Gf}from"path";import{existsSync as og}from"fs";class ou{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 i=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${i}`}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(([,i],[,r])=>i.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let i=0;i<t;i++)this.cache.delete(e[i][0])}set(e,t,i,r){if(!this.options.enabled)return;let n=this.generateKey(e,i),o=r??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let i=this.generateKey(e,t),r=this.cache.get(i);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(i),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!mf(e))return!0;return gf(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let i=this.get(e,t);if(!i)return;if(this.isFileModified(t,i.fileTimestamp)){this.delete(e,t);return}return i.value}setWithFileCheck(e,t,i,r){try{let n=mf(i)?gf(i):null,o=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,r)}catch{this.set(e,t,i,r)}}delete(e,t){let i=this.generateKey(e,t);return this.cache.delete(i)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,i]of this.cache.entries())if(this.isExpired(i))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,n)=>r+n.size,0),i=e.map((r)=>r.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:i[0],newestEntry:i[i.length-1]}}export(){let e={};for(let[t,i]of this.cache.entries())e[t]={value:i.value,timestamp:i.timestamp.toISOString(),ttl:i.ttl,hits:i.hits,size:i.size};return e}import(e){this.cache.clear();for(let[t,i]of Object.entries(e))if(typeof i==="object"&&i!==null){let r=i;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class su{metrics=[];maxMetrics=1000;async track(e,t,i={}){let r=performance.now(),n=new Date;try{let o=await t(),s=performance.now()-r;return this.recordMetric({operation:e,duration:s,timestamp:n,...i}),o}catch(o){let s=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...i}),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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((n)=>n.duration),r=i.reduce((n,o)=>n+o,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function lu(e={}){let{name:t="",alias:i}=e,r=["config",".config"];if(t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let o of n){if(!o)continue;if(r.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)r.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(r.filter(Boolean)))}function sg(e){return lu(e).flatMap((t)=>au.map((i)=>Wr(e.directory,`${t}${i}`)))}function ag(e={}){let t=Wr(e.cwd||pm.cwd());return Array.from(new Set([t,Wr(t,"config"),Wr(t,".config"),e.configDir?Wr(t,e.configDir):void 0].filter((i)=>Boolean(i))))}function fg(e,t){this[e]=cg.bind(null,t)}class Fa{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let i=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${i}`}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(([,i],[,r])=>i.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let i=0;i<t;i++)this.cache.delete(e[i][0])}set(e,t,i,r){if(!this.options.enabled)return;let n=this.generateKey(e,i),o=r??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let i=this.generateKey(e,t),r=this.cache.get(i);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(i),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!yf(e))return!0;return wf(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let i=this.get(e,t);if(!i)return;if(this.isFileModified(t,i.fileTimestamp)){this.delete(e,t);return}return i.value}setWithFileCheck(e,t,i,r){try{let n=yf(i)?wf(i):null,o=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,r)}catch{this.set(e,t,i,r)}}delete(e,t){let i=this.generateKey(e,t);return this.cache.delete(i)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,i]of this.cache.entries())if(this.isExpired(i))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,n)=>r+n.size,0),i=e.map((r)=>r.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:i[0],newestEntry:i[i.length-1]}}export(){let e={};for(let[t,i]of this.cache.entries())e[t]={value:i.value,timestamp:i.timestamp.toISOString(),ttl:i.ttl,hits:i.hits,size:i.size};return e}import(e){this.cache.clear();for(let[t,i]of Object.entries(e))if(typeof i==="object"&&i!==null){let r=i;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Wa{metrics=[];maxMetrics=1000;async track(e,t,i={}){let r=performance.now(),n=new Date;try{let o=await t(),s=performance.now()-r;return this.recordMetric({operation:e,duration:s,timestamp:n,...i}),o}catch(o){let s=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...i}),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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((n)=>n.duration),r=i.reduce((n,o)=>n+o,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function hg(e,t={}){let i=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return i?`${e}:${i}`:e}function pg(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function mg(e){return e.getStats().size*2}function La(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&He(t[0])&&"id"in t[0]&&t[0].id===3&&He(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(He(t)&&He(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(He(e)&&"arr"in e&&Array.isArray(e.arr)&&He(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&He(t[0])&&He(e[0])){let r=[...t];for(let n of e)if(He(n)&&"name"in n){if(!r.find((o)=>He(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(He(n)&&"path"in n){if(!r.find((o)=>He(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>bo(o,n)))r.push(n);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}if(!He(t)||!He(e))return t;let i={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(n===null||n===void 0)continue;else if(He(n)&&He(i[r]))i[r]=La(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&He(n[0])&&He(i[r][0])){let o=[...n];for(let s of i[r])if(He(s)&&"name"in s){if(!o.find((a)=>He(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(He(s)&&"path"in s){if(!o.find((a)=>He(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>bo(a,s)))o.push(s);i[r]=o}else if(n.every((o)=>typeof o==="string")&&i[r].every((o)=>typeof o==="string")){let o=[...n];for(let s of i[r])if(!o.includes(s))o.push(s);i[r]=o}else i[r]=n;else i[r]=n}return i}function bo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!bo(e[i],t[i]))return!1;return!0}if(He(e)&&He(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!bo(e[n],t[n]))return!1}return!0}return!1}function He(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function gg(e,t){if(!nu(e))return null;try{let i=await import(e),r=i.default||i;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return La(t,r)}catch{return null}}catch{return null}}async function yg({name:e="",cwd:t,defaultConfig:i}){let r=t||Sa.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let a of n){let l=wo(r,`${s}${a}`),f=await gg(l,i);if(f!==null)return f}try{let s=wo(r,"package.json");if(nu(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return La(i,a)}catch{}}}catch{}return i}function wg(e,t={}){let i=yo.cwd();while(i.includes("storage"))i=bf(i,"..");let r=bf(i,e||"");if(t?.relative)return $m(yo.cwd(),r);return r}async function Cg(){try{let e=await yg({name:"clarity",defaultConfig:uo,cwd:yo.cwd(),endpoint:"",headers:{}});return{...uo,...e}}catch{return uo}}function Ze(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vg(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ri<"u"){let e=ri.type;if(e==="renderer"||e==="worker")return!1;return!!(ri.versions&&(ri.versions.node||ri.versions.bun))}return!1}class fu{async format(e){let t=await vg(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:tr.pid,hostname:t(),environment:tr.env.NODE_ENV||"development",platform:tr.platform,version:tr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tr.env.NODE_ENV||tr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $o{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={...Aa},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new fu,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??ft.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ho,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ho};return{...ho,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Aa.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await km(this.config.logDirectory,Ef.F_OK|Ef.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Tm(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:pi.from(e);try{if(!sa(this.currentLogFile))await aa(this.currentLogFile,"",{mode:420});if(r=Sf(this.currentLogFile,"a",420),Am(r,a,{flag:"a"}),xf(r),r!==void 0)oa(r),r=void 0;if((await Qi(this.currentLogFile)).size===0){if(await aa(this.currentLogFile,a,{flag:"w",mode:420}),(await Qi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(r!==void 0)try{oa(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(n===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}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return er(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return er(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return er(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ze())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return na(16).toString("hex")}generateKey(){return na(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(),i=na(16),r=xm("aes-256-gcm",t,i),n=pi.concat([r.update(e,"utf8"),r.final()]),o=r.getAuthTag();return{encrypted:pi.concat([i,n,o]),iv:i}}async compressData(e){return new Promise((t,i)=>{let r=kf(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(pi.from(pi.concat(n)))),r.on("error",i),r.write(e),r.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(Ze())return;let e=await Qi(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 i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Xn(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.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=`${i}.${s}`;if(await Qi(i).catch(()=>null))try{if(await Af(i,a),t.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await Zn(a)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await aa(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await Qi(i).catch(()=>null))await Af(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await Xn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await Zn(er(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=$f(e),r=Em(t),n=kf();await Om(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);await this.writeToFile(r),console.log(r)}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 i={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(i)}}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()})),sa(this.currentLogFile))try{let e=Sf(this.currentLogFile,"r+");xf(e),oa(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(!Ze()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Xn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zn(er(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}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?Ke.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=ft.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Ke.cyan(n)}`;if(!s)return f.trim();let u=a(f).trim().length,d=a(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${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 i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let a=t[r++];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(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}async log(e,t,...i){let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);if(this.fancy&&!Ze()){let f=vu[e],u=this.options.showTags!==!1&&this.name?Ke.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:Ke.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.error(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:Ke.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.error(d),a){let h=a.split(`
|
|
168
|
+
`,files:[...o.keys()],exportCount:Ae.size,warnings:n}}var cm,dm;var mf=ye(()=>{pt();$r();Gn();Pi();Jn();cm=/^[A-Z_$][\w$]*$/i;dm=/^(?: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$]+)?/});import pm from"process";import{existsSync as gf,statSync as yf}from"fs";import{resolve as Wr}from"path";import mm from"process";import{existsSync as kC,mkdirSync as TC,readdirSync as OC,readFileSync as gm,writeFileSync as RC}from"fs";import{homedir as Xi}from"os";import{dirname as DC,resolve as Jt}from"path";import Oo from"process";import{existsSync as wf,statSync as Cf}from"fs";import{existsSync as Sa,mkdirSync as ym,readdirSync as wm,writeFileSync as Cm}from"fs";import{homedir as Zi}from"os";import{dirname as vf,resolve as Ct}from"path";import Ii from"process";import{join as vm,relative as bm,resolve as bf}from"path";import go from"process";import{existsSync as nu,mkdirSync as VC,readdirSync as UC,writeFileSync as zC}from"fs";import{homedir as na}from"os";import{dirname as qC,resolve as wt}from"path";import _r from"process";import{join as $m,relative as xm,resolve as $f}from"path";import yo from"process";import{existsSync as ou,mkdirSync as QC,readdirSync as ev,writeFileSync as tv}from"fs";import{dirname as rv,resolve as wo}from"path";import Ea from"process";import{Buffer as pi}from"buffer";import{createCipheriv as Sm,createDecipheriv as Em,randomBytes as oa}from"crypto";import{closeSync as sa,createReadStream as xf,createWriteStream as Am,existsSync as aa,fsyncSync as Sf,openSync as Ef,writeFileSync as km}from"fs";import{access as Tm,constants as Af,mkdir as Om,readdir as Xn,rename as kf,stat as Qi,unlink as Zn,writeFile as la}from"fs/promises";import{join as er}from"path";import ft from"process";import{pipeline as Rm}from"stream/promises";import{createGzip as Tf}from"zlib";import tr from"process";import ri from"process";import{Buffer as ei}from"buffer";import{createCipheriv as Pm,createDecipheriv as Mm,randomBytes as ca}from"crypto";import{closeSync as fa,createReadStream as Of,createWriteStream as Dm,existsSync as Qn,fsyncSync as Rf,openSync as Pf,writeFileSync as Im}from"fs";import{access as Nm,constants as Mf,mkdir as Fm,readdir as eo,rename as Df,stat as ir,unlink as to,writeFile as ua}from"fs/promises";import{isAbsolute as Wm,join as rr,resolve as Lm}from"path";import We from"process";import{pipeline as Bm}from"stream/promises";import{createGzip as If}from"zlib";import nr from"process";import ni from"process";import io from"process";import{existsSync as ro}from"fs";import{resolve as da}from"path";import{existsSync as _m}from"fs";import{existsSync as jm,readdirSync as Gm}from"fs";import{extname as ha,resolve as Nf}from"path";import Vm from"process";import{join as Um,relative as zm,resolve as Ff}from"path";import Co from"process";import{Buffer as ti}from"buffer";import{createCipheriv as Km,createDecipheriv as Hm,randomBytes as pa}from"crypto";import{closeSync as ma,createReadStream as Wf,createWriteStream as qm,existsSync as no,fsyncSync as Lf,openSync as Bf,writeFileSync as Jm}from"fs";import{access as Ym,constants as _f,mkdir as Xm,readdir as oo,rename as jf,stat as or,unlink as so,writeFile as ga}from"fs/promises";import{isAbsolute as Zm,join as sr,resolve as Qm}from"path";import Le from"process";import{pipeline as eg}from"stream/promises";import{createGzip as Gf}from"zlib";import ar from"process";import oi from"process";import ao from"process";import{readFileSync as tg,realpathSync as ig}from"fs";import{createRequire as rg}from"module";import{pathToFileURL as ng}from"url";import{existsSync as ya,statSync as og}from"fs";import{resolve as Vf}from"path";import{existsSync as sg}from"fs";class su{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 i=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${i}`}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(([,i],[,r])=>i.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let i=0;i<t;i++)this.cache.delete(e[i][0])}set(e,t,i,r){if(!this.options.enabled)return;let n=this.generateKey(e,i),o=r??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let i=this.generateKey(e,t),r=this.cache.get(i);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(i),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!gf(e))return!0;return yf(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let i=this.get(e,t);if(!i)return;if(this.isFileModified(t,i.fileTimestamp)){this.delete(e,t);return}return i.value}setWithFileCheck(e,t,i,r){try{let n=gf(i)?yf(i):null,o=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,r)}catch{this.set(e,t,i,r)}}delete(e,t){let i=this.generateKey(e,t);return this.cache.delete(i)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,i]of this.cache.entries())if(this.isExpired(i))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,n)=>r+n.size,0),i=e.map((r)=>r.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:i[0],newestEntry:i[i.length-1]}}export(){let e={};for(let[t,i]of this.cache.entries())e[t]={value:i.value,timestamp:i.timestamp.toISOString(),ttl:i.ttl,hits:i.hits,size:i.size};return e}import(e){this.cache.clear();for(let[t,i]of Object.entries(e))if(typeof i==="object"&&i!==null){let r=i;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class au{metrics=[];maxMetrics=1000;async track(e,t,i={}){let r=performance.now(),n=new Date;try{let o=await t(),s=performance.now()-r;return this.recordMetric({operation:e,duration:s,timestamp:n,...i}),o}catch(o){let s=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...i}),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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((n)=>n.duration),r=i.reduce((n,o)=>n+o,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function cu(e={}){let{name:t="",alias:i}=e,r=["config",".config"];if(t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let o of n){if(!o)continue;if(r.push(o,`.${o}.config`,`${o}.config`,`.${o}`),t)r.push(`${t}.${o}.config`,`.${t}.${o}.config`)}return Array.from(new Set(r.filter(Boolean)))}function ag(e){return cu(e).flatMap((t)=>lu.map((i)=>Wr(e.directory,`${t}${i}`)))}function lg(e={}){let t=Wr(e.cwd||mm.cwd());return Array.from(new Set([t,Wr(t,"config"),Wr(t,".config"),e.configDir?Wr(t,e.configDir):void 0].filter((i)=>Boolean(i))))}function ug(e,t){this[e]=fg.bind(null,t)}class Wa{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 i=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${i}`}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(([,i],[,r])=>i.timestamp.getTime()-r.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let i=0;i<t;i++)this.cache.delete(e[i][0])}set(e,t,i,r){if(!this.options.enabled)return;let n=this.generateKey(e,i),o=r??this.options.ttl,s=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:o,hits:0,size:s}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let i=this.generateKey(e,t),r=this.cache.get(i);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(i),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(e,t){try{if(!wf(e))return!0;return Cf(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let i=this.get(e,t);if(!i)return;if(this.isFileModified(t,i.fileTimestamp)){this.delete(e,t);return}return i.value}setWithFileCheck(e,t,i,r){try{let n=wf(i)?Cf(i):null,o=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:o},i,r)}catch{this.set(e,t,i,r)}}delete(e,t){let i=this.generateKey(e,t);return this.cache.delete(i)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,i]of this.cache.entries())if(this.isExpired(i))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((r,n)=>r+n.size,0),i=e.map((r)=>r.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:i[0],newestEntry:i[i.length-1]}}export(){let e={};for(let[t,i]of this.cache.entries())e[t]={value:i.value,timestamp:i.timestamp.toISOString(),ttl:i.ttl,hits:i.hits,size:i.size};return e}import(e){this.cache.clear();for(let[t,i]of Object.entries(e))if(typeof i==="object"&&i!==null){let r=i;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class La{metrics=[];maxMetrics=1000;async track(e,t,i={}){let r=performance.now(),n=new Date;try{let o=await t(),s=performance.now()-r;return this.recordMetric({operation:e,duration:s,timestamp:n,...i}),o}catch(o){let s=performance.now()-r;throw this.recordMetric({operation:`${e}:error`,duration:s,timestamp:n,...i}),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((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let i=t.map((n)=>n.duration),r=i.reduce((n,o)=>n+o,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...i),maxDuration:Math.max(...i),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function pg(e,t={}){let i=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return i?`${e}:${i}`:e}function mg(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gg(e){return e.getStats().size*2}function Ba(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&He(t[0])&&"id"in t[0]&&t[0].id===3&&He(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(He(t)&&He(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(He(e)&&"arr"in e&&Array.isArray(e.arr)&&He(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&He(t[0])&&He(e[0])){let r=[...t];for(let n of e)if(He(n)&&"name"in n){if(!r.find((o)=>He(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(He(n)&&"path"in n){if(!r.find((o)=>He(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>bo(o,n)))r.push(n);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}if(!He(t)||!He(e))return t;let i={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(n===null||n===void 0)continue;else if(He(n)&&He(i[r]))i[r]=Ba(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&He(n[0])&&He(i[r][0])){let o=[...n];for(let s of i[r])if(He(s)&&"name"in s){if(!o.find((a)=>He(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(He(s)&&"path"in s){if(!o.find((a)=>He(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>bo(a,s)))o.push(s);i[r]=o}else if(n.every((o)=>typeof o==="string")&&i[r].every((o)=>typeof o==="string")){let o=[...n];for(let s of i[r])if(!o.includes(s))o.push(s);i[r]=o}else i[r]=n;else i[r]=n}return i}function bo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!bo(e[i],t[i]))return!1;return!0}if(He(e)&&He(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!bo(e[n],t[n]))return!1}return!0}return!1}function He(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function yg(e,t){if(!ou(e))return null;try{let i=await import(e),r=i.default||i;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return Ba(t,r)}catch{return null}}catch{return null}}async function wg({name:e="",cwd:t,defaultConfig:i}){let r=t||Ea.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],o=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let s of o)for(let a of n){let l=wo(r,`${s}${a}`),f=await yg(l,i);if(f!==null)return f}try{let s=wo(r,"package.json");if(ou(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Ba(i,a)}catch{}}}catch{}return i}function Cg(e,t={}){let i=yo.cwd();while(i.includes("storage"))i=$f(i,"..");let r=$f(i,e||"");if(t?.relative)return xm(yo.cwd(),r);return r}async function vg(){try{let e=await wg({name:"clarity",defaultConfig:uo,cwd:yo.cwd(),endpoint:"",headers:{}});return{...uo,...e}}catch{return uo}}function Ze(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bg(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ri<"u"){let e=ri.type;if(e==="renderer"||e==="worker")return!1;return!!(ri.versions&&(ri.versions.node||ri.versions.bun))}return!1}class uu{async format(e){let t=await bg(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:tr.pid,hostname:t(),environment:tr.env.NODE_ENV||"development",platform:tr.platform,version:tr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tr.env.NODE_ENV||tr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $o{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={...ka},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uu,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??ft.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ho,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ho};return{...ho,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ka.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Tm(this.config.logDirectory,Af.F_OK|Af.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Om(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:pi.from(e);try{if(!aa(this.currentLogFile))await la(this.currentLogFile,"",{mode:420});if(r=Ef(this.currentLogFile,"a",420),km(r,a,{flag:"a"}),Sf(r),r!==void 0)sa(r),r=void 0;if((await Qi(this.currentLogFile)).size===0){if(await la(this.currentLogFile,a,{flag:"w",mode:420}),(await Qi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(r!==void 0)try{sa(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(n===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}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return er(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return er(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return er(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ze())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return oa(16).toString("hex")}generateKey(){return oa(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(),i=oa(16),r=Sm("aes-256-gcm",t,i),n=pi.concat([r.update(e,"utf8"),r.final()]),o=r.getAuthTag();return{encrypted:pi.concat([i,n,o]),iv:i}}async compressData(e){return new Promise((t,i)=>{let r=Tf(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(pi.from(pi.concat(n)))),r.on("error",i),r.write(e),r.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(Ze())return;let e=await Qi(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 i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Xn(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.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=`${i}.${s}`;if(await Qi(i).catch(()=>null))try{if(await kf(i,a),t.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await Zn(a)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await la(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await Qi(i).catch(()=>null))await kf(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await Xn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await Zn(er(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=xf(e),r=Am(t),n=Tf();await Rm(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);await this.writeToFile(r),console.log(r)}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 i={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(i)}}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()})),aa(this.currentLogFile))try{let e=Ef(this.currentLogFile,"r+");Sf(e),sa(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(!Ze()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Xn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zn(er(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}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?Ke.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=ft.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Ke.cyan(n)}`;if(!s)return f.trim();let u=a(f).trim().length,d=a(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${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 i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let a=t[r++];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(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}async log(e,t,...i){let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);if(this.fancy&&!Ze()){let f=bu[e],u=this.options.showTags!==!1&&this.name?Ke.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:Ke.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.error(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:Ke.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:s,level:e}),console.error(d),a){let h=a.split(`
|
|
169
169
|
`);for(let p of h)if(p.trim()&&!p.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:Ke.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!Ze()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}if(!this.shouldLog(e))return;let l=`${o} ${this.environment}.${e.toUpperCase()}: ${s}
|
|
170
170
|
`;if(a)l+=`${a}
|
|
171
171
|
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(e){let t=performance.now();if(this.fancy&&!Ze()){let i=this.options.showTags!==!1&&this.name?Ke.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:Ke.blue("\u25D0"),tag:i,message:`${Ke.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let r=performance.now(),n=Math.round(r-t),o=`${e} completed in ${n}ms`,s=new Date,a=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)l+=` ${JSON.stringify(i)}`;if(l+=`
|
|
172
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!Ze()){let f=this.options.showTags!==!1&&this.name?Ke.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Ke.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!Ze())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new $o(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(i),i}createReadStream(){if(Ze())throw Error("createReadStream is not supported in browser environments");if(!
|
|
172
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!Ze()){let f=this.options.showTags!==!1&&this.name?Ke.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:Ke.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!Ze())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new $o(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(i),i}createReadStream(){if(Ze())throw Error("createReadStream is not supported in browser environments");if(!aa(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xf(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 i=this.keys.get(this.currentKeyId);try{let r=pi.isBuffer(e)?e:pi.from(e,"base64"),n=r.slice(0,16),o=r.slice(-16),s=r.slice(16,-16),a=Em("aes-256-gcm",i,n);return a.setAuthTag(o),pi.concat([a.update(s),a.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ze()}isServerMode(){return!Ze()}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,i=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!Ze()){let o=e.split(`
|
|
173
173
|
`),s=Math.max(...o.map((u)=>u.length))+2,a=`\u250C${"\u2500".repeat(s)}\u2510`,l=`\u2514${"\u2500".repeat(s)}\u2518`,f=o.map((u)=>{let d=" ".repeat(s-u.length-2);return`\u2502 ${u}${d} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:i,message:Ke.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:Ke.cyan(a)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:i,message:Ke.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:i,message:Ke.cyan(l),showTimestamp:!1}))}else if(!Ze())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let n=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
174
174
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(Ze())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Ke.cyan("?")} ${e} (y/n) `);let i=(r)=>{let n=r.toString().trim().toLowerCase();ft.stdin.removeListener("data",i);try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!1)}catch{}ft.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!0)}catch{}ft.stdin.resume(),ft.stdin.once("data",i)})}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 i=e;if(t&&t.length>0){let n=/%([sdijfo%])/g,o=0;if(i=e.replace(n,(s,a)=>{if(a==="%")return"%";if(o>=t.length)return s;let l=t[o++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return s}}),o<t.length)i+=` ${t.slice(o).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!Ze()){let n=this.options.showTags!==!1&&this.name?Ke.gray(this.formatTag(this.name)):"",o=Ke.blue("\u25D0");console.error(`${o} ${n} ${Ke.cyan(i)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
175
175
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(e,t=""){if(!this.enabled||!this.fancy||Ze()||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 i=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:i,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ze())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,r)),n!==void 0)this.activeProgressBar.message=n;let o=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,o)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ze())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Ze())return;ft.stdout.write(`${"\r".padEnd(ft.stdout.columns||80)}\r`),this.log(n,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Ze()||!ft.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*i/100),n=e.barLength-r,o=Ke.green("\u2501".repeat(r)),s=Ke.gray("\u2501".repeat(n)),a=`[${o}${s}]`,l=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||i===100?Ke.green("\u2713"):Ke.blue("\u25B6"),d=this.options.showTags!==!1&&this.name?` ${Ke.gray(this.formatTag(this.name))}`:"",h=`\r${u}${d} ${a} ${l}${f}`,p=ft.stdout.columns||80,m=" ".repeat(Math.max(0,p-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,ft.stdout.write(e.lastRenderedLine),t)ft.stdout.write(`
|
|
176
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ze()||!ft.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(Ze()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Xn(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=er(this.config.logDirectory,r);if(e.before)try{if((await Qi(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await Zn(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function fo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Be(t[0])&&"id"in t[0]&&t[0].id===3&&Be(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Be(t)&&Be(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(Be(e)&&"arr"in e&&Array.isArray(e.arr)&&Be(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Be(t[0])&&Be(e[0])){let r=[...t];for(let n of e)if(Be(n)&&"name"in n){if(!r.find((o)=>Be(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(Be(n)&&"path"in n){if(!r.find((o)=>Be(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>xo(o,n)))r.push(n);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}if(!Be(t)||!Be(e))return t;let i={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(n===null||n===void 0)continue;else if(Be(n)&&Be(i[r]))i[r]=fo(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&Be(n[0])&&Be(i[r][0])){let o=[...n];for(let s of i[r])if(Be(s)&&"name"in s){if(!o.find((a)=>Be(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Be(s)&&"path"in s){if(!o.find((a)=>Be(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>xo(a,s)))o.push(s);i[r]=o}else if(n.every((o)=>typeof o==="string")&&i[r].every((o)=>typeof o==="string")){let o=[...n];for(let s of i[r])if(!o.includes(s))o.push(s);i[r]=o}else i[r]=n;else i[r]=n}return i}function Ba(e,t,i="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return i==="replace"?t:fo(e,t);if(Array.isArray(e))return i==="replace"?t:fo(e,t);if(!Be(t)||!Be(e))return t;let r={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let o=t[n],s=r[n];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(i==="replace")r[n]=o;else r[n]=fo(s,o);else if(Be(o)&&Be(s))r[n]=Ba(s,o,i);else r[n]=o}return r}function xo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!xo(e[i],t[i]))return!1;return!0}if(Be(e)&&Be(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!xo(e[n],t[n]))return!1}return!0}return!1}function Be(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function lo(e,t,i="replace"){if(!ru(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 Ba(t,n,i)}catch{return null}}catch{return null}}function bg(e,t,i=!1){if(!e)return t;let r=e.toUpperCase().replace(/-/g,"_"),n={...t};function o(s,a=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...a,f],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),p=`${r}_${d.map(h).join("_")}`,m=`${r}_${d.map((g)=>g.toUpperCase()).join("_")}`;if(i)dt.info(`Checking environment variable ${p} for config ${e}.${d.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[f]=o(u,d);else{let g=_r.env[p]||_r.env[m];if(g!==void 0){if(i)dt.info(`Using environment variable ${g?p:m} for config ${e}.${d.join(".")}`);if(typeof u==="number")l[f]=Number(g);else if(typeof u==="boolean")l[f]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse(g);if(Array.isArray(C))l[f]=C;else l[f]=g.split(",").map((b)=>b.trim())}catch{l[f]=g.split(",").map((C)=>C.trim())}else l[f]=g}}}return l}return o(n)}async function $g({name:e="",alias:t,cwd:i,configDir:r,defaultConfig:n,verbose:o=!1,checkEnv:s=!0,arrayStrategy:a="replace"}){let l=s&&typeof n==="object"&&n!==null&&!Array.isArray(n)?bg(e,n,o):n,f=i||_r.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)dt.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let d=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),p=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([f,wt(f,"config"),wt(f,".config"),r?wt(f,r):void 0].filter(Boolean)));for(let C of g){if(o)dt.info(`Searching for configuration in: ${C}`);let b=[wt(f,"config"),wt(f,".config")].concat(r?[wt(f,r)]:[]).includes(C)?[...d,...h,...p,...m]:[...h,...d,...m,...p];for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from: ${M}`);return S}}}if(e){let C=wt(ra(),".config",e),b=["config",`${e}.config`];if(t)b.push(`${t}.config`);if(o)dt.info(`Checking user config directory: ${C}`);for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from user config directory: ${M}`);return S}}}if(e){let C=wt(ra(),".config"),b=[`.${e}.config`];if(t)b.push(`.${t}.config`);if(o)dt.info(`Checking user config directory for dotfile configs: ${C}`);for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from user config directory dotfile: ${M}`);return S}}}if(e){let C=ra(),b=[`.${e}.config`,`.${e}`];if(t)b.push(`.${t}.config`),b.push(`.${t}`);if(o)dt.info(`Checking user home directory for dotfile configs: ${C}`);for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from user home directory: ${M}`);return S}}}try{let C=wt(f,"package.json");if(ru(C)){let b=await import(C),c=b[e];if(!c&&t){if(c=b[t],c&&o)dt.success(`Using alias "${t}" configuration from package.json`)}if(c&&typeof c==="object"&&!Array.isArray(c))try{if(o)dt.success(`Configuration loaded from package.json: ${c===b[e]?e:t}`);return Ba(l,c,a)}catch(A){if(o)dt.warn("Failed to merge package.json config:",A)}}}catch(C){if(o)dt.warn("Failed to load package.json:",C)}if(o)dt.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return l}function xg(e,t={}){let i=go.cwd();while(i.includes("storage"))i=vf(i,"..");let r=vf(i,e||"");if(t?.relative)return vm(go.cwd(),r);return r}async function Sg(){try{let e=await $g({name:"clarity",alias:"logging",defaultConfig:po,cwd:go.cwd()});return{...po,...e||{}}}catch{return po}}function nt(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Eg(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ni<"u"){let e=ni.type;if(e==="renderer"||e==="worker")return!1;return!!(ni.versions&&(ni.versions.node||ni.versions.bun))}return!1}class uu{async format(e){let t=await Eg(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:nr.pid,hostname:t(),environment:nr.env.NODE_ENV||"development",platform:nr.platform,version:nr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:nr.env.NODE_ENV||nr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class So{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={...ka},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uu,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??We.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{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},i=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[i]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...mo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...mo};return{...mo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ka.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!nt()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Im(this.config.logDirectory,Pf.F_OK|Pf.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Nm(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ei.from(e);try{if(!Qn(this.currentLogFile))await fa(this.currentLogFile,"",{mode:420});if(r=Rf(this.currentLogFile,"a",420),Dm(r,a,{flag:"a"}),Of(r),r!==void 0)ca(r),r=void 0;if((await ir(this.currentLogFile)).size===0){if(await fa(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(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(r!==void 0)try{ca(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(n===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}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return rr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return rr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return rr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(nt())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return la(16).toString("hex")}generateKey(){return la(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(),i=la(16),r=Rm("aes-256-gcm",t,i),n=ei.isBuffer(e)?e:ei.from(e,"utf8"),o=r.update(n),s=r.final(),a=o.length+s.length,l=r.getAuthTag(),f=ei.allocUnsafe(16+a+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),l.copy(f,16+a),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=Df(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(ei.from(ei.concat(n)))),r.on("error",i),r.write(e),r.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(nt())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 i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await eo(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.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=`${i}.${s}`;if(await ir(i).catch(()=>null))try{if(await Mf(i,a),t.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await to(a)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await fa(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await ir(i).catch(()=>null))await Mf(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await eo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await to(rr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=Tf(e),r=Mm(t),n=Df();await Lm(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),Qn(this.currentLogFile))try{let e=Rf(this.currentLogFile,"r+");Of(e),ca(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(!nt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await eo(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await to(rr(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}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()?Re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||nt())return!1;let e=typeof We.env.NO_COLOR<"u",t=We.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof We.stderr<"u"&&We.stderr.isTTY||typeof We.stdout<"u"&&We.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=We.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Re.cyan(n)}`;if(!s)return f.trim();let u=a(f).trim().length,d=a(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${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 i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let a=t[r++];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(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,r,n)=>{let o=Re.underline(Re.blue(r)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,l="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,r)=>Re.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,r)=>Re.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,r)=>Re.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,r)=>Re.italic(r)),t=t.replace(/~([^~]+)~/g,(i,r)=>Re.strikethrough(r)),t}supportsHyperlinks(){if(nt())return!1;let e=We.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 i=We.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Fm(t)||t.startsWith("./")||t.startsWith("../"))t=Wm(t);else return null;return Qn(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,i=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:i}}async log(e,t,...i){let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);let{consoleText:l,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":bu[e],h=this.options.showTags!==!1&&this.name?Re.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Re.gray(l),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Re.green(l),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.error(p),a){let m=a.split(`
|
|
176
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ze()||!ft.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(Ze()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Xn(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=er(this.config.logDirectory,r);if(e.before)try{if((await Qi(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await Zn(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function fo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Be(t[0])&&"id"in t[0]&&t[0].id===3&&Be(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Be(t)&&Be(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(Be(e)&&"arr"in e&&Array.isArray(e.arr)&&Be(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Be(t[0])&&Be(e[0])){let r=[...t];for(let n of e)if(Be(n)&&"name"in n){if(!r.find((o)=>Be(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(Be(n)&&"path"in n){if(!r.find((o)=>Be(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>xo(o,n)))r.push(n);return r}if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}if(!Be(t)||!Be(e))return t;let i={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let n=t[r];if(n===null||n===void 0)continue;else if(Be(n)&&Be(i[r]))i[r]=fo(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&Be(n[0])&&Be(i[r][0])){let o=[...n];for(let s of i[r])if(Be(s)&&"name"in s){if(!o.find((a)=>Be(a)&&("name"in a)&&a.name===s.name))o.push(s)}else if(Be(s)&&"path"in s){if(!o.find((a)=>Be(a)&&("path"in a)&&a.path===s.path))o.push(s)}else if(!o.some((a)=>xo(a,s)))o.push(s);i[r]=o}else if(n.every((o)=>typeof o==="string")&&i[r].every((o)=>typeof o==="string")){let o=[...n];for(let s of i[r])if(!o.includes(s))o.push(s);i[r]=o}else i[r]=n;else i[r]=n}return i}function _a(e,t,i="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return i==="replace"?t:fo(e,t);if(Array.isArray(e))return i==="replace"?t:fo(e,t);if(!Be(t)||!Be(e))return t;let r={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let o=t[n],s=r[n];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(s))if(i==="replace")r[n]=o;else r[n]=fo(s,o);else if(Be(o)&&Be(s))r[n]=_a(s,o,i);else r[n]=o}return r}function xo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!xo(e[i],t[i]))return!1;return!0}if(Be(e)&&Be(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!xo(e[n],t[n]))return!1}return!0}return!1}function Be(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function lo(e,t,i="replace"){if(!nu(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 _a(t,n,i)}catch{return null}}catch{return null}}function $g(e,t,i=!1){if(!e)return t;let r=e.toUpperCase().replace(/-/g,"_"),n={...t};function o(s,a=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...a,f],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),p=`${r}_${d.map(h).join("_")}`,m=`${r}_${d.map((g)=>g.toUpperCase()).join("_")}`;if(i)dt.info(`Checking environment variable ${p} for config ${e}.${d.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[f]=o(u,d);else{let g=_r.env[p]||_r.env[m];if(g!==void 0){if(i)dt.info(`Using environment variable ${g?p:m} for config ${e}.${d.join(".")}`);if(typeof u==="number")l[f]=Number(g);else if(typeof u==="boolean")l[f]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse(g);if(Array.isArray(C))l[f]=C;else l[f]=g.split(",").map((b)=>b.trim())}catch{l[f]=g.split(",").map((C)=>C.trim())}else l[f]=g}}}return l}return o(n)}async function xg({name:e="",alias:t,cwd:i,configDir:r,defaultConfig:n,verbose:o=!1,checkEnv:s=!0,arrayStrategy:a="replace"}){let l=s&&typeof n==="object"&&n!==null&&!Array.isArray(n)?$g(e,n,o):n,f=i||_r.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)dt.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let d=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),p=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([f,wt(f,"config"),wt(f,".config"),r?wt(f,r):void 0].filter(Boolean)));for(let C of g){if(o)dt.info(`Searching for configuration in: ${C}`);let b=[wt(f,"config"),wt(f,".config")].concat(r?[wt(f,r)]:[]).includes(C)?[...d,...h,...p,...m]:[...h,...d,...m,...p];for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from: ${M}`);return S}}}if(e){let C=wt(na(),".config",e),b=["config",`${e}.config`];if(t)b.push(`${t}.config`);if(o)dt.info(`Checking user config directory: ${C}`);for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from user config directory: ${M}`);return S}}}if(e){let C=wt(na(),".config"),b=[`.${e}.config`];if(t)b.push(`.${t}.config`);if(o)dt.info(`Checking user config directory for dotfile configs: ${C}`);for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from user config directory dotfile: ${M}`);return S}}}if(e){let C=na(),b=[`.${e}.config`,`.${e}`];if(t)b.push(`.${t}.config`),b.push(`.${t}`);if(o)dt.info(`Checking user home directory for dotfile configs: ${C}`);for(let c of b)for(let A of u){let M=wt(C,`${c}${A}`),S=await lo(M,l,a);if(S!==null){if(o)dt.success(`Configuration loaded from user home directory: ${M}`);return S}}}try{let C=wt(f,"package.json");if(nu(C)){let b=await import(C),c=b[e];if(!c&&t){if(c=b[t],c&&o)dt.success(`Using alias "${t}" configuration from package.json`)}if(c&&typeof c==="object"&&!Array.isArray(c))try{if(o)dt.success(`Configuration loaded from package.json: ${c===b[e]?e:t}`);return _a(l,c,a)}catch(A){if(o)dt.warn("Failed to merge package.json config:",A)}}}catch(C){if(o)dt.warn("Failed to load package.json:",C)}if(o)dt.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return l}function Sg(e,t={}){let i=go.cwd();while(i.includes("storage"))i=bf(i,"..");let r=bf(i,e||"");if(t?.relative)return bm(go.cwd(),r);return r}async function Eg(){try{let e=await xg({name:"clarity",alias:"logging",defaultConfig:po,cwd:go.cwd()});return{...po,...e||{}}}catch{return po}}function nt(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ag(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ni<"u"){let e=ni.type;if(e==="renderer"||e==="worker")return!1;return!!(ni.versions&&(ni.versions.node||ni.versions.bun))}return!1}class du{async format(e){let t=await Ag(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:nr.pid,hostname:t(),environment:nr.env.NODE_ENV||"development",platform:nr.platform,version:nr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:nr.env.NODE_ENV||nr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class So{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={...Ta},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new du,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??We.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{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},i=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[i]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...mo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...mo};return{...mo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ta.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!nt()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Nm(this.config.logDirectory,Mf.F_OK|Mf.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Fm(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ei.from(e);try{if(!Qn(this.currentLogFile))await ua(this.currentLogFile,"",{mode:420});if(r=Pf(this.currentLogFile,"a",420),Im(r,a,{flag:"a"}),Rf(r),r!==void 0)fa(r),r=void 0;if((await ir(this.currentLogFile)).size===0){if(await ua(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(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(r!==void 0)try{fa(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(n===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}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return rr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return rr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return rr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(nt())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return ca(16).toString("hex")}generateKey(){return ca(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(),i=ca(16),r=Pm("aes-256-gcm",t,i),n=ei.isBuffer(e)?e:ei.from(e,"utf8"),o=r.update(n),s=r.final(),a=o.length+s.length,l=r.getAuthTag(),f=ei.allocUnsafe(16+a+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),l.copy(f,16+a),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=If(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(ei.from(ei.concat(n)))),r.on("error",i),r.write(e),r.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(nt())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 i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await eo(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.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=`${i}.${s}`;if(await ir(i).catch(()=>null))try{if(await Df(i,a),t.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await to(a)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await ua(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await ir(i).catch(()=>null))await Df(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await eo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await to(rr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=Of(e),r=Dm(t),n=If();await Bm(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),Qn(this.currentLogFile))try{let e=Pf(this.currentLogFile,"r+");Rf(e),fa(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(!nt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await eo(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await to(rr(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}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()?Re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||nt())return!1;let e=typeof We.env.NO_COLOR<"u",t=We.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof We.stderr<"u"&&We.stderr.isTTY||typeof We.stdout<"u"&&We.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=We.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Re.cyan(n)}`;if(!s)return f.trim();let u=a(f).trim().length,d=a(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${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 i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let a=t[r++];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(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,r,n)=>{let o=Re.underline(Re.blue(r)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,l="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,r)=>Re.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,r)=>Re.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,r)=>Re.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,r)=>Re.italic(r)),t=t.replace(/~([^~]+)~/g,(i,r)=>Re.strikethrough(r)),t}supportsHyperlinks(){if(nt())return!1;let e=We.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 i=We.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Wm(t)||t.startsWith("./")||t.startsWith("../"))t=Lm(t);else return null;return Qn(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,i=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:i}}async log(e,t,...i){let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);let{consoleText:l,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":$u[e],h=this.options.showTags!==!1&&this.name?Re.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Re.gray(l),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Re.green(l),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.error(p),a){let m=a.split(`
|
|
177
177
|
`);for(let g of m)if(g.trim()&&!g.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:Re.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!nt()){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}
|
|
178
178
|
`;if(a)u+=`${a}
|
|
179
179
|
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let i={update:(n,o)=>{},finish:(n)=>{},interrupt:(n,o)=>{}};if(!this.enabled)return i;let r=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!nt()&&We.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!nt()&&We.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,o="info")=>{if(!nt()&&We.stdout.isTTY)We.stdout.write(`
|
|
180
180
|
`);if(this[o==="warning"?"warn":o](n),this.activeProgressBar&&this.shouldStyleConsole()&&!nt()&&We.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let i=this.options.showTags!==!1&&this.name?Re.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Re.blue("\u25D0"),tag:i,message:`${Re.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let r=performance.now(),n=Math.round(r-t),o=`${e} completed in ${n}ms`,s=new Date,a=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)l+=` ${JSON.stringify(i)}`;if(l+=`
|
|
181
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?Re.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":Re.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!nt())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new So(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(i),i}createReadStream(){if(nt())throw Error("createReadStream is not supported in browser environments");if(!Qn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
181
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?Re.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":Re.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!nt())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new So(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(i),i}createReadStream(){if(nt())throw Error("createReadStream is not supported in browser environments");if(!Qn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Of(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 i=this.keys.get(this.currentKeyId);try{let r=ei.isBuffer(e)?e:ei.from(e,"base64"),n=r.subarray(0,16),o=r.subarray(r.length-16),s=r.subarray(16,r.length-16),a=Mm("aes-256-gcm",i,n);a.setAuthTag(o);let l=a.update(s),f=a.final(),u=l.length+f.length,d=ei.allocUnsafe(u);return l.copy(d,0),f.copy(d,l.length),d.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return nt()}isServerMode(){return!nt()}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,i=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:n,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
182
182
|
`),l=Math.max(...a.map((h)=>h.length))+2,f=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,d=a.map((h)=>this.formatConsoleMessage({timestamp:i,message:Re.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:Re.cyan(f),showTimestamp:!1})),d.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:i,message:Re.cyan(u),showTimestamp:!1}))}else if(!nt())console.error(`${r} ${this.environment}.INFO: [BOX] ${o}`);let s=`${r} ${this.environment}.INFO: [BOX] ${o}
|
|
183
183
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(nt())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Re.cyan("?")} ${e} (y/n) `);let i=(r)=>{let n=r.toString().trim().toLowerCase();We.stdin.removeListener("data",i);try{if(typeof We.stdin.setRawMode==="function")We.stdin.setRawMode(!1)}catch{}We.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof We.stdin.setRawMode==="function")We.stdin.setRawMode(!0)}catch{}We.stdin.resume(),We.stdin.once("data",i)})}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 i=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,a=0;if(i=e.replace(s,(l,f)=>{if(f==="%")return"%";if(a>=t.length)return l;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 l}}),a<t.length)i+=` ${t.slice(a).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:n}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?Re.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${Re.blue("\u25D0")} `;console.error(`${a}${s} ${Re.cyan(r)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
184
184
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!We.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*i/100),n=e.barLength-r,o=Re.green("\u2501".repeat(r)),s=Re.gray("\u2501".repeat(n)),a=`[${o}${s}]`,l=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||i===100?Re.green("\u2713"):Re.blue("\u25B6"),d=this.options.showTags!==!1&&this.name?` ${Re.gray(this.formatTag(this.name))}`:"",h=`\r${u}${d} ${a} ${l}${f}`,p=We.stdout.columns||80,m=" ".repeat(Math.max(0,p-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,We.stdout.write(e.lastRenderedLine),t)We.stdout.write(`
|
|
185
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||nt()||!We.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(nt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await eo(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=rr(this.config.logDirectory,r);if(e.before)try{if((await ir(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await to(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function
|
|
185
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||nt()||!We.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(nt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await eo(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=rr(this.config.logDirectory,r);if(e.before)try{if((await ir(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await to(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function hu(e,t={}){let{maxRetries:i=3,retryDelay:r=1000,isRetryable:n=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=i;a++)try{return await e()}catch(l){if(s=l instanceof Error?l:Error(String(l)),a===i||!n(s))break;if(r>0)await new Promise((f)=>setTimeout(f,r))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function pu(e){return e instanceof Ot}function kg(e){return e instanceof Eo}function Tg(e){if(pu(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 Ro{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,i={}){let{prefix:r,useCamelCase:n=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:l=!0}=i,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),d={...t};return this.processObject(d,[],u,{useCamelCase:n,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:d,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Vr.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,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],a=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${i}_${a.join("_")}`,f=r.useBackwardCompatibility?`${i}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,i,r);else{let u=io.env[l]||(f?io.env[f]:void 0);if(u!==void 0){if(r.verbose){let d=io.env[l]?l:f}try{e[n]=this.parseEnvironmentValue(u,typeof o,l,r.customParsers,r.configName)}catch(d){if(d instanceof Ao)throw d;throw gi.envVar(l,u,typeof o,r.configName)}}}}}parseEnvironmentValue(e,t,i,r,n){for(let[o,s]of Object.entries(r))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw gi.envVar(i,e,`${t} (via ${o.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},i=e.toUpperCase();for(let[r,n]of Object.entries(io.env))if(r.startsWith(i)&&n!==void 0)t[r]=n;return t}validateEnvironmentVariable(e,t,i){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(i)try{this.parseEnvironmentValue(e,t,i,{})}catch(n){r.push(`Cannot parse value "${t}" as ${i}: ${n}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,i={}){let{prefix:r,format:n="text"}=i,o=r||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),n){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],a=`${i}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,i,r);else r.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 i=`Environment Variables for ${t}:
|
|
186
186
|
|
|
187
187
|
`;for(let r of e)i+=`${r.key}
|
|
188
188
|
`,i+=` Type: ${r.type}
|
|
@@ -194,25 +194,25 @@ ${ae.join(`
|
|
|
194
194
|
`;i+=`| Variable | Type | Description | Example |
|
|
195
195
|
`,i+=`|----------|------|-------------|----------|
|
|
196
196
|
`;for(let r of e)i+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
197
|
-
`;return i}}function Tg(e,t){let i=wu("process");if(typeof i>"u"||!i.env)return t;let r=i.env[e];return r!==void 0?r:t}function pu(e,t,i={}){return mu(e,t,i,new WeakMap)}function mu(e,t,i,r){let{arrayMergeMode:n="replace",skipNullish:o=!1,customMerger:s}=i;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 gu(e,t,n,r);if(!Nt(t)||!Nt(e))return t;return Mg(e,t,i,r)}function gu(e,t,i,r){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(i){case"replace":return t;case"concat":return Og(e,t);case"smart":return Rg(e,t,r);default:return t}return t}function Og(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>Ea(n,r)))i.push(r);return i}function Rg(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(Nt(t[0])&&Nt(e[0]))return Pg(e,t,i);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}function Pg(e,t,i){let r=[...t];for(let n of e){if(!Nt(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in n){if(r.find((l)=>Nt(l)&&(a in l)&&l[a]===n[a])){s=!0;break}}if(!s)r.push(n)}return r}function Mg(e,t,i,r){let n=t;if(Nt(n)&&r.has(n))return r.get(n);let o={...e};if(Nt(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let a=n[s],l=o[s];if(i.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(Nt(a)&&Nt(l))o[s]=mu(l,a,i,r);else if(Array.isArray(a)||Array.isArray(l))o[s]=gu(l,a,i.arrayMergeMode||"smart",r);else o[s]=a}return o}function _a(e,t,i="replace"){return pu(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Ea(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Ea(e[i],t[i]))return!1;return!0}if(Nt(e)&&Nt(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Ea(e[n],t[n]))return!1}return!0}return!1}function Nt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Po{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,i={}){let{arrayStrategy:r="replace",useCache:n=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=i;if(n){let f=cr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let l=async()=>{if(!ro(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),d=u.default||u,h="default"in u,p=Object.keys(u).length>0;if(!h&&!p)throw new jr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof d!=="object"||d===null||Array.isArray(d))throw new jr(e,Error("Configuration must export a valid object"),"unknown");let m={config:_a(t,d,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)cr.setWithFileCheck("file",m,e,o);return m}catch(f){throw f instanceof Error?gi.configLoad(e,f):gi.configLoad(e,Error(String(f)))}};if(s)return Vr.track("loadFromPath",l,{path:e});return l()}async tryLoadFromPaths(e,t,i={}){for(let r of e)try{let n=await this.loadFromPath(r,t,i);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(i.verbose)console.warn(`Failed to load config from ${r}:`,n)}return null}generateConfigPaths(e,t,i){let r=this.generateNamePatterns(e,i),n=[];for(let o of r)for(let s of this.extensions)n.push(ua(t,`${o}${s}`));return n}generateNamePatterns(e,t){let i=[];if(i.push("config",".config"),e)i.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(i.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)i.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return i.filter(Boolean)}checkFileAccess(e){return du(async()=>ro(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!ro(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let a=ua(e,`${o}${s}`);if(await this.checkFileAccess(a))r.push(a)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=ua(e,s);if(await this.checkFileAccess(a))r.push(a)}}catch{return[]}return r}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(!ro(e))return t.push("Configuration file does not exist"),t;let i=await import(e),r=i.default||i;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),o=n(e,"utf8");JSON.parse(o)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(i){t.push(`Failed to load configuration file: ${i}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let i=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let n=await this.loadFromPath(r,{},t);if(n)i.set(r,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${r}:`,n)}})),i}}class ja{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:l=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:a,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:d}}};if(a)return await Vr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!Bm(t))throw new Gr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),n=r.default||r;if(Array.isArray(n))return this.validateWithRules(e,n,i);else return this.validateWithJSONSchema(e,n,i)}catch(r){throw new Gr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,i){let r=[],n=[];return this.validateObjectAgainstSchema(e,t,"",r,n,i),{isValid:r.length===0,errors:r,warnings:n}}validateObjectAgainstSchema(e,t,i,r,n,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(r.push({path:i,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(r.push({path:i,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)r.push({path:i,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)r.push({path:i,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))r.push({path:i,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)r.push({path:i,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:i,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=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,r,n,o),o.stopOnFirstError&&r.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(r.push({path:i?`${i}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,l]of Object.entries(t.properties))if(a in s){let f=i?`${i}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],l,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(s))if(!a.has(l))n.push({path:i?`${i}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let r=[],n=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(r.push(...a),i.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:n}}validateWithRule(e,t,i){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)r.push({path:i,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)r.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)r.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:i,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))r.push({path:i,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)r.push({path:i,message:t.message||n,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let i=t.split("."),r=e;for(let n of i)if(r&&typeof r==="object"&&n in r)r=r[n];else return;return r}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of i){let[,n,o,s]=r;t.push({path:n,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:xu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ga{fileLoader=new Po;envProcessor=new Ro;validator=new ja;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e;try{if(i?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let a;try{a=await this.loadConfigurationStrategies(s,!0,i)}catch(l){let f=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(f)throw l;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(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),d=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),h=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(f&&(h||u))throw l;if(d&&(!f||!h))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: ${l.message}`]};else throw l}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(n||o)await this.validateConfiguration(a.config,n,o,s.name);if(i?.enabled&&a)this.cacheResult(s.name||"",a,i,s);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);a.metrics=l}return a}catch(a){let l=Date.now()-t;throw _t.error(`Configuration loading failed after ${l}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,cwd:o,configDir:s,defaultConfig:a,checkEnv:l=!0,arrayStrategy:f="replace",verbose:u=!1}=e,d=o||Ii.cwd(),h=[],p=await this.loadLocalConfiguration(r,n,d,s,a,f,u,l,i);if(p)return h.push(...this.getLocalSearchPaths(r,n,d,s)),this.finalizeResult(p,h,l,r,u);let m=await this.loadHomeConfiguration(r,n,a,f,u,l);if(m)return h.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(m,h,l,r,u);let g=await this.loadPackageJsonConfiguration(r,n,d,a,f,u,l);if(g)return h.push(Ct(d,"package.json")),this.finalizeResult(g,h,l,r,u);if(h.push(...this.getAllSearchPaths(r,n,d,s)),t)throw gi.configNotFound(r,h,n);return{...await this.applyEnvironmentVariables(r,a,l,u),warnings:[`No configuration file found for "${r}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,r,n,o,s,a,l){let f=a?Lr(e,n,s):n,u=this.getLocalDirectories(i,r);for(let d of u){if(s)_t.info(`Searching for configuration in: ${d}`);let h=this.fileLoader.generateConfigPaths(e,d,t),p=await this.fileLoader.tryLoadFromPaths(h,f,{arrayStrategy:o,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(p){if(s)_t.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,i,r,n,o){if(!e)return null;let s=o?Lr(e,i,n):i,a=[Ct(Zi(),".config",e),Ct(Zi(),".config"),Zi()];for(let l of a){if(n)_t.info(`Checking home directory: ${l}`);let f=this.fileLoader.generateConfigPaths(e,l,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:r,verbose:n});if(u){if(n)_t.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s){let a=s?Lr(e,r,o):r;try{let l=Ct(i,"package.json");if(!xa(l))return null;let f=await import(l),u=f[e],d=e;if(!u&&t)u=f[t],d=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)_t.success(`Configuration loaded from package.json: ${d}`);return{config:_a(a,u,n),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(o)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(e,t,i,r){if(!i||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Lr(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,r,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,r){let n=[];if(i){let o=i(e);if(o)n.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)n.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw gi.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return cr.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);cr.set(n,t,void 0,i.ttl)}generateCacheKey(e,t){let i=[e];if(t.alias)i.push(`alias:${t.alias}`);if(t.cwd)i.push(`cwd:${t.cwd}`);if(t.configDir)i.push(`configDir:${t.configDir}`);if("checkEnv"in t)i.push(`checkEnv:${t.checkEnv}`);return i.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ct(e,"config"),Ct(e,".config"),t?Ct(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,i,r){let n=[];return n.push(...this.getLocalSearchPaths(e,t,i,r)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ct(i,"package.json")),n}getLocalSearchPaths(e,t,i,r){let n=this.getLocalDirectories(i,r),o=[];for(let s of n)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[Ct(Zi(),".config",e),Ct(Zi(),".config"),Zi()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function Vf(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")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||i}async function Dg(e){return si.loadConfig({...e,__strictErrorHandling:!0})}async function yu(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},i="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let r;if(i)r=await si.loadConfig(e);else r=await si.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let n=r instanceof Error?r.name:"UnknownError",o=r instanceof Error?r.message:String(r);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||o.includes("config"))&&e.verbose)_t.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let s=i?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await si.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Ig(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await si.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Vf(i)))return(await si.applyEnvironmentVariables(e,{},!0,!1)).config;throw i}}try{return(await si.loadConfig({...e,cwd:e.cwd||Ii.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Vf(t)))return(await si.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Ng(e,t,i="replace"){let r=new Po;try{let n=await r.loadFromPath(e,t,{arrayStrategy:i,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Lr(e,t,i=!1){let r=new Ro,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...a,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((g)=>g.toUpperCase()).join("")}`,`${n}_${d.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let g of h)if(p=Ii.env[g],p!==void 0){m=g;break}if(p!==void 0&&m)if(typeof u==="boolean")l[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let g=Number(p);if(!Number.isNaN(g))l[f]=g}else if(Array.isArray(u))try{l[f]=JSON.parse(p)}catch{l[f]=p.split(",").map((g)=>g.trim())}else l[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))l[f]=o(u,d)}return l}return o(t)}function Fg(e){let t=Ct(Ii.cwd(),e.configDir),i=Ct(Ii.cwd(),e.generatedDir),r=Ct(i,"config-types.ts");if(!xa(Cf(r)))gm(Cf(r),{recursive:!0,mode:511});let n=xa(t)?ym(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${uy}
|
|
197
|
+
`;return i}}function Og(e,t){let i=Cu("process");if(typeof i>"u"||!i.env)return t;let r=i.env[e];return r!==void 0?r:t}function mu(e,t,i={}){return gu(e,t,i,new WeakMap)}function gu(e,t,i,r){let{arrayMergeMode:n="replace",skipNullish:o=!1,customMerger:s}=i;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 yu(e,t,n,r);if(!Nt(t)||!Nt(e))return t;return Dg(e,t,i,r)}function yu(e,t,i,r){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(i){case"replace":return t;case"concat":return Rg(e,t);case"smart":return Pg(e,t,r);default:return t}return t}function Rg(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>Aa(n,r)))i.push(r);return i}function Pg(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(Nt(t[0])&&Nt(e[0]))return Mg(e,t,i);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}function Mg(e,t,i){let r=[...t];for(let n of e){if(!Nt(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in n){if(r.find((l)=>Nt(l)&&(a in l)&&l[a]===n[a])){s=!0;break}}if(!s)r.push(n)}return r}function Dg(e,t,i,r){let n=t;if(Nt(n)&&r.has(n))return r.get(n);let o={...e};if(Nt(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let a=n[s],l=o[s];if(i.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(Nt(a)&&Nt(l))o[s]=gu(l,a,i,r);else if(Array.isArray(a)||Array.isArray(l))o[s]=yu(l,a,i.arrayMergeMode||"smart",r);else o[s]=a}return o}function ja(e,t,i="replace"){return mu(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Aa(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Aa(e[i],t[i]))return!1;return!0}if(Nt(e)&&Nt(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Aa(e[n],t[n]))return!1}return!0}return!1}function Nt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Po{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,i={}){let{arrayStrategy:r="replace",useCache:n=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1}=i;if(n){let f=cr.getWithFileCheck("file",e);if(f){if(a)console.log(`Configuration loaded from cache: ${e}`);return f}}let l=async()=>{if(!ro(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),d=u.default||u,h="default"in u,p=Object.keys(u).length>0;if(!h&&!p)throw new jr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof d!=="object"||d===null||Array.isArray(d))throw new jr(e,Error("Configuration must export a valid object"),"unknown");let m={config:ja(t,d,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)cr.setWithFileCheck("file",m,e,o);return m}catch(f){throw f instanceof Error?gi.configLoad(e,f):gi.configLoad(e,Error(String(f)))}};if(s)return Vr.track("loadFromPath",l,{path:e});return l()}async tryLoadFromPaths(e,t,i={}){for(let r of e)try{let n=await this.loadFromPath(r,t,i);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(i.verbose)console.warn(`Failed to load config from ${r}:`,n)}return null}generateConfigPaths(e,t,i){let r=this.generateNamePatterns(e,i),n=[];for(let o of r)for(let s of this.extensions)n.push(da(t,`${o}${s}`));return n}generateNamePatterns(e,t){let i=[];if(i.push("config",".config"),e)i.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(i.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)i.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return i.filter(Boolean)}checkFileAccess(e){return hu(async()=>ro(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!ro(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let a=da(e,`${o}${s}`);if(await this.checkFileAccess(a))r.push(a)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=da(e,s);if(await this.checkFileAccess(a))r.push(a)}}catch{return[]}return r}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(!ro(e))return t.push("Configuration file does not exist"),t;let i=await import(e),r=i.default||i;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),o=n(e,"utf8");JSON.parse(o)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(i){t.push(`Failed to load configuration file: ${i}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let i=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let n=await this.loadFromPath(r,{},t);if(n)i.set(r,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${r}:`,n)}})),i}}class Ga{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:l=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:a,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:d}}};if(a)return await Vr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!_m(t))throw new Gr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),n=r.default||r;if(Array.isArray(n))return this.validateWithRules(e,n,i);else return this.validateWithJSONSchema(e,n,i)}catch(r){throw new Gr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,i){let r=[],n=[];return this.validateObjectAgainstSchema(e,t,"",r,n,i),{isValid:r.length===0,errors:r,warnings:n}}validateObjectAgainstSchema(e,t,i,r,n,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(r.push({path:i,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(r.push({path:i,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)r.push({path:i,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)r.push({path:i,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))r.push({path:i,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)r.push({path:i,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:i,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=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,r,n,o),o.stopOnFirstError&&r.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(r.push({path:i?`${i}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,l]of Object.entries(t.properties))if(a in s){let f=i?`${i}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],l,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(s))if(!a.has(l))n.push({path:i?`${i}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let r=[],n=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(r.push(...a),i.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:n}}validateWithRule(e,t,i){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)r.push({path:i,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)r.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)r.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:i,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))r.push({path:i,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)r.push({path:i,message:t.message||n,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let i=t.split("."),r=e;for(let n of i)if(r&&typeof r==="object"&&n in r)r=r[n];else return;return r}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of i){let[,n,o,s]=r;t.push({path:n,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:Su},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Va{fileLoader=new Po;envProcessor=new Ro;validator=new Ga;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e;try{if(i?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let a;try{a=await this.loadConfigurationStrategies(s,!0,i)}catch(l){let f=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(f)throw l;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(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),d=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),h=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(f&&(h||u))throw l;if(d&&(!f||!h))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: ${l.message}`]};else throw l}else a={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(n||o)await this.validateConfiguration(a.config,n,o,s.name);if(i?.enabled&&a)this.cacheResult(s.name||"",a,i,s);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);a.metrics=l}return a}catch(a){let l=Date.now()-t;throw _t.error(`Configuration loading failed after ${l}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,cwd:o,configDir:s,defaultConfig:a,checkEnv:l=!0,arrayStrategy:f="replace",verbose:u=!1}=e,d=o||Ii.cwd(),h=[],p=await this.loadLocalConfiguration(r,n,d,s,a,f,u,l,i);if(p)return h.push(...this.getLocalSearchPaths(r,n,d,s)),this.finalizeResult(p,h,l,r,u);let m=await this.loadHomeConfiguration(r,n,a,f,u,l);if(m)return h.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(m,h,l,r,u);let g=await this.loadPackageJsonConfiguration(r,n,d,a,f,u,l);if(g)return h.push(Ct(d,"package.json")),this.finalizeResult(g,h,l,r,u);if(h.push(...this.getAllSearchPaths(r,n,d,s)),t)throw gi.configNotFound(r,h,n);return{...await this.applyEnvironmentVariables(r,a,l,u),warnings:[`No configuration file found for "${r}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,r,n,o,s,a,l){let f=a?Lr(e,n,s):n,u=this.getLocalDirectories(i,r);for(let d of u){if(s)_t.info(`Searching for configuration in: ${d}`);let h=this.fileLoader.generateConfigPaths(e,d,t),p=await this.fileLoader.tryLoadFromPaths(h,f,{arrayStrategy:o,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(p){if(s)_t.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,i,r,n,o){if(!e)return null;let s=o?Lr(e,i,n):i,a=[Ct(Zi(),".config",e),Ct(Zi(),".config"),Zi()];for(let l of a){if(n)_t.info(`Checking home directory: ${l}`);let f=this.fileLoader.generateConfigPaths(e,l,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:r,verbose:n});if(u){if(n)_t.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s){let a=s?Lr(e,r,o):r;try{let l=Ct(i,"package.json");if(!Sa(l))return null;let f=await import(l),u=f[e],d=e;if(!u&&t)u=f[t],d=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)_t.success(`Configuration loaded from package.json: ${d}`);return{config:ja(a,u,n),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(o)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(e,t,i,r){if(!i||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Lr(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,r,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,r){let n=[];if(i){let o=i(e);if(o)n.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)n.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw gi.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return cr.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);cr.set(n,t,void 0,i.ttl)}generateCacheKey(e,t){let i=[e];if(t.alias)i.push(`alias:${t.alias}`);if(t.cwd)i.push(`cwd:${t.cwd}`);if(t.configDir)i.push(`configDir:${t.configDir}`);if("checkEnv"in t)i.push(`checkEnv:${t.checkEnv}`);return i.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ct(e,"config"),Ct(e,".config"),t?Ct(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,i,r){let n=[];return n.push(...this.getLocalSearchPaths(e,t,i,r)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ct(i,"package.json")),n}getLocalSearchPaths(e,t,i,r){let n=this.getLocalDirectories(i,r),o=[];for(let s of n)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[Ct(Zi(),".config",e),Ct(Zi(),".config"),Zi()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function Uf(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")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||i}async function Ig(e){return si.loadConfig({...e,__strictErrorHandling:!0})}async function wu(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},i="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let r;if(i)r=await si.loadConfig(e);else r=await si.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let n=r instanceof Error?r.name:"UnknownError",o=r instanceof Error?r.message:String(r);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||o.includes("config"))&&e.verbose)_t.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let s=i?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await si.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function Ng(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await si.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Uf(i)))return(await si.applyEnvironmentVariables(e,{},!0,!1)).config;throw i}}try{return(await si.loadConfig({...e,cwd:e.cwd||Ii.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Uf(t)))return(await si.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Fg(e,t,i="replace"){let r=new Po;try{let n=await r.loadFromPath(e,t,{arrayStrategy:i,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Lr(e,t,i=!1){let r=new Ro,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...a,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((g)=>g.toUpperCase()).join("")}`,`${n}_${d.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let g of h)if(p=Ii.env[g],p!==void 0){m=g;break}if(p!==void 0&&m)if(typeof u==="boolean")l[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let g=Number(p);if(!Number.isNaN(g))l[f]=g}else if(Array.isArray(u))try{l[f]=JSON.parse(p)}catch{l[f]=p.split(",").map((g)=>g.trim())}else l[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))l[f]=o(u,d)}return l}return o(t)}function Wg(e){let t=Ct(Ii.cwd(),e.configDir),i=Ct(Ii.cwd(),e.generatedDir),r=Ct(i,"config-types.ts");if(!Sa(vf(r)))ym(vf(r),{recursive:!0,mode:511});let n=Sa(t)?wm(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${dy}
|
|
198
198
|
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
199
|
-
`;
|
|
200
|
-
${n.map((l)=>{let f=
|
|
199
|
+
`;Cm(r,o,{mode:438})}function Lg(e){let t=null,i=null,r=()=>{if(!i)i=wu(e).then((o)=>(t=o,o),(o)=>{let s="defaultConfig"in e?e.defaultConfig:{};if(t=s,"verbose"in e&&e.verbose)_t.warn("Config loading failed, using defaults:",[o instanceof Error?o:Error(String(o))]);return s});return i},n="defaultConfig"in e?e.defaultConfig:{};return t=n,r(),new Proxy({},{get(o,s){if(t)return t[s];let a=n[s];return r(),a},has(o,s){return s in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(o,s){return Object.getOwnPropertyDescriptor(t||n,s)},set(o,s,a){if(!t)t={...n};return t[s]=a,!0}})}function Bg(e){let t=Nf(Vm.cwd(),e?.configDir||"./config");function i(){if(!jm(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Gm(t).filter((l)=>n.has(ha(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),a=new Map;for(let{base:l,file:f}of s){let u=ha(f).toLowerCase(),d=a.get(l);if(!d){a.set(l,f);continue}let h=ha(d).toLowerCase();if(o.indexOf(u)<o.indexOf(h))a.set(l,f)}return Array.from(a.entries()).map(([l,f])=>({base:l,file:f})).sort((l,f)=>l.base.localeCompare(f.base))}function r(){let n=i(),o=n.map((l)=>l.base),s=o.length?o.map((l)=>`'${l}'`).join(" | "):"string",a=n.length?`{
|
|
200
|
+
${n.map((l)=>{let f=Nf(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
|
|
201
201
|
`)}
|
|
202
202
|
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
203
203
|
export type ConfigByName = ${a}
|
|
204
204
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
205
205
|
export type ConfigOf = Config
|
|
206
|
-
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:r(),loader:"ts"}))}}}function hy(e,t={}){let i=Co.cwd();while(i.includes("storage"))i=Nf(i,"..");let r=Nf(i,e||"");if(t?.relative)return Um(Co.cwd(),r);return r}function st(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function my(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof oi<"u"){let e=oi.type;if(e==="renderer"||e==="worker")return!1;return!!(oi.versions&&(oi.versions.node||oi.versions.bun))}return!1}class ku{async format(e){let t=await my(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ar.pid,hostname:t(),environment:ar.env.NODE_ENV||"development",platform:ar.platform,version:ar.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ar.env.NODE_ENV||ar.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mo{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={...ko},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ku,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??Le.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{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},i=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[i]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ba,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ba};return{...ba,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ko.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!st()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Jm(this.config.logDirectory,Bf.F_OK|Bf.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Ym(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ti.from(e);try{if(!no(this.currentLogFile))await ma(this.currentLogFile,"",{mode:420});if(r=Lf(this.currentLogFile,"a",420),qm(r,a,{flag:"a"}),Wf(r),r!==void 0)pa(r),r=void 0;if((await or(this.currentLogFile)).size===0){if(await ma(this.currentLogFile,a,{flag:"w",mode:420}),(await or(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(r!==void 0)try{pa(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(n===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}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return sr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return sr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return sr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(st())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return ha(16).toString("hex")}generateKey(){return ha(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(),i=ha(16),r=zm("aes-256-gcm",t,i),n=ti.isBuffer(e)?e:ti.from(e,"utf8"),o=r.update(n),s=r.final(),a=o.length+s.length,l=r.getAuthTag(),f=ti.allocUnsafe(16+a+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),l.copy(f,16+a),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=jf(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(ti.from(ti.concat(n)))),r.on("error",i),r.write(e),r.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(st())return;if(!this.shouldWriteToFile())return;let e=await or(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await oo(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.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=`${i}.${s}`;if(await or(i).catch(()=>null))try{if(await _f(i,a),t.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await so(a)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await ma(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await or(i).catch(()=>null))await _f(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await oo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await so(sr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=Ff(e),r=Hm(t),n=jf();await Qm(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),no(this.currentLogFile))try{let e=Lf(this.currentLogFile,"r+");Wf(e),pa(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(!st()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await oo(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await so(sr(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?Pe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||st())return!1;let e=typeof Le.env.NO_COLOR<"u",t=Le.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Le.stderr<"u"&&Le.stderr.isTTY||typeof Le.stdout<"u"&&Le.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=Le.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Pe.cyan(n)}`;if(!s)return f.trim();let u=a(f).trim().length,d=a(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${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 i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let a=t[r++];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(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,r,n)=>{let o=Pe.underline(Pe.blue(r)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,l="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,r)=>Pe.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,r)=>Pe.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,r)=>Pe.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,r)=>Pe.italic(r)),t=t.replace(/~([^~]+)~/g,(i,r)=>Pe.strikethrough(r)),t}supportsHyperlinks(){if(st())return!1;let e=Le.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 i=Le.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Xm(t)||t.startsWith("./")||t.startsWith("../"))t=Zm(t);else return null;return no(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,i=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:i}}async log(e,t,...i){if(!this.shouldLog(e))return;let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);let{consoleText:l,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":vy[e],h=this.options.showTags!==!1&&this.name?Pe.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Pe.gray(l),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Pe.green(l),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.error(p),a){let m=a.split(`
|
|
206
|
+
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:r(),loader:"ts"}))}}}function py(e,t={}){let i=Co.cwd();while(i.includes("storage"))i=Ff(i,"..");let r=Ff(i,e||"");if(t?.relative)return zm(Co.cwd(),r);return r}function st(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gy(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof oi<"u"){let e=oi.type;if(e==="renderer"||e==="worker")return!1;return!!(oi.versions&&(oi.versions.node||oi.versions.bun))}return!1}class Tu{async format(e){let t=await gy(),i=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:i})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ar.pid,hostname:t(),environment:ar.env.NODE_ENV||"development",platform:ar.platform,version:ar.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ar.env.NODE_ENV||ar.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mo{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={...ko},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Tu,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??Le.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let i={...t},r=t.timestamp!==void 0;if(r)delete i.timestamp;if(this.config={...this.config,...i,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),o=this.generateKey();this.currentKeyId=n,this.keys.set(n,o),this.encryptionKeys.set(n,{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},i=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[i]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...$a,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...$a};return{...$a,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ko.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},i={...t,...Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0))};if(!i.level||!["debug","info","success","warning","error"].includes(i.level))i.level=t.level;return i}shouldWriteToFile(){return!st()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let r,n=0,o=3,s=1000;while(n<o)try{try{try{await Ym(this.config.logDirectory,_f.F_OK|_f.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Xm(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ti.from(e);try{if(!no(this.currentLogFile))await ga(this.currentLogFile,"",{mode:420});if(r=Bf(this.currentLogFile,"a",420),Jm(r,a,{flag:"a"}),Lf(r),r!==void 0)ma(r),r=void 0;if((await or(this.currentLogFile)).size===0){if(await ga(this.currentLogFile,a,{flag:"w",mode:420}),(await or(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${o}:`,u);let d=s*2**n;await new Promise((h)=>setTimeout(h,d)),n++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(r!==void 0)try{ma(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(n===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}n++;let l=s*2**(n-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(t);let i=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(i,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return sr(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return sr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return sr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(st())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,i=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),i=this.generateKey();this.currentKeyId=t,this.keys.set(t,i),this.encryptionKeys.set(t,{key:i,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,s],[,a])=>a.createdAt.getTime()-s.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,o=Math.max(1,n);if(r.length>o)for(let[s]of r.slice(o))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return pa(16).toString("hex")}generateKey(){return pa(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(),i=pa(16),r=Km("aes-256-gcm",t,i),n=ti.isBuffer(e)?e:ti.from(e,"utf8"),o=r.update(n),s=r.final(),a=o.length+s.length,l=r.getAuthTag(),f=ti.allocUnsafe(16+a+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),l.copy(f,16+a),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=Gf(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(ti.from(ti.concat(n)))),r.on("error",i),r.write(e),r.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(st())return;if(!this.shouldWriteToFile())return;let e=await or(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let i=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await oo(this.config.logDirectory),o=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,f)=>{let u=Number.parseInt(l.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=`${i}.${s}`;if(await or(i).catch(()=>null))try{if(await jf(i,a),t.compress)try{let l=`${a}.gz`;await this.compressLogFile(a,l),await so(a)}catch(l){console.error("Error compressing rotated file:",l)}if(o.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${i}.1`;await ga(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await or(i).catch(()=>null))await jf(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await oo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await so(sr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=Wf(e),r=qm(t),n=Gf();await eg(i,n,r)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let i of this.logBuffer){let r=await this.formatter.format(i);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}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()})),no(this.currentLogFile))try{let e=Bf(this.currentLogFile,"r+");Lf(e),ma(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(!st()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await oo(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await so(sr(this.config.logDirectory,t))}catch(i){console.error(`Failed to delete temp file ${t}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?Pe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||st())return!1;let e=typeof Le.env.NO_COLOR<"u",t=Le.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Le.stderr<"u"&&Le.stderr.isTTY||typeof Le.stdout<"u"&&Le.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,a=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(s)p.push(t);if(o==="warning")p.push("WARN");else if(o==="error")p.push("ERROR");else if(i)p.push(i.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)p.push(r.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let l=Le.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${i} ${n}`;else if(o==="info"||o==="success")f=`${i} ${r} ${n}`;else f=`${i} ${r} ${Pe.cyan(n)}`;if(!s)return f.trim();let u=a(f).trim().length,d=a(t).length,h=Math.max(1,l-2-u-d);return`${f.trim()}${" ".repeat(h)}${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 i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let a=t[r++];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(r<t.length)n+=` ${t.slice(r).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(i,r,n)=>{let o=Pe.underline(Pe.blue(r)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(s)}`,l="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${a}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),t=t.replace(/`([^`]+)`/g,(i,r)=>Pe.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,r)=>Pe.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,r)=>Pe.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,r)=>Pe.italic(r)),t=t.replace(/~([^~]+)~/g,(i,r)=>Pe.strikethrough(r)),t}supportsHyperlinks(){if(st())return!1;let e=Le.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 i=Le.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Zm(t)||t.startsWith("./")||t.startsWith("../"))t=Qm(t);else return null;return no(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,i=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:i}}async log(e,t,...i){if(!this.shouldLog(e))return;let r=new Date,n=this.formatConsoleTimestamp(r),o=this.formatFileTimestamp(r),s,a;if(t instanceof Error)s=t.message,a=t.stack;else s=this.formatMessage(t,i);let{consoleText:l,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":by[e],h=this.options.showTags!==!1&&this.name?Pe.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Pe.gray(l),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Pe.green(l),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:l,level:e}),console.error(p),a){let m=a.split(`
|
|
207
207
|
`);for(let g of m)if(g.trim()&&!g.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:Pe.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!st()){if(console.error(`${o} ${this.environment}.${e.toUpperCase()}: ${s}`),a)console.error(a)}let u=`${o} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
208
208
|
`;if(a)u+=`${a}
|
|
209
209
|
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let i={update:(n,o)=>{},finish:(n)=>{},interrupt:(n,o)=>{}};if(!this.enabled)return i;let r=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!st()&&Le.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,o)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),o!==void 0)this.activeProgressBar.message=o;if(this.shouldStyleConsole()&&!st()&&Le.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,o="info")=>{if(!st()&&Le.stdout.isTTY)Le.stdout.write(`
|
|
210
210
|
`);if(this[o==="warning"?"warn":o](n),this.activeProgressBar&&this.shouldStyleConsole()&&!st()&&Le.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let i=this.options.showTags!==!1&&this.name?Pe.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Pe.blue("\u25D0"),tag:i,message:`${Pe.cyan(e)}...`}))}return async(i)=>{if(!this.enabled)return;let r=performance.now(),n=Math.round(r-t),o=`${e} completed in ${n}ms`,s=new Date,a=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${o}`;if(i)l+=` ${JSON.stringify(i)}`;if(l+=`
|
|
211
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?Pe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":Pe.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!st())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new Mo(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(i),i}createReadStream(){if(st())throw Error("createReadStream is not supported in browser environments");if(!no(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
211
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?Pe.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":Pe.green("\u2713"),tag:f,message:`${o}${i?` ${JSON.stringify(i)}`:""}`}))}else if(!st())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,i=new Mo(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(i),i}createReadStream(){if(st())throw Error("createReadStream is not supported in browser environments");if(!no(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Wf(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 i=this.keys.get(this.currentKeyId);try{let r=ti.isBuffer(e)?e:ti.from(e,"base64"),n=r.subarray(0,16),o=r.subarray(r.length-16),s=r.subarray(16,r.length-16),a=Hm("aes-256-gcm",i,n);a.setAuthTag(o);let l=a.update(s),f=a.final(),u=l.length+f.length,d=ti.allocUnsafe(u);return l.copy(d,0),f.copy(d,l.length),d.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return st()}isServerMode(){return!st()}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,i=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:n,fileText:o}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
|
|
212
212
|
`),l=Math.max(...a.map((h)=>h.length))+2,f=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,d=a.map((h)=>this.formatConsoleMessage({timestamp:i,message:Pe.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:i,message:Pe.cyan(f),showTimestamp:!1})),d.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:i,message:Pe.cyan(u),showTimestamp:!1}))}else if(!st())console.error(`${r} ${this.environment}.INFO: [BOX] ${o}`);let s=`${r} ${this.environment}.INFO: [BOX] ${o}
|
|
213
213
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(st())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Pe.cyan("?")} ${e} (y/n) `);let i=(r)=>{let n=r.toString().trim().toLowerCase();Le.stdin.removeListener("data",i);try{if(typeof Le.stdin.setRawMode==="function")Le.stdin.setRawMode(!1)}catch{}Le.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Le.stdin.setRawMode==="function")Le.stdin.setRawMode(!0)}catch{}Le.stdin.resume(),Le.stdin.once("data",i)})}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 i=e;if(t&&t.length>0){let s=/%([sdijfo%])/g,a=0;if(i=e.replace(s,(l,f)=>{if(f==="%")return"%";if(a>=t.length)return l;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 l}}),a<t.length)i+=` ${t.slice(a).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:n}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?Pe.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${Pe.blue("\u25D0")} `;console.error(`${a}${s} ${Pe.cyan(r)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
214
214
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!Le.stdout.isTTY)return;let i=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),r=Math.round(e.barLength*i/100),n=e.barLength-r,o=Pe.green("\u2501".repeat(r)),s=Pe.gray("\u2501".repeat(n)),a=`[${o}${s}]`,l=`${i}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||i===100?Pe.green("\u2713"):Pe.blue("\u25B6"),d=this.options.showTags!==!1&&this.name?` ${Pe.gray(this.formatTag(this.name))}`:"",h=`\r${u}${d} ${a} ${l}${f}`,p=Le.stdout.columns||80,m=" ".repeat(Math.max(0,p-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,Le.stdout.write(e.lastRenderedLine),t)Le.stdout.write(`
|
|
215
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||st()||!Le.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(st()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await oo(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=sr(this.config.logDirectory,r);if(e.before)try{if((await or(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await so(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function
|
|
215
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||st()||!Le.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(st()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await oo(this.config.logDirectory),i=[];for(let r of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let n=sr(this.config.logDirectory,r);if(e.before)try{if((await or(n)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${n}:`,o);continue}i.push(n)}if(i.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${i.length} log file(s)...`);for(let r of i)try{await so(r),console.warn(`Deleted log file: ${r}`)}catch(n){console.error(`Failed to delete log file ${r}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function $y(e,t={}){let{maxRetries:i=3,retryDelay:r=1000,isRetryable:n=()=>!0,fallback:o}=t,s=Error("Unknown error occurred");for(let a=0;a<=i;a++)try{return await e()}catch(l){if(s=l instanceof Error?l:Error(String(l)),a===i||!n(s))break;if(r>0)await new Promise((f)=>setTimeout(f,r))}if(o!==void 0)return o;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class za{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,i={}){let{prefix:r,useCamelCase:n=!0,useBackwardCompatibility:o=!0,customParsers:s={},verbose:a=!1,trackPerformance:l=!0}=i,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=r||this.generateEnvPrefix(e),d={...t};return this.processObject(d,[],u,{useCamelCase:n,useBackwardCompatibility:o,customParsers:s,verbose:a,configName:e}),{config:d,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Fa.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,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],a=s.map((u)=>this.formatEnvKey(u,r.useCamelCase)),l=`${i}_${a.join("_")}`,f=r.useBackwardCompatibility?`${i}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,s,i,r);else{let u=ao.env[l]||(f?ao.env[f]:void 0);if(u!==void 0){if(r.verbose){let d=ao.env[l]?l:f}try{e[n]=this.parseEnvironmentValue(u,typeof o,l,r.customParsers,r.configName)}catch(d){if(d instanceof Ua)throw d;throw mi.envVar(l,u,typeof o,r.configName)}}}}}parseEnvironmentValue(e,t,i,r,n){for(let[o,s]of Object.entries(r))try{return s(e)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(e,t))try{return o.parse(e)}catch{throw mi.envVar(i,e,`${t} (via ${o.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},i=e.toUpperCase();for(let[r,n]of Object.entries(ao.env))if(r.startsWith(i)&&n!==void 0)t[r]=n;return t}validateEnvironmentVariable(e,t,i){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))r.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(i)try{this.parseEnvironmentValue(e,t,i,{})}catch(n){r.push(`Cannot parse value "${t}" as ${i}: ${n}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(e,t,i={}){let{prefix:r,format:n="text"}=i,o=r||this.generateEnvPrefix(e),s=[];switch(this.extractEnvVarInfo(t,[],o,s),n){case"markdown":return this.formatAsMarkdown(s,e);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,e)}}extractEnvVarInfo(e,t,i,r){for(let[n,o]of Object.entries(e)){let s=[...t,n],a=`${i}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,s,i,r);else r.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 i=`Environment Variables for ${t}:
|
|
216
216
|
|
|
217
217
|
`;for(let r of e)i+=`${r.key}
|
|
218
218
|
`,i+=` Type: ${r.type}
|
|
@@ -224,76 +224,76 @@ export type ConfigOf = Config
|
|
|
224
224
|
`;i+=`| Variable | Type | Description | Example |
|
|
225
225
|
`,i+=`|----------|------|-------------|----------|
|
|
226
226
|
`;for(let r of e)i+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
227
|
-
`;return i}}function Nu(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}async function Fu(e){let t=tg(e),i=co.get(t),r,n=new Promise((o)=>{r=o});co.set(t,n),await i;try{if(eg(t),iu.cache[t]?.loaded===!0||$a.has(t))delete iu.cache[t];try{let o=await import(rg(t).href);return $a.delete(t),o}catch(o){throw $a.add(t),o}}finally{if(r(),co.get(t)===n)co.delete(t)}}function $y(e,t,i={}){return Wu(e,t,i,new WeakMap)}function Wu(e,t,i,r){let{arrayMergeMode:n="replace",skipNullish:o=!1,customMerger:s}=i;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 Lu(e,t,n,r);if(!Ft(t)||!Ft(e))return t;return Ay(e,t,i,r)}function Lu(e,t,i,r){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(i){case"replace":return t;case"concat":return xy(e,t);case"smart":return Sy(e,t,r);default:return t}return t}function xy(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>Ia(n,r)))i.push(r);return i}function Sy(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(Ft(t[0])&&Ft(e[0]))return Ey(e,t,i);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}function Ey(e,t,i){let r=[...t];for(let n of e){if(!Ft(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in n){if(r.find((l)=>Ft(l)&&(a in l)&&l[a]===n[a])){s=!0;break}}if(!s)r.push(n)}return r}function Ay(e,t,i,r){let n=t;if(Ft(n)&&r.has(n))return r.get(n);let o={...e};if(Ft(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let a=n[s],l=o[s];if(i.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(Ft(a)&&Ft(l))o[s]=Wu(l,a,i,r);else if(Array.isArray(a)||Array.isArray(l))o[s]=Lu(l,a,i.arrayMergeMode||"smart",r);else o[s]=a}return o}function Bu(e,t,i="replace"){return $y(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Ia(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Ia(e[i],t[i]))return!1;return!0}if(Ft(e)&&Ft(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Ia(e[n],t[n]))return!1}return!0}return!1}function Ft(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class _u{extensions=au;async loadFromPath(e,t,i={}){let{arrayStrategy:r="replace",useCache:n=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1,strictDiscovery:l=!1}=i;if(n){let u=vo.getWithFileCheck("file",e);if(u){if(a)console.log(`Configuration loaded from cache: ${e}`);return u}}let f=async()=>{try{try{ng(e)}catch(g){if(Nu(g)||!l)return null;throw g}let u=await Fu(e),d=Object.hasOwn(u,"default"),h=Object.keys(u).length>0,p=d?u.default:u;if(!d&&!h)throw new lr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof p!=="object"||p===null||Array.isArray(p))throw new lr(e,Error("Configuration must export a valid object"),"unknown");let m={config:Bu(t,p,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)vo.setWithFileCheck("file",m,e,o);return m}catch(u){throw u instanceof Error?mi.configLoad(e,u):mi.configLoad(e,Error(String(u)))}};if(s)return Na.track("loadFromPath",f,{path:e});return f()}async tryLoadFromPaths(e,t,i={}){for(let r of e)try{let n=await this.loadFromPath(r,t,i);if(n)return n}catch(n){if(n instanceof lr)throw n;if(i.verbose)console.warn(`Failed to load config from ${r}:`,n)}return null}generateConfigPaths(e,t,i){return sg({name:e,directory:t,alias:i})}generateNamePatterns(e,t){return lu({name:e,alias:t})}checkFileAccess(e){return by(async()=>ga(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!ga(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let a=Gf(e,`${o}${s}`);if(await this.checkFileAccess(a))r.push(a)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=Gf(e,s);if(await this.checkFileAccess(a))r.push(a)}}catch{return[]}return r}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(!ga(e))return t.push("Configuration file does not exist"),t;let i=await import(e),r=i.default||i;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),o=n(e,"utf8");JSON.parse(o)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(i){t.push(`Failed to load configuration file: ${i}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let i=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let n=await this.loadFromPath(r,{},t);if(n)i.set(r,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${r}:`,n)}})),i}}class ju{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:l=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:a,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:d}}};if(a)return await Na.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!og(t))throw new To(t,[{path:"",message:"Schema file does not exist"}]);let r=await Fu(t),n=Object.hasOwn(r,"default")?r.default:r;if(Array.isArray(n))return this.validateWithRules(e,n,i);else{if(typeof n!=="object"||n===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(e,n,i)}}catch(r){throw new To(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,i){let r=[],n=[];return this.validateObjectAgainstSchema(e,t,"",r,n,i),{isValid:r.length===0,errors:r,warnings:n}}validateObjectAgainstSchema(e,t,i,r,n,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(r.push({path:i,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(r.push({path:i,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)r.push({path:i,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)r.push({path:i,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))r.push({path:i,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)r.push({path:i,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:i,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=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,r,n,o),o.stopOnFirstError&&r.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(r.push({path:i?`${i}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,l]of Object.entries(t.properties))if(a in s){let f=i?`${i}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],l,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(s))if(!a.has(l))n.push({path:i?`${i}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let r=[],n=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(r.push(...a),i.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:n}}validateWithRule(e,t,i){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)r.push({path:i,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)r.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)r.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:i,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))r.push({path:i,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)r.push({path:i,message:t.message||n,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let i=t.split("."),r=e;for(let n of i)if(r&&typeof r==="object"&&n in r)r=r[n];else return;return r}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of i){let[,n,o,s]=r;t.push({path:n,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:ky},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Ty(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((i)=>`"${i}"`).join(", ")}`}class Gu{fileLoader=new _u;envProcessor=new Ua;validator=new ju;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e,a=s.errorPolicy==="throw"?{...i,enabled:!1}:i;try{if(a?.enabled){let f=this.checkCache(s.name||"",s);if(f)return f}let l;try{l=await this.loadConfigurationStrategies(s,!0,a)}catch(f){if(s.configFile||s.errorPolicy==="throw"&&!(f instanceof Br))throw f;let u=s.__strictErrorHandling;if(f instanceof Br){if(u&&s.errorPolicy!=="throw")throw f;l={...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(f instanceof lr){let d=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),h=!d&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),p=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(p||d))throw f;if(h&&(!u||!p))l={...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(!u)l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(n||o)await this.validateConfiguration(l.config,n,o,s.name);if(a?.enabled&&l)this.cacheResult(s.name||"",l,a,s);if(r?.enabled){let f={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(f);if(r.slowThreshold&&f.duration>r.slowThreshold)ii.warn(`Slow configuration loading detected: ${f.duration}ms for ${s.name}`);l.metrics=f}return l}catch(l){if(l instanceof Br)throw l;let f=Date.now()-t;throw ii.error(`Configuration loading failed after ${f}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,configFile:o,cwd:s,configDir:a,defaultConfig:l,checkEnv:f=!0,arrayStrategy:u="replace",verbose:d=!1}=e,h=s||Oo.cwd(),p=[];if(o){let b=Jt(h,o);p.push(b);let c=f?Fr(r,l,d):l,A=await this.fileLoader.tryLoadFromPaths([b],c,{arrayStrategy:u,verbose:d,cacheTtl:i?.ttl,useCache:i?.enabled!==!1&&(!i?.ttl||i.ttl>100),strictDiscovery:!0});if(!A)throw mi.configNotFound(r||o,p,n);if(d)ii.success(`Configuration loaded from explicit path: ${b}`);return this.finalizeResult(A,p,f,r,d)}let m=await this.loadLocalConfiguration(r,n,h,a,l,u,d,f,i,e.errorPolicy==="throw");if(m)return p.push(...this.getLocalSearchPaths(r,n,h,a)),this.finalizeResult(m,p,f,r,d);let g=await this.loadHomeConfiguration(r,n,l,u,d,f,i,e.errorPolicy==="throw");if(g)return p.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(g,p,f,r,d);let C=await this.loadPackageJsonConfiguration(r,n,h,l,u,d,f,e.errorPolicy);if(C)return p.push(Jt(h,"package.json")),this.finalizeResult(C,p,f,r,d);if(p.push(...this.getAllSearchPaths(r,n,h,a)),t)throw mi.configNotFound(r,p,n);return{...await this.applyEnvironmentVariables(r,l,f,d),warnings:[`No configuration file found for "${r}"${Ty(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,r,n,o,s,a,l,f=!1){let u=a?Fr(e,n,s):n,d=this.getLocalDirectories(i,r);for(let h of d){if(s)ii.info(`Searching for configuration in: ${h}`);let p=this.fileLoader.generateConfigPaths(e,h,t),m=await this.fileLoader.tryLoadFromPaths(p,u,{arrayStrategy:o,verbose:s,cacheTtl:l?.ttl,useCache:l?.enabled!==!1&&(!l?.ttl||l.ttl>100),strictDiscovery:f});if(m){if(s)ii.success(`Configuration loaded from: ${m.source.path}`);return m}}return null}async loadHomeConfiguration(e,t,i,r,n,o,s,a=!1){if(!e)return null;let l=o?Fr(e,i,n):i,f=[Jt(Xi(),".config",e),Jt(Xi(),".config"),Xi()];for(let u of f){if(n)ii.info(`Checking home directory: ${u}`);let d=this.fileLoader.generateConfigPaths(e,u,t),h=await this.fileLoader.tryLoadFromPaths(d,l,{arrayStrategy:r,verbose:n,cacheTtl:s?.ttl,useCache:s?.enabled!==!1&&(!s?.ttl||s.ttl>100),strictDiscovery:a});if(h){if(n)ii.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s,a){let l=s?Fr(e,r,o):r,f=Jt(i,"package.json"),u=a==="throw";try{let d=JSON.parse(mm(f,"utf8"));if(typeof d!=="object"||d===null||Array.isArray(d))throw Error("package.json must contain an object");let h=d,p=t===void 0?[]:Array.isArray(t)?t:[t],m=[e,...p.filter(Boolean)].find((C)=>Object.hasOwn(h,C)&&(u||Boolean(h[C])));if(m===void 0)return null;let g=h[m];if(typeof g!=="object"||g===null||Array.isArray(g))throw Error(`Configuration field "${m}" must contain an object`);if(o)ii.success(`Configuration loaded from package.json: ${m}`);return{config:Bu(l,g,n),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(d){if(Nu(d))return null;if(u)throw mi.configLoad(f,d instanceof Error?d:Error(String(d)));if(o)ii.warn("Failed to load package.json:",[d instanceof Error?d:Error(String(d))]);return null}}async applyEnvironmentVariables(e,t,i,r){if(!i||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Fr(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,r,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,r){let n=[];if(i){let o=i(e);if(o)n.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)n.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw mi.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return vo.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);vo.set(n,t,void 0,i.ttl)}generateCacheKey(e,t){let i=[e];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;i.push(`alias:${r}`)}if(t.cwd)i.push(`cwd:${t.cwd}`);if(t.configFile)i.push(`configFile:${t.configFile}`);if(t.configDir)i.push(`configDir:${t.configDir}`);if("checkEnv"in t)i.push(`checkEnv:${t.checkEnv}`);return i.join("|")}getLocalDirectories(e,t){return ag({cwd:e,configDir:t})}getAllSearchPaths(e,t,i,r){let n=[];return n.push(...this.getLocalSearchPaths(e,t,i,r)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Jt(i,"package.json")),n}getLocalSearchPaths(e,t,i,r){let n=this.getLocalDirectories(i,r),o=[];for(let s of n)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[Jt(Xi(),".config",e),Jt(Xi(),".config"),Xi()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function Fr(e,t,i=!1){let r=new Ua,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...a,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((g)=>g.toUpperCase()).join("")}`,`${n}_${d.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let g of h)if(p=Oo.env[g],p!==void 0){m=g;break}if(p!==void 0&&m)if(typeof u==="boolean")l[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let g=Number(p);if(!Number.isNaN(g))l[f]=g}else if(Array.isArray(u))try{l[f]=JSON.parse(p)}catch{l[f]=p.split(",").map((g)=>g.trim())}else l[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))l[f]=o(u,d)}return l}return o(t)}var vo,Na,au,lg,cg=(e)=>e,ug=(e,t)=>{for(var i in t)lg(e,i,{get:t[i],enumerable:!0,configurable:!0,set:fg.bind(t,i)})},dg=(e,t)=>()=>(e&&(t=e(e=0)),t),cu,wu,cr,Vr,Cu,Bg,_g,Uf,uo,Aa,ut,Ke,jg,zf,Gg,Kf,Vg,Ug,ya,zg,Hf,qf,wa,Kg,Hg,qg,Jg,ho,vu,Yg,dt,Xg,Zg,Jf,po,ka,ot,Re,Qg,Yf,ey,Xf,ty,iy,Ca,ry,Zf,Qf,ny,va,oy,sy,ay,ly,cy,mo,bu,fy,uy="0.15.6",Ot,Eo,jr,Ta,Oa,Ao,Ra,Pa,Gr,Ma,Da,gi,$u,xu,_t,si,Su,Eu,dy,py,Au,ko,Yv,Tu,Pe,Xv,gy,Zv,yy,Qv,eb,eu,tb,wy,Cy,ib,tu,rb,nb,ob,sb,ab,ba,vy,lb,jt,Br,lr,Ou,Ru,Va,Pu,Mu,To,Du,Iu,mi,iu,co,$a,ky,ii,cb,fb,ub,Oy,Vu;var Uu=ye(()=>{vo=new ou,Na=new su,au=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];lg=Object.defineProperty;cu={};ug(cu,{withErrorRecovery:()=>du,tryLoadConfig:()=>Ng,loadConfigWithResult:()=>Dg,loadConfig:()=>yu,isRetryableError:()=>kg,isConfigNotFoundError:()=>Ag,isBunfigError:()=>hu,globalPerformanceMonitor:()=>Vr,globalCache:()=>cr,getEnvOrDefault:()=>Tg,generateConfigTypes:()=>Fg,defaultGeneratedDir:()=>Eu,defaultConfigDir:()=>Su,deepMergeWithArrayStrategy:()=>_a,deepMerge:()=>pu,createLibraryConfig:()=>Wg,config:()=>Ig,bunfigPlugin:()=>Lg,applyEnvVarsToConfig:()=>Lr,TypeGenerationError:()=>Pa,SchemaValidationError:()=>Gr,PluginError:()=>Da,PerformanceMonitor:()=>Wa,FileSystemError:()=>Ra,ErrorFactory:()=>gi,EnvVarError:()=>Ao,EnvProcessor:()=>Ro,ConfigValidator:()=>ja,ConfigValidationError:()=>Ta,ConfigNotFoundError:()=>Eo,ConfigMergeError:()=>Oa,ConfigLoader:()=>Ga,ConfigLoadError:()=>jr,ConfigFileLoader:()=>Po,ConfigCache:()=>Fa,CacheUtils:()=>Cu,BunfigError:()=>Ot,BrowserConfigError:()=>Ma,ArrayMergeStrategies:()=>$u});dy=dg(async()=>{wu=import.meta.require,cr=new Fa,Vr=new Wa,Cu={createKey:hg,isEquivalent:pg,estimateMemoryUsage:mg},Bg=wo(Sa.cwd(),"config"),_g=wo(Sa.cwd(),"src/generated"),Uf=yo.env.CLARITY_LOG_DIR||bm(wg(),"logs"),uo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Uf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Aa=await Cg(),ut={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"},Ke=ut,jg=ut.red,zf=ut.green,Gg=ut.yellow,Kf=ut.blue,Vg=ut.magenta,Ug=ut.cyan,ya=ut.white,zg=ut.gray,Hf=ut.bgRed,qf=ut.bgYellow,wa=ut.bold,Kg=ut.dim,Hg=ut.italic,qg=ut.underline,Jg=ut.reset,ho={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vu={debug:"\uD83D\uDD0D",info:Kf("\u2139"),success:zf("\u2713"),warning:qf(ya(wa(" WARN "))),error:Hf(ya(wa(" ERROR ")))},Yg=new $o("stacks"),dt=new $o("bunfig",{showTags:!0}),Xg=wt(_r.cwd(),"config"),Zg=wt(_r.cwd(),"src/generated"),Jf=go.env.CLARITY_LOG_DIR||Cm(xg(),"logs"),po={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Jf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ka=await Sg(),ot={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"},Re=ot,Qg=ot.red,Yf=ot.green,ey=ot.yellow,Xf=ot.blue,ty=ot.magenta,iy=ot.cyan,Ca=ot.white,ry=ot.gray,Zf=ot.bgRed,Qf=ot.bgYellow,ny=ot.bgGray,va=ot.bold,oy=ot.dim,sy=ot.italic,ay=ot.underline,ly=ot.strikethrough,cy=ot.reset,mo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bu={debug:"\uD83D\uDD0D",info:Xf("\u2139"),success:Yf("\u2713"),warning:Qf(Ca(va(" WARN "))),error:Zf(Ca(va(" ERROR ")))},fy=new So("stacks"),Ot=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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Eo=class extends Ot{code="CONFIG_NOT_FOUND";constructor(e,t,i){let r=i?` or alias "${i}"`:"";super(`Configuration "${e}"${r} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}},jr=class extends Ot{code="CONFIG_LOAD_ERROR";constructor(e,t,i){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:i,originalError:t.name,originalMessage:t.message});this.cause=t}},Ta=class extends Ot{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}},Oa=class extends Ot{code="CONFIG_MERGE_ERROR";constructor(e,t,i,r){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Ao=class extends Ot{code="ENV_VAR_ERROR";constructor(e,t,i,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:r})}},Ra=class extends Ot{code="FILE_SYSTEM_ERROR";constructor(e,t,i){super(`File system ${e} failed for "${t}": ${i.message}`,{operation:e,path:t,originalError:i.name,originalMessage:i.message});this.cause=i}},Pa=class extends Ot{code="TYPE_GENERATION_ERROR";constructor(e,t,i){super(`Failed to generate types from "${e}" to "${t}": ${i.message}`,{configDir:e,outputPath:t,originalError:i.name,originalMessage:i.message});this.cause=i}},Gr=class extends Ot{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:e,configName:i,validationErrors:t,errorCount:t.length})}},Ma=class extends Ot{code="BROWSER_CONFIG_ERROR";constructor(e,t,i,r){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:r})}},Da=class extends Ot{code="PLUGIN_ERROR";constructor(e,t,i){super(`Plugin "${e}" failed during ${t}: ${i.message}`,{pluginName:e,operation:t,originalError:i.name,originalMessage:i.message});this.cause=i}},gi={configNotFound(e,t,i){return new Eo(e,t,i)},configLoad(e,t,i){return new jr(e,t,i)},configValidation(e,t,i){return new Ta(e,t,i)},configMerge(e,t,i,r){return new Oa(e,t,i,r)},envVar(e,t,i,r){return new Ao(e,t,i,r)},fileSystem(e,t,i){return new Ra(e,t,i)},typeGeneration(e,t,i){return new Pa(e,t,i)},schemaValidation(e,t,i){return new Gr(e,t,i)},browserConfig(e,t,i,r){return new Ma(e,t,i,r)},plugin(e,t,i){return new Da(e,t,i)}},$u={replace:"replace",concat:"concat",smart:"smart"},xu=/^https?:\/\//,_t=new So("bunfig",{showTags:!0}),si=new Ga,Su=Ct(Ii.cwd(),"config"),Eu=Ct(Ii.cwd(),"src/generated")});py=Co.env.CLARITY_LOG_DIR||Vm(hy(),"logs"),Au={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:py,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ko={...Au},Yv=(async()=>{try{let{loadConfig:e}=await dy().then(()=>cu),t=await e({name:"clarity",alias:"logging",defaultConfig:Au,cwd:Co.cwd()});if(t)Object.assign(ko,t)}catch{}return ko})();Tu={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},Pe=Tu,{red:Xv,green:gy,yellow:Zv,blue:yy,magenta:Qv,cyan:eb,white:eu,gray:tb,bgRed:wy,bgYellow:Cy,bgGray:ib,bold:tu,dim:rb,italic:nb,underline:ob,strikethrough:sb,reset:ab}=Tu,ba={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vy={debug:"\uD83D\uDD0D",info:yy("\u2139"),success:gy("\u2713"),warning:Cy(eu(tu(" WARN "))),error:wy(eu(tu(" ERROR ")))};lb=new Mo("stacks");jt=class jt 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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};Br=class Br extends jt{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(e,t,i){let r=i===void 0?[]:Array.isArray(i)?i.filter(Boolean):[i],n="";if(r.length===1)n=` or alias "${r[0]}"`;else if(r.length>1)n=` or aliases ${r.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}};lr=class lr extends jt{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(e,t,i){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:i,originalError:t.name,originalMessage:t.message});this.cause=t}};Ou=class Ou extends jt{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}};Ru=class Ru extends jt{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(e,t,i,r){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}};Va=class Va extends jt{name="EnvVarError";code="ENV_VAR_ERROR";constructor(e,t,i,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:r})}};Pu=class Pu extends jt{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(e,t,i){super(`File system ${e} failed for "${t}": ${i.message}`,{operation:e,path:t,originalError:i.name,originalMessage:i.message});this.cause=i}};Mu=class Mu extends jt{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(e,t,i){super(`Failed to generate types from "${e}" to "${t}": ${i.message}`,{configDir:e,outputPath:t,originalError:i.name,originalMessage:i.message});this.cause=i}};To=class To extends jt{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(e,t,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:e,configName:i,validationErrors:t,errorCount:t.length})}};Du=class Du extends jt{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(e,t,i,r){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:r})}};Iu=class Iu extends jt{name="PluginError";code="PLUGIN_ERROR";constructor(e,t,i){super(`Plugin "${e}" failed during ${t}: ${i.message}`,{pluginName:e,operation:t,originalError:i.name,originalMessage:i.message});this.cause=i}};mi={configNotFound(e,t,i){return new Br(e,t,i)},configLoad(e,t,i){return new lr(e,t,i)},configValidation(e,t,i){return new Ou(e,t,i)},configMerge(e,t,i,r){return new Ru(e,t,i,r)},envVar(e,t,i,r){return new Va(e,t,i,r)},fileSystem(e,t,i){return new Pu(e,t,i)},typeGeneration(e,t,i){return new Mu(e,t,i)},schemaValidation(e,t,i){return new To(e,t,i)},browserConfig(e,t,i,r){return new Du(e,t,i,r)},plugin(e,t,i){return new Iu(e,t,i)}};iu=ig(import.meta.url),co=new Map,$a=new Set;ky=/^https?:\/\//;ii=new Mo("bunfig",{showTags:!0});cb=new Gu;fb=Jt(Oo.cwd(),"config"),ub=Jt(Oo.cwd(),"src/generated"),Oy={cwd:hm.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Vu=Oy});import{existsSync as zu}from"fs";import{basename as Ry,dirname as Py,extname as Ku,isAbsolute as Do,relative as ai,resolve as li}from"path";async function qu(e,t){let i=await Fy(e);Ny(e,i);let r=i.slice(),n=await(t?t():qn(e)),o=null;if(e.autoIncludeReExports!==!1&&r.length>0){o=await Ir(r,{includeImports:!0,resolveSpecifier:n});let d=li(e.cwd,e.root),h=e.exclude||[],p=[];for(let m of o.reachable){if(r.includes(m))continue;if(!za(m))continue;if(m.endsWith(".d.ts"))continue;if(m.includes("node_modules"))continue;let g=e.outputStructure==="flat"&&i.some((C)=>n.isPackageLocal?.(C,m));if(!Yt(m,d)&&!g){de.warn(`Skipping auto-included source outside root: ${ai(e.cwd,m)}`);continue}if(zr(m,h,d))continue;p.push(m)}if(p.length>0)r=[...r,...p],de.debug(`Auto-included ${p.length} file(s) reached via relative re-exports`)}let s=Wy(r,e),a=o??await Ir(r,{includeImports:!0,resolveSpecifier:n}),l=await Xc([...a.sources.keys()],n,e.isolatedDeclarations??!1,a.sources),f=new Set(r);for(let[d,h]of l){if(!f.has(d))continue;for(let p of h){let m=n(p,d).resolved;if(m&&!f.has(m))throw Error(`Module augmentation import ${JSON.stringify(p)} from ${d} requires a source not emitted by this package build: ${m}`)}}let u=[...l].map(([d,h])=>[d,[...h].sort()]).sort(([d],[h])=>d.localeCompare(h));return Object.freeze({entryFiles:Object.freeze(i),files:Object.freeze(r),outputBySource:s,resolver:n,reachability:o,augmentationImports:l,getResolutionFingerprint:()=>JSON.stringify({resolution:n.cacheKey?.(r),augmentations:u})})}function Dy(e){let t=Ur.get(e);if(!t){if(t=new Hu(e),Ur.set(e,t),Ur.size>My){let i=Ur.keys().next().value;if(i!==void 0)Ur.delete(i)}}return t}function zr(e,t,i){if(!t||t.length===0)return!1;let r=ai(i,e);for(let n of t){let o=Dy(n);if(o.match(r)||o.match(e))return!0}return!1}function Ny(e,t){let i=li(e.cwd,e.root),r=` root: ${i}
|
|
227
|
+
`;return i}}function Fu(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}async function Wu(e){let t=ig(e),i=co.get(t),r,n=new Promise((o)=>{r=o});co.set(t,n),await i;try{if(tg(t),ru.cache[t]?.loaded===!0||xa.has(t))delete ru.cache[t];try{let o=await import(ng(t).href);return xa.delete(t),o}catch(o){throw xa.add(t),o}}finally{if(r(),co.get(t)===n)co.delete(t)}}function xy(e,t,i={}){return Lu(e,t,i,new WeakMap)}function Lu(e,t,i,r){let{arrayMergeMode:n="replace",skipNullish:o=!1,customMerger:s}=i;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 Bu(e,t,n,r);if(!Ft(t)||!Ft(e))return t;return ky(e,t,i,r)}function Bu(e,t,i,r){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(i){case"replace":return t;case"concat":return Sy(e,t);case"smart":return Ey(e,t,r);default:return t}return t}function Sy(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>Na(n,r)))i.push(r);return i}function Ey(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(Ft(t[0])&&Ft(e[0]))return Ay(e,t,i);if(t.every((r)=>typeof r==="string")&&e.every((r)=>typeof r==="string")){let r=[...t];for(let n of e)if(!r.includes(n))r.push(n);return r}return t}function Ay(e,t,i){let r=[...t];for(let n of e){if(!Ft(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let a of o)if(a in n){if(r.find((l)=>Ft(l)&&(a in l)&&l[a]===n[a])){s=!0;break}}if(!s)r.push(n)}return r}function ky(e,t,i,r){let n=t;if(Ft(n)&&r.has(n))return r.get(n);let o={...e};if(Ft(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let a=n[s],l=o[s];if(i.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){o[s]=a;continue}if(Ft(a)&&Ft(l))o[s]=Lu(l,a,i,r);else if(Array.isArray(a)||Array.isArray(l))o[s]=Bu(l,a,i.arrayMergeMode||"smart",r);else o[s]=a}return o}function _u(e,t,i="replace"){return xy(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Na(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Na(e[i],t[i]))return!1;return!0}if(Ft(e)&&Ft(t)){let i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(let n of i){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Na(e[n],t[n]))return!1}return!0}return!1}function Ft(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ju{extensions=lu;async loadFromPath(e,t,i={}){let{arrayStrategy:r="replace",useCache:n=!0,cacheTtl:o,trackPerformance:s=!0,verbose:a=!1,strictDiscovery:l=!1}=i;if(n){let u=vo.getWithFileCheck("file",e);if(u){if(a)console.log(`Configuration loaded from cache: ${e}`);return u}}let f=async()=>{try{try{og(e)}catch(g){if(Fu(g)||!l)return null;throw g}let u=await Wu(e),d=Object.hasOwn(u,"default"),h=Object.keys(u).length>0,p=d?u.default:u;if(!d&&!h)throw new lr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof p!=="object"||p===null||Array.isArray(p))throw new lr(e,Error("Configuration must export a valid object"),"unknown");let m={config:_u(t,p,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)vo.setWithFileCheck("file",m,e,o);return m}catch(u){throw u instanceof Error?mi.configLoad(e,u):mi.configLoad(e,Error(String(u)))}};if(s)return Fa.track("loadFromPath",f,{path:e});return f()}async tryLoadFromPaths(e,t,i={}){for(let r of e)try{let n=await this.loadFromPath(r,t,i);if(n)return n}catch(n){if(n instanceof lr)throw n;if(i.verbose)console.warn(`Failed to load config from ${r}:`,n)}return null}generateConfigPaths(e,t,i){return ag({name:e,directory:t,alias:i})}generateNamePatterns(e,t){return cu({name:e,alias:t})}checkFileAccess(e){return $y(async()=>ya(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!ya(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let a=Vf(e,`${o}${s}`);if(await this.checkFileAccess(a))r.push(a)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let a=Vf(e,s);if(await this.checkFileAccess(a))r.push(a)}}catch{return[]}return r}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(!ya(e))return t.push("Configuration file does not exist"),t;let i=await import(e),r=i.default||i;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),o=n(e,"utf8");JSON.parse(o)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(i){t.push(`Failed to load configuration file: ${i}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let i=new Map;return await Promise.allSettled(e.map(async(r)=>{try{let n=await this.loadFromPath(r,{},t);if(n)i.set(r,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${r}:`,n)}})),i}}class Gu{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:a=!0,verbose:l=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:a,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...s],h);else return this.validateWithJSONSchema(e,t,h)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:d}}};if(a)return await Fa.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!sg(t))throw new To(t,[{path:"",message:"Schema file does not exist"}]);let r=await Wu(t),n=Object.hasOwn(r,"default")?r.default:r;if(Array.isArray(n))return this.validateWithRules(e,n,i);else{if(typeof n!=="object"||n===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(e,n,i)}}catch(r){throw new To(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(e,t,i){let r=[],n=[];return this.validateObjectAgainstSchema(e,t,"",r,n,i),{isValid:r.length===0,errors:r,warnings:n}}validateObjectAgainstSchema(e,t,i,r,n,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(r.push({path:i,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(r.push({path:i,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)r.push({path:i,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)r.push({path:i,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))r.push({path:i,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)r.push({path:i,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)r.push({path:i,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=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,a,r,n,o),o.stopOnFirstError&&r.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(r.push({path:i?`${i}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[a,l]of Object.entries(t.properties))if(a in s){let f=i?`${i}.${a}`:a;if(this.validateObjectAgainstSchema(s[a],l,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(s))if(!a.has(l))n.push({path:i?`${i}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,i){let r=[],n=[];for(let o of t)try{let s=this.getValueByPath(e,o.path),a=this.validateWithRule(s,o,o.path);if(r.push(...a),i.stopOnFirstError&&r.length>0)break}catch(s){r.push({path:o.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:n}}validateWithRule(e,t,i){let r=[];if(t.required&&(e===void 0||e===null))return r.push({path:i,message:t.message||`Property '${i}' is required`,expected:"required",rule:"required"}),r;if(e===void 0||e===null)return r;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)r.push({path:i,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)r.push({path:i,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)r.push({path:i,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))r.push({path:i,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))r.push({path:i,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)r.push({path:i,message:t.message||n,rule:"custom"})}return r}getValueByPath(e,t){if(!t)return e;let i=t.split("."),r=e;for(let n of i)if(r&&typeof r==="object"&&n in r)r=r[n];else return;return r}generateRulesFromInterface(e){let t=[],i=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of i){let[,n,o,s]=r;t.push({path:n,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:Ty},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Oy(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((i)=>`"${i}"`).join(", ")}`}class Vu{fileLoader=new ju;envProcessor=new za;validator=new Gu;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e,a=s.errorPolicy==="throw"?{...i,enabled:!1}:i;try{if(a?.enabled){let f=this.checkCache(s.name||"",s);if(f)return f}let l;try{l=await this.loadConfigurationStrategies(s,!0,a)}catch(f){if(s.configFile||s.errorPolicy==="throw"&&!(f instanceof Br))throw f;let u=s.__strictErrorHandling;if(f instanceof Br){if(u&&s.errorPolicy!=="throw")throw f;l={...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(f instanceof lr){let d=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),h=!d&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),p=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(p||d))throw f;if(h&&(!u||!p))l={...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(!u)l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(n||o)await this.validateConfiguration(l.config,n,o,s.name);if(a?.enabled&&l)this.cacheResult(s.name||"",l,a,s);if(r?.enabled){let f={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(f);if(r.slowThreshold&&f.duration>r.slowThreshold)ii.warn(`Slow configuration loading detected: ${f.duration}ms for ${s.name}`);l.metrics=f}return l}catch(l){if(l instanceof Br)throw l;let f=Date.now()-t;throw ii.error(`Configuration loading failed after ${f}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,configFile:o,cwd:s,configDir:a,defaultConfig:l,checkEnv:f=!0,arrayStrategy:u="replace",verbose:d=!1}=e,h=s||Oo.cwd(),p=[];if(o){let b=Jt(h,o);p.push(b);let c=f?Fr(r,l,d):l,A=await this.fileLoader.tryLoadFromPaths([b],c,{arrayStrategy:u,verbose:d,cacheTtl:i?.ttl,useCache:i?.enabled!==!1&&(!i?.ttl||i.ttl>100),strictDiscovery:!0});if(!A)throw mi.configNotFound(r||o,p,n);if(d)ii.success(`Configuration loaded from explicit path: ${b}`);return this.finalizeResult(A,p,f,r,d)}let m=await this.loadLocalConfiguration(r,n,h,a,l,u,d,f,i,e.errorPolicy==="throw");if(m)return p.push(...this.getLocalSearchPaths(r,n,h,a)),this.finalizeResult(m,p,f,r,d);let g=await this.loadHomeConfiguration(r,n,l,u,d,f,i,e.errorPolicy==="throw");if(g)return p.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(g,p,f,r,d);let C=await this.loadPackageJsonConfiguration(r,n,h,l,u,d,f,e.errorPolicy);if(C)return p.push(Jt(h,"package.json")),this.finalizeResult(C,p,f,r,d);if(p.push(...this.getAllSearchPaths(r,n,h,a)),t)throw mi.configNotFound(r,p,n);return{...await this.applyEnvironmentVariables(r,l,f,d),warnings:[`No configuration file found for "${r}"${Oy(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,r,n,o,s,a,l,f=!1){let u=a?Fr(e,n,s):n,d=this.getLocalDirectories(i,r);for(let h of d){if(s)ii.info(`Searching for configuration in: ${h}`);let p=this.fileLoader.generateConfigPaths(e,h,t),m=await this.fileLoader.tryLoadFromPaths(p,u,{arrayStrategy:o,verbose:s,cacheTtl:l?.ttl,useCache:l?.enabled!==!1&&(!l?.ttl||l.ttl>100),strictDiscovery:f});if(m){if(s)ii.success(`Configuration loaded from: ${m.source.path}`);return m}}return null}async loadHomeConfiguration(e,t,i,r,n,o,s,a=!1){if(!e)return null;let l=o?Fr(e,i,n):i,f=[Jt(Xi(),".config",e),Jt(Xi(),".config"),Xi()];for(let u of f){if(n)ii.info(`Checking home directory: ${u}`);let d=this.fileLoader.generateConfigPaths(e,u,t),h=await this.fileLoader.tryLoadFromPaths(d,l,{arrayStrategy:r,verbose:n,cacheTtl:s?.ttl,useCache:s?.enabled!==!1&&(!s?.ttl||s.ttl>100),strictDiscovery:a});if(h){if(n)ii.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s,a){let l=s?Fr(e,r,o):r,f=Jt(i,"package.json"),u=a==="throw";try{let d=JSON.parse(gm(f,"utf8"));if(typeof d!=="object"||d===null||Array.isArray(d))throw Error("package.json must contain an object");let h=d,p=t===void 0?[]:Array.isArray(t)?t:[t],m=[e,...p.filter(Boolean)].find((C)=>Object.hasOwn(h,C)&&(u||Boolean(h[C])));if(m===void 0)return null;let g=h[m];if(typeof g!=="object"||g===null||Array.isArray(g))throw Error(`Configuration field "${m}" must contain an object`);if(o)ii.success(`Configuration loaded from package.json: ${m}`);return{config:_u(l,g,n),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(d){if(Fu(d))return null;if(u)throw mi.configLoad(f,d instanceof Error?d:Error(String(d)));if(o)ii.warn("Failed to load package.json:",[d instanceof Error?d:Error(String(d))]);return null}}async applyEnvironmentVariables(e,t,i,r){if(!i||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Fr(e,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,i,r,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,i,r){let n=[];if(i){let o=i(e);if(o)n.push(...o)}if(t){let o=await this.validator.validateConfiguration(e,t);if(!o.isValid)n.push(...o.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(n.length>0)throw mi.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return vo.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);vo.set(n,t,void 0,i.ttl)}generateCacheKey(e,t){let i=[e];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;i.push(`alias:${r}`)}if(t.cwd)i.push(`cwd:${t.cwd}`);if(t.configFile)i.push(`configFile:${t.configFile}`);if(t.configDir)i.push(`configDir:${t.configDir}`);if("checkEnv"in t)i.push(`checkEnv:${t.checkEnv}`);return i.join("|")}getLocalDirectories(e,t){return lg({cwd:e,configDir:t})}getAllSearchPaths(e,t,i,r){let n=[];return n.push(...this.getLocalSearchPaths(e,t,i,r)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Jt(i,"package.json")),n}getLocalSearchPaths(e,t,i,r){let n=this.getLocalDirectories(i,r),o=[];for(let s of n)o.push(...this.fileLoader.generateConfigPaths(e,s,t));return o}getHomeSearchPaths(e,t){if(!e)return[];let i=[Jt(Xi(),".config",e),Jt(Xi(),".config"),Xi()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function Fr(e,t,i=!1){let r=new za,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,a=[]){let l={...s};for(let[f,u]of Object.entries(s)){let d=[...a,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((g)=>g.toUpperCase()).join("")}`,`${n}_${d.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let g of h)if(p=Oo.env[g],p!==void 0){m=g;break}if(p!==void 0&&m)if(typeof u==="boolean")l[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let g=Number(p);if(!Number.isNaN(g))l[f]=g}else if(Array.isArray(u))try{l[f]=JSON.parse(p)}catch{l[f]=p.split(",").map((g)=>g.trim())}else l[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))l[f]=o(u,d)}return l}return o(t)}var vo,Fa,lu,cg,fg=(e)=>e,dg=(e,t)=>{for(var i in t)cg(e,i,{get:t[i],enumerable:!0,configurable:!0,set:ug.bind(t,i)})},hg=(e,t)=>()=>(e&&(t=e(e=0)),t),fu,Cu,cr,Vr,vu,_g,jg,zf,uo,ka,ut,Ke,Gg,Kf,Vg,Hf,Ug,zg,wa,Kg,qf,Jf,Ca,Hg,qg,Jg,Yg,ho,bu,Xg,dt,Zg,Qg,Yf,po,Ta,ot,Re,ey,Xf,ty,Zf,iy,ry,va,ny,Qf,eu,oy,ba,sy,ay,ly,cy,fy,mo,$u,uy,dy="0.15.6",Ot,Eo,jr,Oa,Ra,Ao,Pa,Ma,Gr,Da,Ia,gi,xu,Su,_t,si,Eu,Au,hy,my,ku,ko,Xv,Ou,Pe,Zv,yy,Qv,wy,eb,tb,tu,ib,Cy,vy,rb,iu,nb,ob,sb,ab,lb,$a,by,cb,jt,Br,lr,Ru,Pu,Ua,Mu,Du,To,Iu,Nu,mi,ru,co,xa,Ty,ii,fb,ub,db,Ry,Uu;var zu=ye(()=>{vo=new su,Fa=new au,lu=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];cg=Object.defineProperty;fu={};dg(fu,{withErrorRecovery:()=>hu,tryLoadConfig:()=>Fg,loadConfigWithResult:()=>Ig,loadConfig:()=>wu,isRetryableError:()=>Tg,isConfigNotFoundError:()=>kg,isBunfigError:()=>pu,globalPerformanceMonitor:()=>Vr,globalCache:()=>cr,getEnvOrDefault:()=>Og,generateConfigTypes:()=>Wg,defaultGeneratedDir:()=>Au,defaultConfigDir:()=>Eu,deepMergeWithArrayStrategy:()=>ja,deepMerge:()=>mu,createLibraryConfig:()=>Lg,config:()=>Ng,bunfigPlugin:()=>Bg,applyEnvVarsToConfig:()=>Lr,TypeGenerationError:()=>Ma,SchemaValidationError:()=>Gr,PluginError:()=>Ia,PerformanceMonitor:()=>La,FileSystemError:()=>Pa,ErrorFactory:()=>gi,EnvVarError:()=>Ao,EnvProcessor:()=>Ro,ConfigValidator:()=>Ga,ConfigValidationError:()=>Oa,ConfigNotFoundError:()=>Eo,ConfigMergeError:()=>Ra,ConfigLoader:()=>Va,ConfigLoadError:()=>jr,ConfigFileLoader:()=>Po,ConfigCache:()=>Wa,CacheUtils:()=>vu,BunfigError:()=>Ot,BrowserConfigError:()=>Da,ArrayMergeStrategies:()=>xu});hy=hg(async()=>{Cu=import.meta.require,cr=new Wa,Vr=new La,vu={createKey:pg,isEquivalent:mg,estimateMemoryUsage:gg},_g=wo(Ea.cwd(),"config"),jg=wo(Ea.cwd(),"src/generated"),zf=yo.env.CLARITY_LOG_DIR||$m(Cg(),"logs"),uo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ka=await vg(),ut={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"},Ke=ut,Gg=ut.red,Kf=ut.green,Vg=ut.yellow,Hf=ut.blue,Ug=ut.magenta,zg=ut.cyan,wa=ut.white,Kg=ut.gray,qf=ut.bgRed,Jf=ut.bgYellow,Ca=ut.bold,Hg=ut.dim,qg=ut.italic,Jg=ut.underline,Yg=ut.reset,ho={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bu={debug:"\uD83D\uDD0D",info:Hf("\u2139"),success:Kf("\u2713"),warning:Jf(wa(Ca(" WARN "))),error:qf(wa(Ca(" ERROR ")))},Xg=new $o("stacks"),dt=new $o("bunfig",{showTags:!0}),Zg=wt(_r.cwd(),"config"),Qg=wt(_r.cwd(),"src/generated"),Yf=go.env.CLARITY_LOG_DIR||vm(Sg(),"logs"),po={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Yf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ta=await Eg(),ot={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"},Re=ot,ey=ot.red,Xf=ot.green,ty=ot.yellow,Zf=ot.blue,iy=ot.magenta,ry=ot.cyan,va=ot.white,ny=ot.gray,Qf=ot.bgRed,eu=ot.bgYellow,oy=ot.bgGray,ba=ot.bold,sy=ot.dim,ay=ot.italic,ly=ot.underline,cy=ot.strikethrough,fy=ot.reset,mo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$u={debug:"\uD83D\uDD0D",info:Zf("\u2139"),success:Xf("\u2713"),warning:eu(va(ba(" WARN "))),error:Qf(va(ba(" ERROR ")))},uy=new So("stacks"),Ot=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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Eo=class extends Ot{code="CONFIG_NOT_FOUND";constructor(e,t,i){let r=i?` or alias "${i}"`:"";super(`Configuration "${e}"${r} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}},jr=class extends Ot{code="CONFIG_LOAD_ERROR";constructor(e,t,i){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:i,originalError:t.name,originalMessage:t.message});this.cause=t}},Oa=class extends Ot{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}},Ra=class extends Ot{code="CONFIG_MERGE_ERROR";constructor(e,t,i,r){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Ao=class extends Ot{code="ENV_VAR_ERROR";constructor(e,t,i,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:r})}},Pa=class extends Ot{code="FILE_SYSTEM_ERROR";constructor(e,t,i){super(`File system ${e} failed for "${t}": ${i.message}`,{operation:e,path:t,originalError:i.name,originalMessage:i.message});this.cause=i}},Ma=class extends Ot{code="TYPE_GENERATION_ERROR";constructor(e,t,i){super(`Failed to generate types from "${e}" to "${t}": ${i.message}`,{configDir:e,outputPath:t,originalError:i.name,originalMessage:i.message});this.cause=i}},Gr=class extends Ot{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:e,configName:i,validationErrors:t,errorCount:t.length})}},Da=class extends Ot{code="BROWSER_CONFIG_ERROR";constructor(e,t,i,r){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:r})}},Ia=class extends Ot{code="PLUGIN_ERROR";constructor(e,t,i){super(`Plugin "${e}" failed during ${t}: ${i.message}`,{pluginName:e,operation:t,originalError:i.name,originalMessage:i.message});this.cause=i}},gi={configNotFound(e,t,i){return new Eo(e,t,i)},configLoad(e,t,i){return new jr(e,t,i)},configValidation(e,t,i){return new Oa(e,t,i)},configMerge(e,t,i,r){return new Ra(e,t,i,r)},envVar(e,t,i,r){return new Ao(e,t,i,r)},fileSystem(e,t,i){return new Pa(e,t,i)},typeGeneration(e,t,i){return new Ma(e,t,i)},schemaValidation(e,t,i){return new Gr(e,t,i)},browserConfig(e,t,i,r){return new Da(e,t,i,r)},plugin(e,t,i){return new Ia(e,t,i)}},xu={replace:"replace",concat:"concat",smart:"smart"},Su=/^https?:\/\//,_t=new So("bunfig",{showTags:!0}),si=new Va,Eu=Ct(Ii.cwd(),"config"),Au=Ct(Ii.cwd(),"src/generated")});my=Co.env.CLARITY_LOG_DIR||Um(py(),"logs"),ku={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:my,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ko={...ku},Xv=(async()=>{try{let{loadConfig:e}=await hy().then(()=>fu),t=await e({name:"clarity",alias:"logging",defaultConfig:ku,cwd:Co.cwd()});if(t)Object.assign(ko,t)}catch{}return ko})();Ou={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},Pe=Ou,{red:Zv,green:yy,yellow:Qv,blue:wy,magenta:eb,cyan:tb,white:tu,gray:ib,bgRed:Cy,bgYellow:vy,bgGray:rb,bold:iu,dim:nb,italic:ob,underline:sb,strikethrough:ab,reset:lb}=Ou,$a={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},by={debug:"\uD83D\uDD0D",info:wy("\u2139"),success:yy("\u2713"),warning:vy(tu(iu(" WARN "))),error:Cy(tu(iu(" ERROR ")))};cb=new Mo("stacks");jt=class jt 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,i])=>`${t}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};Br=class Br extends jt{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(e,t,i){let r=i===void 0?[]:Array.isArray(i)?i.filter(Boolean):[i],n="";if(r.length===1)n=` or alias "${r[0]}"`;else if(r.length>1)n=` or aliases ${r.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:i,searchPaths:t,searchPathCount:t.length})}};lr=class lr extends jt{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(e,t,i){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:i,originalError:t.name,originalMessage:t.message});this.cause=t}};Ru=class Ru extends jt{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}};Pu=class Pu extends jt{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(e,t,i,r){super(`Failed to merge configuration from "${e}" with "${t}": ${i.message}`,{sourcePath:e,targetPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}};Ua=class Ua extends jt{name="EnvVarError";code="ENV_VAR_ERROR";constructor(e,t,i,r){super(`Failed to parse environment variable "${e}" with value "${t}" as ${i}`,{envKey:e,envValue:t,expectedType:i,configName:r})}};Mu=class Mu extends jt{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(e,t,i){super(`File system ${e} failed for "${t}": ${i.message}`,{operation:e,path:t,originalError:i.name,originalMessage:i.message});this.cause=i}};Du=class Du extends jt{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(e,t,i){super(`Failed to generate types from "${e}" to "${t}": ${i.message}`,{configDir:e,outputPath:t,originalError:i.name,originalMessage:i.message});this.cause=i}};To=class To extends jt{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(e,t,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:e,configName:i,validationErrors:t,errorCount:t.length})}};Iu=class Iu extends jt{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(e,t,i,r){super(`Failed to fetch configuration from "${e}": ${t} ${i}`,{endpoint:e,status:t,statusText:i,configName:r})}};Nu=class Nu extends jt{name="PluginError";code="PLUGIN_ERROR";constructor(e,t,i){super(`Plugin "${e}" failed during ${t}: ${i.message}`,{pluginName:e,operation:t,originalError:i.name,originalMessage:i.message});this.cause=i}};mi={configNotFound(e,t,i){return new Br(e,t,i)},configLoad(e,t,i){return new lr(e,t,i)},configValidation(e,t,i){return new Ru(e,t,i)},configMerge(e,t,i,r){return new Pu(e,t,i,r)},envVar(e,t,i,r){return new Ua(e,t,i,r)},fileSystem(e,t,i){return new Mu(e,t,i)},typeGeneration(e,t,i){return new Du(e,t,i)},schemaValidation(e,t,i){return new To(e,t,i)},browserConfig(e,t,i,r){return new Iu(e,t,i,r)},plugin(e,t,i){return new Nu(e,t,i)}};ru=rg(import.meta.url),co=new Map,xa=new Set;Ty=/^https?:\/\//;ii=new Mo("bunfig",{showTags:!0});fb=new Vu;ub=Jt(Oo.cwd(),"config"),db=Jt(Oo.cwd(),"src/generated"),Ry={cwd:pm.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Uu=Ry});import{existsSync as Ku}from"fs";import{basename as Py,dirname as My,extname as Hu,isAbsolute as Do,relative as ai,resolve as li}from"path";async function Ju(e,t){let i=await Wy(e);Fy(e,i);let r=i.slice(),n=await(t?t():qn(e)),o=null;if(e.autoIncludeReExports!==!1&&r.length>0){o=await Ir(r,{includeImports:!0,resolveSpecifier:n});let d=li(e.cwd,e.root),h=e.exclude||[],p=[];for(let m of o.reachable){if(r.includes(m))continue;if(!Ka(m))continue;if(m.endsWith(".d.ts"))continue;if(m.includes("node_modules"))continue;let g=e.outputStructure==="flat"&&i.some((C)=>n.isPackageLocal?.(C,m));if(!Yt(m,d)&&!g){de.warn(`Skipping auto-included source outside root: ${ai(e.cwd,m)}`);continue}if(zr(m,h,d))continue;p.push(m)}if(p.length>0)r=[...r,...p],de.debug(`Auto-included ${p.length} file(s) reached via relative re-exports`)}let s=Ly(r,e),a=o??await Ir(r,{includeImports:!0,resolveSpecifier:n}),l=await Zc([...a.sources.keys()],n,e.isolatedDeclarations??!1,a.sources),f=new Set(r);for(let[d,h]of l){if(!f.has(d))continue;for(let p of h){let m=n(p,d).resolved;if(m&&!f.has(m))throw Error(`Module augmentation import ${JSON.stringify(p)} from ${d} requires a source not emitted by this package build: ${m}`)}}let u=[...l].map(([d,h])=>[d,[...h].sort()]).sort(([d],[h])=>d.localeCompare(h));return Object.freeze({entryFiles:Object.freeze(i),files:Object.freeze(r),outputBySource:s,resolver:n,reachability:o,augmentationImports:l,getResolutionFingerprint:()=>JSON.stringify({resolution:n.cacheKey?.(r),augmentations:u})})}function Iy(e){let t=Ur.get(e);if(!t){if(t=new qu(e),Ur.set(e,t),Ur.size>Dy){let i=Ur.keys().next().value;if(i!==void 0)Ur.delete(i)}}return t}function zr(e,t,i){if(!t||t.length===0)return!1;let r=ai(i,e);for(let n of t){let o=Iy(n);if(o.match(r)||o.match(e))return!0}return!1}function Fy(e,t){let i=li(e.cwd,e.root),r=` root: ${i}
|
|
228
228
|
entrypoints: ${e.entrypoints.map((o)=>JSON.stringify(o)).join(", ")||"(none)"}
|
|
229
229
|
`+(e.exclude?.length?` exclude: ${e.exclude.map((o)=>JSON.stringify(o)).join(", ")}
|
|
230
|
-
`:"")+"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)=>Do(o)&&
|
|
231
|
-
${r}`)}let n=e.entrypoints.filter((o)=>{if(
|
|
232
|
-
${r}`)}async function Fy(e){let t=[],i=li(e.cwd,e.root),r=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let o of n)if(Do(o)&&za(o)){if(!o.includes("node_modules")){if(!Yt(o,i)&&e.outputStructure!=="flat")de.warn(`Skipping entrypoint outside root: ${ai(e.cwd,o)}`);else if(!zr(o,r,i))t.push(o)}}else{let s=new Hu(o);for await(let a of s.scan({cwd:i,absolute:!0,onlyFiles:!0}))if(za(a)&&!a.includes("node_modules")){if(!zr(a,r,i))t.push(a)}}return[...new Set(t.map((o)=>li(o)))].sort()}function Yt(e,t){let i=ai(t,e);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Do(i)}function Wy(e,t){let i=new Map,r=new Map;for(let n of e){let o=fr(n,t),s=i.get(o);if(s&&s!==n)throw Error(`Output path collision: ${ai(t.cwd,s)} and ${ai(t.cwd,n)} both emit ${ai(t.cwd,o)}`);i.set(o,n),r.set(n,o)}return r}function za(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function fr(e,t){let i=li(t.cwd,t.root),r=ai(i,e),n=/\.d\.(?:ts|mts|cts)$/.test(r)?r:r.replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(o)=>{if(o===".mts"||o===".mjs")return".d.mts";if(o===".cts"||o===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return li(t.cwd,t.outdir,n);else{let o=Ry(n);return li(t.cwd,t.outdir,o)}}function Ly(e,t,i=""){let r=ai(Py(e),t).replace(/\\/g,"/");if(r=r.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),i)r+=i;if(!r.startsWith("."))r=`./${r}`;return r}function Ju(e,t,i,r){let n=fr(e,t);return(o)=>{let s=i(o,e);if(!s.isRelative||!s.resolved)return{kind:"unchanged",reason:s.isRelative?"unresolved":"external",specifier:o,emittedSpecifier:o};if(/\.d\.(?:ts|mts|cts)$/.test(s.resolved)){if(t.moduleSpecifierMode!=="node")return{kind:"unchanged",reason:"preserved-declaration",specifier:o,emittedSpecifier:o};if(r&&!r.has(s.resolved))throw Error(`Local declaration ${JSON.stringify(o)} from ${e} targets an authored declaration not emitted by this package build: ${s.resolved}. Declaration-only dependencies must be delivered with the package before this importer can be emitted.`)}if(s.isAlias&&r&&!r.has(s.resolved))throw Error(`Local alias ${JSON.stringify(o)} from ${e} targets a declaration excluded from this package build: ${s.resolved}`);if(r&&!r.has(s.resolved)&&zr(s.resolved,t.exclude??[],li(t.cwd,t.root)))throw Error(`Local reference ${JSON.stringify(o)} from ${e} targets a source excluded from this package build: ${s.resolved}`);let a=s.isAlias?s.suffix??"":o.match(/[?#].*$/)?.[0]??"",l=a?o.slice(0,-a.length):o,f=Ku(l),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";if(!u&&t.moduleSpecifierMode==="node"){let h=Ku(s.resolved);u=h===".mts"||h===".mjs"?".mjs":h===".cts"||h===".cjs"?".cjs":".js"}let d=fr(s.resolved,t);return{kind:"local",specifier:o,resolvedSource:s.resolved,declarationOutput:d,emittedSpecifier:Ly(n,d,u)+a}}}var Hu,My=50,Ur,Iy;var Ka=ye(()=>{Zc();Kn();Jn();({Glob:Hu}=globalThis.Bun);Ur=new Map;Iy=/[*?[\]{}!]/});var Yu;var Xu=ye(()=>{Yu=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 Zu(e,t={strings:!0}){let i="",r=0;while(r<e.length){let n=e.slice(r,r+2);if(n==="//"){let s=e.indexOf(`
|
|
230
|
+
`:"")+"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)=>Do(o)&&Ku(o)&&!Yt(o,i)).length===e.entrypoints.length)return;throw Error(`No source files matched. Nothing was generated.
|
|
231
|
+
${r}`)}let n=e.entrypoints.filter((o)=>{if(Ny.test(o))return!1;return!Ku(Do(o)?o:li(i,o))});if(n.length>0)throw Error(`Entrypoint${n.length>1?"s":""} not found: ${n.map((o)=>JSON.stringify(o)).join(", ")}
|
|
232
|
+
${r}`)}async function Wy(e){let t=[],i=li(e.cwd,e.root),r=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let o of n)if(Do(o)&&Ka(o)){if(!o.includes("node_modules")){if(!Yt(o,i)&&e.outputStructure!=="flat")de.warn(`Skipping entrypoint outside root: ${ai(e.cwd,o)}`);else if(!zr(o,r,i))t.push(o)}}else{let s=new qu(o);for await(let a of s.scan({cwd:i,absolute:!0,onlyFiles:!0}))if(Ka(a)&&!a.includes("node_modules")){if(!zr(a,r,i))t.push(a)}}return[...new Set(t.map((o)=>li(o)))].sort()}function Yt(e,t){let i=ai(t,e);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Do(i)}function Ly(e,t){let i=new Map,r=new Map;for(let n of e){let o=fr(n,t),s=i.get(o);if(s&&s!==n)throw Error(`Output path collision: ${ai(t.cwd,s)} and ${ai(t.cwd,n)} both emit ${ai(t.cwd,o)}`);i.set(o,n),r.set(n,o)}return r}function Ka(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function fr(e,t){let i=li(t.cwd,t.root),r=ai(i,e),n=/\.d\.(?:ts|mts|cts)$/.test(r)?r:r.replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(o)=>{if(o===".mts"||o===".mjs")return".d.mts";if(o===".cts"||o===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return li(t.cwd,t.outdir,n);else{let o=Py(n);return li(t.cwd,t.outdir,o)}}function By(e,t,i=""){let r=ai(My(e),t).replace(/\\/g,"/");if(r=r.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),i)r+=i;if(!r.startsWith("."))r=`./${r}`;return r}function Yu(e,t,i,r){let n=fr(e,t);return(o)=>{let s=i(o,e);if(!s.isRelative||!s.resolved)return{kind:"unchanged",reason:s.isRelative?"unresolved":"external",specifier:o,emittedSpecifier:o};if(/\.d\.(?:ts|mts|cts)$/.test(s.resolved)){if(t.moduleSpecifierMode!=="node")return{kind:"unchanged",reason:"preserved-declaration",specifier:o,emittedSpecifier:o};if(r&&!r.has(s.resolved))throw Error(`Local declaration ${JSON.stringify(o)} from ${e} targets an authored declaration not emitted by this package build: ${s.resolved}. Declaration-only dependencies must be delivered with the package before this importer can be emitted.`)}if(s.isAlias&&r&&!r.has(s.resolved))throw Error(`Local alias ${JSON.stringify(o)} from ${e} targets a declaration excluded from this package build: ${s.resolved}`);if(r&&!r.has(s.resolved)&&zr(s.resolved,t.exclude??[],li(t.cwd,t.root)))throw Error(`Local reference ${JSON.stringify(o)} from ${e} targets a source excluded from this package build: ${s.resolved}`);let a=s.isAlias?s.suffix??"":o.match(/[?#].*$/)?.[0]??"",l=a?o.slice(0,-a.length):o,f=Hu(l),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";if(!u&&t.moduleSpecifierMode==="node"){let h=Hu(s.resolved);u=h===".mts"||h===".mjs"?".mjs":h===".cts"||h===".cjs"?".cjs":".js"}let d=fr(s.resolved,t);return{kind:"local",specifier:o,resolvedSource:s.resolved,declarationOutput:d,emittedSpecifier:By(n,d,u)+a}}}var qu,Dy=50,Ur,Ny;var Ha=ye(()=>{Qc();Kn();Jn();({Glob:qu}=globalThis.Bun);Ur=new Map;Ny=/[*?[\]{}!]/});var Xu;var Zu=ye(()=>{Xu=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 Qu(e,t={strings:!0}){let i="",r=0;while(r<e.length){let n=e.slice(r,r+2);if(n==="//"){let s=e.indexOf(`
|
|
233
233
|
`,r),a=s===-1?e.length:s;i+=" ".repeat(a-r),r=a;continue}if(n==="/*"){let s=e.indexOf("*/",r+2),a=s===-1?e.length:s+2;for(let l=r;l<a;l++)i+=e[l]===`
|
|
234
234
|
`?`
|
|
235
235
|
`:" ";r=a;continue}let o=e[r];if(t.strings&&(o==='"'||o==="'"||o==="`")){let s=o;i+=" ",r++;while(r<e.length){if(e[r]==="\\"){i+=" ",r+=2;continue}if(e[r]===s){i+=" ",r++;break}i+=e[r]===`
|
|
236
236
|
`?`
|
|
237
|
-
`:" ",r++}continue}i+=o,r++}return i}function
|
|
237
|
+
`:" ",r++}continue}i+=o,r++}return i}function jy(e){let t=new Set,i=[/\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 r of i)for(let n of e.matchAll(r))t.add(n[1]);return t}function Gy(e){let t=new Set;for(let i of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let r=i[1],n=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(r);if(n)t.add(n[1]);let o=r.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let a of o.split(",")){let l=a.trim();if(/^[A-Za-z_$][\w$]*$/.test(l))t.add(l)}let s=/\{([\s\S]*?)\}/.exec(r);if(s)for(let a of s[1].split(",")){let l=a.trim().replace(/^type\s+/,"");if(!l)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(l);t.add(f?f[1]:l.split(/\s+/)[0])}}for(let i of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(i[1]);return t}function Vy(e){let t=new Set,i=(n)=>{for(let o of n.split(",")){let s=o.trim().split(/\s+|=/)[0]?.trim();if(s&&/^[A-Za-z_$][\w$]*$/.test(s))t.add(s)}},r=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let n of e.matchAll(r))i(n[1]);for(let n of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))i(n[1]);for(let n of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(n[1]);for(let n of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(n[1]);return t}function Uy(e){let t=new Map,i=(n)=>{let o=1;for(let s=0;s<n&&s<e.length;s++)if(e.charCodeAt(s)===10)o++;return o},r=(n,o,s)=>{for(let a of n.matchAll(/\b([A-Z][\w$]*)\b/g)){let l=a[1];if(t.has(l))continue;let f=n.slice(a.index+l.length);if(/^\s*\??:/.test(f))continue;t.set(l,{line:i(o),context:s.trim().slice(0,120)})}};for(let n of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))r(n[1],n.index+n[0].indexOf("="),n[0]);for(let n of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))r(n[1],n.index,n[0]);for(let n of e.matchAll(/:\s*([^;,){}\n=]+)/g))r(n[1],n.index,n[0]);for(let n of e.matchAll(/<([^<>()]*)>/g))r(n[1],n.index,n[0]);return t}function ed(e){let t=Qu(e),i=Qu(e,{strings:!1}),r=new Set([...jy(t),...Gy(i),...Vy(t),...Xu,..._y]),n=[];for(let[o,s]of Uy(t)){if(r.has(o))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${o}\\b`).test(t))continue;n.push({name:o,line:s.line,context:s.context})}return n.sort((o,s)=>o.line-s.line||o.name.localeCompare(s.name))}var _y;var td=ye(()=>{Zu();_y=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function yi(e,t){let i=1,r=1;for(let n=0;n<t;n++)if(e.charCodeAt(n)===10)i++,r=1;else r++;return{line:i,column:r}}function rd(e){let t=[],i=[],r=[],n={")":"(","]":"[","}":"{"},o=0,s=0,a=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),d=e.charCodeAt(f+1);if(a!==-1){if(u===42&&d===47)i.push({start:a,end:f+2}),a=-1,f++;continue}if(o){if(u===92)f++;else if(u===o)i.push({start:s,end:f+1}),o=0;continue}if(u===47&&d===42){a=f,f++;continue}if(u===47&&d===47){let p=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;i.push({start:p,end:f});continue}if(u===39||u===34||u===96){o=u,s=f;continue}let h=e[f];if(h==="("||h==="["||h==="{")r.push({char:h,offset:f});else if(n[h]){let p=r.pop();if(!p||p.char!==n[h])t.push({...yi(e,f),message:`Unexpected closing delimiter ${h}`,code:"DTSX1004"})}}if(o)t.push({...yi(e,s),message:"Unterminated string literal",code:"DTSX1002"});if(a!==-1)t.push({...yi(e,a),message:"Unterminated block comment",code:"DTSX1003"});for(let f of r)t.push({...yi(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let l=[[/\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 l)for(let d of e.matchAll(f)){if(i.some((h)=>d.index>=h.start&&d.index<h.end))continue;t.push({...yi(e,d.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(i.some((d)=>f.index>=d.start&&f.index<d.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...yi(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.push(...Ky(e,i)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function Ky(e,t){let i=[],r=(n)=>t.some((o)=>n>=o.start&&n<o.end);for(let n of e.matchAll(/\b(import|export)\s+(?:type\s+)?\{/g)){let o=n.index;if(r(o))continue;let s=o+n[0].length-1,a=-1;for(let u=s+1;u<e.length;u++){if(r(u))continue;let d=e[u];if(d==="{"){a=-2;break}if(d==="}"){a=u;break}}if(a<0)continue;let l=e.slice(s+1,a);if(!l.trim())continue;let f=s+1;for(let u of l.split(",")){let d=u.trim();if(d){let h=f+u.indexOf(d);if(d.includes(";"))i.push({...yi(e,h),message:`Unexpected ';' in ${n[1]} clause \u2014 specifiers are separated by ','`,code:"DTSX1006"});else if(!zy.test(d))i.push({...yi(e,h),message:`Invalid ${n[1]} specifier '${d}'`,code:"DTSX1006"})}f+=u.length+1}}return i}var id,zy;var nd=ye(()=>{id=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,zy=new RegExp(`^(?:type\\s+)?${id}(?:\\s+as\\s+${id})?$`,"u")});import Hy from"process";import{join as jb,resolve as qy}from"path";function qa(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function Io(e,t,i="lf"){let r=t.replace(/\r\n/g,`
|
|
238
238
|
`);if(!r.endsWith(`
|
|
239
239
|
`))r+=`
|
|
240
240
|
`;if(i==="crlf")r=r.replace(/\n/g,`\r
|
|
241
|
-
`);if(await
|
|
241
|
+
`);if(await Pl(e,r)!==Buffer.byteLength(r,"utf8"))throw Error(`Incomplete declaration write: ${e}`)}async function od(e){try{let t=e?.cwd||Hy.cwd();return(await Mr(qy(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function sd(e,t){let i={isValid:!0,errors:[]};for(let r of rd(e))i.errors.push({line:r.line,column:r.column,message:r.message,code:r.code});for(let r of ed(e))i.errors.push({line:r.line,column:1,message:`'${r.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: ${r.context}`,code:"dangling-type-reference"});return i.isValid=i.errors.length===0,i}function ad(e,t,i){if(e===t)return"";let r=e.split(`
|
|
242
242
|
`),n=t.split(`
|
|
243
243
|
`),o=new Map,s=new Map;for(let u=0;u<r.length;u++)o.set(r[u],(o.get(r[u])??0)+1);for(let u=0;u<n.length;u++)s.set(n[u],(s.get(n[u])??0)+1);let a=[],l=[];for(let[u,d]of o){let h=d-(s.get(u)??0);for(let p=0;p<h;p++)a.push(u)}for(let[u,d]of s){let h=d-(o.get(u)??0);for(let p=0;p<h;p++)l.push(u)}if(a.length===0&&l.length===0)return"";let f=[`--- ${i}`,`+++ ${i}`];for(let u=0;u<a.length;u++)f.push(`- ${a[u]}`);for(let u=0;u<l.length;u++)f.push(`+ ${l[u]}`);return f.join(`
|
|
244
|
-
`)}function
|
|
244
|
+
`)}function ld(e,t,i,r){let n=e.split(`
|
|
245
245
|
`),o=[];function s(d){let h="",p=d<0?-d<<1|1:d<<1;do{let m=p&31;if(p>>>=5,p>0)m|=32;h+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[m]}while(p>0);return h}let a=0,l=0,f=0,u=r.split(`
|
|
246
|
-
`).length;for(let d=0;d<n.length;d++){if(n[d].trim()===""){o.push("");continue}a=0;let h=Math.min(d,u-1),p=[],m=0-a,g=0,C=h-l,b=0-f;p.push(s(m)+s(g)+s(C)+s(b)),a=0,l=h,f=0,o.push(p.join(","))}return{version:3,file:t,sourceRoot:"",sources:[i],sourcesContent:[r],mappings:o.join(";")}}function
|
|
247
|
-
${
|
|
248
|
-
`}var
|
|
246
|
+
`).length;for(let d=0;d<n.length;d++){if(n[d].trim()===""){o.push("");continue}a=0;let h=Math.min(d,u-1),p=[],m=0-a,g=0,C=h-l,b=0-f;p.push(s(m)+s(g)+s(C)+s(b)),a=0,l=h,f=0,o.push(p.join(","))}return{version:3,file:t,sourceRoot:"",sources:[i],sourcesContent:[r],mappings:o.join(";")}}function cd(e,t){return`${e}
|
|
247
|
+
${qa()}${t}
|
|
248
|
+
`}var Ja=ye(()=>{gr();td();nd();Xs()});import{chmod as Jy,lstat as Qa,mkdir as No,readdir as Yy,realpath as Xy,rename as Ya,rm as fd,rmdir as Zy,stat as ud,writeFile as Qy}from"fs/promises";import{basename as e1,dirname as Kr,isAbsolute as hd,parse as t1,relative as dd,resolve as mt}from"path";function Ci(e,t){return e instanceof Error&&"code"in e&&e.code===t}async function wi(e){try{return await Qa(e)}catch(t){if(Ci(t,"ENOENT"))return;throw t}}async function ur(e){let t=mt(e);try{return await Xy(t)}catch(i){if(!Ci(i,"ENOENT")||Kr(t)===t)throw i;return mt(await ur(Kr(t)),e1(t))}}async function tl(e){let t=mt(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(hd(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");if(!Yt(mt(t,e.bundleOutput),t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===t1(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[i,r]=await Promise.all([ur(t),ur(mt(e.cwd,e.root))]);if(Yt(r,i))throw Error("Refusing to clean an outdir that contains the source root")}function pd(e){return[".d.ts",".d.mts",".d.cts",".d.ts.map",".d.mts.map",".d.cts.map"].some((t)=>e.endsWith(t))}function Xa(e,t){return e.dev===t.dev&&e.ino===t.ino}async function el(e,t){try{if(!(await ud(e)).isDirectory())throw Error(`Declaration output parent is not a directory: ${e}`);return}catch(r){if(!Ci(r,"ENOENT"))throw r}let i=Kr(e);if(i===e)throw Error(`Cannot create declaration output directory: ${e}`);await el(i,t);try{await No(e),t.push(e)}catch(r){if(!Ci(r,"EEXIST")||!(await ud(e)).isDirectory())throw r}}async function md(e,t,i){for(let r of(await Yy(e,{withFileTypes:!0})).sort((n,o)=>n.name.localeCompare(o.name))){let n=mt(e,r.name);if(n===t)continue;if(r.isDirectory())await md(n,t,i);else if(pd(r.name)){let o=await wi(n);if(!o)throw Error(`Declaration output changed during inventory: ${n}`);i.set(n,o)}}}function Za(e,t,i,r,n){return Object.assign(AggregateError(t,e),{code:"DTSX_PUBLICATION_FAILED",phase:i,recoveryDirectory:r,outputsCommitted:n})}async function gd(e,t){if(e.dryRun||t.size===0&&!e.clean)return;await tl(e);let i=mt(e.cwd,e.outdir);if(t.size===0&&!await wi(i))return;let r=mt(i,".dtsx-publication"),n=new Map;for(let[m,g]of t){let C=mt(m);if(!hd(m)||C===i||!Yt(C,i)||Yt(C,r)||!pd(C))throw Error(`Invalid declaration publication target: ${m}`);if(n.has(C))throw Error(`Duplicate declaration publication target: ${m}`);n.set(C,g)}let o=[],s=[],a=[],l=!1,f,u,d=!1;async function h(m,g){let C=await ur(Kr(m));if(!Yt(C,g))throw Error(`Declaration publication parent escapes outdir: ${m}`);if(Yt(C,mt(g,".dtsx-publication")))throw Error(`Declaration publication target overlaps its transaction directory: ${m}`)}async function p(){if(!l)return;if(!f)throw Error(`Cannot verify declaration publication ownership: ${r}`);let m=await wi(r);if(!m||!Xa(m,f))throw Error(`Declaration publication ownership changed: ${r}`);if(u&&await ur(r)!==mt(u,".dtsx-publication"))throw Error(`Declaration publication location changed: ${r}`);await fd(r,{recursive:!0})}try{await el(i,o);try{await No(r)}catch(C){if(Ci(C,"EEXIST"))throw Error(`Declaration publication is active or requires recovery at ${r}`,{cause:C});throw C}l=!0,f=await Qa(r),u=await ur(i);let m=new Map;if(e.clean)await md(i,r,m);for(let C of n.keys()){await h(C,u);let b=await wi(C);if(b&&!b.isFile())throw Error(`Declaration publication target is not a regular file: ${C}`);if(b)m.set(C,b)}for(let C of m.keys())await h(C,u);await No(mt(r,"staged")),await No(mt(r,"backups"));let g=new Map;for(let C of new Set([...m.keys(),...n.keys()])){let b=g.size.toString();g.set(C,{path:C,existing:m.get(C),backup:mt(r,"backups",b),staged:n.has(C)?mt(r,"staged",b):void 0})}await Qy(mt(r,"manifest.json"),JSON.stringify({version:1,outdir:i,targets:[...g.values()].map((C)=>({path:dd(i,C.path),backup:dd(r,C.backup),hadPrevious:!!C.existing}))}));for(let[C,b]of n){let c=g.get(C),A=c.staged;if(await Io(A,b.content,b.lineEnding),!e.clean&&c.existing)await Jy(A,c.existing.mode&511);c.stagedIdentity=await Qa(A)}for(let C of g.values()){if(!C.existing)continue;await h(C.path,u);let b=await wi(C.path);if(!b||!Xa(b,C.existing))throw Error(`Declaration output changed before commit: ${C.path}`);await Ya(C.path,C.backup),s.push(C)}for(let C of g.values()){if(!C.staged||!C.stagedIdentity)continue;if(await h(C.path,u),await el(Kr(C.path),o),await h(C.path,u),await wi(C.path))throw Error(`Declaration output appeared during commit: ${C.path}`);await Ya(C.staged,C.path),a.push({path:C.path,identity:C.stagedIdentity})}d=!0;try{await p()}catch(C){throw Za(`Declaration outputs committed, but transaction cleanup failed at ${r}`,[C],"finalize",r,!0)}}catch(m){if(d)throw m;let g=[];for(let b of a.toReversed())try{if(u)await h(b.path,u);let c=await wi(b.path);if(!c)continue;if(!Xa(c,b.identity))throw Error(`Installed declaration changed before rollback: ${b.path}`);await fd(b.path)}catch(c){g.push(c)}for(let b of s.toReversed())try{if(u)await h(b.path,u);if(await wi(b.path))throw Error(`Cannot restore declaration over an existing path: ${b.path}`);await Ya(b.backup,b.path)}catch(c){g.push(c)}if(g.length>0)throw Za(`Declaration rollback failed; recovery data retained at ${r}`,[m,...g],"rollback",r,!1);let C=[];try{await p()}catch(b){C.push(b)}for(let b of o.toReversed())try{await Zy(b)}catch(c){if(!Ci(c,"ENOENT")&&!Ci(c,"ENOTEMPTY")&&!Ci(c,"EEXIST"))C.push(c)}if(C.length>0)throw Za(`Prior declarations retained, but publication cleanup failed at ${r}`,[m,...C],"cleanup",l?r:void 0,!1);throw m}}var yd=ye(()=>{Ha();Ja()});function wd(e,t,i){let r={file:t,message:"Unknown error",code:Hr.UNKNOWN_ERROR};if(e instanceof Error){r.message=e.message,r.stack=e.stack;let n=e.message.match(/\((\d+),(\d+)\)/);if(n)r.location={line:Number.parseInt(n[1],10),column:Number.parseInt(n[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))r.code=Hr.FILE_NOT_FOUND,r.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))r.code=Hr.SYNTAX_ERROR,r.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))r.code=Hr.TYPE_INFERENCE_ERROR,r.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))r.code=Hr.PARSE_ERROR,r.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")r.message=e;return r}function Cd(e,t){let i=[],r=e.file;if(e.location)r+=`:${e.location.line}:${e.location.column}`;if(e.code)r+=` [${e.code}]`;if(i.push(r),i.push(` Error: ${e.message}`),t&&e.location){i.push("");let n=t.split(`
|
|
249
249
|
`),o=e.location.line-1;if(o>=0&&o<n.length){let s=Math.max(0,o-1),a=Math.min(n.length-1,o+1);for(let l=s;l<=a;l++){let f=(l+1).toString().padStart(4," "),u=l===o?">":" ";if(i.push(` ${u} ${f} | ${n[l]}`),l===o&&e.location.column>0){let d=" ".repeat(10+e.location.column-1);i.push(` ${d}^`)}}}}if(e.suggestion)i.push(""),i.push(` Suggestion: ${e.suggestion}`);return i.join(`
|
|
250
|
-
`)}var Hr;var
|
|
250
|
+
`)}var Hr;var vd=ye(()=>{Hr={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"}});async function i1(){if(Fo!==null)return Fo;try{return vi=await import("prettier"),Fo=!0,!0}catch{return Fo=!1,!1}}async function r1(e,t){if(!vi)return null;try{if(t&&vi.resolveConfig){let i=await vi.resolveConfig(t);if(i)return i}if(e&&vi.resolveConfig){let i=await vi.resolveConfig(e);if(i)return i}return null}catch{return null}}async function n1(e,t){if(!vi)throw Error("Prettier is not available");let i={...t,parser:t.parser||"typescript"};return vi.format(e,i)}function o1(e,t={}){let{indentSize:i=2,useTabs:r=!1,maxLineWidth:n=100,trailingNewline:o=!0,normalizeWhitespace:s=!0,sortImports:a=!0,groupImports:l=!0}=t,f=e,u=r?"\t":" ".repeat(i);if(f.indexOf(`\r
|
|
251
251
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
252
252
|
`);if(s){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
253
253
|
|
|
254
254
|
|
|
255
255
|
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
256
256
|
|
|
257
|
-
`);f=
|
|
257
|
+
`);f=s1(f,u)}if(a||l)f=a1(f,{sort:a,group:l});if(n>0)f=c1(f,n,u);if(o&&!f.endsWith(`
|
|
258
258
|
`))f+=`
|
|
259
|
-
`;return f}function
|
|
259
|
+
`;return f}function s1(e,t){let i=e.split(`
|
|
260
260
|
`),r=[];for(let n of i){let o=n.match(/^(\s*)(.*)$/);if(!o){r.push(n);continue}let[,s,a]=o;if(!a){r.push("");continue}let l=s.replace(/\t/g," ").length,f=Math.floor(l/2);r.push(t.repeat(f)+a)}return r.join(`
|
|
261
|
-
`)}function
|
|
262
|
-
`),r=[],n=[],o=!1,s=0;for(let l=0;l<i.length;l++){let f=i[l],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=l;let d=u[1];r.push({line:f,source:u[2],isType:d.startsWith("import type ")||d.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!1;n.push(f)}}if(r.length===0)return e;if(t.sort)r.sort((l,f)=>{if(l.isType!==f.isType)return l.isType?1:-1;return
|
|
263
|
-
`)}function
|
|
264
|
-
`),n=[];for(let o of r){if(o.length<=t){n.push(o);continue}if(o.trimStart().startsWith("import ")){n.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",a=s+i,l=
|
|
265
|
-
`)}function
|
|
261
|
+
`)}function a1(e,t){let i=e.split(`
|
|
262
|
+
`),r=[],n=[],o=!1,s=0;for(let l=0;l<i.length;l++){let f=i[l],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){o=!0,s=l;let d=u[1];r.push({line:f,source:u[2],isType:d.startsWith("import type ")||d.startsWith("import type\t")})}else if(o&&f.trim()==="")continue;else{if(o)o=!1;n.push(f)}}if(r.length===0)return e;if(t.sort)r.sort((l,f)=>{if(l.isType!==f.isType)return l.isType?1:-1;return l1(l.source,f.source)});let a;if(t.group){let l=[],f=[],u=[],d=[],h=[];for(let p=0;p<r.length;p++){let m=r[p],g=m.source;if(g.charCodeAt(0)===46)h.push(m);else if(g.startsWith("node:"))l.push(m);else if(g.charCodeAt(0)===64)d.push(m);else if(g.includes("/"))u.push(m);else f.push(m)}a=[...l.map((p)=>p.line),...l.length>0&&f.length>0?[""]:[],...f.map((p)=>p.line),...(l.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((p)=>p.line),...d.length>0&&(l.length>0||f.length>0||u.length>0)?[""]:[],...d.map((p)=>p.line),...h.length>0?[""]:[],...h.map((p)=>p.line)]}else a=r.map((l)=>l.line);return[...a,"",...n].join(`
|
|
263
|
+
`)}function l1(e,t){let i=e.startsWith("node:"),r=t.startsWith("node:");if(i!==r)return i?-1:1;let n=e.startsWith("."),o=t.startsWith(".");if(n!==o)return n?1:-1;return e.localeCompare(t)}function c1(e,t,i){let r=e.split(`
|
|
264
|
+
`),n=[];for(let o of r){if(o.length<=t){n.push(o);continue}if(o.trimStart().startsWith("import ")){n.push(o);continue}let s=o.match(/^(\s*)/)?.[1]||"",a=s+i,l=u1(o,s,a);if(l){n.push(...l);continue}if(o.includes("{")&&o.includes("}")){let f=d1(o,t,s,a);n.push(...f);continue}if(o.includes(" | ")){let f=h1(o,t,s,a);n.push(...f);continue}n.push(o)}return n.join(`
|
|
265
|
+
`)}function u1(e,t,i){let r=e.match(f1);if(!r)return null;let[,n,o,s,a]=r,l=s.split(",").map((d)=>d.trim()).filter(Boolean);if(l.length<=1)return[e];let f=`${t}${n}${o??""} {`,u=a?`${t}} ${a};`:`${t}};`;return[f,...l.map((d)=>`${i}${d},`),u]}function d1(e,t,i,r){let n=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!n)return[e];let[,,o,s,a,l]=n,f=a.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${i}${o}${s}`,...f.map((u)=>`${r}${u.trim()};`),`${i}${l.trim()}`]}function h1(e,t,i,r){let n=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!n)return[e];let[,,o,s]=n,a=s.split(/\s*\|\s*/).filter((l)=>l.trim());if(a.length<=2)return[e];return[`${i}${o}`,...a.map((l,f)=>`${r}${f>0?"| ":" "}${l.trim()}`)]}async function bd(e,t={},i){let r=[];if(t.usePrettier!==!1){if(await i1())try{let n={...await r1(t.prettierConfigPath,i),...t.prettierOptions,parser:"typescript"};return{content:await n1(e,n),usedPrettier:!0}}catch(n){r.push(`Prettier formatting failed: ${n}. Using built-in formatter.`)}else if(t.usePrettier===!0)r.push("Prettier requested but not available. Using built-in formatter.")}return{content:o1(e,t.builtIn),usedPrettier:!1,warnings:r.length>0?r:void 0}}var Fo=null,vi=null,f1;var $d=ye(()=>{f1=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});function xd(e,t){let i=new Set;for(let r of Rr(e,"imports.ts",!1)){if(r.kind!=="import")continue;let n=Ri(r.text),o=n&&t.get(n.source);if(!n||n.isTypeOnly||!o)continue;let s=Wo(o);for(let a of n.namedItems)if(!a.isTypeOnly&&s.some((l)=>l.name===a.originalName))i.add(a.name);if(n.defaultName&&s.some((a)=>a.isDefault))i.add(n.defaultName)}return i}function Wo(e){let t=Rr(e,"dependency.ts",!1).filter((i)=>i.kind==="function");return t.filter((i)=>i.isExported&&!i.generics&&t.filter((r)=>r.name===i.name).length===1&&vn(e,i.name)===1).map((i)=>({name:i.name,isDefault:Boolean(i.isDefault)})).sort((i,r)=>i.name.localeCompare(r.name))}var Sd=ye(()=>{vs();Gn();Pi()});import Td from"process";import{existsSync as p1}from"fs";import{arch as m1,platform as Ed}from"os";import{fileURLToPath as g1}from"url";function Lo(e,t="engine"){if(e===void 0||e===null||e==="")return;if(typeof e==="string"&&y1.includes(e))return e;throw Error(`Invalid ${t} ${JSON.stringify(e)}: expected "native" or "typescript"`)}function C1(e){return Lo(e)??w1??Lo(Td.env.DTSX_ENGINE,"DTSX_ENGINE")??"native"}function Ad(){return`${Ed()==="win32"?"windows":Ed()}-${m1()}`}function v1(e){let t=[],i=Td.env.DTSX_NATIVE_LIBRARY;if(i)t.push(i);for(let r of[`../native/${Ad()}/${e}`,`../../native/${Ad()}/${e}`,`../../zig-dtsx/zig-out/lib/${e}`,`../../zig-dtsx/zig-out/bin/${e}`])try{t.push(g1(new URL(r,import.meta.url)))}catch{}return t}function b1(){if(typeof globalThis.Bun>"u")return null;let e;try{e=import.meta.require("bun:ffi")}catch{return null}let{dlopen:t,FFIType:i,ptr:r,suffix:n,toArrayBuffer:o}=e,s=n==="dll"?`zig-dtsx.${n}`:`libzig-dtsx.${n}`;for(let a of v1(s)){if(!p1(a))continue;try{let l=t(a,{process_source_checked_v1:{args:[i.ptr,i.u64,i.bool,i.bool,i.ptr,i.ptr],returns:i.ptr},process_source_with_context_v1:{args:[i.ptr,i.u64,i.bool,i.bool,i.ptr,i.u64,i.ptr,i.ptr],returns:i.ptr},free_result:{args:[i.ptr,i.u64],returns:i.void}}),{symbols:f}=l,u=new TextDecoder;return{checked:(d,h,p,m,g,C)=>f.process_source_checked_v1(r(d),h,p,m,r(g),r(C)),contextual:(d,h,p,m,g,C,b,c)=>f.process_source_with_context_v1(r(d),h,p,m,r(g),C,r(b),r(c)),read:(d,h)=>{if(!d)return"";let p=h?u.decode(o(d,0,h)):"";return f.free_result(d,h),p}}}catch{continue}}return null}function $1(){if(il===void 0)il=b1();return il}function Od(e,t){if(C1(t.engine)==="typescript")return null;let i=$1();if(!i)return null;if(e.length*3>dr.length)dr=new Uint8Array(e.length*3);let{written:r}=kd.encodeInto(e,dr),n=t.sourceFile!==void 0||(t.inferenceSources?.size??0)>0||(t.augmentationImports?.size??0)>0,o;if(n){let a=t.sourceFile??"source.ts",l=kd.encode(JSON.stringify({version:1,moduleSpecifierMode:"preserve",sourceFile:a,outputFile:a.replace(/\.(?:[cm]?[jt]sx?|vue|stx)$/,".d.ts"),sourceHash:new Bun.CryptoHasher("sha256").update(dr.subarray(0,r)).digest("hex"),rewrites:[],augmentationImports:[...t.augmentationImports??[]],inferenceSources:[...t.inferenceSources??[]].map(([f,u])=>({specifier:f,source:u}))}));o=i.contextual(dr,r,t.keepComments,t.isolatedDeclarations,l,l.length,rl,nl)}else o=i.checked(dr,r,t.keepComments,t.isolatedDeclarations,rl,nl);let s=Number(rl[0]);if(nl[0]!==0)return i.read(o,s),null;return i.read(o,s)}var y1,w1,il,kd,dr,rl,nl;var Rd=ye(()=>{y1=["native","typescript"];kd=new TextEncoder,dr=new Uint8Array(65536),rl=new BigUint64Array(1),nl=new Uint32Array(1)});function Dd(e,t={}){let{lineEnding:i="lf",trailingNewline:r=!0,maxBlankLines:n=1,trimTrailingWhitespace:o=!0,normalizeIndentation:s=!0,indent:a={style:"spaces",size:2},declarationOrder:l,importGrouping:f,preserveComments:u=!0,insertFinalNewline:d=!0}=t,h=e;if(h=E1(h,i),f?.enabled!==!1)h=R1(h,f||{});if(l)h=P1(h,l);if(o)h=A1(h);if(h=k1(h,n),s)h=O1(h,a);if(r||d)h=T1(h);return h}function E1(e,t){let i=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
266
266
|
`)!==-1)i=i.replace(/\r\n/g,`
|
|
267
267
|
`);if(i.indexOf("\r")!==-1)i=i.replace(/\r/g,`
|
|
268
268
|
`)}if(t==="crlf")i=i.replace(/\n/g,`\r
|
|
269
|
-
`);return i}function
|
|
269
|
+
`);return i}function A1(e){return e.split(`
|
|
270
270
|
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
271
|
-
`)}function
|
|
272
|
-
`.repeat(t+1))}function
|
|
273
|
-
`}function
|
|
271
|
+
`)}function k1(e,t){let i=new RegExp(`\\n{${t+2},}`,"g");return e.replace(i,`
|
|
272
|
+
`.repeat(t+1))}function T1(e){return`${e.replace(/\s+$/,"")}
|
|
273
|
+
`}function O1(e,t){let{style:i="spaces",size:r=2}=t,n=i==="tabs"?"\t":" ".repeat(r),o=e.split(`
|
|
274
274
|
`),s=[];for(let a of o){let l=a.match(/^([\t ]*)(.*)$/);if(!l){s.push(a);continue}let[,f,u]=l;if(!u){s.push("");continue}let d=f.replace(/\t/g," "),h=Math.floor(d.length/2);s.push(n.repeat(h)+u)}return s.join(`
|
|
275
|
-
`)}function
|
|
276
|
-
`),s=[],a=[],l=-1;for(let m=0;m<o.length;m++){let g=o[m],C=
|
|
277
|
-
`)}function
|
|
278
|
-
`),s=[],a=[],l=[],f=null,u=0,d=!0,h=!1,p=[];for(let C=0;C<o.length;C++){let b=o[C],c=b.trim(),A=u,M=c.startsWith("///"),S=A===0&&!M&&(c.startsWith("//")||c.startsWith("/*"));if(h||S){if(p.push(b),!h&&c.startsWith("/*")&&!c.includes("*/"))h=!0;else if(h&&c.includes("*/"))h=!1;continue}if(A===0&&p.length>0&&c===""){p.push(b);continue}u+=(b.match(/\{/g)||[]).length,u-=(b.match(/\}/g)||[]).length;let
|
|
279
|
-
`)}function
|
|
280
|
-
`){let n=i,o=r;while(n<o&&(e[n]===" "||e[n]==="\t"||e[n]==="\r"))n++;while(o>n&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(n,o);if(i=r+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(
|
|
281
|
-
`;n+=
|
|
275
|
+
`)}function R1(e,t){let{groups:i=S1,separateGroups:r=!0,alphabetize:n=!0}=t,o=e.split(`
|
|
276
|
+
`),s=[],a=[],l=-1;for(let m=0;m<o.length;m++){let g=o[m],C=Pd(g);if(C)s.push({line:g,source:C.source,group:C.group,isType:C.isType}),l=m;else if(s.length>0&&g.trim()==="")continue;else if(s.length>0||g.trim()!==""){if(s.length===0||m>l+1)a.push(g)}}if(s.length===0)return e;let f=new Map;for(let m of i)f.set(m,[]);for(let m of s)(f.get(m.group)||f.get("external")||[]).push(m);if(n)for(let[,m]of f)m.sort((g,C)=>{if(g.isType!==C.isType)return g.isType?1:-1;return g.source.localeCompare(C.source)});let u=[],d=null;for(let m of i){let g=f.get(m)||[];if(g.length===0)continue;if(r&&d!==null)u.push("");for(let C of g)u.push(C.line);d=m}let h=o.slice(0,o.findIndex((m)=>Pd(m)!==null)),p=a;while(p.length>0&&p[0].trim()==="")p.shift();return[...h,...u,"",...p].join(`
|
|
277
|
+
`)}function Pd(e){let t=e.trim(),i=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!i){let o=t.match(/^import\s+['"]([^'"]+)['"]/);if(o)return{source:o[1],group:Md(o[1]),isType:!1};return null}let r=!!i[1],n=i[2];return{source:n,group:r?"type":Md(n),isType:r}}function Md(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 P1(e,t){let{kinds:i=x1,alphabetize:r=!1,groupExports:n=!0}=t,o=e.split(`
|
|
278
|
+
`),s=[],a=[],l=[],f=null,u=0,d=!0,h=!1,p=[];for(let C=0;C<o.length;C++){let b=o[C],c=b.trim(),A=u,M=c.startsWith("///"),S=A===0&&!M&&(c.startsWith("//")||c.startsWith("/*"));if(h||S){if(p.push(b),!h&&c.startsWith("/*")&&!c.includes("*/"))h=!0;else if(h&&c.includes("*/"))h=!1;continue}if(A===0&&p.length>0&&c===""){p.push(b);continue}u+=(b.match(/\{/g)||[]).length,u-=(b.match(/\}/g)||[]).length;let T=M1(c);if(d&&T&&T.kind!=="import"&&!c.startsWith("//")&&!c.startsWith("/*"))d=!1;if(d){if(p.length>0){if(T?.kind==="import"||!T)a.push(...p),p.length=0}a.push(b);continue}if(T&&u<=1){if(f)s.push(f);f={lines:p.length>0?[...p,b]:[b],kind:T.kind,name:T.name,isExport:T.isExport},p.length=0}else if(f)f.lines.push(b);else{if(c==="")continue;l.push(b)}}if(f)s.push(f);if(p.length>0)l.push(...p);s.sort((C,b)=>{if(n&&C.isExport!==b.isExport)return C.isExport?-1:1;let c=i.indexOf(C.kind),A=i.indexOf(b.kind),M=c>=0?c:i.length,S=A>=0?A:i.length;if(M!==S)return M-S;if(r)return C.name.localeCompare(b.name);return 0});let m=[...a],g=null;for(let C of s){if(g!==null&&C.kind!==g)m.push("");m.push(...C.lines),g=C.kind}if(l.length>0)m.push(""),m.push(...l);return m.join(`
|
|
279
|
+
`)}function M1(e){let t=e.startsWith("export "),i=t?e.slice(7):e;if(e.startsWith("import "))return{kind:"import",name:e.match(/from\s+['"]([^'"]+)['"]/)?.[1]||"",isExport:!1};if(i.startsWith("type ")||i.startsWith("declare type "))return{kind:"type",name:i.match(/type\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("interface ")||i.startsWith("declare interface "))return{kind:"interface",name:i.match(/interface\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("class ")||i.startsWith("abstract class ")||i.startsWith("declare class ")||i.startsWith("declare abstract class "))return{kind:"class",name:i.match(/class\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("enum ")||i.startsWith("const enum ")||i.startsWith("declare enum ")||i.startsWith("declare const enum "))return{kind:"enum",name:i.match(/enum\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("function ")||i.startsWith("async function ")||i.startsWith("declare function ")||i.startsWith("declare async function "))return{kind:"function",name:i.match(/function\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("const ")||i.startsWith("let ")||i.startsWith("var ")||i.startsWith("declare const ")||i.startsWith("declare let ")||i.startsWith("declare var "))return{kind:"variable",name:i.match(/(?:const|let|var)\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("namespace ")||i.startsWith("declare namespace "))return{kind:"namespace",name:i.match(/namespace\s+(\w+)/)?.[1]||"",isExport:t};if(i.startsWith("module ")||i.startsWith("declare module "))return{kind:"module",name:i.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 x1,S1;var Id=ye(()=>{x1=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],S1=["builtin","external","scoped","internal","parent","sibling","index","type"]});class Bo{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)}hasDeclarationHooks(){return this.plugins.some((e)=>e.onDeclarations!==void 0)}unregister(e){let t=this.plugins.findIndex((i)=>i.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 i of this.plugins)if(i.onStart){let r=await i.onStart(t);if(r)t=r}return this.config=t,t}async runOnBeforeFile(e,t){let i=t;for(let r of this.plugins)if(r.onBeforeFile){let n={filePath:e,sourceCode:t,content:i,config:this.config,log:this.createLogger(r.name)},o=await r.onBeforeFile(n);if(typeof o==="string")i=o}return i}async runOnDeclarations(e,t,i){let r=i;for(let n of this.plugins)if(n.onDeclarations){let o={filePath:e,sourceCode:t,declarations:r,config:this.config,log:this.createLogger(n.name)},s=await n.onDeclarations(o);if(s)r=s}return r}async runOnAfterFile(e,t,i){let r=i;for(let n of this.plugins)if(n.onAfterFile){let o={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(n.name)},s=await n.onAfterFile(o);if(typeof s==="string")r=s}return r}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,i){for(let r of this.plugins)if(r.onError){let n={filePath:t,sourceCode:i,config:this.config,log:this.createLogger(r.name)};await r.onError(e,n)}}}function D1(e){return e}var s$,a$;var Nd=ye(()=>{s$=new Bo;a$=D1({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((i)=>i.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})})});function Fd(e){let t=[],i=0;for(let r=0;r<=e.length;r++)if(r===e.length||e[r]===`
|
|
280
|
+
`){let n=i,o=r;while(n<o&&(e[n]===" "||e[n]==="\t"||e[n]==="\r"))n++;while(o>n&&(e[o-1]===" "||e[o-1]==="\t"||e[o-1]==="\r"))o--;let s=e.slice(n,o);if(i=r+1,s.startsWith("///")){if(s.indexOf("<")===-1)continue;if(I1.test(s)||N1.test(s)||F1.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}var I1,N1,F1;var Wd=ye(()=>{I1=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,N1=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,F1=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/});function Ld(e,t){throw Error(t||`Unexpected value: ${e}`)}function Gd(e,t,i=!0,r=["bun"]){let n="",o=t.sourceCode;if(o){let S=0;while(S<o.length&&(o.charCodeAt(S)===32||o.charCodeAt(S)===9||o.charCodeAt(S)===10||o.charCodeAt(S)===13))S++;if(S<o.length-2&&o.charCodeAt(S)===47&&o.charCodeAt(S+1)===47&&o.charCodeAt(S+2)===47){let T=Fd(o);if(T.length>0)for(let N=0;N<T.length;N++){if(n)n+=`
|
|
281
|
+
`;n+=T[N]}}}let s=[],a=[],l=[],f=[],u=[],d=[],h=[],p=[],m=[];for(let S of e){let T=S.kind;switch(T){case"import":s.push(S);break;case"function":a.push(S);break;case"variable":l.push(S);break;case"interface":f.push(S);break;case"type":u.push(S);break;case"class":d.push(S);break;case"enum":h.push(S);break;case"module":p.push(S);break;case"export":m.push(S);break;case"namespace":p.push(S);break;case"unknown":break;default:Ld(T,`Unhandled declaration kind: ${T}`)}}let g=[],C=[],b=[],c=new Set;for(let S of m){let T=Kt(S.leadingComments,i);if(S.text.startsWith("export default")){let N=S.text.endsWith(";")?S.text:`${S.text};`;b.push(T+N)}else{let N=S.text.trim();if(!N.endsWith(";"))N+=";";let B=T+N;if(!c.has(B))if(c.add(B),B.includes("export type"))g.push(B);else C.push(B)}}let A=[];if(s.length>0){let{usedItems:S}=Un(e);for(let N of s){if(N.isSideEffect){let pe=N.text.trim(),D=pe.endsWith(";")?pe:`${pe};`;A.push(D);continue}let B=Ri(N.text);if(!B)continue;let{defaultName:ee,namedItems:K,isTypeOnly:te,namespaceName:he}=B,Ae=ee?S.has(ee):!1,Se=he?S.has(he):!1;if(B.isImportEquals){if(Ae){let pe=N.text.trim();A.push(pe.endsWith(";")?pe:`${pe};`)}else if(t.augmentationImports?.has(B.source)){let pe=Bn(N.text);if(!pe)throw Error("Cannot locate an augmentation import module literal");A.push(`import ${pe};`)}continue}let fe="",re=0;for(let pe=0;pe<K.length;pe++){let D=K[pe];if(S.has(D.name)){if(re>0)fe+=", ";if(!te&&D.isTypeOnly)fe+="type ";fe+=D.originalName===D.name?D.name:`${D.originalName} as ${D.name}`,re++}}if(Ae||Se||re>0){let pe=te?"import type ":"import ";if(Se&&he){if(Ae&&ee)pe+=`${ee}, `;pe+=`* as ${he}`}else if(Ae&&ee)pe+=re>0?`${ee}, { ${fe} }`:ee;else if(re>0)pe+=`{ ${fe} }`;let D=Bn(N.text);if(!D)throw Error("Cannot locate a grammatical module literal in the import declaration");pe+=` from ${D};`,A.push(pe)}else if(t.augmentationImports?.has(B.source)){let pe=Bn(N.text);if(!pe)throw Error("Cannot locate an augmentation import module literal");A.push(`import ${pe};`)}}let T=r.length;if(A.length>1){if(Bd!==r)Bd=r,_d=r.map((K)=>`from '${K}`),jd=r.map((K)=>`from "${K}`);let N=_d,B=jd,ee=new Map;for(let K of A){let te=T;for(let he=0;he<r.length;he++)if(K.includes(N[he])||K.includes(B[he])){te=he;break}ee.set(K,te)}A.sort((K,te)=>{let he=ee.get(K),Ae=ee.get(te);return he!==Ae?he-Ae:K.localeCompare(te)})}}for(let S=0;S<A.length;S++){if(n)n+=`
|
|
282
282
|
`;n+=A[S]}for(let S=0;S<g.length;S++){if(n)n+=`
|
|
283
|
-
`;n+=g[S]}let M=[a,l,f,u,d,h,p];for(let S=0;S<M.length;S++){let
|
|
283
|
+
`;n+=g[S]}let M=[a,l,f,u,d,h,p];for(let S=0;S<M.length;S++){let T=M[S];for(let N=0;N<T.length;N++){let B=T[N],ee="",K=B.kind;switch(K){case"function":ee=Mc(B,i);break;case"variable":ee=Vi(B,i);break;case"interface":ee=Dc(B,i);break;case"type":ee=Ic(B,i);break;case"class":ee=Nc(B,i);break;case"enum":ee=Fc(B,i);break;case"module":case"namespace":ee=Wc(B,i);break;case"import":case"export":case"unknown":break;default:Ld(K,`Unhandled declaration kind in processor: ${K}`)}if(ee){if(n)n+=`
|
|
284
284
|
`;n+=ee}}}for(let S=0;S<C.length;S++){if(n)n+=`
|
|
285
285
|
`;n+=C[S]}for(let S=0;S<b.length;S++){if(n)n+=`
|
|
286
|
-
`;n+=b[S]}if(m.length===0&&_i(t.sourceCode)&&(e.some(
|
|
287
|
-
`:""}export {};`;return n}var
|
|
288
|
-
${
|
|
289
|
-
${X}`);else de.debug(`[no changes] ${B}`)}catch{de.info(`[new file] ${Xt(i.cwd,B)}`)}},K=(D)=>{if(!i.validate)return 0;let qe=
|
|
290
|
-
...`:"")),de.debug("--- End preview ---")};if(o){let D=o.getCachedIfValid(S,i.cwd);if(D){if(i.bundle)p.set(S,D);await ee(D);let qe=K(D);if(i.dryRun)te(D);else{if(i.declarationMap)N=
|
|
291
|
-
`);if(i.failOnUnresolvedReExport)throw Error(N);de.warn(N),de.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(i.bundle&&(s.filesGenerated>0||a>0)&&f.length>0)try{de.debug("Bundling declarations...");let S=f.length===1&&!!i.bundleOutput;for(let
|
|
286
|
+
`;n+=b[S]}if(m.length===0&&_i(t.sourceCode)&&(e.some(Zl)||!Jl(n)))n+=`${n?`
|
|
287
|
+
`:""}export {};`;return n}var Bd=null,_d,jd;var Vd=ye(()=>{$r();Wd();kn();Ln();Pi();Hs();_d=[],jd=[]});function j1(e){switch(e){case"strict":return L1;case"readonly":return B1;case"simplified":return _1;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 zd{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...W1);if(e.presets)for(let t of e.presets)this.rules.push(...j1(t));this.rules.push(...e.rules),this.rules.sort((t,i)=>(i.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let i=this.rules[t],r=typeof i.pattern==="string"?new RegExp(i.pattern.replace(G1,"\\$&"),i.global?"g":""):i.pattern;e[t]={rule:i,regex:r}}this.compiled=e}map(e,t={}){let i=!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":""}`,r=this.cache.get(i);if(r!==void 0)return r;let n=e,o=null;for(let s=0;s<this.compiled.length;s++){let{rule:a,regex:l}=this.compiled[s];if(a.condition){if(!o)o={type:e,...t};if(!a.condition(o))continue}if(l.lastIndex=0,l.test(n)){if(l.lastIndex=0,n=n.replace(l,a.replacement),l.lastIndex=0,!a.global)break}}if(this.cache.size>=Ud){let s=Math.ceil(Ud*0.1),a=0;for(let l of this.cache.keys()){if(a++>=s)break;this.cache.delete(l)}}return this.cache.set(i,n),n}mapAll(e,t={}){return e.map((i)=>this.map(i,{...t,type:i}))}addRule(e){this.rules.push(e),this.rules.sort((t,i)=>(i.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((i)=>{let r=typeof i.pattern==="string"?i.pattern:i.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?r!==e:!e.test(r)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function _o(e={rules:[]}){return new zd(e)}function Kd(e,t,i={}){return e.replace(/:\s*([^;,)\]}]+)/g,(r,n)=>`: ${t.map(n.trim(),i)}`)}var W1,L1,B1,_1,G1,Ud=2048,y$,w$;var Hd=ye(()=>{W1=[{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}],L1=[{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}],B1=[{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}],_1=[{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}];G1=/[.*+?^${}()|[\]\\]/g;y$=_o({rules:[]}),w$=_o({rules:[],presets:["strict"]})});import{availableParallelism as V1}from"os";import{basename as Yd,dirname as U1,relative as Xt,resolve as z1}from"path";function sl(e){let t=ol.get(e);if(!t)t=qn(e),ol.set(e,t),t.catch(()=>ol.delete(e));return t}async function qd(e,t,i,r,n,o=Io){let s=Yd(e)||"output.d.ts",a=Xt(U1(e),t),l=`${s}.map`,f=i.lastIndexOf(`
|
|
288
|
+
${qa()}`),u=f===-1?i:i.slice(0,f),d=ld(u,s,a,r),h=`${e}.map`;return await o(h,JSON.stringify(d)),de.debug(` Generated source map: ${Xt(n,h)}`),l}async function al(e){let t=Date.now(),i={...Uu,...e};if(i.logLevel)qs(i.logLevel);else if(i.verbose)qs("debug");let r=new Bo;if(i.plugins&&i.plugins.length>0){for(let S of i.plugins)r.register(S),de.debug(`Registered plugin: ${S.name}`);i=await r.runOnStart(i)}if(i.moduleSpecifierMode!==void 0&&i.moduleSpecifierMode!=="preserve"&&i.moduleSpecifierMode!=="node")throw Error("moduleSpecifierMode must be preserve or node");if(Lo(i.engine,"engine"),await tl(i),i.isolatedDeclarations===void 0)i.isolatedDeclarations=await od(i);let n=i.typeMappings?_o(i.typeMappings):void 0,o=null,s={generationMode:i.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},a=0;de.debug("Starting DTS generation..."),de.debug(`Using ${s.generationMode} declaration generation path`),de.debug("Config:",i);let l=await Ju(i,()=>sl(i)),f=l.entryFiles,u=[...l.files],{resolver:d,reachability:h}=l;if(Xd.set(i,new Set(u)),i.incremental){let S=l.getResolutionFingerprint();if(!i.isolatedDeclarations){let T=new Set(u),N=new Map;for(let ee of u){let K=await Et(ee);N.set(ee,Wo(K));for(let te of Mi(K,{includeImports:!0})){let he=d(te.specifier,ee).resolved;if(he&&!he.split(/[/\\]/).includes("node_modules")&&!T.has(he))T.add(he),N.set(he,Wo(await Et(he)))}}let B=[...N].sort(([ee],[K])=>ee.localeCompare(K));S=JSON.stringify([S,B])}if(o=new os(i,S),i.clearCache){if(de.debug("Clearing build cache..."),!i.dryRun)o.clear()}else if(o.load()){let T=o.getStats();de.debug(`Loaded build cache with ${T.entries} entries`)}else de.debug("No existing build cache found, starting fresh");if(!i.dryRun)Ol(i.cwd)}if(o&&!i.dryRun){let S=o.prune(new Set(u),i.cwd);if(S>0)de.debug(`Pruned ${S} deleted files from cache`)}if(de.debug(`Found ${u.length} TypeScript files`),i.progress&&u.length>0){let S=i.parallel?"parallel":"sequential";de.info(`Processing ${u.length} files (${S})...`)}let p=new Map,m=new Map,g=async(S,T,N="lf")=>{m.set(S,{content:T,lineEnding:N})},C=async(S,T)=>{let N;try{let B=fr(S,i),ee=async(D)=>{if(!i.diff)return;try{let qe=await Et(B),X=ad(qe,D,Xt(i.cwd,B));if(X)de.info(`
|
|
289
|
+
${X}`);else de.debug(`[no changes] ${B}`)}catch{de.info(`[new file] ${Xt(i.cwd,B)}`)}},K=(D)=>{if(!i.validate)return 0;let qe=sd(D,B);if(qe.isValid)return de.debug(`[validation] ${B} - OK`),0;de.warn(`[validation] ${Xt(i.cwd,B)} has ${qe.errors.length} error(s):`);for(let X of qe.errors){let G=` Line ${X.line}:${X.column}`;if(X.code)G+=` [${X.code}]`;if(G+=` - ${X.message}`,de.warn(G),X.suggestion)de.warn(` Suggestion: ${X.suggestion}`)}return qe.errors.length},te=(D)=>{de.info(`[dry-run] Would generate: ${B}`),de.debug("--- Content preview ---"),de.debug(D.slice(0,500)+(D.length>500?`
|
|
290
|
+
...`:"")),de.debug("--- End preview ---")};if(o){let D=o.getCachedIfValid(S,i.cwd);if(D){if(i.bundle)p.set(S,D);await ee(D);let qe=K(D);if(i.dryRun)te(D);else{if(i.declarationMap)N=T??await Et(S),await qd(B,S,D,N,i.cwd,g);await g(B,D,i.lineEnding)}return de.debug(`[cached] ${Xt(i.cwd,B)}`),{success:!0,file:S,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:qe}}}N=T??await Et(S);let{content:he,declarationCount:Ae,importCount:Se,exportCount:fe}=await H1(S,N,i,r,n,l.augmentationImports.get(S));if(i.bundle)p.set(S,he);let re=he;if(i.prettier||i.indentStyle||i.indentSize){let D=await bd(re,{usePrettier:i.prettier,builtIn:{indentSize:i.indentSize||2,useTabs:i.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},B);re=D.content;for(let qe of D.warnings??[])de.warn(`[format] ${qe}`)}if(i.declarationMap){let D=`${Yd(B)||"output.d.ts"}.map`;re=cd(re,D)}await ee(re);let pe=K(re);if(i.dryRun)te(re);else{if(i.declarationMap&&N)await qd(B,S,re,N,i.cwd,g);if(await g(B,re,i.lineEnding),o&&N)o.update(S,N,re,i.cwd);de.debug(`Generated: ${B}`)}return{success:!0,file:S,declarationCount:Ae,importCount:Se,exportCount:fe,validationErrorCount:pe}}catch(B){let ee=wd(B,S,N);if(i.plugins&&i.plugins.length>0)await r.runOnError(B instanceof Error?B:Error(String(B)),S,N||"");return{success:!1,file:S,declarationCount:0,importCount:0,exportCount:0,dtsError:ee,validationErrorCount:0}}},b=i.parallel||i.parallel!==!1&&u.length>=10,c=Ml(i.concurrency,V1?.()??8),A=new Map;if(b&&u.length>1){let S=u.map(async(T)=>{try{let N=await Et(T);return{file:T,source:N}}catch{return{file:T,source:null}}});for(let T of await Promise.all(S))if(T.source!==null)A.set(T.file,T.source)}let M=(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(i.validate){if(s.filesValidated++,S.validationErrorCount)s.validationErrors+=S.validationErrorCount}}else if(s.filesFailed++,S.dtsError){s.errors.push(S.dtsError);let T=Cd(S.dtsError);if(i.continueOnError)de.warn(T);else throw de.error(T),Error(S.dtsError.message)}};if(b)for(let S=0;S<u.length;S+=c){let T=u.slice(S,S+c),N=await Promise.all(T.map((B)=>C(B,A.get(B))));for(let B of N)M(B);if(i.progress){let B=Math.round(s.filesProcessed/u.length*100);de.info(`[${s.filesProcessed}/${u.length}] ${B}%`)}}else for(let S of u){let T=await C(S);if(M(T),i.progress){let N=Math.round(s.filesProcessed/u.length*100),B=T.cached?"[cached]":"";de.info(`[${s.filesProcessed}/${u.length}] ${N}% - ${Xt(i.cwd,S)} ${B}`)}}if(!i.bundle){let S=[];if(h)for(let T of h.unresolved)S.push({from:T.from,specifier:T.specifier,reason:"missing"});if(i.autoIncludeReExports===!1&&u.length>0){let T=new Set(u);for(let N of u){let B;try{B=await Et(N)}catch{continue}for(let ee of Mi(B)){let K=d(ee.specifier,N);if(!K.isRelative)continue;if(!K.resolved)S.push({from:N,specifier:ee.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(K.resolved)&&!T.has(K.resolved))S.push({from:N,specifier:ee.specifier,reason:"not-emitted"})}}}if(S.length>0){let T=[];T.push(`Found ${S.length} re-export(s) pointing at siblings that won't be in the output:`);for(let B of S){let ee=Xt(i.cwd,B.from);if(B.reason==="missing")T.push(` ${ee} \u2192 '${B.specifier}' (path not found on disk)`);else T.push(` ${ee} \u2192 '${B.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let N=T.join(`
|
|
291
|
+
`);if(i.failOnUnresolvedReExport)throw Error(N);de.warn(N),de.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(i.bundle&&(s.filesGenerated>0||a>0)&&f.length>0)try{de.debug("Bundling declarations...");let S=f.length===1&&!!i.bundleOutput;for(let T of f){let N=await Ir([T],{includeImports:!0,resolveSpecifier:d}),B=new Set;for(let he of N.reachable){if(he.endsWith(".d.ts"))continue;if(he.includes("node_modules"))continue;B.add(he)}let ee=u.filter((he)=>B.has(he));if(!ee.includes(T))ee.push(T);let K=pf(T,ee,p,{cwd:i.cwd,keepComments:i.keepComments});for(let he of new Set(K.warnings))de.warn(`[bundle] ${he}`);let te=S?z1(i.cwd,i.outdir,i.bundleOutput):fr(T,i);if(i.dryRun)de.info(`[dry-run] Would bundle ${K.files.length} files to: ${Xt(i.cwd,te)}`);else await g(te,K.content,i.lineEnding),de.debug(`Prepared ${K.files.length} bundled files for: ${Xt(i.cwd,te)}`);if(S)break}}catch(S){let T=S instanceof Error?S.message:String(S);throw de.error(`Bundle failed: ${T}`),S}if(!i.dryRun)await gd(i,m);if(o&&!i.dryRun)o.save(),de.debug("Saved build cache");if(s.durationMs=Date.now()-t,i.stats)if(i.outputFormat==="json")console.log(JSON.stringify(s,null,2));else{if(de.info(`
|
|
292
292
|
--- Generation Statistics ---`),de.info(`Files processed: ${s.filesProcessed}`),de.info(`Files generated: ${s.filesGenerated}`),a>0)de.info(`Files cached: ${a}`);if(s.filesFailed>0)de.info(`Files failed: ${s.filesFailed}`);if(de.info(`Declarations found: ${s.declarationsFound}`),de.info(`Imports processed: ${s.importsProcessed}`),de.info(`Exports processed: ${s.exportsProcessed}`),s.filesValidated>0){if(de.info(`Files validated: ${s.filesValidated}`),s.validationErrors>0)de.info(`Validation errors: ${s.validationErrors}`)}if(de.info(`Duration: ${s.durationMs}ms`),s.errors.length>0){de.info(`
|
|
293
|
-
Errors:`);for(let S of s.errors){let
|
|
294
|
-
`)}if(i.plugins&&i.plugins.length>0)await r.runOnEnd(s);return de.debug("DTS generation complete!"),s}async function
|
|
295
|
-
`)){if(!n||n.startsWith(" ")||n.startsWith("\t")||n.startsWith("}")||n.startsWith("*")||n.startsWith("/"))continue;if(t++,n.startsWith("import "))i++;else if(n.startsWith("export "))r++}return{declarationCount:t,importCount:i,exportCount:r}}function
|
|
293
|
+
Errors:`);for(let S of s.errors){let T=` - ${S.file}`;if(S.location)T+=`:${S.location.line}:${S.location.column}`;if(S.code)T+=` [${S.code}]`;if(T+=`: ${S.message}`,de.info(T),S.suggestion)de.info(` Suggestion: ${S.suggestion}`)}}de.info(`-----------------------------
|
|
294
|
+
`)}if(i.plugins&&i.plugins.length>0)await r.runOnEnd(s);return de.debug("DTS generation complete!"),s}async function K1(e,t,i){let r=await sl(i),n=Yu(t,i,r,Xd.get(i));return df(e,(o)=>n(o).emittedSpecifier)}async function H1(e,t,i,r,n,o){let s=t;if(r)s=await r.runOnBeforeFile(e,t);let a=new Map;if(!i.isolatedDeclarations){let m=await sl(i);for(let g of Mi(s,{includeImports:!0})){let C=m(g.specifier,e).resolved;if(C&&!C.split(/[/\\]/).includes("node_modules"))a.set(g.specifier,await Et(C))}}let l=r?.hasDeclarationHooks()?null:J1(s,e,i,a,o);if(l!==null)return Jd(l,e,s,i,r,n,q1(l));let f=a.size?xd(s,a):void 0,u=Vn(s,e,i.keepComments,i.isolatedDeclarations??!1,f);if(r)u=await r.runOnDeclarations(e,s,u);let d=0,h=0;for(let m=0;m<u.length;m++){let g=u[m];if(g.kind==="import")d++;if(g.kind==="export"||g.isExported)h++}let p=Gd(u,{filePath:e,sourceCode:s,declarations:u,augmentationImports:o},i.keepComments,i.importOrder);return Jd(p,e,s,i,r,n,{declarationCount:u.length,importCount:d,exportCount:h})}function q1(e){let t=0,i=0,r=0;for(let n of e.split(`
|
|
295
|
+
`)){if(!n||n.startsWith(" ")||n.startsWith("\t")||n.startsWith("}")||n.startsWith("*")||n.startsWith("/"))continue;if(t++,n.startsWith("import "))i++;else if(n.startsWith("export "))r++}return{declarationCount:t,importCount:i,exportCount:r}}function J1(e,t,i,r,n){let o=i.importOrder??["bun"];if(o.length!==1||o[0]!=="bun")return null;let s=cn(t)?dn(e):pn(t)?mn(e):e;return Od(s,{keepComments:i.keepComments??!0,isolatedDeclarations:i.isolatedDeclarations??!1,engine:i.engine,sourceFile:t,inferenceSources:r,augmentationImports:n})}async function Jd(e,t,i,r,n,o,s){let a=await K1(e,t,r);if(o)a=Kd(a,o,{filePath:t});if(r.normalizeOutput===!0||r.declarationOrder)a=Dd(a,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)a=await n.runOnAfterFile(t,i,a);return{content:a,...s}}var ol,Xd;var Zd=ye(()=>{gr();Dl();hn();ms();Ks();Kn();Jn();mf();Rl();zu();Ha();Ja();yd();vd();$d();Sd();Rd();Id();Nd();Vd();Hd();ol=new WeakMap,Xd=new WeakMap});var Qd=ye(()=>{Zd()});import ih from"process";import{dirname as Y1,relative as eh,resolve as jo,sep as Go}from"path";class rh{listeners=new Map;on(e,t){let i=this.listeners.get(e)||[];i.push(t),this.listeners.set(e,i)}async emit(e,t){let i={type:e,timestamp:Date.now(),data:t},r=this.listeners.get(e)||[];for(let n of r)await n(i)}}function nh(e={}){let{onSuccess:t,onError:i,failOnError:r=!0,incremental:n=!1,cacheDir:o=".dtsx-cache",on:s,timeout:a=60000,continueOnError:l=!1,verbose:f=!1,...u}=e,d=new rh;if(s){for(let[h,p]of Object.entries(s))if(p)d.on(h,p)}return{name:"bun-plugin-dtsx",async setup(h){let p=Date.now();try{let m=Q1({...u,incremental:n,cacheDir:o},h);if(m.clean){let A=jo(m.cwd??ih.cwd(),m.outdir??"./dist");if(th.has(A))m.clean=!1;else th.add(A)}if(await d.emit("start",{type:"start",files:m.entrypoints||[],config:m}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),n)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let C=await(async()=>new Promise((A,M)=>{let S=setTimeout(()=>{M(new qr(`Generation timed out after ${a}ms`,"TIMEOUT_ERROR",{timeout:a}))},a);al(m).then((T)=>{clearTimeout(S),A(T)}).catch((T)=>{clearTimeout(S),M(T)})}))(),b=Date.now()-p,c=Math.max(0,C.filesProcessed-C.filesGenerated-C.filesFailed);if(await d.emit("complete",{type:"complete",stats:C,duration:b,fromCache:c}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${b}ms`),c>0)console.log(`[bun-plugin-dtsx] ${c} files served from cache`)}if(t)await t(C)}catch(m){let g=X1(m);if(await d.emit("error",{type:"error",error:g}),i)await i(g);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${g.code}`),console.error(` Message: ${g.message}`),g.context)console.error(` Context: ${JSON.stringify(g.context)}`);if(f&&g.stack)console.error(` Stack: ${g.stack}`)}if(r&&!l)throw g}}}}function X1(e){if(e instanceof qr)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 qr(e.message,t,{originalError:e.name},e)}return new qr(String(e),"GENERATION_ERROR")}function Z1(e){let t=e.map((r)=>Y1(r).split(Go)),i=t[0];for(let r of t.slice(1)){let n=0;while(n<i.length&&n<r.length&&i[n]===r[n])n++;i=i.slice(0,n)}return i.join(Go)||Go}function Q1(e,t){let i=e.cwd||ih.cwd(),r=t?.config?.entrypoints,n=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",o=e.root||e.build?.config.root||t?.config.root;if(!o&&r?.length){let a=Z1(r.map((l)=>jo(i,l)));o=eh(i,a)||"."}o=o||"./src";let s=e.entrypoints;if(!s)if(r?.length){let a=jo(i,o),l=[];for(let f of r){let u=jo(i,f);if(u===a||u.startsWith(a+Go))l.push(eh(a,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${o}": ${f}`)}s=l.length?l:["index.ts"]}else s=["index.ts"];return{...e,cwd:i,root:o,entrypoints:s,outdir:n,clean:e.clean??!0,tsconfigPath:e.tsconfigPath,moduleSpecifierMode:e.moduleSpecifierMode??((t?.config.target??e.build?.config.target)==="node"?"node":"preserve")}}var qr,th;var oh=ye(()=>{Qd();qr=class qr extends Error{code;context;cause;constructor(e,t,i,r){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=i,this.cause=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};th=new Set});import{mkdir as e0,stat as t0}from"fs/promises";import{bold as ll,dim as cl,green as i0,italic as sh,log as r0}from"@stacksjs/cli";import{path as Rt}from"@stacksjs/path";import{glob as ah}from"@stacksjs/storage";function Qo(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 i=new Map,r=new Set,n=(s,a)=>{let l=i.get(s);if(l!==void 0)return l;if(r.has(s))throw Error(`dependency cycle: ${[...a,s].join(" -> ")}`);r.add(s);let f=t.get(s).dependencies.filter((d)=>d!==s&&t.has(d)),u=f.length?1+Math.max(...f.map((d)=>n(d,[...a,s]))):0;return r.delete(s),i.set(s,u),u},o=[];for(let s of[...e].sort((a,l)=>a.name.localeCompare(l.name)))(o[n(s.name,[])]||=[]).push(s);return o.filter(Boolean)}import{existsSync as vh,readdirSync as bh,readFileSync as xl}from"fs";import{join as es}from"path";function $h(e){return[...bh(e,{withFileTypes:!0}).filter((i)=>i.isDirectory()).map((i)=>es(e,i.name)),e].filter((i)=>{let r=es(i,"package.json");if(!vh(r))return!1;let n=JSON.parse(xl(r,"utf8"));return!n.private&&!!n.scripts?.build})}async function xh(e){let t=e.map((n)=>{let o=JSON.parse(xl(es(n,"package.json"),"utf8"));if(!o.name||!o.scripts?.build)throw Error(`Not a buildable workspace package: ${n}`);return{name:o.name,dir:n,dependencies:Object.keys(o.dependencies??{})}}),i=Qo(t),r=[];for(let{name:n,dir:o,dependencies:s}of i.flat()){let a=r.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(", ")}`),r.push({name:n,dir:o,exitCode:null,blockedBy:a});continue}console.log(`Building ${o}`);let l=Bun.spawn([process.execPath,"run","build"],{cwd:o,stdout:"inherit",stderr:"inherit"});r.push({name:n,dir:o,exitCode:await l.exited,blockedBy:[]})}return r}async function n0(e){let t=await ah([Rt.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),i=new Bun.Transpiler({loader:"ts",target:"bun"});for(let r of t){let n=await Bun.file(r).text();try{i.transformSync(n)}catch(o){throw Error(`Invalid declaration generated at ${r}: ${o instanceof Error?o.message:String(o)}`)}}}async function o0(e){let t=Rt.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let i=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(i.exitCode===0)return;let r=new TextDecoder().decode(i.stderr??new Uint8Array),n=/SyntaxError|needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i;if(n.test(r)){let o=r.split(`
|
|
296
296
|
`).find((s)=>n.test(s))??r.trim().split(`
|
|
297
297
|
`)[0];throw Error(`Built package at ${t} cannot be imported: ${o}
|
|
298
|
-
Fix the generated module at its source before publishing.`)}}async function
|
|
299
|
-
`),await
|
|
298
|
+
Fix the generated module at its source before publishing.`)}}async function fx(e){let i=Date.now()-e.startTime,r=e.pkgName??`@stacksjs/${Rt.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(Rt.resolve(e.dir,"dist","tsconfig.json"),`${JSON.stringify({compilerOptions:{paths:{}}},null,2)}
|
|
299
|
+
`),await n0(e.dir),await o0(e.dir);let n=await ah([Rt.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let o of n){let s=await t0(o),a;if(s.size<1048576)a=`${(s.size/1024).toFixed(2)}kb`;else a=`${(s.size/1024/1024).toFixed(2)}mb`;let l=Rt.relative(e.dir,o).replace("dist/","");console.log(`${ll(cl(`[${a}]`))} ${cl("dist/")}${l}`)}console.log(`${ll(cl(`[${i}ms]`))} Built ${sh(ll(i0(r)))}`)}async function ux(e){let t=e.pkgName??`@stacksjs/${Rt.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else r0.info(`Building ${sh(t)}...`);return{startTime:Date.now()}}async function dx(e){await Promise.resolve().then(() => oh());let i=Rt.resolve(e.dir,"src"),r=Rt.resolve(e.dir,"dist"),n=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:i}))).filter((s)=>!s.endsWith(".d.ts")).filter((s)=>!s.endsWith(".test.ts")&&!s.endsWith(".spec.ts")).filter((s)=>!s.split(/[\\/]/).some((a)=>a==="tests"||a==="__tests__"));await Bun.build({entrypoints:n.map((s)=>Rt.resolve(i,s)),outdir:r,root:i,target:"bun",format:"esm",splitting:!1,external:e.external??a0(),plugins:[nh({root:i,outdir:r})]});let o=new Bun.Transpiler({loader:"ts",target:"browser",minifyWhitespace:!0,define:{"process.env.NODE_ENV":"process.env.NODE_ENV"}});for(let s of n){let a=o.transformSync(await Bun.file(Rt.resolve(i,s)).text());a=s0(a);let l=Rt.resolve(r,s.replace(/\.ts$/,".js"));await e0(Rt.dirname(l),{recursive:!0}),await Bun.write(l,a)}}function s0(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function a0(e=[]){let t=[];try{let i=Ch("fs"),r=JSON.parse(i.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(r.dependencies??{}),...Object.keys(r.peerDependencies??{}),...Object.keys(r.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((i)=>`${i}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{xh as buildWorkspacePackages,Qo as dependencyLayers,a0 as frameworkExternal,ux as intro,fx as outro,s0 as rewriteRelativeTsSpecifiers,dx as transpilePackage,n0 as validateDeclarations,o0 as validateRuntimeExports,$h as workspaceBuildTargets};
|