@stacksjs/build 0.75.539 → 0.75.542
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 +201 -197
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,184 +1,188 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
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 yh=import.meta.require;function mr(e){if($h)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 $h;var ts=ye(()=>{$h=typeof globalThis.Bun?.hash==="function"});import{existsSync as rn,mkdirSync as xh,readFileSync as rs,renameSync as Sh,rmdirSync as Eh,rmSync as Sl,statSync as $l,writeFileSync as El}from"fs";import{join as ns,relative as tn,resolve as xl}from"path";function Ah(e){try{Sl(ns(e,Al),{force:!0});try{Eh(e)}catch{}}catch{}}class os{cacheDir;manifestPath;manifest=null;configHash;constructor(e,t){this.cacheDir=xl(e.cwd,e.cacheDir??nn),this.manifestPath=ns(this.cacheDir,Al),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:xl(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))xh(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{El(e,JSON.stringify(this.manifest,null,2)),Sh(e,this.manifestPath)}finally{if(rn(e))Sl(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=$l(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=$l(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,Ah(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 kl(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
|
-
${
|
|
6
|
-
`;
|
|
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
|
|
8
|
-
`&&t[n]!=="\r")t[n]=" ";i=r;continue}i++}return t.join("")}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
|
|
11
|
-
`,o.index)+1,
|
|
5
|
+
${nn}/
|
|
6
|
+
`;El(t,n)}}catch{}}var is=28,nn=".dtsx-cache",Al="manifest.json";var Tl=ye(()=>{ts()});import{readFile as kh,stat as C0,writeFile as Th}from"fs/promises";async function Ol(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 Th(e,i),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function Et(e){if(on)return globalThis.Bun.file(e).text();return kh(e,"utf-8")}var on,v0;var gr=ye(()=>{on=typeof globalThis.Bun<"u",v0=!on&&typeof process<"u"&&!!process.versions?.node});function Rl(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 Pl=()=>{};function cn(e){return e.endsWith(".vue")}function Oh(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
|
+
`,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 Rh(e,t){let i=Dl(e,t);if(!i)return null;return i.kind==="interface"?e.slice(i.bodyStart,i.end):e.slice(i.bodyStart,i.end).trim()}function Dl(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 Ph(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=Ph(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(Ml[t])return{type:Ml[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 Mh(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 Dh(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 Il(e){return Mh(e)??Dh(e)}function Ih(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 Nh(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=Ih(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=Fh(t,i);return t}function Fh(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
|
+
`,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
|
|
14
|
-
`,n.index)+1;if(!i.has(o))continue;if(/\bexport\b/.test(e.slice(o,n.index)))continue;let s=n[1],
|
|
15
|
-
`)
|
|
16
|
-
`)
|
|
17
|
-
`&&u===0){f=
|
|
18
|
-
`)f++;t.push({name:
|
|
19
|
-
`&&i===0)t.add(r+1);r++}return t}function
|
|
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
|
|
21
|
-
`)s++;let
|
|
22
|
-
`){let s=r(),
|
|
23
|
-
${t.scriptSetup.content}`:t.script.content;if(i=C.script,C.options){let b=
|
|
24
|
-
`)}var
|
|
25
|
-
defineProps<${i}>()`,null)}function
|
|
26
|
-
`)&&r===0){let
|
|
27
|
-
`),i=null,r=
|
|
28
|
-
`)}var
|
|
29
|
-
`,i)+1,n=
|
|
30
|
-
`,f+2);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(
|
|
31
|
-
`,
|
|
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=Wh(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 Wh(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=Bh(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(Lh(s,o.name))continue;if(new RegExp(`\\btypeof\\s+${o.name}\\b`).test(t))continue;r=s}return r}function Lh(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 Bh(e){let t=[],i=_h(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
|
+
`,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
|
+
`)l++;while(l<e.length&&/\s/.test(e[l])&&e[l]!==`
|
|
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
|
+
`&&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 _h(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
|
+
`&&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
|
+
`,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
|
+
`)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=jh(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 jh(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=Dl(s,o);if(!a)continue;let l=Rh(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 Nh(n.generic)??n.generic;if(n.arg){let o=Il(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=Oh(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=Il(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 Ml;var hn=ye(()=>{Ml={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 Gh(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 Vh(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 Uh(e){return[...Gh(e),...Vh(e)].sort((t,i)=>t.start-i.start)}function zh(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 Kh(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 Hh(e){return/\b(?:const|let|var)\s+\$?props\s*:\s*([^=;\n]+)/.exec(e)?.[1]?.trim()??null}function qh(e){let t=/^\s*(?:\|\||\?\?)\s*([^;\n]+)/.exec(e)?.[1]?.trim();if(/^['"`]/.test(t??""))return"string";if(/^(?:true|false)\b/.test(t??""))return"boolean";if(/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)\b/.test(t??""))return"number";if(/^\[/.test(t??""))return"unknown[]";if(/^\{/.test(t??""))return"Record<string, unknown>";if(/^\s*(?:===?|!==?)\s*(?:true|false)\b/.test(e))return"boolean";return"unknown"}function Jh(e,t){if(!e||e==="unknown")return t;if(t==="unknown"||e===t)return e;return[...new Set([...e.split(" | "),...t.split(" | ")])].join(" | ")}function Yh(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=qh(e.slice(r.lastIndex));i.set(o,Jh(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 Xh(e){let t=un(e,null);if(t)return t;let i=Kh(e)??Hh(e);if(!i)return Yh(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 Zh(e){return fs(e)}function Nl(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 Qh(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(!Nl(e.slice(i,l)))t.push([i,l]);i=l}n++}if(i<e.length&&!Nl(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=Uh(e).filter(zh).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=Zh(t),s=Xh(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=Qh(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
|
+
`)}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=ep(e,r,i);if(n!==-1){i=n-1;continue}return i}}function ep(e,t,i){let r=0;for(let n=t;n<=i;n++){let o=e.charCodeAt(n);if(r){if(o===92){n++;continue}if(o===r)r=0;continue}if(o===39||o===34||o===96){r=o;continue}if(o===47&&n+1<=i&&e.charCodeAt(n+1)===47)return n}return-1}function Fl(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 Wl(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 tp(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);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!=="."&&Wl(p));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 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||Fl(d))}f++}return!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===41)return tp(e,r);if(Fl(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 Wl(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 ys(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):ys(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=ys(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=ys(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!==Ll)Bl=ue(e),Ll=e;return Bl}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),l=o?e.indexOf("}",s):s+(n==="x"?2:4),a=e.slice(s,l);if(l<s||l>i||!/^[\da-f]+$/i.test(a)||o&&a.length>6)return;let f=Number.parseInt(a,16);if(f>1114111)return;t+=String.fromCodePoint(f),r=o?l:l-1;break}default:if(/\d/.test(n))return;t+=n}}return t}function oi(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 ln(e){let t=ce(e),i=(l)=>t[l]?e.slice(t[l].start,t[l].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=wt(i(n+4));if(s===void 0)return;return{name:i(n),source:s,isTypeOnly:r,end:t[t.length-1].end}}function Rt(e){let t=ce(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",l=[],a=!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)!==".")a=!0;if(p==="declare"&&n(h+1)==="module"&&o(h+2)&&n(h+3)==="{")l.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 c=h+1;c<t.length;c++)if(n(c)==="{")m++;else if(n(c)==="}"&&--m===0)return c+1;else if(t[c].kind==="literal"||n(c)===";")return-1;return-1}function d(h,p,m,c){let C=t[h];if(!C||C.kind!=="quoted"||r.has(C.start))return;let b=wt(e.slice(C.start,C.end));if(b===void 0)return;r.add(C.start),i.push({specifier:b,kind:p,isTypeOnly:m,category:c,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 c=n(m)==="type";if(c)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,c,"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 c=n(m)==="type"&&n(m+1)!=="from"&&n(m+1)!=="="&&n(m+1)!==",";if(c)m++;if(s(m)){if(m++,n(m)==="="){if(n(m+1)==="require"&&n(m+2)==="("&&n(m+4)===")")d(m+3,"import",c,"static-import");continue}if(n(m)===",")m=u(m+1)}else m=u(m);if(m>=0&&n(m)==="from")d(m+1,"import",c,"static-import")}}if(a&&l.length){for(let h of l)d(h,"import",!0,"augmentation");i.sort((h,p)=>h.start-p.start)}return i}var bl,$l;var ht=me(()=>{hr();$l=[]});function cn(e,t){let i=ce(e),r=0,n=0;for(let o=0;o<i.length;o++){let s=i[o],l=e.slice(s.start,s.end),a=i[o+1];if(r===0&&l==="function"&&a?.kind==="word"&&e.slice(a.start,a.end)===t)n++;if(["{","(","["].includes(l))r++;else if(["}",")","]"].includes(l))r--}return n}var is=me(()=>{ht()});function El(e){let t=ce(e),i=(a)=>t[a]?e.slice(t[a].start,t[a].end):"",r=new Map,n=[];for(let a=0;a<t.length;a++)if(["(","[","{"].includes(i(a)))n.push(a);else if([")","]","}"].includes(i(a))){let f=n.pop();if(f===void 0||!["()","[]","{}"].includes(i(f)+i(a)))throw Error("Unbalanced binding pattern");r.set(f,a)}if(n.length)throw Error("Unbalanced binding pattern");for(let a=0;a<t.length;a++){if(i(a)!=="<")continue;let f=["=",",","(",":","?","[","{"].includes(i(a-1)),u=1;for(let d=a+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(a,d);break}let h=r.get(d);if(h!==void 0)d=h}}let o=(a,f)=>({text:a<f?e.slice(t[a].start,t[f-1].end):"",offset:t[a]?.start??e.length}),s=(a,f,u)=>{for(let d=a;d<f;d++){if(i(d)===u)return d;let h=r.get(d);if(h!==void 0)d=h}return},l=(a,f)=>{let u=s(a,f,"="),d=u===void 0?void 0:o(u+1,f);if(u!==void 0)f=u;if(a+1===f&&t[a]?.kind==="word")return{kind:"name",name:i(a),defaultValue:d};let h=i(a)==="{"?"object":i(a)==="["?"array":void 0;if(!h||r.get(a)!==f-1)throw Error(`Invalid binding target: ${o(a,f).text}`);let p=[],m=a+1;while(m<f-1){let c=s(m,f-1,","),C=c??f-1;if(m===C)p.push(void 0);else if(i(m)==="."&&i(m+1)==="."&&i(m+2)===".")p.push({rest:!0,target:l(m+3,C)});else if(h==="array")p.push({rest:!1,target:l(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:l(b+2,C)})}else{let b=m+1;if(t[m].kind!=="word"&&t[m].kind!=="quoted")while(b<C&&i(b)!==":")b++;let v=i(b)===":";if(!v&&t[m].kind!=="word")throw Error("Invalid object binding key");p.push({key:o(m,v?b:m+1).text,rest:!1,target:l(v?b+1:m,C)})}if(c===void 0)break;m=c+1}return{kind:h,elements:p,defaultValue:d}};return l(0,t.length)}function rs(e,t){if(e.kind==="name")t.push(e.name);else for(let i of e.elements)if(i)rs(i.target,t)}function fn(e){let t=[];return rs(El(e),t),t}function xl(e){let t=El(e.pattern),i=[];if(rs(t,i),!i.length)return[];let r=[e.root],n=!1,o={start:e.root.start,end:e.root.end},s=(a,f)=>{let u=e.allocateName();return r.push({kind:"variable",name:u,text:`declare ${f} ${u}: unknown;`,value:a.text,initializerStart:e.patternOffset+a.offset,modifiers:[f],isExported:!1,...o}),u},l=(a,f)=>{if(a.defaultValue){let v=s(a.defaultValue,e.kind),k=e.allocateName();f=`(${f}) extends infer ${k} ? ${k} extends undefined ? typeof ${v} : ${k} : never`}if(a.kind==="name"){let v=n?void 0:e.comments;n=!0,r.push({kind:"variable",name:a.name,text:`${e.exported?"export ":""}declare ${e.kind} ${a.name}: ${f};`,typeAnnotation:f,modifiers:[e.kind],isExported:e.exported,leadingComments:v,...o});return}let u=a.elements,d=[],h=[],p=[];for(let v of u){if(!v){d.push("");continue}let k=e.allocateName(),W=v.key;if(v.computed)W=`[${s(v.computed,"const")}]`;d.push(v.rest?`...${k}`:a.kind==="object"?`${W}: ${k}`:k),h.push({target:v.target,index:p.length}),p.push(`typeof ${k}`)}let m=e.allocateName(),c=e.allocateName(),C=e.allocateName(),b=a.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:c,text:`type ${c} = (typeof ${m}) extends (...args: never[]) => infer ${C} ? ${C} : never;`,isExported:!1,...o});for(let v of h)l(v.target,`${c}[${v.index}]`)};return l(t,`typeof ${e.root.name}`),r}var un=me(()=>{ht()});function Pt(e,t,i=0){if(i>=64)return;let r=e.trim(),n=ce(r);if(!n.length)return;if(n[0].start!==0||n[n.length-1].end!==r.length)return Pt(r.slice(n[0].start,n[n.length-1].end),t,i+1);if(n.length===1&&n[0].kind==="quoted")return wt(r);if(n.length===1&&n[0].kind==="word"){let u=t.get(r);return typeof u==="object"?void 0:u}if(Sl.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=Sl.exec(r.slice(d.start));if(p){while(n[u+1]?.start<d.start+p[0].length)u++;continue}if(o)continue;let m=Wh.find((b)=>r.startsWith(b,d.start));if(!m)continue;let c=n[u-1],C=c?r.slice(c.start,c.end):"";if(!(!c||c.kind==="punctuation"&&![")","]"].includes(C)&&!/\d/.test(C))&&(!s||ns[m]<s.priority||ns[m]===s.priority&&m!=="**"))s={start:d.start,operator:m,priority:ns[m]};while(n[u+1]?.start<d.start+m.length)u++}if(s){let u=Pt(r.slice(0,s.start),t,i+1),d=Pt(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 Pt(r.slice(1,-1),t,i+1)}if(["+","-","~"].includes(r[0])){let u=Pt(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 l="",a=1;for(let u=1;u<r.length-1;u++){if(r[u]==="\\"){u++;continue}if(r[u]!=="$"||r[u+1]!=="{")continue;let d=wt(`\`${r.slice(a,u)}\``);if(d===void 0)return;l+=d;let h=0,p=n.find((c)=>{if(c.start<u+2||c.kind!=="punctuation")return!1;let C=r.slice(c.start,c.end);if(C==="{")h++;if(C!=="}")return!1;if(h===0)return!0;return h--,!1});if(!p)return;let m=Pt(r.slice(u+2,p.start),t,i+1);if(m===void 0)return;l+=String(m),u=p.start,a=u+1}let f=wt(`\`${r.slice(a,-1)}\``);return f===void 0?void 0:l+f}function Al(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,l)=>(s.start??0)-(l.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 l=ce(s.value),a=l.length===1&&l[0].kind==="word"?r.get(s.value.slice(l[0].start,l[0].end)):void 0;if(s.typeAnnotation==="unique symbol"||s.typeAnnotation==="symbol"||typeof a==="object"||!o&&l[0]?.kind==="word"&&s.value.slice(l[0].start,l[0].end)==="Symbol"&&["(","."].includes(s.value.slice(l[1]?.start,l[1]?.end))){r.set(s.name,Fh);continue}if(s.modifiers?.[0]!=="const"||s.typeAnnotation||s.modifiers.includes("const assertion"))continue;let f=Pt(s.value,r);if(f!==void 0){if(r.set(s.name,f),!(l.length===1&&l[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(l.length===1&&l[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=ce(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=Pt(r,t??new Map);return typeof n==="string"?{name:oi(n,"'")}:{index:!0}}function Tl(e,t){if(!t||!e.trimStart().startsWith("["))return!1;let i=ce(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 Ol(e){if(!e.trimStart().startsWith("[")||!e.includes("`"))return!1;let t=ce(e);return e[t[1]?.start]==="`"&&t.some((i)=>i.kind==="punctuation"&&e[i.start]==="{")}var Fh,Sl,ns,Wh;var dn=me(()=>{ht();Fh={kind:"symbol"},Sl=/^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:[\d_]+(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?)/,ns={"|":1,"^":2,"&":3,"<<":4,">>":4,">>>":4,"+":5,"-":5,"*":6,"/":6,"%":6,"**":7},Wh=[">>>","<<",">>","**","+","-","*","/","%","|","^","&"]});function hn(e){let t=ce(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 os(e){let t=ce(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 Pi(e){return Pl(e,mi(e))}function Rl(e){for(let t=1024;t<e.length;t*=8){let i=e.slice(0,t),r=Ml(i,ce(i),t);if(r!==void 0)return r}return Pl(e,ce(e))}function Pl(e,t){return Ml(e,t,1/0)??!1}function Ml(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 l=e.charCodeAt(o.start);if(l===123||l===40||l===91)r++;else if(l===125||l===41||l===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 l=t[n+1];if(l===void 0?i!==1/0:l.end>=i)return;let a=l?e.slice(l.start,l.end):"";if(a!=="("&&a!==".")return!0}}return i===1/0?!1:void 0}function Dl(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 Il(e,t){let i=e.text,r=ce(i),n=(d)=>r[d]?i.slice(r[d].start,r[d].end):"",o=(d)=>r[d]?.kind==="word",s=new Map,l=[];for(let d=0;d<r.length;d++){let h=n(d);if(h==="("||h==="["||h==="{"||h==="<")l.push(d);else if(h===")"||h==="]"||h==="}"||h===">"&&n(d-1)!=="="){let p=l.at(-1);if(p!==void 0&&(n(p)==="("&&h===")"||n(p)==="["&&h==="]"||n(p)==="{"&&h==="}"||n(p)==="<"&&h===">"))l.pop(),s.set(p,d)}}let a=[];for(let d=0;d<r.length;d++){if(n(d)!=="(")continue;let h=s.get(d);if(h===void 0||!(n(h+1)===":"||n(h+1)==="="&&n(h+2)===">"))continue;let p=new Set,m=d+1;while(m<h){let C=m;while(C<h&&n(C)!==","){let k=s.get(C);if(k!==void 0)C=k+1;else C++}let b=m;while(b<C&&n(b)!==":"&&n(b)!=="="){let k=s.get(b);if(k!==void 0)b=k+1;else b++}let v=m;while([".","public","private","protected","readonly","override"].includes(n(v)))v++;if(n(v)==="{"||n(v)==="[")for(let k of fn(i.slice(r[v].start,r[b-1].end)))p.add(k);else if(o(v))p.add(n(v));m=C+1}let c=h+(n(h+1)===":"?2:3);while(c<r.length){if([";",",",")","]","}"].includes(n(c))||n(c)===">"&&n(c-1)!=="=")break;let C=s.get(c);if(C!==void 0)c=C+1;else c++}a.push({start:d,end:c,names:p})}let f=(d)=>{if(!o(d))return;let h=n(d);if(!a.some((p)=>d>=p.start&&d<p.end&&p.names.has(h)))t.add(h)},u=(d,h)=>{for(let p=d;p<h;p++){if(n(p)==="<"&&s.has(p)){p=s.get(p);continue}if(!o(p)||n(p-1)==="."||n(p+1)===":")continue;if(["true","false","null","undefined","new","this","super","as","satisfies","typeof","void","keyof"].includes(n(p)))continue;f(p)}};for(let d=0;d<r.length;d++){if(n(d)==="typeof")f(d+1);if(n(d)==="export"){let h=d+1;if(n(h)==="default"){if(!["function","class","abstract"].includes(n(h+1)))u(h+1,r.length);continue}if(n(h)==="type")h++;if(n(h)==="{"){let p=s.get(h);if(p===void 0||n(p+1)==="from")continue;for(let m=h+1;m<p;){if(n(m)==="type"&&o(m+1)&&n(m+1)!=="as")m++;f(m);while(m<p&&n(m)!==",")m++;m++}}}if(n(d)==="["){let h=s.get(d);if(h!==void 0&&[":","?","("].includes(n(h+1))&&n(d+2)!==":"&&n(d+2)!=="in")u(d+1,h)}}if(e.kind==="class"){let d=-1;for(let h=0;h<r.length&&n(h)!=="{";h++)if(n(h)==="<"&&s.has(h))h=s.get(h);else if(n(h)==="extends"){d=h;break}if(d!==-1){let h=d+1;while(h<r.length&&n(h)!=="{"&&n(h)!=="implements"){let p=s.get(h);if(p!==void 0)h=p+1;else h++}u(d+1,h)}}}var pr=me(()=>{ht();un()});function ss(e){return typeof e==="string"?oi(e,"'"):String(e)}function Lh(e,t,i=new Map){let r=ce(e),n=new Map(i),o=new Map,s=[],l=1,a=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"&&a===0&&(p===","||p==="}")){let m=r.slice(l,d),c=m[0];if(c){let C=c.kind==="quoted"?wt(e.slice(c.start,c.end)):e.slice(c.start,c.end),b=m.findIndex((k)=>k.kind==="punctuation"&&e[k.start]==="="),v=f;if(b>=0){let k=m.slice(b+1),W="",A=m[b].end;for(let R=0;R+2<k.length;R++){let[V,B,O]=k.slice(R,R+3);if(V.kind!=="word"||O.kind!=="word"||e.slice(B.start,B.end)!==".")continue;let z=n.get(`${e.slice(V.start,V.end)}.${e.slice(O.start,O.end)}`);if(z===void 0||typeof z==="object")continue;W+=e.slice(A,V.start)+ss(z),A=O.end,R+=2}W+=e.slice(A,m.at(-1).end),v=Pt(W,n),s.push({start:m[b].start,end:m.at(-1).end,text:v===void 0?"":`= ${ss(v)}`})}else if(v!==void 0)s.push({start:c.end,end:c.end,text:` = ${ss(v)}`});if(f=typeof v==="number"?v+1:void 0,C!==void 0){if(n.delete(C),n.delete(`${t}.${C}`),v!==void 0)o.set(C,v),n.set(C,v),n.set(`${t}.${C}`,v)}}l=d+1}else if(h.kind==="punctuation"){if("([{".includes(p))a++;else if(")]}".includes(p))a--}}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 Nl(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(ce(n.text.slice(0,o)).some((l)=>n.text.slice(l.start,l.end)==="declare"))continue;let s=Lh(n.text.slice(o),n.name,r);n.text=n.text.slice(0,o)+s.body;for(let[l,a]of s.members)r.set(`${n.name}.${l}`,a)}else if(n.kind==="variable"&&n.modifiers?.[0]==="const"&&!n.typeAnnotation&&!n.modifiers.includes("const assertion")&&typeof n.value==="string"){let o=Pt(n.value,r);if(o!==void 0)r.set(n.name,o)}}var Fl=me(()=>{ht();dn()});function Wl(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 pn(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 ce(n)){if(h.kind==="punctuation"&&n[h.start]===","&&s===0)o.push([]);else o[o.length-1].push(h);s+=Wl(n,h)}let l=o.map((h)=>{let p=0,m=-1;for(let[v,k]of h.entries()){if(p===0&&k.kind==="punctuation"&&n[k.start]===":"){m=v;break}p+=Wl(n,k)}let c=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:c,required:h.length>0&&!c&&!b&&C!=="this"}}),a=-1;for(let[h,p]of l.entries())if(p.required)a=h;let f=[];for(let[h,p]of l.entries()){if(h>=a||!p.question||p.colon<0)continue;let m=p.tokens[p.colon+1],c=p.tokens.at(-1);if(!m||!c)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+c.end,end:r+c.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 Ll(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Bl(e,t){if(t>=e.length||!Ll(e.charCodeAt(t)))return t;let i=t+1;while(i<e.length&&(Ll(e.charCodeAt(i))||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57))i++;return i}function as(e,t){let i=t;while(i<e.length&&e.charCodeAt(i)<=32)i++;return i}function mr(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 a=0;a<r.length;a++){let f=r.charCodeAt(a);if(f===34||f===39||f===96){a++;while(a<r.length&&r.charCodeAt(a)!==f){if(r.charCodeAt(a)===92)a++;a++}if(a>=r.length)return null;continue}if(f===47&&(r.charCodeAt(a+1)===47||r.charCodeAt(a+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,a)),s=a+1}if(o!==0)return null;if(r.slice(s).trim()||n.length===0)n.push(r.slice(s));let l=[];for(let a of n){let f=a.trim(),u=Bl(f,0);if(u===0)return null;let d=f.slice(0,u),h=d,p=as(f,u);if(f.charCodeAt(p)===58){let c=as(f,p+1),C=Bl(f,c);if(C===c)return null;h=f.slice(c,C),p=as(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;l.push({key:d,alias:h,value:m})}return l}function mn(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 ls=me(()=>{ht()});function Lt(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 Ll,Bl;var pt=ye(()=>{Bi();Bl=[]});function _l(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 ws(e,t){if(e.kind==="name")t.push(e.name);else for(let i of e.elements)if(i)ws(i.target,t)}function wn(e){let t=[];return ws(_l(e),t),t}function jl(e){let t=_l(e.pattern),i=[];if(ws(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 Cs=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(Gl.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=Gl.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||vs[m]<s.priority||vs[m]===s.priority&&m!=="**"))s={start:d.start,operator:m,priority:vs[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 Vl(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 Ul(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 zl(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 Kl(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,Gl,vs,rp;var bn=ye(()=>{pt();ip={kind:"symbol"},Gl=/^(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:[\d_]+(?:\.[\d_]*)?|\.[\d_]+)(?:[eE][+-]?[\d_]+)?)/,vs={"|":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 bs(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 ql(e,Mt(e))}function Hl(e){for(let t=1024;t<e.length;t*=8){let i=e.slice(0,t),r=Jl(i,ue(i),t);if(r!==void 0)return r}return ql(e,ue(e))}function ql(e,t){return Jl(e,t,1/0)??!1}function Jl(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 Yl(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 Xl(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 $s(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)+$s(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?"":`= ${$s(c)}`})}else if(c!==void 0)s.push({start:g.end,end:g.end,text:` = ${$s(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 Zl(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 Ql=ye(()=>{pt();bn()});function ec(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(ec(o,i))r=!0,n=!1,t.at++;else if(o===95&&r&&!n&&t.at+1<e.length&&ec(e.charCodeAt(t.at+1),i))n=!0,t.at++;else break}return r&&!n}function tc(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=tc(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=tc(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 xs=ye(()=>{pt();Sn()});function ic(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+=ic(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+=ic(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 rc(e){return e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function nc(e,t){if(t>=e.length||!rc(e.charCodeAt(t)))return t;let i=t+1;while(i<e.length&&(rc(e.charCodeAt(i))||e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57))i++;return i}function Ss(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=nc(f,0);if(u===0)return null;let d=f.slice(0,u),h=d,p=Ss(f,u);if(f.charCodeAt(p)===58){let g=Ss(f,p+1),C=nc(f,g);if(C===g)return null;h=f.slice(g,C),p=Ss(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 Es=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}
|
|
35
36
|
`;return`${r.trim()}
|
|
36
37
|
`}let i="";for(let r=0;r<e.length;r++){if(r>0)i+=`
|
|
37
38
|
`;i+=e[r].trim()}return`${i}
|
|
38
|
-
`}function
|
|
39
|
-
`)||o.includes("\r"))return"string";return o}if(o.charCodeAt(0)===39||o.charCodeAt(0)===34){let l=
|
|
40
|
-
`;if(i==="t")return"\t";if(i==="r")return"\r";if(i==="0")return"\x00";return i})}function
|
|
39
|
+
`}function Er(e){return e.replaceAll("*/","*\\/")}var kn=()=>{};function ks(e){return hc(e).replace(/\n[ \t]*(?=\n)/g,"")}function hc(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 Ds(){Nn=!0,yt=null}function Is(){Nn=!1;let e=yt;return yt=null,e}function As(e,t){let i=0,r=0;while((r=e.indexOf(t,r))!==-1)i++,r+=t.length;return i}function oc(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&&oc(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&&oc(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=yc(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=op(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 Os(o,t,r+1,n);if(o.startsWith("{")&&o.endsWith("}"))return xc(o,t,r+1,n);if(o.startsWith("class ")||o.startsWith("class{"))return xp(o);if(o.startsWith("new "))return Ns(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 Ec(o,i,r,t);if(o.startsWith("`")&&o.endsWith("`"))return $p(o,t);if(o.startsWith("Promise."))return vc(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(pc(o))return"boolean";if(cp(o))return"number";return"unknown"}function sc(e){let t=e.charCodeAt(0);if(t!==39&&t!==34)return!1;return qt(e,0,t)===e.length}function op(e){if(sc(e))return e;let t=sp(e);if(t.length<2)return null;let i=!1,r=!0,n="";for(let o of t){let s=o.trim();if(sc(s))i=!0,n+=ap(s);else r=!1}if(r)return lp(n);if(i)return"string";return null}function sp(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 ap(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 lp(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}'`}function cp(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 pc(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 fp(e,t=!1,i=0,r){return Te(e,t,!0,i,r)}function Qt(e,t=!1,i="",r,n){let o=Ts(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=bp(e,l);if(d!==-1){l=Mn(e,d);continue}}if(u===61&&e.charCodeAt(l+1)===62){let d=Cc(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=ks(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":gc(s);return t&&!f.startsWith("Promise<")?`Promise<${f}>`:f}function Ts(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 up(e,t){let i=Object.hasOwn(ac,e)?ac[e]:void 0;return i&&Object.hasOwn(i,t)?i[t]:void 0}function Zt(e){return e.includes(`
|
|
41
43
|
`)?e.replaceAll(`
|
|
42
44
|
`,`
|
|
43
|
-
`):e}function
|
|
44
|
-
|
|
45
|
-
|
|
45
|
+
`):e}function dp(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&&dp(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(vp(s))return Te(s,!1);let u=wc(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:gc([c,A])}for(let c of["??","||","&&"]){let A=mc(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 yp(M,S,c)}}let d=hp(s);if(d&&r)return r(d,n);let h=yc(s);if(h)return r?r(h,n):h;if(pc(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 O=S.startsWith("..."),N=Dt(O?S.slice(3):S,t,i,r,n,o+1);return O?`(NonNullable<${N}> extends Iterable<infer Element> ? Element : never)`:N});return`(${[...new Set(A)].join(" | ")||"never"})[]`}}let m=f??(s.startsWith("{")&&s.endsWith("}")?xc(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)),O=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,O=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=O&&Ae&&te.length===1?up(O.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 hp(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 mc(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 pp(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 mp(e,t){let i=pp(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&&gp(f))continue;else if(s&&/^-?\d+(?:\.\d+)?$/.test(f))continue;else a.push(f);return a.join(" | ")}function gp(e){let t=e[0];return e.length>=2&&(t==="'"||t==='"')&&e.endsWith(t)&&!e.slice(1,-1).includes(t)}function yp(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 mp(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 wp(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 Cp(e,t){let i=e.trim();while(Fn(i))i=i.slice(1,-1).trim();let r=mc(i,"??");if(r!==-1&&i.slice(r+2).trim()==="{}")return wp(t(i.slice(0,r)));let n=wc(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 gc(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 yc(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
|
+
`,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 vp(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=Ms(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 wc(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 Cc(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 bp(e,t){let i=0,r=0,n=0,o=!1,s=!1;for(let a=t;a<e.length;a++){if(a=Cc(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 $p(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 Ns(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 xp(e){return"{ new (...args: any[]): any }"}function vc(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=vc(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 Os(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(Os(g,!0,i+1,r));else p.push(Te(g,!0,!1,i+1,r))}return`readonly [
|
|
46
49
|
${p.join(` |
|
|
47
50
|
`)}
|
|
48
|
-
]`}let
|
|
49
|
-
`,
|
|
50
|
-
`),o;if(n.includes("@defaultValue"))o=n;else{let s=`@defaultValue ${
|
|
51
|
-
`))
|
|
52
|
-
* ${
|
|
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(Os(m,t,i+1,r));else l.push(fp(m,t,i+1,r));if(a)f.push(yt);yt=g}if(a)if(Rs(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("[")&&Rs(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 bc(e){return e==="number"||e==="string"||e==="boolean"}function $c(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 Fs(e,t,i){let r=t.trim();if(!bc(i)||!Dn(r))return"";let n=(e??[]).map((s)=>s.trim()).filter((s)=>s.startsWith("/**")||s.startsWith("//")).join(`
|
|
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
|
+
`))l=`/**
|
|
55
|
+
* ${l.slice(4)}`;o=`${l}
|
|
53
56
|
* ${s}
|
|
54
57
|
*/`}else o=`/**
|
|
55
58
|
* ${n.startsWith("// ")?n.slice(3):n.startsWith("//")?n.slice(2):n}
|
|
56
59
|
* ${s}
|
|
57
60
|
*/`}}return o.split(`
|
|
58
|
-
`).map((s)=>{let
|
|
61
|
+
`).map((s)=>{let a=s.trim();if(!a)return"";return a.startsWith("*")?` ${a}`:` ${a}`}).join(`
|
|
59
62
|
`)+`
|
|
60
|
-
`}function
|
|
61
|
-
`:"",
|
|
62
|
-
${
|
|
63
|
-
${
|
|
64
|
-
${
|
|
65
|
-
${
|
|
66
|
-
${
|
|
63
|
+
`}function Rs(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 xc(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=kp(o),a=new Set(s.flatMap(([b])=>{let c=uc(Ps(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}=Ps(b),S=A?`${A}
|
|
64
|
+
`:"",O=uc(M);if(O&&Kl(O.name))continue;let N=M,B=!1;if(M==="..."){let re=c.trim(),pe=n?Cp(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(Rp(te)){B=!0;let re=Pp(M);if(re){N=re.name;let pe="";if(te.startsWith("async "))pe="async ";if(te.charCodeAt(pe.length)===42)pe+="*";K=dc(re.name,pe+re.typeParams+te.slice(pe.length))}else K=dc(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=lc(K)}let he=yt;yt=ee;let Ae=N,Se=c.trim(),fe=Ul(N,r);if(!zl(O?.name??N,r)&&!(O?.kind==="set"&&a.has(O.name)))u.push(O?Op(O.kind,K):K);if(fe&&"index"in fe)d=!0;else{if(fe&&"name"in fe)N=fe.name;if(O){let re=Tp(O.kind,O.name,K);if(re){l.push(`${S}${Zt(re)}`);continue}}if(!t&&bc(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=hc(Ae);if(Se.endsWith("as const"));else if(Dn(Se))p.push(`${re}: ${Se}`);else if(Se.startsWith("[")&&Rs(Se))p.push(`${re}: ${Rn(Se)}`);else if(Se.startsWith("{")){if(he)p.push(`${re}: ${he}`)}else if(B)p.push(`${re}: ${ks(lc(K))}`),m++;else if(!Se.startsWith("[")&&(Se.includes("=>")||Se.startsWith("function")||Se.startsWith("async"))){let pe=Ec(Se,!1,0,!0);p.push(`${re}: ${ks(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
|
+
${A}${p.join(`,
|
|
67
|
+
${A}`)}
|
|
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
|
+
${l.join(`;
|
|
67
70
|
`)}
|
|
68
|
-
}`:"{}";if(f.length===0)return
|
|
69
|
-
`).map((f)=>
|
|
70
|
-
`),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(!
|
|
71
|
-
`),key:e.slice(i).trim()}}function
|
|
72
|
-
`))
|
|
73
|
-
${r}`:r,r]);else if(r.startsWith("...")&&r.length>3)e.push(["...",r.slice(3).trim()])}function ql(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 fp(e,t,i){let r=i.trim();if(r.charCodeAt(0)!==40)return null;let n=ot(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 l=s.slice(2).trim();if(e==="get")return`get ${t}(): ${l||"unknown"}`;return`set ${t}(${o})`}function up(e,t){let i=t.trim(),r=ot(i,0,"(",")");if(!i.startsWith("(")||r===-1)return"unknown";if(e==="get"){let l=i.slice(r+1).trim();return l.startsWith("=>")?l.slice(2).trim():"unknown"}let n=i.slice(1,r).trim(),o=n.startsWith("{")?ot(n,0,"{","}"):n.startsWith("[")?ot(n,0,"[","]"):0,s=n.indexOf(":",Math.max(0,o));return s===-1?"unknown":n.slice(s+1).trim()}function dp(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=vs(o,1);if(s?.kind==="arrow")return!1;if(s?.kind==="body")return!0}return!1}}}return!1}function hp(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 Jl(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("("),l=ot(i,s,"(",")");if(s===-1||l===-1)return"() => unknown";let a=i.slice(s,l+1),f="unknown",u=i.slice(l+1).trimStart();if(u.charCodeAt(0)===58){let h=u.slice(1),p=vs(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=ot(u,0,"{","}");if(h!==-1){let p=Kt(u.slice(1,h),r,a);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=gi(a);return`${o}${d} => ${f}`}function vs(e,t){let i=0,r=0,n=0,o=0,s=!1,l=0;for(let a=t;a<e.length;a++){let f=e.charCodeAt(a);if(s){if(f===92)a++;else if(f===l)s=!1;continue}if(f===34||f===39||f===96){s=!0,l=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(a-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,a).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:a,kind:"body"}}else if(f===61&&a+1<e.length&&e.charCodeAt(a+1)===62&&i===0&&r===0&&n===0&&o===0)return{index:a,kind:"arrow"}}return null}function ot(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 wi(e){let t=0,i=0,r=!1,n="";for(let o=0;o<e.length-1;o++){let s=e[o],l=e[o+1],a=o>0?e[o-1]:"";if(!r&&(s==='"'||s==="'"||s==="`"))r=!0,n=s;else if(r&&s===n&&a!=="\\")r=!1;if(!r){if(s==="<"){let f=ot(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==="="&&l===">"&&t===0&&i===0)return o}}return-1}function lc(e,t=!1,i=0,r=!0){let n=e.trim();if(n.length>200&&cs(n,"=>")>2&&cs(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(),l=wi(s);if(l===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let a=s.substring(0,l).trim(),f=s.substring(l+2).trim(),u=gs(a),{params:d,returnType:h}=u;if(d=gi(d),d==="()"||d==="")d="()";else if(!d.startsWith("("))d=`(${d})`;let p=h;if(p);else if(f.startsWith("{"))p=Kt(f.slice(1,f.endsWith("}")?-1:void 0),!0,u.params);else p=St(f,ds(u.params));let m=`${d} => ${h||p.startsWith("Promise<")?p:`Promise<${p}>`}`;return t?`(${m})`:m}if(n.includes("=>")){let s="",l=n;if(n.startsWith("<")){let C=ot(n,0,"<",">");if(C!==-1)s=n.substring(0,C+1),l=n.substring(C+1).trim()}let a=wi(l);if(a===-1)return t?"(() => unknown)":"() => unknown";let f=l.substring(0,a).trim(),u=l.substring(a+2).trim(),d=gs(f),{params:h,returnType:p}=d;if(h=gi(h),h==="()"||h==="")h="()";else if(!h.startsWith("("))h=`(${h})`;let m="unknown";if(p)m=p;else if(u.startsWith("{"))m=Kt(u.slice(1,u.endsWith("}")?-1:void 0),!1,d.params);else if(wn(u)||xn(u)&&wn(u.slice(1,-1).trim()))m="JSX.Element";else if(u.includes("=>")){let C=u.trimStart(),b=C.indexOf("("),v=b!==-1?ot(C,b,"(",")"):-1,k=v!==-1?C.indexOf("=>",v):-1;if(b===0&&v!==-1&&k!==-1){let W=C.substring(b+1,v).trim(),A=gi(W);if(s.includes("T")&&A.includes("T"))m=`(${A}) => T`;else m=`(${A}) => any`}else m="any"}else m=St(u,ds(d.params));let c=`${s}${h} => ${m}`;return t?`(${c})`:c}if(n.startsWith("function")){let s=8,l=n.length;while(s<l&&n.charCodeAt(s)<=32)s++;let a=!1;if(s<l&&n.charCodeAt(s)===42){a=!0,s++;while(s<l&&n.charCodeAt(s)<=32)s++}let f="";if(s<l&&n.charCodeAt(s)===60){let h=s,p=1;s++;while(s<l&&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<l&&n.charCodeAt(s)<=32)s++}let u=n.indexOf("(",s);if(u!==-1){let h=1,p=u+1;while(p<l&&h>0){let k=n.charCodeAt(p);if(k===40)h++;else if(k===41)h--;p++}let m=n.substring(u+1,p-1).trim(),c=m?gi(`(${m})`):"()";if(a){let k=n.substring(p).trim(),W=k.indexOf("Generator<");if(W!==-1){let R=W+10,V=k.indexOf(">",R);if(V!==-1){let B=k.substring(R,V),O=`${f}${c} => Generator<${B}>`;return t?`(${O})`:O}}let A=`${f}${c} => Generator<any, any, any>`;return t?`(${A})`:A}let C="unknown",b=n.substring(p).trimStart();if(b.charCodeAt(0)===58){let k=b.slice(1),W=vs(k,0),A=(W?k.slice(0,W.index):k).trim();if(A)C=A}let v=`${f}${c} => ${C}`;return t?`(${v})`:v}let d="(...args: any[]) => unknown";return t?`(${d})`:d}if(n.includes("=>")&&n.includes("(")&&n.includes(")")){if(n.length>100||cs(n,"=>")>2){let s="";if(n.charCodeAt(0)===60){let d=ot(n,0,"<",">");if(d!==-1)s=n.substring(0,d+1)}let l=n.indexOf("("),a=l!==-1?ot(n,l,"(",")"):-1,f=l!==-1&&a!==-1?n.substring(l,a+1):"(...args: any[])";f=gi(f);let u=`${s}${f} => any`;return t?`(${u})`:u}return t?`(${n})`:n}let o="() => unknown";return t?`(${o})`:o}function gs(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let i=ot(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 cc(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 Sn(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=Bt(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 l=!1;for(n++;n<e.length;n++){let a=e.charCodeAt(n);if(a===92)n++;else if(a===91)l=!0;else if(a===93)l=!1;else if(a===47&&!l)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)&&yr(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 $n=20,En=!1,pt=null,Vl;var vr=me(()=>{ht();un();dn();ls();gn();Vl={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 fc(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 l=new Map;for(let h of t)if(h.kind==="function"){let p=(l.get(h.name)??0)+1;if(l.set(h.name,p),p>1)s.add(h.name)}let a=mi(e),f=(h)=>a[h]?e.slice(a[h].start,a[h].end):"",u=new Map,d=0;for(let h=0;h<a.length;h++){let p=a[h];if(p.kind==="punctuation"){let R=e.charCodeAt(p.start);if(R===40||R===91||R===123)d++;else if(R===41||R===93||R===125)d--;continue}if(d||a[h+2]?.kind!=="word"||f(h+1)!=="."||f(h+3)!=="=")continue;let m=f(h);if(!o.has(m))continue;let c=f(h+2),C=h+4,b=C,v=0;for(;b<a.length;b++){let R=f(b);if(!v&&R===";")break;if(!v&&b>C&&/[\r\n]/.test(e.slice(a[b-1].end,a[b].start))&&(["export","const","let","var","function","class"].includes(R)||o.has(R)&&f(b+1)==="."))break;if(["(","[","{"].includes(R))v++;else if([")","]","}"].includes(R))v--}if(b===C)continue;let k=uc(e.slice(a[C].start,a[b-1].end),n,s),W=u.get(m);if(!W)u.set(m,W=new Map);let A=W.get(c);if(!A)W.set(c,A=[]);if(!A.includes(k))A.push(k);h=b-1}for(let[h,p]of u){let m=o.get(h),c=[...p].map(([b,v])=>` let ${b}: ${v.map((k)=>k.includes("=>")&&v.length>1?`(${k})`:k).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 Sp(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=Sp(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 lc(e){let t=e.split(`
|
|
72
|
+
`).map((f)=>Sc(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=Sc(g),b=m.slice(0,m.length-m.trimStart().length);h.push(b+Ep(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 Sc(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 Ep(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,cc);let f=!a.endsWith("?")?"?":"";return`${a}${f}: ${cc(e.slice(i+1))}`}return e}function cc(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 Ap(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 Ps(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 kp(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=Ap(r),S=M>0?r.slice(0,M):"",O=r.slice(M),N="";if(O.startsWith("async ")||O.startsWith("async\t")||O.startsWith(`async
|
|
75
|
+
`))O=O.slice(6).trimStart(),N="async ";if(O.startsWith("*"))O=O.slice(1).trimStart(),N+="*";r=S+O,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())fc(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())fc(t,i.trim());return t}function fc(e,t){let{comments:i,key:r}=Ps(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 uc(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=Ws(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 dc(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=Ws(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 Ws(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 Ec(e,t=!1,i=0,r=!0){let n=e.trim();if(n.length>200&&As(n,"=>")>2&&As(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=Ms(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,Ts(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=Ms(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,Ts(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=Ws(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||As(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 Ms(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 Ac(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,ac;var Tr=ye(()=>{Bi();pt();Cn();bn();Sn();xs();Es();kn();ac={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 kc(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=Tc(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(`
|
|
74
77
|
`),C=m.isExported&&!m.isDefault?"export ":"";if(m.isDefault)m.text=m.text.replace("export default function ","declare function ");if(m.text+=`
|
|
75
78
|
${C}declare namespace ${h} {
|
|
76
|
-
${
|
|
79
|
+
${g}
|
|
77
80
|
}`,m.isDefault)m.text+=`
|
|
78
|
-
export default ${h};`}}function
|
|
81
|
+
export default ${h};`}}function Tc(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 Tc(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 Oc=ye(()=>{pt();Tr()});function Mp(e){if(e.includes(`
|
|
79
82
|
`))return`/**
|
|
80
83
|
* ${e}
|
|
81
84
|
*/
|
|
82
85
|
`;return`/** ${e} */
|
|
83
|
-
`}function
|
|
84
|
-
`))
|
|
86
|
+
`}function Dp(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 Rc(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)Ds();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=Is();if(u)if(u.includes(`
|
|
87
|
+
`))l=`@defaultValue
|
|
85
88
|
* \`\`\`ts
|
|
86
89
|
${u.split(`
|
|
87
90
|
`).map((d)=>` * ${d}`).join(`
|
|
88
91
|
`)}
|
|
89
|
-
* \`\`\``;else
|
|
90
|
-
`))
|
|
92
|
+
* \`\`\``;else l=`@defaultValue \`${u}\``}}else if(t&&s&&e.typeAnnotation&&Ac(e.typeAnnotation)){Ds();let f=s.trim(),u=f.endsWith("as const")?f.slice(0,-8).trim():f;Te(u,!1,!1,0,e.computedKeyConstants);let d=Is();if(d)if(d.includes(`
|
|
93
|
+
`))l=`@defaultValue
|
|
91
94
|
* \`\`\`ts
|
|
92
95
|
${d.split(`
|
|
93
96
|
`).map((h)=>` * ${h}`).join(`
|
|
94
97
|
`)}
|
|
95
|
-
* \`\`\``;else
|
|
98
|
+
* \`\`\``;else l=`@defaultValue \`${d}\``}if(l=Er(l),r+=`: ${o};`,l&&i&&i.includes("@defaultValue"))l="";if(l&&i){let f=i.trimEnd(),u=f.lastIndexOf("*/");if(u!==-1){let d=f.slice(0,u).trimEnd();if(d.startsWith("/** ")&&!d.includes(`
|
|
96
99
|
`))d=`/**
|
|
97
100
|
* ${d.slice(4)}`;return`${d}
|
|
98
|
-
* ${
|
|
101
|
+
* ${l}
|
|
99
102
|
*/
|
|
100
103
|
`+r}return`/**
|
|
101
104
|
* ${f.replace(/^\/\/\s*/,"")}
|
|
102
|
-
* ${
|
|
105
|
+
* ${l}
|
|
103
106
|
*/
|
|
104
|
-
${r}`}if(a)return`${pp(a)}${r}`;return i+r}function pc(e,t=!0){let i=Lt(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=mp(e.text);if(o!==-1)n+=` ${e.text.slice(o)}`;else n+=" {}";return i+n}function mc(e,t=!0){let i=Lt(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),l=s.length;while(l>0&&(s.charCodeAt(l-1)===59||s.charCodeAt(l-1)===32||s.charCodeAt(l-1)===10||s.charCodeAt(l-1)===13))l--;if(l<s.length)s=s.slice(0,l);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 gc(e,t=!0){return Lt(e.leadingComments,t)+e.text}function yc(e,t=!0){let i=Lt(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=Lt(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 An=me(()=>{gn();vr()});function Cc(e){let t=vi.get(e);if(t)return vi.delete(e),vi.set(e,t),t;return null}function vc(e,t){if(vi.set(e,t),vi.size>200){let i=0;for(let r of vi.keys()){if(i++>=20)break;vi.delete(r)}}}var vi;var bc=me(()=>{vi=new Map});function bs(e){return Rt(e).find((t)=>t.category==="static-import")}function gp(e){return ce(e).map((t)=>e.slice(t.start,t.end)).join(" ")}function yp(e){let t=bs(e);return t?e.lastIndexOf(" from ",t.start):-1}function kn(e){let t=bs(e);return t?oi(t.specifier,"'"):void 0}function bi(e){let t=Cc(e);if(t)return t;let i=$i(e),r=i?[i.defaultName,i.namespaceName,...i.namedItems.map((n)=>n.name)].filter((n)=>n!==null):[];return vc(e,r),r}function wp(e){let t=[],i=0;for(let n of ce(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 $i(e){e=gp(e);let t=ln(e);if(t)return{defaultName:t.name,namedItems:[],source:t.source,isTypeOnly:t.isTypeOnly,isNamespace:!1,namespaceName:null,isImportEquals:!0};let i=yp(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 l=null,a=[],f=!1,u=null,d=o.includes("{")?-1:o.indexOf("* as ");if(d!==-1)return f=!0,u=o.slice(d+5).trim(),l=o.slice(0,d).trim().replace(/,$/,"").trim()||null,{defaultName:l,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(","))l=m.slice(0,-1).trim()||null;let c=o.slice(h+1,p),C=wp(c);for(let b of C){let v=Cp(b),k=v?b.slice(5).trim():b,W=k.lastIndexOf(" as "),A,R;if(W!==-1)R=k.slice(0,W).trim(),A=k.slice(W+4).trim();else A=k,R=k;a.push({name:A,originalName:R,isTypeOnly:s||v,isDefault:!1})}}else l=o.trim()||null;return{defaultName:l,namedItems:a,source:n,isTypeOnly:s,isNamespace:f,namespaceName:u}}function Cp(e){let t=ce(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 Ei=me(()=>{ht();bc()});function $s(e,t){let i=(r)=>ce(r).map((n)=>r.slice(n.start,n.end)).join("");return i(e)===i(t)}function Ec(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=Ec(t);if(!i)return;let r=ce(e),n=0,o=0,s=[];for(let a of r){let f=e.slice(a.start,a.end);if(f==="("||f==="["||f==="{"||f==="<")n++;else if(f===")"||f==="]"||f==="}"||f===">")n--;else if(f==="|"&&n===0)s.push(e.slice(o,a.start).trim()),o=a.end}s.push(e.slice(o).trim());let l=s.find((a)=>$s(a,t));if(l)return l;if(s.includes(i))return i==="boolean"&&(t==="true"||t==="false")?t:i;return}function xc(e,t,i,r=new Set){let n=new Map,o=[],s=new Set;for(let T of[...t,...i.values()]){if(s.has(T))continue;if(s.add(T),o.push(T),T.kind==="import")for(let j of bi(T.text))n.set(j,{declared:`typeof ${j}`,flow:`typeof ${j}`,unresolved:!1});else if(["function","class","enum"].includes(T.kind))n.set(T.name,{declared:`typeof ${T.name}`,flow:`typeof ${T.name}`,unresolved:!1});else if(T.kind==="variable")n.set(T.name,{declared:T.typeAnnotation,unresolved:!1})}o.sort((T,j)=>(T.start??0)-(j.start??0));let l=new Set(o.filter((T)=>T.kind==="function"&&!T.generics).map((T)=>T.name));for(let T of r)l.add(T);let a=new Map,f=(T)=>{if(T=T.trimStart(),a.has(T))return a.get(T);if(a.set(T,void 0),!dt(T.charCodeAt(0)))return;let j=1;while(He(T.charCodeAt(j)))j++;if(!l.has(T.slice(0,j)))return;let M=ce(T);if(M[0]?.kind!=="word"||!M[1]||T.slice(M[1].start,M[1].end)!=="(")return;let _=1;for(let G=2;G<M.length;G++){let Y=T.slice(M[G].start,M[G].end);if(Y==="(")_++;else if(Y===")"&&--_===0){let re=G===M.length-1?T.slice(M[0].start,M[0].end):void 0;return a.set(T,re),re}}return},u=new Set(o.filter((T)=>T.kind==="variable"&&!T.typeAnnotation&&typeof T.value==="string").map((T)=>f(T.value)).filter((T)=>T!==void 0)).size?mi(e):void 0,d=new Map;if(u){let T=0;for(let j=0;j<u.length;j++){let M=e.slice(u[j].start,u[j].end);if(T===0&&M==="function"){let _=u[j+1],G=_&&e.slice(_.start,_.end)==="*"?u[j+2]:_;if(G?.kind==="word"){let Y=e.slice(G.start,G.end);d.set(Y,(d.get(Y)??0)+1)}}if(["{","(","["].includes(M))T++;else if(["}",")","]"].includes(M))T--}}let h=new Map;for(let T of o)if(T.kind==="function"&&!T.generics&&d.get(T.name)===1)h.set(T.name,T);for(let T of r){let j=o.find((M)=>M.kind==="import"&&bi(M.text).includes(T));if(j)h.set(T,j)}let p="__dtsx_call_result";while(e.includes(p))p+="_";let m=(T)=>`(typeof ${T}) extends (...args: never[]) => infer ${p} ? ${p} : never`,c=new Map,C=!1;for(let T of o){if(T.kind!=="variable"||T.typeAnnotation||typeof T.value!=="string")continue;let j=f(T.value);if(j&&h.has(j))c.set(T,m(j)),n.get(T.name).active=!0,n.get(j).active=!0,C=!0;if(T.modifiers?.[0]!=="const")continue;let M=hn(T.value);if(!M||M===T.name||!n.has(M))continue;n.get(M).active=!0,n.get(T.name).active=!0,C=!0}if(!C)return;let b=u??mi(e),v=(T)=>b[T]?e.slice(b[T].start,b[T].end):"",k=new Map,W=new Map,A=new Set,R=new Set,V=new Set,B=new Map,O=[];for(let T=0;T<b.length;T++){let j=v(T),M=O.at(-1);if(M!==void 0)W.set(T,M);if(j==="{"&&["=","(","[",",",":","?","return","yield"].includes(v(T-1)))A.add(T);if(["(","[","{"].includes(j))O.push(T);else if([")","]","}"].includes(j)){let _=O.at(-1);if(_!==void 0&&["()","[]","{}"].includes(v(_)+j))O.pop(),k.set(_,T)}}let z=new Map;for(let T=0;T<b.length;){if(b[T].kind!=="punctuation"){T++;continue}let j=[">>>=","**=","&&=","||=","??=","<<=",">>=","===","!==",">>>","**","&&","||","??","<<",">>","=>","==","!=","<=",">=","++","--","+=","-=","*=","/=","%=","&=","|=","^=","="].find((_)=>e.startsWith(_,b[T].start))??v(T);z.set(T,j);let M=b[T].start+j.length;do T++;while(T<b.length&&b[T].start<M)}for(let T=0;T<b.length;T++){let j=we(T);if(j!==void 0)R.add(j)}for(let T of R)fe(T);let X=0;function ae(T){let j=hn(T);if(j){let Y=n.get(j);return{type:Y?.flow,unresolved:Y?.unresolved??!1}}let M=f(T),_=M?h.get(M):void 0;if(_)return{type:_.returnType&&Ec(_.returnType)?_.returnType:m(M),unresolved:!1};let G=Te(T,!0);return{type:G==="unknown"?void 0:G,unresolved:!1}}function be(T){return z.get(T)??""}function ke(T){if(b[T]?.kind!=="word"||V.has(T)||v(T-1)==="."||v(T-1)==="#"&&v(T-2)===".")return;let j=n.get(v(T));if(!j?.active)return;let M=be(T+1);if(["=","+=","-=","*=","/=","%=","**=","<<=",">>=",">>>=","&=","|=","^=","&&=","||=","??="].includes(M))return{binding:j,operator:M};if(["++","--"].includes(M)&&!/[\r\n]/.test(e.slice(b[T].end,b[T+1].start)))return{binding:j,operator:M};if(T>=2&&["++","--"].includes(be(T-2))){let _=b[T-3],G=_&&(_.kind==="word"||_.kind==="quoted"||[")","]"].includes(v(T-3)));if(!_||!G||/[\r\n;]/.test(e.slice(_.end,b[T-2].start)))return{binding:j,operator:be(T-2)}}return}function ve(T){let j=ke(T);return j?.operator==="="?j.binding:void 0}function we(T){if(b[T]?.kind!=="word"||v(T)!=="class"||v(T-1)==="."||["(",":","="].includes(v(T+1)))return;let j=T+1,M=0;while(j<b.length){let _=v(j);if(_==="{"&&M===0)return j;if(_==="class"){let G=we(j);if(G!==void 0){j=(k.get(G)??G)+1;continue}}if(_==="function"){let G=xe(j,b.length);if(G){j=G.end;continue}}if(_==="<")M++;else if(_===">"&&be(j-1)!=="=>"&&M>0)M--;if(_===";")break;j=(k.get(j)??j)+1}return}function ge(T,j,M){let _=T,G=!1,Y=M?["public","protected","private","static","abstract","override","declare","readonly","accessor","async","get","set"]:["async","get","set"];while(Y.includes(v(_))&&!["(","<","?","!",":","=",";","}"].includes(v(_+1))){if(v(_)==="static")G=!0;_++}if(v(_)==="*")_++;if(M&&v(_)==="#")_++;if(v(_)==="["){let Ae=k.get(_);return Ae===void 0?void 0:{next:Ae+1,isStatic:G}}if(b[_]?.kind==="word"||b[_]?.kind==="quoted")return{next:_+1,isStatic:G};let re=_+1;while(re<j&&b[re-1].end===b[re].start&&!["(","<","?","!",":","=",";","}","[","{",","].includes(v(re)))re++;if(_<j&&Te(e.slice(b[_].start,b[re-1].end),!1)==="number")return{next:re,isStatic:G};return}function ie(T,j,M){let _=ge(T,j,M);if(!_)return;let G=_.next;if(M&&["?","!"].includes(v(G)))G++;if(v(G)==="<"){let Y=1;G++;while(G<j&&Y>0){if(v(G)==="<")Y++;else if(v(G)===">"&&be(G-1)!=="=>")Y--;G=(k.get(G)??G)+1}if(Y!==0)return}return G}function I(T,j,M){return ie(T,j,M)===j}function K(T,j){let M=0,_=-1;for(let G=T;G<j;G=(k.get(G)??G)+1)if(v(G)==="<"&&(M>0||G>T&&(b[G-1].kind==="word"||[")","]"].includes(v(G-1))))){if(M===0)_=G;M++}else if(v(G)===">"&&be(G-1)!=="=>"&&M>0){if(M--,G===j-1&&M===0)return _<G-1}return!1}function Q(T,j){if(v(T)==="static"&&v(T+1)==="{")return!0;let M=ie(T,j,!0);return M!==void 0&&(M===j||["(",":","=",";","}"].includes(v(M)))}function oe(T,j,M=!1){let _=k.get(j)??b.length,G=T;while(G<_){if(v(G)===";"||M&&be(G)==="=")return G;if(G>T&&W.get(G)===j&&/[\r\n]/.test(e.slice(b[G-1].end,b[G].start))){let Y=v(G-1),re=!(Y===">"&&K(T,G)&&Q(G,_))&&["+","-","*","/","%","=","<",">","&","|","^","!","~","?",":",",",".","(","[","{","as","in","of","new","typeof","keyof","extends","instanceof","satisfies","await","yield","void"].includes(Y),Ae=[".","?",":",")","]","}",",","+","-","*","/","%","<",">","=","&","|","^","`","(","[","as","satisfies","instanceof","in"].includes(v(G));if(!re&&!Ae)return G}G=(k.get(G)??G)+1}return _}function ue(T,j){for(let M=T;M<j;M++){if(v(M)==="["&&k.has(M)){M=k.get(M);continue}if(b[M].kind==="word")V.add(M)}}function fe(T){let j=k.get(T)??b.length,M=T+1;while(M<j){if(v(M)===";"){M++;continue}if(v(M)==="static"&&v(M+1)==="{"){M=(k.get(M+1)??M+1)+1;continue}let _=ge(M,j,!0);if(!_){M++;continue}let G=ie(M,j,!0);if(G===void 0){M++;continue}if(ue(M,G),v(G)==="("){let re=k.get(G),Ae=re===void 0?void 0:Ee(re,j);if(Ae!==void 0){M=(k.get(Ae)??Ae)+1;continue}}let Y=G;if(v(Y)===":")Y=oe(Y+1,T,!0);if(be(Y)==="="){ue(M,Y+1);let re=Y+1,Ae=oe(re,T);if(!_.isStatic&&Ae>re)B.set(re,Ae);M=Ae}else{let re=oe(G,T);ue(M,re),M=Math.max(M+1,re)}}}function pe(T){let j=W.get(T);if(j===void 0)return!1;let M=R.has(j);if(!M&&!A.has(j))return!1;if(I(j+1,T,M))return!0;for(let _=j+1;_<T;_++){let G=W.get(_),Y=W.get(_)===j&&(v(_)===","||M&&v(_)===";"),re=M&&v(_)==="}"&&G!==void 0&&W.get(G)===j,Ae=M&&W.get(_+1)===j&&/[\r\n]/.test(e.slice(b[_].end,b[_+1].start));if((Y||re||Ae)&&I(_+1,T,M))return!0}return!1}function Ee(T,j){let M=T+1,_=v(M)===":"?M+1:void 0;while(M<j){if(v(M)==="{"&&(_===void 0||!os(e.slice(b[_].start,b[M].start))))return M;if(_===void 0)return;M=(k.get(M)??M)+1}return}function xe(T,j){let M=-1;if(v(T)==="("){let G=k.get(T);if(G!==void 0&&pe(T))M=Ee(G,j)??-1;else if(G!==void 0&&be(G+1)==="=>")M=G+3;else if(G!==void 0&&v(G+1)===":"){let Y=G+2;while(Y<j&&v(Y)!==";"){if(be(Y)==="=>"){M=Y+2;break}Y=(k.get(Y)??Y)+1}}}else if(b[T]?.kind==="word"&&be(T+1)==="=>")M=T+3;else if(v(T)==="function"){let G=T+1;while(G<j&&v(G)!=="(")G=(k.get(G)??G)+1;let Y=k.get(G);if(Y===void 0)return;M=Y+1;let re=v(M)===":"?M+1:void 0;while(M<j){if(v(M)==="{"&&(re===void 0||!os(e.slice(b[re].start,b[M].start))))break;M=(k.get(M)??M)+1}}if(M<0||M>=j)return;if(v(M)==="{")return{start:T,end:(k.get(M)??j-1)+1};let _=M;while(_<j&&![",",";",")","]","}"].includes(v(_)))_=(k.get(_)??_)+1;return{start:T,end:_}}function Je(T,j,M=!0){for(let _=T;_<j;_++){let G=B.get(_);if(G!==void 0){_=Math.min(G,j)-1;continue}let Y=M?xe(_,j):void 0;if(Y){let Ae=Y.end;while(v(Ae)===")")Ae++;if(v(Ae)==="("||v(Ae)==="."&&["call","apply"].includes(v(Ae+1))&&v(Ae+2)==="(")Je(Y.start,Y.end,!1);_=Y.end-1;continue}let re=ke(_);if(re)re.binding.flow=void 0,re.binding.unresolved=!0}}function hi(T){let j=!1;while(X<b.length&&b[X].start<T){let M=v(X);if(["if","else","for","while","do","switch","try","catch","finally","with"].includes(M))j=!0;if(M===";")j=!1;if(M==="("||M==="{"||M==="["){let Y=k.get(X)??X+1;while(Y<b.length&&b[Y].start>=T)Y--;if(Je(X+1,Y),X=Y+1,M==="{")j=!1;continue}let _=ve(X);if(_){let Y=X+2,re=Y,Ae=[];while(re<b.length&&b[re].start<T){let ct=v(re);if(Ae.length===0&&(ct===";"||re>Y&&/[\r\n]/.test(e.slice(b[re-1].end,b[re].start))&&(ve(re)||["if","for","while","switch","try","do","return","throw"].includes(ct))))break;if(ct==="("||ct==="{"||ct==="[")Ae.push(ct==="("?")":ct==="{"?"}":"]");else if(ct===Ae.at(-1))Ae.pop();re++}let Ot=re>Y?e.slice(b[Y].start,b[re-1].end):"";Je(Y,re);let Ut=ae(Ot);_.flow=!j&&Ut.type?_.declared?$c(_.declared,Ut.type):Ut.type:void 0,_.unresolved=j||Ut.unresolved||!_.flow,X=re;continue}let G=ke(X);if(G)G.binding.flow=void 0,G.binding.unresolved=!0;X++}}for(let T of o){hi(T.start??0);let j=X;while(X<b.length&&b[X].start<(T.end??0))X++;if(T.kind!=="variable")continue;if(T.initializerStart!==void 0){let Ot=j;while(Ot<X&&b[Ot].start<T.initializerStart)Ot++;Je(Ot,X)}let M=n.get(T.name);if(!M.active)continue;let _=typeof T.value==="string"?T.value:"";if(!_){M.flow=M.declared;continue}let G=ae(_),Y=hn(_),re=Y?n.get(Y):void 0,Ae=c.get(T);if(Ae)T.inferredType=Ae,T.text=`${T.isExported?"export ":""}declare ${T.modifiers?.[0]??"const"} ${T.name}: ${Ae};`;else if(!T.typeAnnotation&&T.modifiers?.[0]==="const"&&Y&&Y!==T.name&&re){if(G.unresolved)T.inferenceError="DTSX_UNSUPPORTED_VALUE_FLOW";else if(G.type)T.inferredType=re.declared&&$s(re.declared,G.type)?`typeof ${Y}`:G.type,T.text=`${T.isExported?"export ":""}declare const ${T.name}: ${T.inferredType};`}if(T.typeAnnotation)M.flow=G.type?$c(T.typeAnnotation,G.type)??T.typeAnnotation:T.typeAnnotation;else if(T.inferredType)M.declared=T.inferredType,M.flow=T.inferredType;else{let Ot=T.modifiers?.[0]==="const",Ut=_.trim().startsWith("{")||_.trim().startsWith("["),ct=Te(_,Ot&&!Ut);M.declared=ct==="unknown"?void 0:ct,M.flow=M.declared}M.unresolved=G.unresolved}}var Sc=me(()=>{hr();ht();pr();Ei();vr()});function vp(e,t,i,r,n=""){let o=new Map,s={start:0,end:e.length,header:0,name:"",children:[],results:new Map},l=ce(e),a=[],f=[],u=[],d=new Map;for(let c=0;c<l.length;c++){let C=l[c];if(C.kind!=="punctuation")continue;let b=e.slice(C.start,C.end);if(b==="(")u.push(c);else if(b===")"){let v=u.pop();if(v!==void 0)d.set(c,v)}else if(b==="{")f.push(c);else if(b==="}"){let v=f.pop();if(v===void 0)continue;let k=l[v].start,W=v-1,A=W>=0?e.slice(l[W].start,l[W].end):"";if(A===")"){let R=d.get(W);if(R!==void 0&&R>0&&["if","for","while","switch","catch","with"].includes(e.slice(l[R-1].start,l[R-1].end)))k=l[R-1].start}else if(["else","try","finally","do"].includes(A))k=l[W].start;a.push({open:l[v].start,close:C.start,header:k})}}let h=0,p=(c,C=new Set)=>{let b=new Set(C),v=ce(e.slice(c.start,c.end)),k=0;for(let z=0;z+1<v.length;z++){let X=e.slice(c.start+v[z].start,c.start+v[z].end);if(X==="{")k++;else if(X==="}")k--;else if(!k&&["type","interface"].includes(X))b.add(e.slice(c.start+v[z+1].start,c.start+v[z+1].end))}let W="",A=c.start,R=[...c.results].map(([z,X])=>({type:z,name:X}));for(let z of c.children.sort((X,ae)=>X.header-ae.header)){let X=p(z,b);W+=e.slice(A,z.header)+`
|
|
105
|
-
declare namespace ${
|
|
106
|
-
${
|
|
107
|
+
${r}`}if(l)return`${Mp(l)}${r}`;return i+r}function Pc(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 Mc(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 Dc(e,t=!0){return Kt(e.leadingComments,t)+e.text}function Ic(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 Nc(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 Fc(e){let t=Ti.get(e);if(t)return Ti.delete(e),Ti.set(e,t),t;return null}function Wc(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 Lc=ye(()=>{Ti=new Map});function Ls(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=Ls(e);return t?e.lastIndexOf(" from ",t.start):-1}function Bn(e){let t=Ls(e);return t?hi(t.specifier,"'"):void 0}function Oi(e){let t=Fc(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 Wc(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=Ls(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();Lc()});function Bs(e,t){let i=(r)=>ue(r).map((n)=>r.slice(n.start,n.end)).join("");return i(e)===i(t)}function _c(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 Bc(e,t){if(Bs(e,t))return e;let i=_c(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)=>Bs(l,t));if(a)return a;if(s.includes(i))return i==="boolean"&&(t==="true"||t==="false")?t:i;return}function jc(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&&_c(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||!bs(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||!bs(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?Bc(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&&Bs(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?Bc(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 Gc=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)+`
|
|
108
|
+
declare namespace ${K.name} {
|
|
109
|
+
${te.text}
|
|
107
110
|
}
|
|
108
|
-
`,
|
|
111
|
+
`,S=K.end+1;for(let he of te.exports)O.push({type:`${K.name}.${he.name}`,name:he.name})}M+=`${e.slice(S,g.end)}
|
|
109
112
|
;
|
|
110
|
-
${
|
|
111
|
-
`)}`;let
|
|
112
|
-
`);return{declarations:
|
|
113
|
-
${
|
|
114
|
-
}`,moduleForm:"namespace",isExported:!1}),
|
|
115
|
-
`);return
|
|
116
|
-
${
|
|
117
|
-
}`,moduleForm:"namespace",isExported:!1,start:c,end:c}),`typeof ${
|
|
118
|
-
`,c),
|
|
119
|
-
`));continue}break}if(
|
|
120
|
-
`),
|
|
121
|
-
`);let
|
|
122
|
-
`)}function
|
|
123
|
-
`)){let
|
|
124
|
-
`,
|
|
125
|
-
`)===-1&&
|
|
126
|
-
`,
|
|
127
|
-
`))
|
|
128
|
-
|
|
129
|
-
`)
|
|
130
|
-
`)
|
|
131
|
-
|
|
132
|
-
|
|
113
|
+
${O.map((K)=>`export type ${K.name} = ${K.type};`).join(`
|
|
114
|
+
`)}`;let N=jn(M,t,!1);for(let K of O)b.add(K.name);let B=n?js(n).map((K,te)=>[K,`${m}_capture_${te}`]):[],ee=N.map((K)=>n&&["type","interface"].includes(K.kind)?Bp(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:O}},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),O="",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;O+=g.slice(N,S[B].start)+`(${ee})`,N=S[B+2].end,B+=2}return O+g.slice(N)}if(n){let M=js(n).join(", "),S=ue(g),O="",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;O+=`${g.slice(N,S[B+2].end)}<${M}>`,N=S[B+2].end,B+=2}g=O+g.slice(N)}let A=C.text;return r({kind:"module",name:m,text:`declare namespace ${m} {
|
|
116
|
+
${A}
|
|
117
|
+
}`,moduleForm:"namespace",isExported:!1}),g}}}function js(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 Bp(e,t,i,r){let n=new Set(js(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),O=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"||O===":"||O==="?"&&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}${O==="<"?", ":">"}`,c=O==="<"?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(_p(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 _p(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 Uc(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 Vp(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 Vs(e,t,i,!0)}function jn(e,t,i=!0,r){return Vs(e,t,i,!1,!1,r)}function Gs(e,t,i=!0){return Vs(e,t,i,!0,!0)}function Vs(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=[],O=[],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 T=[...h,...p.values()].filter((F)=>F.kind==="function"&&F.name===w[1]);if(T.length!==1||T[0].generics||vn(s,w[1])!==1)return;return T[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 T=x[1],F=T?v.slice(T.start,T.end):"",P=T?.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),Y=L.find((Q)=>Q.kind==="class");if(!Y)throw Error("Cannot extract the class expression declaration");if(ue(R.slice(Y.end??R.length)).some((Q)=>R.slice((Y.end??0)+Q.start,(Y.end??0)+Q.end)!==";"))return;let U=L.map((Q)=>Q.text.replace(/^export\s+/,"").replace(/^declare\s+/,"")).join(`
|
|
118
|
+
`);return g(E,{kind:"module",name:E,text:`declare namespace ${E} {
|
|
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 T=y.charCodeAt(E);if(w){if(T===Tt){E++;continue}if(T===w)w=0;continue}if(T===De||T===Ne||T===Xe){w=T;continue}if(T===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===Gp&&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 J(){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 k(){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 T=s.indexOf("*/",c+2);c=T===-1?f:T+2;continue}}break}let w=c>=f||z()||s.charCodeAt(c)===Ce;return c=v,w}function H(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),T=E.lastIndexOf("<");if(T!==-1&&/^<[A-Za-z]/.test(E.slice(T))&&!E.slice(T).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 q(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,T=x.length;while(E<T){let L=E+T>>>1;if(x[L].start<c)E=L+1;else T=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(H(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 T=s.charCodeAt(c+1);if(T===we){c=pe(c+2);continue}if(T===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 T=E.index,F=s.charCodeAt(T);if(F===De||F===Ne){c=T,G(F),x.lastIndex=c;continue}if(F===Xe){c=T,Z(),x.lastIndex=c;continue}if(F===we){if(c=T,J()){x.lastIndex=c;continue}x.lastIndex=T+1;continue}if(F===y)w++;else if(F===v){if(v===Ve&&T>0&&s.charCodeAt(T-1)===Ue){x.lastIndex=T+1;continue}if(w--,w===0)return c=T+1,c}x.lastIndex=T+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,T=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,J()){if(v===0&&w===0&&x===0&&E===0&&k())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||T)&&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 Y=z();if(c=L,Y)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 sh(){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),T=s.charCodeAt(x);if(E===se&&T===Ce||E===Ge&&T===Je||E===De&&T===De||E===Ne&&T===Ne||E===Xe&&T===Xe){c=w+1;return}}tt()}function ll(){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 cl(){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 T=fe(E,v+1);if(T.startsWith("//")){if(x)break;let F=[T];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 ah(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 T=fe(v,c),F=Wt(T).find((U)=>U.category==="static-import"),P=ue(T),I=E?.isTypeOnly??F?.isTypeOnly??!1,R=P[1]?.kind==="quoted",L=E?.source??F?.specifier??"",Y=vt(v);return{kind:"import",name:"",text:T,isExported:!1,isTypeOnly:I,isSideEffect:R,source:L,leadingComments:Y,start:v,end:c}}function Uo(){let y=c;return et(se,Ce),s.slice(y,c)}function fl(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,T=-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){T=I;break}}}if(T===-1)return y;let F=y.slice(v,T+1),P=Ni(F);return y.slice(0,v)+P+y.slice(T+1)}function ul(y){let v=y.indexOf("//")!==-1||y.indexOf("/*")!==-1,w=y.split(`
|
|
123
|
+
`),x=[],E=[],T=[],F=!1,P=1/0;for(let L=0;L<w.length;L++){let Y=w[L];if(v){if(F){if(Y.includes("*/"))F=!1;continue}let U=Y.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(Y);if(j.charCodeAt(j.length-1)===xe)j=j.slice(0,-1);j=fl(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}T.push(ie)}else{let U=Y.length;while(U>0&&(Y.charCodeAt(U-1)===lt||Y.charCodeAt(U-1)===ct||Y.charCodeAt(U-1)===ze))U--;if(U===0)continue;let Q=U<Y.length?Y.slice(0,U):Y;if(Q.charCodeAt(Q.length-1)===xe)Q=Q.slice(0,-1);Q=fl(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}T.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 Y=E[L];if(Y==="{"){R[L]=Y;continue}let U=T[L];if(U>P)R[L]=x[L];else if(U===P&&(Y.charCodeAt(0)===Ce||Y.charCodeAt(0)===Je||Y.charCodeAt(0)===Me))R[L]=x[L];else{let Q=Math.max(0,U-I);R[L]=" ".repeat(Q)+Y}}return R.join(`
|
|
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 T=v.charCodeAt(E);if(T===32||T===9||T===10||T===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 T=y.charCodeAt(E);if(w){if(v+=y[E],T===Tt&&E+1<y.length){v+=y[++E];continue}if(T===x)w=!1;continue}if(T===De||T===Ne||T===Xe){w=!0,x=T,v+=y[E];continue}if(T===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
|
+
`,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 Y=0;Y<v.length;Y++){let U=v.charCodeAt(Y);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 Y=!1;for(let U=0;U<_s.length;U++){let Q=_s[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)))){Y=!0;break}}}if(!Y)return y}}let w=[],x=0,E=0,T=!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(T){if(R===Tt){I++;continue}if(R===F)T=!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){T=!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 Y=!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(Y){if(ie===Tt){V++;continue}if(ie===U)Y=!1;continue}if(ie===De||ie===Ne||ie===Xe){Y=!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(dl(L))}return En(`(${P.join(", ")})`)}function lh(y){if(!y.startsWith("{")&&!y.startsWith("["))return y;let v="",w=0,x=0,E=!1,T=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===T)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,T=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
|
+
`))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 dl(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 _s)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,T=-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&&T===-1&&(j===0||v.charCodeAt(j-1)!==Ue)&&(j+1>=v.length||v.charCodeAt(j+1)!==Ue&&v.charCodeAt(j+1)!==Ve))T=j}}let R,L,Y=T!==-1;if(E!==-1&&(T===-1||E<T))if(R=v.slice(0,E).trim(),T!==-1)L=v.slice(E+1,T).trim();else L=v.slice(E+1).trim();else if(T!==-1){R=v.slice(0,T).trim();let j=w?null:Sr(R,v.slice(T+1));if(j)return An(j,hr);L=hr(v.slice(T+1).trim())}else R=v,L="unknown";if(R=lh(R),(R.startsWith("{")||R.startsWith("["))&&R.includes(`
|
|
132
|
+
`)){let j=R.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(j.length<=40)R=j;else R=R.split(`
|
|
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("?")||Y;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=ch(v);if(w!==null)return w;return ki(v)??"unknown"}function ch(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=fh(y,"+");if(v.length>1){let w=!1,x=!0,E=[];for(let T of v){let F=T.trim(),P=F.charCodeAt(0);if((P===De||P===Ne)&&Or(F,0,P)===F.length)w=!0,E.push(uh(F));else x=!1}if(x)return dh(E.join(""));if(w)return"string";return null}if(/^[\d\s()+*/%.\-]+$/.test(y)&&/\d/.test(y)&&/[+*/%\-\s]/.test(y))return"number";return null}function fh(y,v){let w=[],x=0,E="",T=0;while(T<y.length){let F=y.charCodeAt(T);if(F===De||F===Ne||F===Xe){let P=Or(y,T,F);E+=y.slice(T,P),T=P;continue}if(F===we&&(y.charCodeAt(T+1)===we||y.charCodeAt(T+1)===42)){if(y.charCodeAt(T+1)===we){let R=y.indexOf(`
|
|
135
|
+
`,T+2),L=R===-1?y.length:R;E+=y.slice(T,L),T=L;continue}let P=y.indexOf("*/",T+2),I=P===-1?y.length:P+2;E+=y.slice(T,I),T=I;continue}if(F===Ee||F===Ge||F===se)x++;else if(F===Me||F===Je||F===Ce)x--;if(y[T]===v&&x===0){w.push(E),E="",T++;continue}E+=y[T],T++}return w.push(E),w}function uh(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 dh(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),T=(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("&")||T("is")||T("extends")};c++,D();let v=c,w=0,x=v;while(c<f){let E=c;if(J()){if(s.charCodeAt(E)!==we)x=c;continue}let T=s.charCodeAt(c);if(T===Ee||T===Ge||T===_e)w++;else if(T===Me||T===Je||T===Ve&&!St())w--;else if(T===se)if(w>0)w++;else if(y())w++;else break;else if(T===Ce){if(w===0)break;w--}else if(w===0&&T===xe)break;if(w===0&&ge()&&!y())break;if(!it(T))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 T=me();if(!T&&!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=Lp(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 Y=Ni(P),U=`${v?x?"export default function ":"export declare function ":"declare function "}${T||(x?"":"default")}${F}${Y}: ${I};`,Q=vt(y),j={kind:"function",name:T||"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,hh=0;function hl(){Ko??=new Set(ue(s).filter((y)=>y.kind==="word").map((y)=>s.slice(y.start,y.end)));for(;;){let y=`__dtsx_binding_${hh++}`;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),T,F=c;if(E===se||E===Ge)et(E,E===se?Ce:Je),T=s.slice(F,c);let P=T?hl():me();if(!P)return tt(),x;D();let I,R,L,Y=!1;if(c<f&&s.charCodeAt(c)===It){c++,D();let be=c,ne=0;while(c<f){if(J()){if(ne===0&&k())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||!Vp(I)))sh();else{c++,D();let be=c;L=be;let ne=0,oe=0,ke;while(c<f){if(ne===0&&oe===0&&q(be,ke))break;if(J())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(Y=!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=T?"const":v,j=T?!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:Y?[Q,"const assertion"]:[Q],leadingComments:T?void 0:U,start:y,end:c};if(T)x.push(...jl({pattern:T,patternOffset:F,root:ie,kind:v,exported:w,comments:U,allocateName:hl}));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(J())continue;let Y=s.charCodeAt(c);if(Y===_e)L++;else if(Y===Ve&&!St())L--;else if(Y===se&&L===0)break;c++}E=fe(R,c)}D();let T=c<f&&s.charCodeAt(c)===se?Uo():"{}",F=ul(T),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,T=0;while(c<f){if(J())continue;let R=s.charCodeAt(c);if(R===Ee||R===se||R===Ge||R===_e)T++;else if(R===Me||R===Ce||R===Je||R===Ve&&!St())T--;else if(T===0&&R===xe)break;if(T===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 T=fe(y,c),F=vt(y);return{kind:"enum",name:x,text:T,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 T=Vt();D();let F="";if(W("extends")){c+=7,D();let Y=c,U=0;while(c<f){if(J())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(Y,c)}let P;if(W("implements")){c+=10,D();let Y=c,U=0;while(c<f){if(J())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(Y,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}${T}${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:T||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,T=!1,F=!1,P=!1,I=!1,R=!1,L=!1,Y=!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")){T=!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")){Y=!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(T)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(),mh(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();":` ${T?"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 ml("get",be,F,I,Y,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 ml("set",be,F,I,Y,ie);else{let ne=s.charCodeAt(c)===Ie;if(ne)c++,D();let oe=Zr();if(!oe){pl();continue}gl(oe,be,F,I,ne,P,Y,ie)}}for(let E of v.pending)E();return S.pop(),`{
|
|
133
137
|
${w.join(`
|
|
134
138
|
`)}
|
|
135
|
-
}`}function
|
|
136
|
-
${
|
|
139
|
+
}`}function Xo(y){return ht(y)||y===Ge||y===Vc||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===Vc)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 pl(){let y=0;while(c<f){if(J())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 ml(y,v,w,x,E,T){gl(y,v,w,x,!1,!1,E,T)}function gl(y,v,w,x,E,T,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 Y=c<f?s.charCodeAt(c):0;if(Y===Ee||Y===_e){let U=Y===_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(Y===It||Y===Ue||Y===xe||Y===Ce||Y===Fe||Y===ze){let U="";if(Y===It){c++,D();let be=c,ne=0;while(c<f){if(J())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(J())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(J())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"&&Uc(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?Fs(I,Q,U):"";P.push(`${ie}${v}${y}${V}: ${U};`)}else pl()}function ph(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 mh(y,v){let w=y.slice(1,-1).trim();if(!w)return;let x=[],E=0,T=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 Y=w.charCodeAt(R+1);if(Y===Ie){R+=2;while(R+1<w.length&&!(w.charCodeAt(R)===Ie&&w.charCodeAt(R+1)===we))R++;R++;continue}if(Y===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)T++;else if(L===Me||L===Ce||L===Je||L===Ve&&!(R>0&&w.charCodeAt(R-1)===Ue))T--;else if(L===Bt&&T===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 Y=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(!Y&&!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(Y){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=dl(V),oe=V.search(/[?:=]/);if(oe!==-1&&V.charCodeAt(oe)!==63&&ph(V))ne=ne.replace(/^([\w$]+)\?:/,"$1:");let ke="";if(a&&!Q&&oe!==-1&&V.charCodeAt(oe)===Ue){let $e=V.slice(oe+1);ke=Fs($c(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};O.push(E),N.push(E);let T=[];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")&&gh("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 Y=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);T.push(`${y}${I}function ${L}${Y}${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 Y="";if(c<f&&s.charCodeAt(c)===It){c++,D();let Q=c,j=0;while(c<f){if(J())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++}Y=fe(Q,c)}if(Y)E.annotatedValues.add(L);let U="";if(c<f&&s.charCodeAt(c)===Ue){c++,D();let Q=c,j=0;while(c<f){if(J())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(!Y&&U){let Q=Xr(U);if(Q)Y=Q;else if(R==="const")Y=zo(U);else Y=hr(U)}if(!Y)Y="unknown";T.push(`${y}${I}${R} ${L}: ${Y};`)}else if(W("interface")){c+=9,D();let R=me();D();let L=Vt();D();let Y="";if(W("extends")){c+=7,D();let Q=c,j=0;while(c<f){if(J())continue;let V=s.charCodeAt(c);if(V===_e)j++;else if(V===Ve&&!St())j--;else if(V===se&&j===0)break;c++}Y=fe(Q,c)}let U=ul(Uo());T.push(`${y}${I}interface ${R}${L}${Y?` extends ${Y}`:""} ${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 Y=c,U=0;while(c<f){if(J())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(Y,c);if(c<f&&s.charCodeAt(c)===xe)c++;T.push(`${y}${I}type ${R}${L} = ${Q}`)}}else if(W("class")){c+=5,D();let R=me();D();let L=Vt();D();let Y=c,U=0;while(c<f){if(J())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(Y,c),j=Q?` ${Q}`:"";if(E.bindings.set(R,"class"),F||E.ambient)E.exports.add(R);let V=Yo(R);T.push(`${y}${I}class ${R}${L}${j} ${V}`)}else if(W("enum")){c+=4,D();let R=me();D();let L=Uo();T.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 Y=Zo(y,L,P);T.push(`${y}${I}${R} ${L} ${Y}`)}else if(W("abstract"))if(c+=8,D(),W("class")){c+=5,D();let R=me();D();let L=Vt();D();let Y=c,U=0;while(c<f){if(J())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(Y,c),j=Q?` ${Q}`:"";if(E.bindings.set(R,"class"),F||E.ambient)E.exports.add(R);let V=Yo(R);T.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)T.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(),T.length===0)return"{}";return`{
|
|
140
|
+
${T.join(`
|
|
137
141
|
`)}
|
|
138
|
-
}`}function Yd(g,w){let y=c+g.length;while(y<f&&Ze(s.charCodeAt(y)))y++;for(let E=0;E<w.length;E++)if(y+E>=f||s.charCodeAt(y+E)!==w.charCodeAt(E))return!1;return y+w.length>=f||!He(s.charCodeAt(y+w.length))}function Oi(g,w,y){c+=y.length,O();let E="",x=s.charCodeAt(c);if(x===Re||x===Ie){let P=c;ae(x),E=s.slice(P,c)}else{E=ie();while(c<f&&s.charCodeAt(c)===_t)c++,E+=`.${ie()}`}O();let S=c<f&&s.charCodeAt(c)===ne?Lo():"{}",D=`${w?"export ":""}declare ${y} ${E} ${S}`,N=yt(g),F=E.startsWith("'")||E.startsWith('"');return{kind:"module",name:E,text:D,isExported:w,moduleForm:F?"quoted":y==="namespace"?"namespace":"identifier",source:F?E.slice(1,-1):void 0,leadingComments:N,start:g,end:c}}function Qa(g,w){re();let y=R(w,c);if(y.charCodeAt(y.length-1)===Ce)y=y.slice(0,-1).trimEnd();if(!y)return;let E=dt(y.charCodeAt(0));for(let P=1;E&&P<y.length;P++)E=He(y.charCodeAt(P));let x=yt(g);if(E){d.push({kind:"export",name:"default",text:`export default ${y};`,isExported:!0,isTypeOnly:!1,leadingComments:x,start:g,end:c});return}let S="__dtsx_default_export__",D=1;while(s.includes(S))S=`__dtsx_default_export_${D++}__`;let N=Gr(y)||k(y)||Te(y,!1),F=N==="unknown"&&Sp(y)?`typeof ${y}`:N;d.push({kind:"variable",name:S,text:`declare const ${S}: ${F};`,isExported:!1,typeAnnotation:F,modifiers:["const"],start:g,end:c}),d.push({kind:"export",name:"default",text:`export default ${S};`,isExported:!0,isTypeOnly:!1,leadingComments:x,start:g,end:c})}function el(){if(s.charCodeAt(c)===ne)return M(ne,he),!0;let g=I("if"),w=I("do"),y=I("try"),E=I("for");if(!g&&!w&&!y&&!E&&!I("while")&&!I("switch")&&!I("with"))return!1;if(ie(),O(),E&&I("await"))c+=5,O();if(!w&&!y&&s.charCodeAt(c)===$e)M($e,Me);if(zr(),O(),g&&I("else"))c+=4,zr();else if(w&&I("while")){if(c+=5,O(),s.charCodeAt(c)===$e)M($e,Me);if(O(),s.charCodeAt(c)===Ce)c++}else if(y){if(I("catch")){if(c+=5,O(),s.charCodeAt(c)===$e)M($e,Me);zr(),O()}if(I("finally"))c+=7,zr()}return!0}function zr(){if(O(),!el())re()}while(c<f){if(O(),c>=f)break;if(el())continue;let g=c,w=s.charCodeAt(c);if(w===105&&I("import"))d.push(jd(g));else if(w===101&&I("export")){c+=6,O();let y=s.charCodeAt(c);if(y===100&&I("default")){c+=7,O();let E=c,x=s.charCodeAt(c);if(x===102&&I("function")){let S=ri(g,!0,!1,!0);if(S)d.push(S)}else if(x===97&&I("async")&&Ur("async")!==Ce)if(c+=5,O(),I("function")){let S=ri(g,!0,!0,!0);if(S)d.push(S)}else Qa(g,E);else if(x===99&&I("class")){let S=ni(g,!0,!1,!0);d.push(S)}else if(x===97&&I("abstract")){if(c+=8,O(),I("class")){let S=ni(g,!0,!0,!0);d.push(S)}}else Qa(g,E)}else if(y===116&&I("type")){let E=c;if(c+=4,O(),c<f&&s.charCodeAt(c)===ne){Ot();let x=R(g,c),S=yt(g);d.push({kind:"export",name:"",text:x,isExported:!0,isTypeOnly:!0,source:ct(x),leadingComments:S,start:g,end:c})}else if(c<f&&s.charCodeAt(c)===We){Ut();let x=R(g,c);d.push({kind:"export",name:"",text:x,isExported:!0,isTypeOnly:!0,source:ct(x),start:g,end:c})}else{c=E;let x=Io(g,!0);d.push(x)}}else if(y===105&&I("interface")){let E=Do(g,!0);d.push(E)}else if(y===102&&I("function")){let E=ri(g,!0,!1,!1);if(E)d.push(E)}else if(y===97&&I("async"))if(c+=5,O(),I("function")){let E=ri(g,!0,!0,!1);if(E)d.push(E)}else re();else if(y===99)if(I("class")){let E=ni(g,!0,!1);d.push(E)}else if(I("const")){let E=c;if(c+=5,O(),I("enum")){c=E+5,O();let x=Ti(g,!0,!0);d.push(x)}else{c=E;let x=pi(g,"const",!0);for(let S=0;S<x.length;S++)d.push(x[S])}}else re();else if(y===97&&I("abstract")){if(c+=8,O(),I("class")){let E=ni(g,!0,!0);d.push(E)}}else if(y===108&&I("let")){let E=pi(g,"let",!0);for(let x=0;x<E.length;x++)d.push(E[x])}else if(y===118&&I("var")){let E=pi(g,"var",!0);for(let x=0;x<E.length;x++)d.push(E[x])}else if(y===101&&I("enum")){let E=Ti(g,!0,!1);d.push(E)}else if(y===100&&I("declare"))c+=7,O(),il(g,!0);else if(y===110&&I("namespace")&&K(9)){let E=Oi(g,!0,"namespace");d.push(E)}else if(y===109&&I("module")&&K(6)){let E=Oi(g,!0,"module");d.push(E)}else if(y===ne){Ot();let E=R(g,c),x=E.includes("export type"),S=yt(g);d.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:x,source:ct(E),leadingComments:S,start:g,end:c})}else if(y===We){Ut();let E=R(g,c),x=yt(g);d.push({kind:"export",name:"",text:E,isExported:!0,isTypeOnly:!1,source:ct(E),leadingComments:x,start:g,end:c})}else{re();let E=R(g,c);if(E)d.push({kind:"export",name:"",text:E,isExported:!0,start:g,end:c})}}else if(w===100&&I("declare"))c+=7,O(),il(g,!1);else if(w===105&&I("interface")){let y=Do(g,!1);h.set(y.name,y)}else if(w===116&&I("type")){let y=Io(g,!1);h.set(y.name,y),d.push(y)}else if(w===102&&I("function")){let y=ri(g,!1,!1,!1);if(y)A(y);else re()}else if(w===97)if(I("async")){let y=c;if(c+=5,O(),I("function")){let E=ri(g,!1,!0,!1);if(E)A(E);else c=y,re()}else c=y,re()}else if(I("abstract"))if(c+=8,O(),I("class")){let y=ni(g,!1,!1);h.set(y.name,y),d.push(y)}else re();else c++,re();else if(w===99)if(I("class")){let y=ni(g,!1,!1);h.set(y.name,y),d.push(y)}else if(I("const")){let y=c;if(c+=5,O(),I("enum")){c=y+5,O();let E=Ti(g,!1,!0);h.set(E.name,E),d.push(E)}else{c=y;let E=pi(g,"const",!1);for(let x=0;x<E.length;x++)h.set(E[x].name,E[x])}}else c++,re();else if(w===101&&I("enum")){let y=Ti(g,!1,!1);h.set(y.name,y),d.push(y)}else if(w===108&&I("let")||w===118&&I("var")){let y=I("let")?"let":"var",E=pi(g,y,!1);for(let x=0;x<E.length;x++)h.set(E[x].name,E[x])}else if(w===109&&I("module")&&K(6)){let y=Oi(g,!1,"module");d.push(y)}else if(w===110&&I("namespace")&&K(9)){let y=Oi(g,!1,"namespace");d.push(y)}else{let y=s.charCodeAt(c);if(y===Ce)c++;else if(y===Re||y===Ie){if(ae(y),c<f&&s.charCodeAt(c)===Ce)c++}else if(y===Ye){if(be(),c<f&&s.charCodeAt(c)===Ce)c++}else if(y===Ep){if(c++,ie(),O(),c<f&&s.charCodeAt(c)===_t)c++,ie(),O();if(c<f&&s.charCodeAt(c)===$e)M($e,Me)}else c++,re()}}if(m.size>0){tl(d);for(let g of p.values())tl(g)}if(fc(s,d,h,p),Nl(d,h),Al(d,h),!a)xc(s,d,h,o);if(n){let g=new Set(d);for(let w of[...h.values(),...[...p.values()].flat()])if(!g.has(w))d.push(w),g.add(w);return d.sort((w,y)=>(w.start??0)-(y.start??0))}if(h.size>0)kp(d,h,p);return d;function tl(g){let w=new Map;for(let E of g)if(E.kind==="function")w.set(E.name,(w.get(E.name)||0)+1);let y=new Set;for(let[E,x]of w)if(x>1)y.add(E);if(y.size>0){let E=new Set;for(let x of y)for(let S=g.length-1;S>=0;S--)if(g[S].kind==="function"&&g[S].name===x&&m.has(g[S])){E.add(S);break}if(E.size>0){let x=[...E].sort((S,D)=>D-S);for(let S of x)g.splice(S,1)}}}function il(g,w){if(I("function")){let y=ri(g,w,!1,!1);if(y)d.push(y)}else if(I("async")){if(c+=5,O(),I("function")){let y=ri(g,w,!0,!1);if(y)d.push(y)}}else if(I("class")){let y=ni(g,w,!1);d.push(y)}else if(I("abstract")){if(c+=8,O(),I("class")){let y=ni(g,w,!0);d.push(y)}}else if(I("interface")){let y=Do(g,w);d.push(y)}else if(I("type")){let y=Io(g,w);d.push(y)}else if(I("enum")){let y=Ti(g,w,!1);d.push(y)}else if(I("const")){let y=c;if(c+=5,O(),I("enum")){c=y+5,O();let E=Ti(g,w,!0);d.push(E)}else{c=y;let E=pi(g,"const",w);for(let x=0;x<E.length;x++)if(w||!u)d.push(E[x]);else h.set(E[x].name,E[x])}}else if(I("let")||I("var")){let y=I("let")?"let":"var",E=pi(g,y,w);for(let x=0;x<E.length;x++)if(w||!u)d.push(E[x]);else h.set(E[x].name,E[x])}else if(I("module")){let y=Oi(g,w,"module");d.push(y)}else if(I("namespace")){let y=Oi(g,w,"namespace");d.push(y)}else if(I("global")){c+=6,O();let y=`declare global ${c<f&&s.charCodeAt(c)===ne?Lo():"{}"}`,E=yt(g);d.push({kind:"module",name:"global",text:y,isExported:!1,moduleForm:"global",leadingComments:E,start:g,end:c})}else re()}}class Tc{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 l=e.charCodeAt(r);if(l>=65&&l<=90||l>=97&&l<=122||l>=48&&l<=57||l===95||l===36||l>127)r++;else break}if(this.firstUnits[o]===1&&this.lengths[Math.min(r-s,64)]===1){let l=e.substring(s,r),a=this.names.get(l);if(a!==void 0){if(t.add(l),a.kind==="function"||a.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===Re||r===Ie||r===Ye){let u=r;i++;while(i<e.length)if(e.charCodeAt(i)===Ct)i+=2;else if(e.charCodeAt(i++)===u)break;continue}if(r===de&&e.charCodeAt(i+1)===de){i+=2;while(i<e.length&&e.charCodeAt(i)!==Ne&&e.charCodeAt(i)!==Ge)i++;continue}if(r===de&&e.charCodeAt(i+1)===We){let u=e.indexOf("*/",i+2);i=u===-1?e.length:u+2;continue}if(!dt(r)){i++;continue}let n=i++;while(i<e.length&&He(e.charCodeAt(i)))i++;let o=n-1,s=i;while(o>=0&&Ze(e.charCodeAt(o)))o--;while(s<e.length&&Ze(e.charCodeAt(s)))s++;let l=o>=0?e.charCodeAt(o):0,a=s<e.length?e.charCodeAt(s):0,f=n>=3&&e.slice(n-3,n)==="...";if(a===At||l===_t&&!f)continue;if(a===$e&&(l===ne||l===Dt))continue;t.add(e.slice(n,i))}}function kp(e,t,i){let r=new Set,n=new Set;for(let u of e)n.add(u.name);let o=new Tc(t),s=new Set,l=new Set,a=(u)=>{if(o.scan(u.text,s))Il(u,l)},f=new Set;for(let u=0;u<e.length;u++){let d=e[u];if(d.kind!=="import"){if(a(d),typeof d.value==="string")kc(d.value,f)}}for(;;){let u=[];for(let[p,m]of t){if(r.has(p))continue;if((m.kind==="function"||m.kind==="variable"?l:s).has(p)||m.kind!=="function"&&f.has(p)){if(!n.has(p)){let c=m.kind==="function"?i.get(p):void 0;if(c)for(let C of c)u.push(C);else u.push(m);n.add(p)}r.add(p)}}if(u.length===0)break;u.sort((p,m)=>(p.start??1/0)-(m.start??1/0));let d=[],h=0;for(let p=0;p<e.length;p++){let m=e[p].start??1/0;while(h<u.length&&(u[h].start??1/0)<=m)d.push(u[h++]);d.push(e[p])}while(h<u.length)d.push(u[h++]);e.length=0;for(let p=0;p<d.length;p++)e.push(d[p]);for(let p of u)if(p.kind!=="import"){if(a(p),typeof p.value==="string")kc(p.value,f)}}}var Qe=32,et=9,Ne=10,Ge=13,de=47,We=42,Re=39,Ie=34,Ye=96,Ct=92,ne=123,he=125,$e=40,Me=41,Ve=91,qe=93,Fe=60,De=62,Ce=59,At=58,je=61,Dt=44,_t=46,Tn=63,Ac=35,Ep=64,xp=36,Es;var Rn=me(()=>{hr();ht();is();un();dn();pr();Fl();ls();vr();dc();An();Sc();Es=["public","protected","private","readonly","override"]});function Rc(e,t,i=!0,r=!1,n){if(Qr(t))e=rn(e);else if(on(t))e=sn(e);let o=sr(e),s=`${t}:${i?1:0}:${r?1:0}:${JSON.stringify([...n??[]].sort())}`,l=Ni.get(s);if(l&&l.contentHash===o)return l.lastAccess=++Oc,l.declarations;let a=r?$r(e,t,i):On(e,t,i,n);if(Ni.set(s,{declarations:a,contentHash:o,lastAccess:++Oc}),Ni.size>Tp){let f=Math.max(1,Math.ceil(Ni.size*0.1)),u=[];for(let[d,h]of Ni)u.push([d,h.lastAccess]);u.sort((d,h)=>d[1]-h[1]);for(let d=0;d<f&&d<u.length;d++)Ni.delete(u[d][0])}return a}var Tp=100,Oc=0,Ni;var Pc=me(()=>{nn();ts();jo();Rn();Ni=new Map});function Pn(e,t,i=!0,r=!1,n){return Rc(e,t,i,r,n)}var ks=me(()=>{Pc()});function Mn(e){let t=new Set,i=[];for(let o of e)if(o.kind==="import")for(let s of bi(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(Ii(o,!1))}}let r=i.join(`
|
|
139
|
-
`),n=new Set;for(let o=0;o<r.length;){if(!
|
|
140
|
-
`;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
|
|
141
|
-
`,
|
|
142
|
-
`){if(e[
|
|
143
|
-
`){let d=e[
|
|
144
|
-
`,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
|
|
145
|
-
`).map((h)=>h.trim()).filter((h)=>h.startsWith("///"))),!1;return!0});let s=o.text.replace(/;\s*$/,"").trim(),
|
|
146
|
-
`;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
|
|
147
|
-
`,u),C=
|
|
148
|
-
`){if(e[
|
|
149
|
-
`||!/\s/.test(m))h=m;u++}return f}function
|
|
150
|
-
export { ${
|
|
151
|
-
}`),
|
|
152
|
-
${
|
|
153
|
-
`)}`)}let
|
|
154
|
-
`));if(
|
|
142
|
+
}`}function gh(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 yl(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"&&Uc(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 wl(){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(),!wl())tt()}while(c<f){if(D(),c>=f)break;if(wl())continue;let y=c,v=s.charCodeAt(c);if(v===105&&W("import"))h.push(ah(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 yl(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 yl(y,x)}else if(w===116&&W("type")){let x=c;if(c+=4,D(),c<f&&s.charCodeAt(c)===se){ll();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){cl();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(),vl(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){ll();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){cl();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(),vl(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,Ns(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){Cl(h);for(let y of C.values())Cl(y)}if(kc(s,h,p,C),Zl(h,p),Vl(h,p),!l)jc(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 Cl(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 vl(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 Kc{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 zc(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 Kc(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))Xl(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")zc(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")zc(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,Vc=35,jp=64,Gp=36,_s;var Gn=ye(()=>{Bi();pt();Cn();Cs();bn();$r();Ql();Sn();xs();Es();Tr();Oc();Ln();Gc();_s=["public","protected","private","readonly","override"]});function qc(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=++Hc,a.declarations;let l=r?Rr(e,t,i):jn(e,t,i,n);if(zi.set(s,{declarations:l,contentHash:o,lastAccess:++Hc}),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,Hc=0,zi;var Jc=ye(()=>{hn();ms();ts();Gn();zi=new Map});function Vn(e,t,i=!0,r=!1,n){return qc(e,t,i,r,n)}var Us=ye(()=>{Jc()});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 zs=ye(()=>{Bi();Ln();Pi()});function Kp(e){if(!e.includes("declare")||!e.includes("module"))return[];return Wt(e).filter((t)=>t.category==="augmentation").map((t)=>t.specifier)}function Hp(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 Yc(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=Kp(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=Hp(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 O=s.get(A);if(!O)O=new Set,s.set(A,O);O.add(M.specifier)}if(!S.declarations.has(c))S.declarations.add(c),f=!0;c=A}}}}return s}var Xc=ye(()=>{gr();pt();Pi();Us();zs()});function Ki(e){return Zc[e]>=Zc[zn]}function Yp(){if(!Jp)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Xp(e,t){let i=Yp();if(e||i)return[`${i}${e}`,...t];return t}function Hi(e,t,i){let r=Xp(t,i);if(Qc){Qc(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 ef(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 ef(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 Ks(e){zn=e}var Zc,zn="info",qp="[dtsx]",Jp=!1,Qc=null,de;var Kn=ye(()=>{Zc={debug:0,info:1,warn:2,error:3,silent:4};de=ef(qp)});function tf(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 rf=()=>{};import{readFileSync as Zp,statSync as Qp}from"fs";import{readFile as em}from"fs/promises";import{createRequire as tm}from"module";import{dirname as Pr,isAbsolute as im,join as Hs,resolve as qs}from"path";function qi(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Hs(e,"tsconfig.json"));for(let i of t)try{if(Qp(i).isFile())return i}catch{}return null}function rm(e,t){if(im(e)||e.startsWith("."))return qi(qs(Pr(t),e));let i=tm(t),r=e.startsWith("@")?/^@[^/]+\/[^/]+/.exec(e)?.[0]:e.split("/")[0];if(r)for(let n of i.resolve.paths(r)??[]){let o=qi(Hs(n,r,"package.json"));if(!o)continue;let s=JSON.parse(Zp(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(qs(Pr(o),s.tsconfig));if(!l)throw Error(`Cannot resolve tsconfig ${JSON.stringify(s.tsconfig)} from ${o}`);return l}let a=qi(Hs(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(tf(await em(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=rm(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=qs(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 Js=ye(()=>{rf()});import{existsSync as Zs,readFileSync as Ys,realpathSync as Dr,statSync as nm}from"fs";import{builtinModules as om}from"module";import{dirname as Qs,extname as sm,isAbsolute as ea,join as sf,relative as af,resolve as Ji}from"path";function Hn(e){try{return nm(e).isFile()}catch{return!1}}function Yi(e,t){let i=e.replace(/[?#].*$/,"");if(!(i.startsWith("./")||i.startsWith("../")||i==="."||i==="..")&&!ea(i))return{resolved:null,isRelative:!1};let r=Qs(t),n=Ji(r,i);if(Hn(n))return{resolved:n,isRelative:!0};let o=sm(n),s=am[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 nf){let l=n+a;if(Hn(l))return{resolved:l,isRelative:!0}}if(Zs(n))for(let a of nf){let l=sf(n,`index${a}`);if(Hn(l))return{resolved:l,isRelative:!0}}return{resolved:null,isRelative:!0}}function lf(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 cf(e,t){if(Object.hasOwn(e,t))return e[t]!==null;let i=Object.keys(e).filter((r)=>r.includes("*")&&lf(r,t)).sort((r,n)=>n.indexOf("*")-r.indexOf("*")||n.length-r.length)[0];return i!==void 0&&e[i]!==null}function of(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 cf(r,i)}function Xs(e,t){let i=af(e,t);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!ea(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(Ys(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([...om,"bun"]),a=(f)=>{let u=Qs(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=sf(u,"package.json");if(Zs(h)){let m={...JSON.parse(Ys(h,"utf8")),directory:Dr(u)};for(let g of d)o.set(g,m);return m}let p=Qs(u);if(p===u)return;u=p}},l=(f,u)=>{if(f.startsWith(".")||ea(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&&(of(d,f)||cf(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])=>lf(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&&of(M,f)&&!M.private&&M.directory!==d?.directory)return{resolved:null,isRelative:!1};let S=Yi(A,u);if(!S.resolved)continue;let O=Dr(S.resolved),N=e.outputStructure==="flat"||Zs(n)&&Xs(Dr(n),O);if(!d||!Xs(d.directory,O)||!N||a(O)?.directory!==d.directory||/\.d\.(?:ts|mts|cts)$/.test(O))throw Error(`Local alias ${JSON.stringify(f)} from ${u} resolves outside its emitted package source: ${O}`);return de.debug(`Resolved local declaration alias ${f} from ${u} to ${O}`),{resolved:e.outputStructure==="flat"?S.resolved:Ji(n,af(Dr(n),O)),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&&Xs(d.directory,Dr(u))},l.cacheKey=(f)=>{let u=f.map((h)=>({file:h,references:Mi(Ys(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 ff(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 nf,am;var Jn=ye(()=>{gr();Kn();pt();Js();nf=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],am={".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 ta(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 cm(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(fm(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
|
+
`,a);a=d===-1?l:d;continue}if(u==="'"||u==='"'){a++;while(a<l&&e[a]!==u&&e[a]!==`
|
|
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 fm(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 uf(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 dm(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?Gs(t,e).map((o)=>({text:o.text,comments:[...o.leadingComments??[]]})):cm(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 uf(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 uf(l[1]))r.localExports.set(d.exported,d.local);continue}if(l=s.match(/^export\s+default\s+([\w$]+)$/),l&&lm.test(l[1])){r.localExports.set("default",l[1]);continue}let f=ta(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(um);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:dm(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=Gs(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
|
+
`;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
|
+
`,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
|
+
`){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 df(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}`,J=h.get(ae);if(!J)J=u(Z),h.set(ae,J);return J},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 J=S(ae).get(Z);if(!J&&!c)n.push(`${Di(r.cwd,X.file)}: '${Z}' is not exported by '${G}'`);return J??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 J=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)??[])J.add(me)}else if(l(le))n.push(`${Di(r.cwd,X)}: '${le}' is not part of the bundle`);else J.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,J),Z}for(let[X,G]of o)for(let Z of G.augmentations){let ae=a(Z.specifier,X);if(!ae)continue;for(let J of Yn(X,Z.body,!0).declared){if(S(ae).has(J))continue;let le=b.get(ae);if(!le)le=new Map,b.set(ae,le);le.set(J,{kind:"local",name:u(J)}),m.clear()}}c=!1,m.clear(),g.clear();let O=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=O.get(X);if(Z)return Z;let ae=u(G);O.set(X,ae);let J=[];for(let[le,ve]of S(X)){if(le==="default")continue;let me=B(ve,le);J.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 { ${J.join(", ")} };
|
|
155
|
+
}`),ae}let K=[],te=[],he=new Set;for(let[X,G]of o){for(let J of G.directives)he.add(J);let Z=new Map;for(let[J,le]of d.get(X))if(J!==le)Z.set(J,le);for(let[J,le]of G.imports){if(G.declared.has(J))continue;let ve=A(G,le.specifier,le.imported);if(!ve)continue;let me=B(ve,J);if(me!==J)Z.set(J,me)}let ae=[];for(let J of G.declarations){if(r.keepComments)ae.push(...J.statement.comments);let le=Nr(J.emit,Z);if(!/[;}]$/.test(le))le+=";";ae.push(le)}for(let J of G.verbatim){if(r.keepComments)te.push(...J.comments);let le=ta(J.text);if(le){let ve=new Map(Z);for(let me of Yn(X,le.body,!0).declared)ve.delete(me);te.push(J.text.slice(0,le.start)+Nr(le.body,ve)+J.text.slice(le.end))}else{let ve=ue(J.text),me=ve[1]?.kind==="quoted"?$t(J.text.slice(ve[1].start,ve[1].end)):void 0;if(me===void 0||!a(me,X))te.push(Nr(J.text,Z))}}for(let J of G.augmentations){let le=a(J.specifier,X),ve=Yn(X,J.body,!0),me=new Map(Z);if(!le){for(let Qe of ve.declared)me.delete(Qe);let W=ta(J.statement.text);if(r.keepComments)te.push(...J.statement.comments);te.push(J.statement.text.slice(0,W.start)+Nr(W.body,me)+J.statement.text.slice(W.end));continue}for(let[W,Qe]of S(le))me.set(W,B(Qe,W));if(r.keepComments)ae.push(...J.statement.comments);for(let W of ve.declarations){if(!W.name||!S(le).has(W.name))throw Error(`Cannot link augmentation '${J.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
|
+
${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"),J=re.get(Z)??{named:[],defaults:[],namespaces:[]};if(re.set(Z,J),ae==="*")J.namespaces.push(G);else if(ae==="default")J.defaults.push(G);else J.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
|
+
`));if(D.push(`/**
|
|
155
159
|
* Bundled TypeScript declarations
|
|
156
160
|
* Generated from ${o.size} source files
|
|
157
|
-
*/`),
|
|
158
|
-
`));if(
|
|
159
|
-
`));if(
|
|
160
|
-
`));let
|
|
161
|
-
`)),{content:`${
|
|
161
|
+
*/`),pe.length>0)D.push(pe.join(`
|
|
162
|
+
`));if(D.push(...K),N.length>0)D.push(N.join(`
|
|
163
|
+
`));if(te.length>0)D.push(te.join(`
|
|
164
|
+
`));let qe=[];if(Se.length>0)qe.push(`export { ${Se.join(", ")} };`);if(qe.push(...fe),qe.length===0)qe.push("export {};");return D.push(qe.join(`
|
|
165
|
+
`)),{content:`${D.join(`
|
|
162
166
|
|
|
163
167
|
`)}
|
|
164
|
-
`,files:[...o.keys()],exportCount:be.size,warnings:n}}var zp,qp;var qc=me(()=>{ht();pr();Rn();Ei();Wn();zp=/^[A-Z_$][\w$]*$/i;qp=/^(?: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 Yp from"process";import{existsSync as Jc,statSync as Yc}from"fs";import{resolve as Or}from"path";import Xp from"process";import{existsSync as Xw,mkdirSync as Zw,readdirSync as Qw,readFileSync as Zp,writeFileSync as eC}from"fs";import{homedir as ji}from"os";import{dirname as rC,resolve as jt}from"path";import yo from"process";import{existsSync as Xc,statSync as Zc}from"fs";import{existsSync as oa,mkdirSync as Qp,readdirSync as em,writeFileSync as tm}from"fs";import{homedir as Gi}from"os";import{dirname as Qc,resolve as gt}from"path";import Ai from"process";import{join as im,relative as rm,resolve as ef}from"path";import ro from"process";import{existsSync as Lf,mkdirSync as hC,readdirSync as pC,writeFileSync as mC}from"fs";import{homedir as Bs}from"os";import{dirname as wC,resolve as mt}from"path";import Mr from"process";import{join as nm,relative as om,resolve as tf}from"path";import no from"process";import{existsSync as Bf,mkdirSync as EC,readdirSync as xC,writeFileSync as SC}from"fs";import{dirname as kC,resolve as oo}from"path";import sa from"process";import{Buffer as si}from"buffer";import{createCipheriv as sm,createDecipheriv as am,randomBytes as _s}from"crypto";import{closeSync as js,createReadStream as rf,createWriteStream as lm,existsSync as Gs,fsyncSync as nf,openSync as of,writeFileSync as cm}from"fs";import{access as fm,constants as sf,mkdir as um,readdir as Bn,rename as af,stat as Vi,unlink as _n,writeFile as Vs}from"fs/promises";import{join as Ui}from"path";import st from"process";import{pipeline as dm}from"stream/promises";import{createGzip as lf}from"zlib";import zi from"process";import Yt from"process";import{Buffer as Ht}from"buffer";import{createCipheriv as hm,createDecipheriv as pm,randomBytes as Us}from"crypto";import{closeSync as zs,createReadStream as cf,createWriteStream as mm,existsSync as jn,fsyncSync as ff,openSync as uf,writeFileSync as gm}from"fs";import{access as ym,constants as df,mkdir as wm,readdir as Gn,rename as hf,stat as Ki,unlink as Vn,writeFile as Ks}from"fs/promises";import{isAbsolute as Cm,join as Hi,resolve as vm}from"path";import Le from"process";import{pipeline as bm}from"stream/promises";import{createGzip as pf}from"zlib";import qi from"process";import Xt from"process";import Un from"process";import{existsSync as zn}from"fs";import{resolve as Hs}from"path";import{existsSync as $m}from"fs";import{existsSync as Em,readdirSync as xm}from"fs";import{extname as qs,resolve as mf}from"path";import Sm from"process";import{join as Am,relative as km,resolve as gf}from"path";import so from"process";import{Buffer as qt}from"buffer";import{createCipheriv as Tm,createDecipheriv as Om,randomBytes as Js}from"crypto";import{closeSync as Ys,createReadStream as yf,createWriteStream as Rm,existsSync as Kn,fsyncSync as wf,openSync as Cf,writeFileSync as Pm}from"fs";import{access as Mm,constants as vf,mkdir as Dm,readdir as Hn,rename as bf,stat as Ji,unlink as qn,writeFile as Xs}from"fs/promises";import{isAbsolute as Im,join as Yi,resolve as Nm}from"path";import Be from"process";import{pipeline as Fm}from"stream/promises";import{createGzip as $f}from"zlib";import Xi from"process";import Zt from"process";import Jn from"process";import{readFileSync as Wm,realpathSync as Lm}from"fs";import{createRequire as Bm}from"module";import{pathToFileURL as _m}from"url";import{existsSync as Zs,statSync as jm}from"fs";import{resolve as Ef}from"path";import{existsSync as Gm}from"fs";class _f{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(!Jc(e))return!0;return Yc(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=Jc(i)?Yc(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 jf{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 Vf(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 Vm(e){return Vf(e).flatMap((t)=>Gf.map((i)=>Or(e.directory,`${t}${i}`)))}function Um(e={}){let t=Or(e.cwd||Xp.cwd());return Array.from(new Set([t,Or(t,"config"),Or(t,".config"),e.configDir?Or(t,e.configDir):void 0].filter((i)=>Boolean(i))))}function Hm(e,t){this[e]=Km.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(!Xc(e))return!0;return Zc(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=Xc(i)?Zc(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 Ca{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 Ym(e,t={}){let i=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return i?`${e}:${i}`:e}function Xm(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Zm(e){return e.getStats().size*2}function va(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Ke(t[0])&&"id"in t[0]&&t[0].id===3&&Ke(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Ke(t)&&Ke(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(Ke(e)&&"arr"in e&&Array.isArray(e.arr)&&Ke(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Ke(t[0])&&Ke(e[0])){let r=[...t];for(let n of e)if(Ke(n)&&"name"in n){if(!r.find((o)=>Ke(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(Ke(n)&&"path"in n){if(!r.find((o)=>Ke(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>lo(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(!Ke(t)||!Ke(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(Ke(n)&&Ke(i[r]))i[r]=va(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&Ke(n[0])&&Ke(i[r][0])){let o=[...n];for(let s of i[r])if(Ke(s)&&"name"in s){if(!o.find((l)=>Ke(l)&&("name"in l)&&l.name===s.name))o.push(s)}else if(Ke(s)&&"path"in s){if(!o.find((l)=>Ke(l)&&("path"in l)&&l.path===s.path))o.push(s)}else if(!o.some((l)=>lo(l,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 lo(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(!lo(e[i],t[i]))return!1;return!0}if(Ke(e)&&Ke(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(!lo(e[n],t[n]))return!1}return!0}return!1}function Ke(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Qm(e,t){if(!Bf(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 va(t,r)}catch{return null}}catch{return null}}async function eg({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 l of n){let a=oo(r,`${s}${l}`),f=await Qm(a,i);if(f!==null)return f}try{let s=oo(r,"package.json");if(Bf(s)){let l=(await import(s))[e];if(l&&typeof l==="object"&&!Array.isArray(l))try{return va(i,l)}catch{}}}catch{}return i}function tg(e,t={}){let i=no.cwd();while(i.includes("storage"))i=tf(i,"..");let r=tf(i,e||"");if(t?.relative)return om(no.cwd(),r);return r}async function ig(){try{let e=await eg({name:"clarity",defaultConfig:Qn,cwd:no.cwd(),endpoint:"",headers:{}});return{...Qn,...e}}catch{return Qn}}function Xe(){if(Yt.env.NODE_ENV==="test"||Yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function rg(){if(Yt.env.NODE_ENV==="test"||Yt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Yt<"u"){let e=Yt.type;if(e==="renderer"||e==="worker")return!1;return!!(Yt.versions&&(Yt.versions.node||Yt.versions.bun))}return!1}class zf{async format(e){let t=await rg(),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:zi.pid,hostname:t(),environment:zi.env.NODE_ENV||"development",platform:zi.platform,version:zi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:zi.env.NODE_ENV||zi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class co{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={...la},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new zf,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??st.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{...eo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...eo};return{...eo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:la.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 fm(this.config.logDirectory,sf.F_OK|sf.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await um(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:si.from(e);try{if(!Gs(this.currentLogFile))await Vs(this.currentLogFile,"",{mode:420});if(r=of(this.currentLogFile,"a",420),cm(r,l,{flag:"a"}),nf(r),r!==void 0)js(r),r=void 0;if((await Vi(this.currentLogFile)).size===0){if(await Vs(this.currentLogFile,l,{flag:"w",mode:420}),(await Vi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let f=a;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{js(r)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(l){if(n===o-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}n++;let a=s*2**(n-1);await new Promise((f)=>setTimeout(f,a))}})();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 Ui(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 Ui(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ui(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Xe())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],[,l])=>l.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 _s(16).toString("hex")}generateKey(){return _s(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=_s(16),r=sm("aes-256-gcm",t,i),n=si.concat([r.update(e,"utf8"),r.final()]),o=r.getAuthTag();return{encrypted:si.concat([i,n,o]),iv:i}}async compressData(e){return new Promise((t,i)=>{let r=lf(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(si.from(si.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(Xe())return;let e=await Vi(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 Bn(this.config.logDirectory),o=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,f)=>{let u=Number.parseInt(a.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,l=`${i}.${s}`;if(await Vi(i).catch(()=>null))try{if(await af(i,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await _n(l)}catch(a){console.error("Error compressing rotated file:",a)}if(o.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${i}.1`;await Vs(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await Vi(i).catch(()=>null))await af(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await Bn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await _n(Ui(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=rf(e),r=lm(t),n=lf();await dm(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()})),Gs(this.currentLogFile))try{let e=of(this.currentLogFile,"r+");nf(e),js(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(!Xe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Bn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await _n(Ui(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?Ue.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,l=(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 a=st.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} ${Ue.cyan(n)}`;if(!s)return f.trim();let u=l(f).trim().length,d=l(t).length,h=Math.max(1,a-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 l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):o});let i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let l=t[r++];switch(s){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 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,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,i);if(this.fancy&&!Xe()){let f=tu[e],u=this.options.showTags!==!1&&this.name?Ue.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:Ue.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:Ue.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),l){let h=l.split(`
|
|
165
|
-
`);for(let p of h)if(p.trim()&&!p.includes(s))console.error(this.formatConsoleMessage({timestamp:n,message:
|
|
166
|
-
`;if(l
|
|
167
|
-
`;
|
|
168
|
-
`,
|
|
169
|
-
`),s=Math.max(...o.map((u)=>u.length))+2,
|
|
170
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(
|
|
171
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(e,t=""){if(!this.enabled||!this.fancy||
|
|
172
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Xe()||!st.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(Xe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Bn(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=Ui(this.config.logDirectory,r);if(e.before)try{if((await Vi(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 _n(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 Zn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&_e(t[0])&&"id"in t[0]&&t[0].id===3&&_e(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(_e(t)&&_e(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(_e(e)&&"arr"in e&&Array.isArray(e.arr)&&_e(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&_e(t[0])&&_e(e[0])){let r=[...t];for(let n of e)if(_e(n)&&"name"in n){if(!r.find((o)=>_e(o)&&("name"in o)&&o.name===n.name))r.push(n)}else if(_e(n)&&"path"in n){if(!r.find((o)=>_e(o)&&("path"in o)&&o.path===n.path))r.push(n)}else if(!r.some((o)=>fo(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(!_e(t)||!_e(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(_e(n)&&_e(i[r]))i[r]=Zn(i[r],n);else if(Array.isArray(n)&&Array.isArray(i[r]))if(n.length>0&&i[r].length>0&&_e(n[0])&&_e(i[r][0])){let o=[...n];for(let s of i[r])if(_e(s)&&"name"in s){if(!o.find((l)=>_e(l)&&("name"in l)&&l.name===s.name))o.push(s)}else if(_e(s)&&"path"in s){if(!o.find((l)=>_e(l)&&("path"in l)&&l.path===s.path))o.push(s)}else if(!o.some((l)=>fo(l,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:Zn(e,t);if(Array.isArray(e))return i==="replace"?t:Zn(e,t);if(!_e(t)||!_e(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]=Zn(s,o);else if(_e(o)&&_e(s))r[n]=ba(s,o,i);else r[n]=o}return r}function fo(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(!fo(e[i],t[i]))return!1;return!0}if(_e(e)&&_e(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(!fo(e[n],t[n]))return!1}return!0}return!1}function _e(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Yn(e,t,i="replace"){if(!Lf(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 ng(e,t,i=!1){if(!e)return t;let r=e.toUpperCase().replace(/-/g,"_"),n={...t};function o(s,l=[]){let a={...s};for(let[f,u]of Object.entries(s)){let d=[...l,f],h=(c)=>c.replace(/([A-Z])/g,"_$1").toUpperCase(),p=`${r}_${d.map(h).join("_")}`,m=`${r}_${d.map((c)=>c.toUpperCase()).join("_")}`;if(i)lt.info(`Checking environment variable ${p} for config ${e}.${d.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[f]=o(u,d);else{let c=Mr.env[p]||Mr.env[m];if(c!==void 0){if(i)lt.info(`Using environment variable ${c?p:m} for config ${e}.${d.join(".")}`);if(typeof u==="number")a[f]=Number(c);else if(typeof u==="boolean")a[f]=c.toLowerCase()==="true";else if(Array.isArray(u))try{let C=JSON.parse(c);if(Array.isArray(C))a[f]=C;else a[f]=c.split(",").map((b)=>b.trim())}catch{a[f]=c.split(",").map((C)=>C.trim())}else a[f]=c}}}return a}return o(n)}async function og({name:e="",alias:t,cwd:i,configDir:r,defaultConfig:n,verbose:o=!1,checkEnv:s=!0,arrayStrategy:l="replace"}){let a=s&&typeof n==="object"&&n!==null&&!Array.isArray(n)?ng(e,n,o):n,f=i||Mr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)lt.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`]:[],c=Array.from(new Set([f,mt(f,"config"),mt(f,".config"),r?mt(f,r):void 0].filter(Boolean)));for(let C of c){if(o)lt.info(`Searching for configuration in: ${C}`);let b=[mt(f,"config"),mt(f,".config")].concat(r?[mt(f,r)]:[]).includes(C)?[...d,...h,...p,...m]:[...h,...d,...m,...p];for(let v of b)for(let k of u){let W=mt(C,`${v}${k}`),A=await Yn(W,a,l);if(A!==null){if(o)lt.success(`Configuration loaded from: ${W}`);return A}}}if(e){let C=mt(Bs(),".config",e),b=["config",`${e}.config`];if(t)b.push(`${t}.config`);if(o)lt.info(`Checking user config directory: ${C}`);for(let v of b)for(let k of u){let W=mt(C,`${v}${k}`),A=await Yn(W,a,l);if(A!==null){if(o)lt.success(`Configuration loaded from user config directory: ${W}`);return A}}}if(e){let C=mt(Bs(),".config"),b=[`.${e}.config`];if(t)b.push(`.${t}.config`);if(o)lt.info(`Checking user config directory for dotfile configs: ${C}`);for(let v of b)for(let k of u){let W=mt(C,`${v}${k}`),A=await Yn(W,a,l);if(A!==null){if(o)lt.success(`Configuration loaded from user config directory dotfile: ${W}`);return A}}}if(e){let C=Bs(),b=[`.${e}.config`,`.${e}`];if(t)b.push(`.${t}.config`),b.push(`.${t}`);if(o)lt.info(`Checking user home directory for dotfile configs: ${C}`);for(let v of b)for(let k of u){let W=mt(C,`${v}${k}`),A=await Yn(W,a,l);if(A!==null){if(o)lt.success(`Configuration loaded from user home directory: ${W}`);return A}}}try{let C=mt(f,"package.json");if(Lf(C)){let b=await import(C),v=b[e];if(!v&&t){if(v=b[t],v&&o)lt.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(o)lt.success(`Configuration loaded from package.json: ${v===b[e]?e:t}`);return ba(a,v,l)}catch(k){if(o)lt.warn("Failed to merge package.json config:",k)}}}catch(C){if(o)lt.warn("Failed to load package.json:",C)}if(o)lt.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function sg(e,t={}){let i=ro.cwd();while(i.includes("storage"))i=ef(i,"..");let r=ef(i,e||"");if(t?.relative)return rm(ro.cwd(),r);return r}async function ag(){try{let e=await og({name:"clarity",alias:"logging",defaultConfig:to,cwd:ro.cwd()});return{...to,...e||{}}}catch{return to}}function tt(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lg(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Xt<"u"){let e=Xt.type;if(e==="renderer"||e==="worker")return!1;return!!(Xt.versions&&(Xt.versions.node||Xt.versions.bun))}return!1}class Kf{async format(e){let t=await lg(),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:qi.pid,hostname:t(),environment:qi.env.NODE_ENV||"development",platform:qi.platform,version:qi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qi.env.NODE_ENV||qi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class uo{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={...ca},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Kf,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},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{...io,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...io};return{...io,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ca.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!tt()&&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,df.F_OK|df.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await wm(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ht.from(e);try{if(!jn(this.currentLogFile))await Ks(this.currentLogFile,"",{mode:420});if(r=uf(this.currentLogFile,"a",420),gm(r,l,{flag:"a"}),ff(r),r!==void 0)zs(r),r=void 0;if((await Ki(this.currentLogFile)).size===0){if(await Ks(this.currentLogFile,l,{flag:"w",mode:420}),(await Ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let f=a;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{zs(r)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(l){if(n===o-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}n++;let a=s*2**(n-1);await new Promise((f)=>setTimeout(f,a))}})();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 Hi(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 Hi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Hi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(tt())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],[,l])=>l.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 Us(16).toString("hex")}generateKey(){return Us(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=Us(16),r=hm("aes-256-gcm",t,i),n=Ht.isBuffer(e)?e:Ht.from(e,"utf8"),o=r.update(n),s=r.final(),l=o.length+s.length,a=r.getAuthTag(),f=Ht.allocUnsafe(16+l+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),a.copy(f,16+l),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=pf(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(Ht.from(Ht.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(tt())return;if(!this.shouldWriteToFile())return;let e=await Ki(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 Gn(this.config.logDirectory),o=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,f)=>{let u=Number.parseInt(a.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,l=`${i}.${s}`;if(await Ki(i).catch(()=>null))try{if(await hf(i,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await Vn(l)}catch(a){console.error("Error compressing rotated file:",a)}if(o.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${i}.1`;await Ks(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await Ki(i).catch(()=>null))await hf(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await Gn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await Vn(Hi(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=cf(e),r=mm(t),n=pf();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()})),jn(this.currentLogFile))try{let e=uf(this.currentLogFile,"r+");ff(e),zs(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(!tt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Gn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Vn(Hi(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()?Oe.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||tt())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,l=(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 a=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} ${Oe.cyan(n)}`;if(!s)return f.trim();let u=l(f).trim().length,d=l(t).length,h=Math.max(1,a-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 l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):o});let i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let l=t[r++];switch(s){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 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=Oe.underline(Oe.blue(r)),s=this.toAbsoluteFilePath(n);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(s)}`,a="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\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)=>Oe.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(i,r)=>Oe.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(i,r)=>Oe.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(i,r)=>Oe.italic(r)),t=t.replace(/~([^~]+)~/g,(i,r)=>Oe.strikethrough(r)),t}supportsHyperlinks(){if(tt())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(Cm(t)||t.startsWith("./")||t.startsWith("../"))t=vm(t);else return null;return jn(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,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,i);let{consoleText:a,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":iu[e],h=this.options.showTags!==!1&&this.name?Oe.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Oe.gray(a),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:a,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Oe.green(a),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:a,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:a,level:e}),console.error(p),l){let m=l.split(`
|
|
173
|
-
`);for(let
|
|
174
|
-
`;if(
|
|
175
|
-
`;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()&&!
|
|
176
|
-
`);if(this[o==="warning"?"warn":o](n),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
177
|
-
`,
|
|
178
|
-
`),
|
|
179
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(
|
|
180
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
181
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
168
|
+
`,files:[...o.keys()],exportCount:Ae.size,warnings:n}}var lm,um;var hf=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 pf,statSync as mf}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 gf,statSync as yf}from"fs";import{existsSync as $a,mkdirSync as gm,readdirSync as ym,writeFileSync as wm}from"fs";import{homedir as Zi}from"os";import{dirname as wf,resolve as Ct}from"path";import Ii from"process";import{join as Cm,relative as vm,resolve as Cf}from"path";import go from"process";import{existsSync as iu,mkdirSync as GC,readdirSync as VC,writeFileSync as UC}from"fs";import{homedir as ia}from"os";import{dirname as HC,resolve as wt}from"path";import _r from"process";import{join as bm,relative as $m,resolve as vf}from"path";import yo from"process";import{existsSync as ru,mkdirSync as ZC,readdirSync as QC,writeFileSync as ev}from"fs";import{dirname as iv,resolve as wo}from"path";import xa from"process";import{Buffer as pi}from"buffer";import{createCipheriv as xm,createDecipheriv as Sm,randomBytes as ra}from"crypto";import{closeSync as na,createReadStream as bf,createWriteStream as Em,existsSync as oa,fsyncSync as $f,openSync as xf,writeFileSync as Am}from"fs";import{access as km,constants as Sf,mkdir as Tm,readdir as Xn,rename as Ef,stat as Qi,unlink as Zn,writeFile as sa}from"fs/promises";import{join as er}from"path";import ft from"process";import{pipeline as Om}from"stream/promises";import{createGzip as Af}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 aa}from"crypto";import{closeSync as la,createReadStream as kf,createWriteStream as Mm,existsSync as Qn,fsyncSync as Tf,openSync as Of,writeFileSync as Dm}from"fs";import{access as Im,constants as Rf,mkdir as Nm,readdir as eo,rename as Pf,stat as ir,unlink as to,writeFile as ca}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 Mf}from"zlib";import nr from"process";import ni from"process";import io from"process";import{existsSync as ro}from"fs";import{resolve as fa}from"path";import{existsSync as Bm}from"fs";import{existsSync as _m,readdirSync as jm}from"fs";import{extname as ua,resolve as Df}from"path";import Gm from"process";import{join as Vm,relative as Um,resolve as If}from"path";import Co from"process";import{Buffer as ti}from"buffer";import{createCipheriv as zm,createDecipheriv as Km,randomBytes as da}from"crypto";import{closeSync as ha,createReadStream as Nf,createWriteStream as Hm,existsSync as no,fsyncSync as Ff,openSync as Wf,writeFileSync as qm}from"fs";import{access as Jm,constants as Lf,mkdir as Ym,readdir as oo,rename as Bf,stat as or,unlink as so,writeFile as pa}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 _f}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 ma,statSync as ng}from"fs";import{resolve as jf}from"path";import{existsSync as og}from"fs";class nu{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(!pf(e))return!0;return mf(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=pf(i)?mf(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 ou{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 au(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 au(e).flatMap((t)=>su.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 Na{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 Fa{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 Wa(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]=Wa(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(!ru(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 Wa(t,r)}catch{return null}}catch{return null}}async function yg({name:e="",cwd:t,defaultConfig:i}){let r=t||xa.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(ru(s)){let a=(await import(s))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Wa(i,a)}catch{}}}catch{}return i}function wg(e,t={}){let i=yo.cwd();while(i.includes("storage"))i=vf(i,"..");let r=vf(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 cu{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={...Ea},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new cu,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:Ea.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,Sf.F_OK|Sf.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(!oa(this.currentLogFile))await sa(this.currentLogFile,"",{mode:420});if(r=xf(this.currentLogFile,"a",420),Am(r,a,{flag:"a"}),$f(r),r!==void 0)na(r),r=void 0;if((await Qi(this.currentLogFile)).size===0){if(await sa(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{na(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 ra(16).toString("hex")}generateKey(){return ra(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=ra(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=Af(),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 Ef(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 sa(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 Ef(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=bf(e),r=Em(t),n=Af();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()})),oa(this.currentLogFile))try{let e=xf(this.currentLogFile,"r+");$f(e),na(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=Cu[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
|
+
`);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
|
+
`;if(a)l+=`${a}
|
|
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(!oa(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bf(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=Sm("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
|
+
`),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
|
+
`.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
|
+
`.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 La(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]=La(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(!iu(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 La(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(ia(),".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(ia(),".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=ia(),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(iu(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 La(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=Cf(i,"..");let r=Cf(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 fu{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={...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??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:Aa.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,Rf.F_OK|Rf.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 ca(this.currentLogFile,"",{mode:420});if(r=Of(this.currentLogFile,"a",420),Dm(r,a,{flag:"a"}),Tf(r),r!==void 0)la(r),r=void 0;if((await ir(this.currentLogFile)).size===0){if(await ca(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{la(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 aa(16).toString("hex")}generateKey(){return aa(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=aa(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=Mf(),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 Pf(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 ca(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 Pf(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=kf(e),r=Mm(t),n=Mf();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=Of(this.currentLogFile,"r+");Tf(e),la(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?"":vu[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
|
+
`);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
|
+
`;if(a)u+=`${a}
|
|
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
|
+
`);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 kf(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=Pm("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
|
+
`),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
|
+
`.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
|
+
`.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 uu(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 du(e){return e instanceof Ot}function Ag(e){return e instanceof Eo}function kg(e){if(du(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}:
|
|
182
186
|
|
|
183
187
|
`;for(let r of e)i+=`${r.key}
|
|
184
188
|
`,i+=` Type: ${r.type}
|
|
@@ -190,25 +194,25 @@ ${ue.join(`
|
|
|
190
194
|
`;i+=`| Variable | Type | Description | Example |
|
|
191
195
|
`,i+=`|----------|------|-------------|----------|
|
|
192
196
|
`;for(let r of e)i+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
193
|
-
`;return i}}function ug(e,t){let i=Qf("process");if(typeof i>"u"||!i.env)return t;let r=i.env[e];return r!==void 0?r:t}function Jf(e,t,i={}){return Yf(e,t,i,new WeakMap)}function Yf(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 l=s(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Xf(e,t,n,r);if(!kt(t)||!kt(e))return t;return mg(e,t,i,r)}function Xf(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 dg(e,t);case"smart":return hg(e,t,r);default:return t}return t}function dg(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>aa(n,r)))i.push(r);return i}function hg(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(kt(t[0])&&kt(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(!kt(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let l of o)if(l in n){if(r.find((a)=>kt(a)&&(l in a)&&a[l]===n[l])){s=!0;break}}if(!s)r.push(n)}return r}function mg(e,t,i,r){let n=t;if(kt(n)&&r.has(n))return r.get(n);let o={...e};if(kt(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let l=n[s],a=o[s];if(i.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[s]=l;continue}if(kt(l)&&kt(a))o[s]=Yf(a,l,i,r);else if(Array.isArray(l)||Array.isArray(a))o[s]=Xf(a,l,i.arrayMergeMode||"smart",r);else o[s]=l}return o}function $a(e,t,i="replace"){return Jf(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(kt(e)&&kt(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 kt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Co{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:l=!1}=i;if(n){let f=Qi.getWithFileCheck("file",e);if(f){if(l)console.log(`Configuration loaded from cache: ${e}`);return f}}let a=async()=>{if(!zn(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 Dr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof d!=="object"||d===null||Array.isArray(d))throw new Dr(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)Qi.setWithFileCheck("file",m,e,o);return m}catch(f){throw f instanceof Error?li.configLoad(e,f):li.configLoad(e,Error(String(f)))}};if(s)return Nr.track("loadFromPath",a,{path:e});return a()}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(Hs(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 Hf(async()=>zn(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!zn(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let l=Hs(e,`${o}${s}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let l=Hs(e,s);if(await this.checkFileAccess(l))r.push(l)}}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(!zn(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 Ea{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:l=!0,verbose:a=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:l,verbose:a};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(l)return await Nr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!$m(t))throw new Ir(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 Ir(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,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(s)){if(r.push({path:i,message:`Expected type ${l.join(" or ")}, got ${s}`,expected:l.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 l=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,l,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 l of t.required)if(!(l in s)){if(r.push({path:i?`${i}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[l,a]of Object.entries(t.properties))if(l in s){let f=i?`${i}.${l}`:l;if(this.validateObjectAgainstSchema(s[l],a,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(s))if(!l.has(a))n.push({path:i?`${i}.${a}`:a,message:`Additional property '${a}' 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),l=this.validateWithRule(s,o,o.path);if(r.push(...l),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:nu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class xa{fileLoader=new Co;envProcessor=new wo;validator=new Ea;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e;try{if(i?.enabled){let a=this.checkCache(s.name||"",s);if(a)return a}let l;try{l=await this.loadConfigurationStrategies(s,!0,i)}catch(a){let f=s.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(f)throw a;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(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),d=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(f&&(h||u))throw a;if(d&&(!f||!h))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(!f)l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else l={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||o)await this.validateConfiguration(l.config,n,o,s.name);if(i?.enabled&&l)this.cacheResult(s.name||"",l,i,s);if(r?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:s.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(a);if(r.slowThreshold&&a.duration>r.slowThreshold)It.warn(`Slow configuration loading detected: ${a.duration}ms for ${s.name}`);l.metrics=a}return l}catch(l){let a=Date.now()-t;throw It.error(`Configuration loading failed after ${a}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,cwd:o,configDir:s,defaultConfig:l,checkEnv:a=!0,arrayStrategy:f="replace",verbose:u=!1}=e,d=o||Ai.cwd(),h=[],p=await this.loadLocalConfiguration(r,n,d,s,l,f,u,a,i);if(p)return h.push(...this.getLocalSearchPaths(r,n,d,s)),this.finalizeResult(p,h,a,r,u);let m=await this.loadHomeConfiguration(r,n,l,f,u,a);if(m)return h.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(m,h,a,r,u);let c=await this.loadPackageJsonConfiguration(r,n,d,l,f,u,a);if(c)return h.push(gt(d,"package.json")),this.finalizeResult(c,h,a,r,u);if(h.push(...this.getAllSearchPaths(r,n,d,s)),t)throw li.configNotFound(r,h,n);return{...await this.applyEnvironmentVariables(r,l,a,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,l,a){let f=l?Rr(e,n,s):n,u=this.getLocalDirectories(i,r);for(let d of u){if(s)It.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:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(p){if(s)It.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?Rr(e,i,n):i,l=[gt(Gi(),".config",e),gt(Gi(),".config"),Gi()];for(let a of l){if(n)It.info(`Checking home directory: ${a}`);let f=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(f,s,{arrayStrategy:r,verbose:n});if(u){if(n)It.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s){let l=s?Rr(e,r,o):r;try{let a=gt(i,"package.json");if(!oa(a))return null;let f=await import(a),u=f[e],d=e;if(!u&&t)u=f[t],d=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(o)It.success(`Configuration loaded from package.json: ${d}`);return{config:$a(l,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(o)It.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}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:Rr(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 li.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return Qi.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);Qi.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,gt(e,"config"),gt(e,".config"),t?gt(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(gt(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=[gt(Gi(),".config",e),gt(Gi(),".config"),Gi()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function xf(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 gg(e){return Qt.loadConfig({...e,__strictErrorHandling:!0})}async function Zf(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 Qt.loadConfig(e);else r=await Qt.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)It.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 Qt.applyEnvironmentVariables(s.name||"",t,!0,s.verbose||!1))?.config??t;return t}}async function yg(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Qt.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"&&xf(i)))return(await Qt.applyEnvironmentVariables(e,{},!0,!1)).config;throw i}}try{return(await Qt.loadConfig({...e,cwd:e.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&xf(t)))return(await Qt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function wg(e,t,i="replace"){let r=new Co;try{let n=await r.loadFromPath(e,t,{arrayStrategy:i,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Rr(e,t,i=!1){let r=new wo,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,l=[]){let a={...s};for(let[f,u]of Object.entries(s)){let d=[...l,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((c)=>c.toUpperCase()).join("")}`,`${n}_${d.map((c)=>c.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let c of h)if(p=Ai.env[c],p!==void 0){m=c;break}if(p!==void 0&&m)if(typeof u==="boolean")a[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let c=Number(p);if(!Number.isNaN(c))a[f]=c}else if(Array.isArray(u))try{a[f]=JSON.parse(p)}catch{a[f]=p.split(",").map((c)=>c.trim())}else a[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))a[f]=o(u,d)}return a}return o(t)}function Cg(e){let t=gt(Ai.cwd(),e.configDir),i=gt(Ai.cwd(),e.generatedDir),r=gt(i,"config-types.ts");if(!oa(Qc(r)))Qp(Qc(r),{recursive:!0,mode:511});let n=oa(t)?em(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${qg}
|
|
197
|
+
`;return i}}function Tg(e,t){let i=yu("process");if(typeof i>"u"||!i.env)return t;let r=i.env[e];return r!==void 0?r:t}function hu(e,t,i={}){return pu(e,t,i,new WeakMap)}function pu(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 mu(e,t,n,r);if(!Nt(t)||!Nt(e))return t;return Mg(e,t,i,r)}function mu(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)=>Sa(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]=pu(l,a,i,r);else if(Array.isArray(a)||Array.isArray(l))o[s]=mu(l,a,i.arrayMergeMode||"smart",r);else o[s]=a}return o}function Ba(e,t,i="replace"){return hu(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Sa(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(!Sa(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(!Sa(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:Ba(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(fa(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 uu(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=fa(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=fa(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 _a{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:$u},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ja{fileLoader=new Po;envProcessor=new Ro;validator=new _a;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(!$a(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:Ba(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 Gf(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 gu(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"&&Gf(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"&&Gf(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(!$a(wf(r)))gm(wf(r),{recursive:!0,mode:511});let n=$a(t)?ym(t).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],o=`// Generated by bunfig v${uy}
|
|
194
198
|
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
195
|
-
`;
|
|
196
|
-
${n.map((
|
|
199
|
+
`;wm(r,o,{mode:438})}function Wg(e){let t=null,i=null,r=()=>{if(!i)i=gu(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 Lg(e){let t=Df(Gm.cwd(),e?.configDir||"./config");function i(){if(!_m(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),o=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=jm(t).filter((l)=>n.has(ua(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=ua(f).toLowerCase(),d=a.get(l);if(!d){a.set(l,f);continue}let h=ua(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=Df(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
|
|
197
201
|
`)}
|
|
198
202
|
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
199
|
-
export type ConfigByName = ${
|
|
203
|
+
export type ConfigByName = ${a}
|
|
200
204
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
201
205
|
export type ConfigOf = Config
|
|
202
|
-
`}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 Yg(e,t={}){let i=so.cwd();while(i.includes("storage"))i=gf(i,"..");let r=gf(i,e||"");if(t?.relative)return km(so.cwd(),r);return r}function rt(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Zg(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zt<"u"){let e=Zt.type;if(e==="renderer"||e==="worker")return!1;return!!(Zt.versions&&(Zt.versions.node||Zt.versions.bun))}return!1}class lu{async format(e){let t=await Zg(),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:Xi.pid,hostname:t(),environment:Xi.env.NODE_ENV||"development",platform:Xi.platform,version:Xi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Xi.env.NODE_ENV||Xi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class vo{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={...mo},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new lu,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??Be.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{...ra,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ra};return{...ra,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:mo.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!rt()&&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 Mm(this.config.logDirectory,vf.F_OK|vf.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await Dm(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:qt.from(e);try{if(!Kn(this.currentLogFile))await Xs(this.currentLogFile,"",{mode:420});if(r=Cf(this.currentLogFile,"a",420),Pm(r,l,{flag:"a"}),wf(r),r!==void 0)Ys(r),r=void 0;if((await Ji(this.currentLogFile)).size===0){if(await Xs(this.currentLogFile,l,{flag:"w",mode:420}),(await Ji(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let f=a;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{Ys(r)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(l){if(n===o-1){let f=l,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}n++;let a=s*2**(n-1);await new Promise((f)=>setTimeout(f,a))}})();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 Yi(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 Yi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(rt())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],[,l])=>l.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 Js(16).toString("hex")}generateKey(){return Js(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=Js(16),r=Tm("aes-256-gcm",t,i),n=qt.isBuffer(e)?e:qt.from(e,"utf8"),o=r.update(n),s=r.final(),l=o.length+s.length,a=r.getAuthTag(),f=qt.allocUnsafe(16+l+16);return i.copy(f,0),o.copy(f,16),s.copy(f,16+o.length),a.copy(f,16+l),{encrypted:f,iv:i}}async compressData(e){return new Promise((t,i)=>{let r=$f(),n=[];r.on("data",(o)=>n.push(o)),r.on("end",()=>t(qt.from(qt.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(rt())return;if(!this.shouldWriteToFile())return;let e=await Ji(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 Hn(this.config.logDirectory),o=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,f)=>{let u=Number.parseInt(a.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,l=`${i}.${s}`;if(await Ji(i).catch(()=>null))try{if(await bf(i,l),t.compress)try{let a=`${l}.gz`;await this.compressLogFile(l,a),await qn(l)}catch(a){console.error("Error compressing rotated file:",a)}if(o.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${i}.1`;await Xs(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),o=i.replace(/\.log$/,`-${n}.log`);if(await Ji(i).catch(()=>null))await bf(i,o)}if(this.currentLogFile=r,t.maxFiles){let n=(await Hn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,s)=>s.localeCompare(o));for(let o of n.slice(t.maxFiles))await qn(Yi(this.config.logDirectory,o))}}}async compressLogFile(e,t){let i=yf(e),r=Rm(t),n=$f();await Fm(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()})),Kn(this.currentLogFile))try{let e=Cf(this.currentLogFile,"r+");wf(e),Ys(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(!rt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Hn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await qn(Yi(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||rt())return!1;let e=typeof Be.env.NO_COLOR<"u",t=Be.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof Be.stderr<"u"&&Be.stderr.isTTY||typeof Be.stdout<"u"&&Be.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:i="",tag:r="",message:n,level:o,showTimestamp:s=!0}=e,l=(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 a=Be.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=l(f).trim().length,d=l(t).length,h=Math.max(1,a-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 l=Number.parseInt(s,10);return l<t[0].length?String(t[0][l]):o});let i=/%([sdijfo%])/g,r=0,n=e.replace(i,(o,s)=>{if(s==="%")return"%";if(r>=t.length)return o;let l=t[r++];switch(s){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 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 l=`file://${encodeURI(s)}`,a="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\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(rt())return!1;let e=Be.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=Be.env.HOME||"";if(i)t=t.replace(/^~(?=$|\/)/,i)}if(Im(t)||t.startsWith("./")||t.startsWith("../"))t=Nm(t);else return null;return Kn(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,l;if(t instanceof Error)s=t.message,l=t.stack;else s=this.formatMessage(t,i);let{consoleText:a,fileText:f}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":ry[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(a),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:a,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:Pe.green(a),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:a,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:h,message:a,level:e}),console.error(p),l){let m=l.split(`
|
|
203
|
-
`);for(let
|
|
204
|
-
`;if(
|
|
205
|
-
`;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()&&!
|
|
206
|
-
`);if(this[o==="warning"?"warn":o](n),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
207
|
-
`,
|
|
208
|
-
`),
|
|
209
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(e){if(
|
|
210
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
211
|
-
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||
|
|
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=If(i,"..");let r=If(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 Au{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 Au,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{...va,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...va};return{...va,...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,Lf.F_OK|Lf.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 pa(this.currentLogFile,"",{mode:420});if(r=Wf(this.currentLogFile,"a",420),qm(r,a,{flag:"a"}),Ff(r),r!==void 0)ha(r),r=void 0;if((await or(this.currentLogFile)).size===0){if(await pa(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{ha(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 da(16).toString("hex")}generateKey(){return da(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=da(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=_f(),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 Bf(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 pa(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 Bf(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=Nf(e),r=Hm(t),n=_f();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=Wf(this.currentLogFile,"r+");Ff(e),ha(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(`
|
|
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
|
+
`;if(a)u+=`${a}
|
|
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
|
+
`);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 Nf(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=Km("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
|
+
`),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
|
+
`.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
|
+
`.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 by(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 Va{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 Ia.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 Ga)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}:
|
|
212
216
|
|
|
213
217
|
`;for(let r of e)i+=`${r.key}
|
|
214
218
|
`,i+=` Type: ${r.type}
|
|
@@ -220,76 +224,76 @@ export type ConfigOf = Config
|
|
|
220
224
|
`;i+=`| Variable | Type | Description | Example |
|
|
221
225
|
`,i+=`|----------|------|-------------|----------|
|
|
222
226
|
`;for(let r of e)i+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
223
|
-
`;return i}}function gu(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}async function yu(e){let t=Lm(e),i=Xn.get(t),r,n=new Promise((o)=>{r=o});Xn.set(t,n),await i;try{if(Wm(t),Wf.cache[t]?.loaded===!0||na.has(t))delete Wf.cache[t];try{let o=await import(_m(t).href);return na.delete(t),o}catch(o){throw na.add(t),o}}finally{if(r(),Xn.get(t)===n)Xn.delete(t)}}function oy(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 l=s(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return Cu(e,t,n,r);if(!Tt(t)||!Tt(e))return t;return cy(e,t,i,r)}function Cu(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 ay(e,t,r);default:return t}return t}function sy(e,t){let i=[...t];for(let r of e)if(!i.some((n)=>ga(n,r)))i.push(r);return i}function ay(e,t,i){if(t.length===0)return e;if(e.length===0)return t;if(Tt(t[0])&&Tt(e[0]))return ly(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 ly(e,t,i){let r=[...t];for(let n of e){if(!Tt(n)){r.push(n);continue}let o=["id","name","key","path","type"],s=!1;for(let l of o)if(l in n){if(r.find((a)=>Tt(a)&&(l in a)&&a[l]===n[l])){s=!0;break}}if(!s)r.push(n)}return r}function cy(e,t,i,r){let n=t;if(Tt(n)&&r.has(n))return r.get(n);let o={...e};if(Tt(n))r.set(n,o);for(let s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;let l=n[s],a=o[s];if(i.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[s]=l;continue}if(Tt(l)&&Tt(a))o[s]=wu(a,l,i,r);else if(Array.isArray(l)||Array.isArray(a))o[s]=Cu(a,l,i.arrayMergeMode||"smart",r);else o[s]=l}return o}function vu(e,t,i="replace"){return oy(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function ga(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(!ga(e[i],t[i]))return!1;return!0}if(Tt(e)&&Tt(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(!ga(e[n],t[n]))return!1}return!0}return!1}function Tt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bu{extensions=Gf;async loadFromPath(e,t,i={}){let{arrayStrategy:r="replace",useCache:n=!0,cacheTtl:o,trackPerformance:s=!0,verbose:l=!1,strictDiscovery:a=!1}=i;if(n){let u=ao.getWithFileCheck("file",e);if(u){if(l)console.log(`Configuration loaded from cache: ${e}`);return u}}let f=async()=>{try{try{jm(e)}catch(c){if(gu(c)||!a)return null;throw c}let u=await yu(e),d=Object.hasOwn(u,"default"),h=Object.keys(u).length>0,p=d?u.default:u;if(!d&&!h)throw new Zi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof p!=="object"||p===null||Array.isArray(p))throw new Zi(e,Error("Configuration must export a valid object"),"unknown");let m={config:vu(t,p,r),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)ao.setWithFileCheck("file",m,e,o);return m}catch(u){throw u instanceof Error?ai.configLoad(e,u):ai.configLoad(e,Error(String(u)))}};if(s)return ya.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 Zi)throw n;if(i.verbose)console.warn(`Failed to load config from ${r}:`,n)}return null}generateConfigPaths(e,t,i){return Vm({name:e,directory:t,alias:i})}generateNamePatterns(e,t){return Vf({name:e,alias:t})}checkFileAccess(e){return ny(async()=>Zs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!Zs(e))return r;if(t||i){let n=this.generateNamePatterns(t||"",i);for(let o of n)for(let s of this.extensions){let l=Ef(e,`${o}${s}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:n}=await import("fs"),o=n(e);for(let s of o)if(this.looksLikeConfigFile(s)){let l=Ef(e,s);if(await this.checkFileAccess(l))r.push(l)}}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(!Zs(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 $u{async validateConfiguration(e,t,i={}){let{stopOnFirstError:r=!1,validateRequired:n=!0,validateTypes:o=!0,customRules:s=[],trackPerformance:l=!0,verbose:a=!1}=i,f=async()=>{let u=[],d=[],h={stopOnFirstError:r,validateRequired:n,validateTypes:o,customRules:s,trackPerformance:l,verbose:a};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(l)return await ya.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,i){try{if(!Gm(t))throw new go(t,[{path:"",message:"Schema file does not exist"}]);let r=await yu(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 go(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,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(s)){if(r.push({path:i,message:`Expected type ${l.join(" or ")}, got ${s}`,expected:l.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 l=i?`${i}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(e[s],t.items,l,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 l of t.required)if(!(l in s)){if(r.push({path:i?`${i}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(t.properties){for(let[l,a]of Object.entries(t.properties))if(l in s){let f=i?`${i}.${l}`:l;if(this.validateObjectAgainstSchema(s[l],a,f,r,n,o),o.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(s))if(!l.has(a))n.push({path:i?`${i}.${a}`:a,message:`Additional property '${a}' 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),l=this.validateWithRule(s,o,o.path);if(r.push(...l),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:fy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function uy(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 Eu{fileLoader=new bu;envProcessor=new Aa;validator=new $u;async loadConfig(e){let t=Date.now(),{cache:i,performance:r,schema:n,validate:o,...s}=e,l=s.errorPolicy==="throw"?{...i,enabled:!1}:i;try{if(l?.enabled){let f=this.checkCache(s.name||"",s);if(f)return f}let a;try{a=await this.loadConfigurationStrategies(s,!0,l)}catch(f){if(s.configFile||s.errorPolicy==="throw"&&!(f instanceof Pr))throw f;let u=s.__strictErrorHandling;if(f instanceof Pr){if(u&&s.errorPolicy!=="throw")throw f;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(f instanceof Zi){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))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(!u)a={...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 a={...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(a.config,n,o,s.name);if(l?.enabled&&a)this.cacheResult(s.name||"",a,l,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)Jt.warn(`Slow configuration loading detected: ${f.duration}ms for ${s.name}`);a.metrics=f}return a}catch(a){if(a instanceof Pr)throw a;let f=Date.now()-t;throw Jt.error(`Configuration loading failed after ${f}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,i){let{name:r="",alias:n,configFile:o,cwd:s,configDir:l,defaultConfig:a,checkEnv:f=!0,arrayStrategy:u="replace",verbose:d=!1}=e,h=s||yo.cwd(),p=[];if(o){let b=jt(h,o);p.push(b);let v=f?Tr(r,a,d):a,k=await this.fileLoader.tryLoadFromPaths([b],v,{arrayStrategy:u,verbose:d,cacheTtl:i?.ttl,useCache:i?.enabled!==!1&&(!i?.ttl||i.ttl>100),strictDiscovery:!0});if(!k)throw ai.configNotFound(r||o,p,n);if(d)Jt.success(`Configuration loaded from explicit path: ${b}`);return this.finalizeResult(k,p,f,r,d)}let m=await this.loadLocalConfiguration(r,n,h,l,a,u,d,f,i,e.errorPolicy==="throw");if(m)return p.push(...this.getLocalSearchPaths(r,n,h,l)),this.finalizeResult(m,p,f,r,d);let c=await this.loadHomeConfiguration(r,n,a,u,d,f,i,e.errorPolicy==="throw");if(c)return p.push(...this.getHomeSearchPaths(r,n)),this.finalizeResult(c,p,f,r,d);let C=await this.loadPackageJsonConfiguration(r,n,h,a,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,l)),t)throw ai.configNotFound(r,p,n);return{...await this.applyEnvironmentVariables(r,a,f,d),warnings:[`No configuration file found for "${r}"${uy(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,i,r,n,o,s,l,a,f=!1){let u=l?Tr(e,n,s):n,d=this.getLocalDirectories(i,r);for(let h of d){if(s)Jt.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:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:f});if(m){if(s)Jt.success(`Configuration loaded from: ${m.source.path}`);return m}}return null}async loadHomeConfiguration(e,t,i,r,n,o,s,l=!1){if(!e)return null;let a=o?Tr(e,i,n):i,f=[jt(ji(),".config",e),jt(ji(),".config"),ji()];for(let u of f){if(n)Jt.info(`Checking home directory: ${u}`);let d=this.fileLoader.generateConfigPaths(e,u,t),h=await this.fileLoader.tryLoadFromPaths(d,a,{arrayStrategy:r,verbose:n,cacheTtl:s?.ttl,useCache:s?.enabled!==!1&&(!s?.ttl||s.ttl>100),strictDiscovery:l});if(h){if(n)Jt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,i,r,n,o,s,l){let a=s?Tr(e,r,o):r,f=jt(i,"package.json"),u=l==="throw";try{let d=JSON.parse(Zp(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 c=h[m];if(typeof c!=="object"||c===null||Array.isArray(c))throw Error(`Configuration field "${m}" must contain an object`);if(o)Jt.success(`Configuration loaded from package.json: ${m}`);return{config:vu(a,c,n),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(d){if(gu(d))return null;if(u)throw ai.configLoad(f,d instanceof Error?d:Error(String(d)));if(o)Jt.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:Tr(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 ai.configValidation(r||"unknown",n,r)}checkCache(e,t){let i=this.generateCacheKey(e,t);return ao.get(i)||null}cacheResult(e,t,i,r){let n=this.generateCacheKey(e,r);ao.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 Um({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(ji(),".config",e),jt(ji(),".config"),ji()],r=[];for(let n of i)r.push(...this.fileLoader.generateConfigPaths(e,n,t));return r}async loadConfigWithResult(e){return this.loadConfig(e)}}function Tr(e,t,i=!1){let r=new Aa,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(s,l=[]){let a={...s};for(let[f,u]of Object.entries(s)){let d=[...l,f],h=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((c)=>c.toUpperCase()).join("")}`,`${n}_${d.map((c)=>c.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,m;for(let c of h)if(p=yo.env[c],p!==void 0){m=c;break}if(p!==void 0&&m)if(typeof u==="boolean")a[f]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let c=Number(p);if(!Number.isNaN(c))a[f]=c}else if(Array.isArray(u))try{a[f]=JSON.parse(p)}catch{a[f]=p.split(",").map((c)=>c.trim())}else a[f]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))a[f]=o(u,d)}return a}return o(t)}var ao,ya,Gf,zm,Km=(e)=>e,qm=(e,t)=>{for(var i in t)zm(e,i,{get:t[i],enumerable:!0,configurable:!0,set:Hm.bind(t,i)})},Jm=(e,t)=>()=>(e&&(t=e(e=0)),t),Uf,Qf,Qi,Nr,eu,$g,Eg,Sf,Qn,la,at,Ue,xg,Af,Sg,kf,Ag,kg,Qs,Tg,Tf,Of,ea,Og,Rg,Pg,Mg,eo,tu,Dg,lt,Ig,Ng,Rf,to,ca,it,Oe,Fg,Pf,Wg,Mf,Lg,Bg,ta,_g,Df,If,jg,ia,Gg,Vg,Ug,zg,Kg,io,iu,Hg,qg="0.15.6",$t,ho,Dr,fa,ua,po,da,ha,Ir,pa,ma,li,ru,nu,It,Qt,ou,su,Jg,Xg,au,mo,bv,cu,Pe,$v,Qg,Ev,ey,xv,Sv,Nf,Av,ty,iy,kv,Ff,Tv,Ov,Rv,Pv,Mv,ra,ry,Dv,Nt,Pr,Zi,fu,uu,Sa,du,hu,go,pu,mu,ai,Wf,Xn,na,fy,Jt,Iv,Nv,Fv,dy,xu;var Su=me(()=>{ao=new _f,ya=new jf,Gf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];zm=Object.defineProperty;Uf={};qm(Uf,{withErrorRecovery:()=>Hf,tryLoadConfig:()=>wg,loadConfigWithResult:()=>gg,loadConfig:()=>Zf,isRetryableError:()=>fg,isConfigNotFoundError:()=>cg,isBunfigError:()=>qf,globalPerformanceMonitor:()=>Nr,globalCache:()=>Qi,getEnvOrDefault:()=>ug,generateConfigTypes:()=>Cg,defaultGeneratedDir:()=>su,defaultConfigDir:()=>ou,deepMergeWithArrayStrategy:()=>$a,deepMerge:()=>Jf,createLibraryConfig:()=>vg,config:()=>yg,bunfigPlugin:()=>bg,applyEnvVarsToConfig:()=>Rr,TypeGenerationError:()=>ha,SchemaValidationError:()=>Ir,PluginError:()=>ma,PerformanceMonitor:()=>Ca,FileSystemError:()=>da,ErrorFactory:()=>li,EnvVarError:()=>po,EnvProcessor:()=>wo,ConfigValidator:()=>Ea,ConfigValidationError:()=>fa,ConfigNotFoundError:()=>ho,ConfigMergeError:()=>ua,ConfigLoader:()=>xa,ConfigLoadError:()=>Dr,ConfigFileLoader:()=>Co,ConfigCache:()=>wa,CacheUtils:()=>eu,BunfigError:()=>$t,BrowserConfigError:()=>pa,ArrayMergeStrategies:()=>ru});Jg=Jm(async()=>{Qf=import.meta.require,Qi=new wa,Nr=new Ca,eu={createKey:Ym,isEquivalent:Xm,estimateMemoryUsage:Zm},$g=oo(sa.cwd(),"config"),Eg=oo(sa.cwd(),"src/generated"),Sf=no.env.CLARITY_LOG_DIR||nm(tg(),"logs"),Qn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},la=await ig(),at={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Ue=at,xg=at.red,Af=at.green,Sg=at.yellow,kf=at.blue,Ag=at.magenta,kg=at.cyan,Qs=at.white,Tg=at.gray,Tf=at.bgRed,Of=at.bgYellow,ea=at.bold,Og=at.dim,Rg=at.italic,Pg=at.underline,Mg=at.reset,eo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tu={debug:"\uD83D\uDD0D",info:kf("\u2139"),success:Af("\u2713"),warning:Of(Qs(ea(" WARN "))),error:Tf(Qs(ea(" ERROR ")))},Dg=new co("stacks"),lt=new co("bunfig",{showTags:!0}),Ig=mt(Mr.cwd(),"config"),Ng=mt(Mr.cwd(),"src/generated"),Rf=ro.env.CLARITY_LOG_DIR||im(sg(),"logs"),to={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ca=await ag(),it={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"},Oe=it,Fg=it.red,Pf=it.green,Wg=it.yellow,Mf=it.blue,Lg=it.magenta,Bg=it.cyan,ta=it.white,_g=it.gray,Df=it.bgRed,If=it.bgYellow,jg=it.bgGray,ia=it.bold,Gg=it.dim,Vg=it.italic,Ug=it.underline,zg=it.strikethrough,Kg=it.reset,io={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},iu={debug:"\uD83D\uDD0D",info:Mf("\u2139"),success:Pf("\u2713"),warning:If(ta(ia(" WARN "))),error:Df(ta(ia(" ERROR ")))},Hg=new uo("stacks"),$t=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}`}},ho=class extends $t{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})}},Dr=class extends $t{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}},fa=class extends $t{code="CONFIG_VALIDATION_ERROR";constructor(e,t,i){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:i,validationErrors:t,errorCount:t.length})}},ua=class extends $t{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}},po=class extends $t{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})}},da=class extends $t{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}},ha=class extends $t{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}},Ir=class extends $t{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})}},pa=class extends $t{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})}},ma=class extends $t{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}},li={configNotFound(e,t,i){return new ho(e,t,i)},configLoad(e,t,i){return new Dr(e,t,i)},configValidation(e,t,i){return new fa(e,t,i)},configMerge(e,t,i,r){return new ua(e,t,i,r)},envVar(e,t,i,r){return new po(e,t,i,r)},fileSystem(e,t,i){return new da(e,t,i)},typeGeneration(e,t,i){return new ha(e,t,i)},schemaValidation(e,t,i){return new Ir(e,t,i)},browserConfig(e,t,i,r){return new pa(e,t,i,r)},plugin(e,t,i){return new ma(e,t,i)}},ru={replace:"replace",concat:"concat",smart:"smart"},nu=/^https?:\/\//,It=new uo("bunfig",{showTags:!0}),Qt=new xa,ou=gt(Ai.cwd(),"config"),su=gt(Ai.cwd(),"src/generated")});Xg=so.env.CLARITY_LOG_DIR||Am(Yg(),"logs"),au={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Xg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mo={...au},bv=(async()=>{try{let{loadConfig:e}=await Jg().then(()=>Uf),t=await e({name:"clarity",alias:"logging",defaultConfig:au,cwd:so.cwd()});if(t)Object.assign(mo,t)}catch{}return mo})();cu={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=cu,{red:$v,green:Qg,yellow:Ev,blue:ey,magenta:xv,cyan:Sv,white:Nf,gray:Av,bgRed:ty,bgYellow:iy,bgGray:kv,bold:Ff,dim:Tv,italic:Ov,underline:Rv,strikethrough:Pv,reset:Mv}=cu,ra={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ry={debug:"\uD83D\uDD0D",info:ey("\u2139"),success:Qg("\u2713"),warning:iy(Nf(Ff(" WARN "))),error:ty(Nf(Ff(" ERROR ")))};Dv=new vo("stacks");Nt=class Nt 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}`}};Pr=class Pr extends Nt{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})}};Zi=class Zi extends Nt{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}};fu=class fu extends Nt{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})}};uu=class uu extends Nt{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}};Sa=class Sa extends Nt{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})}};du=class du extends Nt{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}};hu=class hu extends Nt{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}};go=class go extends Nt{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})}};pu=class pu extends Nt{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})}};mu=class mu extends Nt{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}};ai={configNotFound(e,t,i){return new Pr(e,t,i)},configLoad(e,t,i){return new Zi(e,t,i)},configValidation(e,t,i){return new fu(e,t,i)},configMerge(e,t,i,r){return new uu(e,t,i,r)},envVar(e,t,i,r){return new Sa(e,t,i,r)},fileSystem(e,t,i){return new du(e,t,i)},typeGeneration(e,t,i){return new hu(e,t,i)},schemaValidation(e,t,i){return new go(e,t,i)},browserConfig(e,t,i,r){return new pu(e,t,i,r)},plugin(e,t,i){return new mu(e,t,i)}};Wf=Bm(import.meta.url),Xn=new Map,na=new Set;fy=/^https?:\/\//;Jt=new vo("bunfig",{showTags:!0});Iv=new Eu;Nv=jt(yo.cwd(),"config"),Fv=jt(yo.cwd(),"src/generated"),dy={cwd:Yp.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},xu=dy});import{existsSync as Au}from"fs";import{basename as hy,dirname as py,extname as ku,isAbsolute as bo,relative as ei,resolve as ti}from"path";async function Ou(e,t){let i=await Cy(e);wy(e,i);let r=i.slice(),n=await(t?t():Fn(e)),o=null;if(e.autoIncludeReExports!==!1&&r.length>0){o=await Ar(r,{includeImports:!0,resolveSpecifier:n});let d=ti(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 c=e.outputStructure==="flat"&&i.some((C)=>n.isPackageLocal?.(C,m));if(!Gt(m,d)&&!c){le.warn(`Skipping auto-included source outside root: ${ei(e.cwd,m)}`);continue}if(Wr(m,h,d))continue;p.push(m)}if(p.length>0)r=[...r,...p],le.debug(`Auto-included ${p.length} file(s) reached via relative re-exports`)}let s=vy(r,e),l=o??await Ar(r,{includeImports:!0,resolveSpecifier:n}),a=await Mc([...l.sources.keys()],n,e.isolatedDeclarations??!1,l.sources),f=new Set(r);for(let[d,h]of a){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=[...a].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:a,getResolutionFingerprint:()=>JSON.stringify({resolution:n.cacheKey?.(r),augmentations:u})})}function gy(e){let t=Fr.get(e);if(!t){if(t=new Tu(e),Fr.set(e,t),Fr.size>my){let i=Fr.keys().next().value;if(i!==void 0)Fr.delete(i)}}return t}function Wr(e,t,i){if(!t||t.length===0)return!1;let r=ei(i,e);for(let n of t){let o=gy(n);if(o.match(r)||o.match(e))return!0}return!1}function wy(e,t){let i=ti(e.cwd,e.root),r=` root: ${i}
|
|
227
|
+
`;return i}}function Iu(e){return e instanceof Error&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}async function Nu(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),tu.cache[t]?.loaded===!0||ba.has(t))delete tu.cache[t];try{let o=await import(rg(t).href);return ba.delete(t),o}catch(o){throw ba.add(t),o}}finally{if(r(),co.get(t)===n)co.delete(t)}}function $y(e,t,i={}){return Fu(e,t,i,new WeakMap)}function Fu(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 Wu(e,t,n,r);if(!Ft(t)||!Ft(e))return t;return Ay(e,t,i,r)}function Wu(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)=>Da(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]=Fu(l,a,i,r);else if(Array.isArray(a)||Array.isArray(l))o[s]=Wu(l,a,i.arrayMergeMode||"smart",r);else o[s]=a}return o}function Lu(e,t,i="replace"){return $y(e,t,{arrayMergeMode:i==="replace"?"replace":"smart",skipNullish:!0})}function Da(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(!Da(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(!Da(e[n],t[n]))return!1}return!0}return!1}function Ft(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Bu{extensions=su;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(Iu(g)||!l)return null;throw g}let u=await Nu(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:Lu(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 Ia.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 au({name:e,alias:t})}checkFileAccess(e){return by(async()=>ma(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,i){let r=[];if(!ma(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=jf(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=jf(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(!ma(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 _u{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 Ia.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 Nu(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 ju{fileLoader=new Bu;envProcessor=new Va;validator=new _u;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:Lu(l,g,n),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(d){if(Iu(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 Va,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,Ia,su,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),lu,yu,cr,Vr,wu,Bg,_g,Vf,uo,Ea,ut,Ke,jg,Uf,Gg,zf,Vg,Ug,ga,zg,Kf,Hf,ya,Kg,Hg,qg,Jg,ho,Cu,Yg,dt,Xg,Zg,qf,po,Aa,ot,Re,Qg,Jf,ey,Yf,ty,iy,wa,ry,Xf,Zf,ny,Ca,oy,sy,ay,ly,cy,mo,vu,fy,uy="0.15.6",Ot,Eo,jr,ka,Ta,Ao,Oa,Ra,Gr,Pa,Ma,gi,bu,$u,_t,si,xu,Su,dy,py,Eu,ko,Yv,ku,Pe,Xv,gy,Zv,yy,Qv,eb,Qf,tb,wy,Cy,ib,eu,rb,nb,ob,sb,ab,va,vy,lb,jt,Br,lr,Tu,Ou,Ga,Ru,Pu,To,Mu,Du,mi,tu,co,ba,ky,ii,cb,fb,ub,Oy,Gu;var Vu=ye(()=>{vo=new nu,Ia=new ou,su=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];lg=Object.defineProperty;lu={};ug(lu,{withErrorRecovery:()=>uu,tryLoadConfig:()=>Ng,loadConfigWithResult:()=>Dg,loadConfig:()=>gu,isRetryableError:()=>kg,isConfigNotFoundError:()=>Ag,isBunfigError:()=>du,globalPerformanceMonitor:()=>Vr,globalCache:()=>cr,getEnvOrDefault:()=>Tg,generateConfigTypes:()=>Fg,defaultGeneratedDir:()=>Su,defaultConfigDir:()=>xu,deepMergeWithArrayStrategy:()=>Ba,deepMerge:()=>hu,createLibraryConfig:()=>Wg,config:()=>Ig,bunfigPlugin:()=>Lg,applyEnvVarsToConfig:()=>Lr,TypeGenerationError:()=>Ra,SchemaValidationError:()=>Gr,PluginError:()=>Ma,PerformanceMonitor:()=>Fa,FileSystemError:()=>Oa,ErrorFactory:()=>gi,EnvVarError:()=>Ao,EnvProcessor:()=>Ro,ConfigValidator:()=>_a,ConfigValidationError:()=>ka,ConfigNotFoundError:()=>Eo,ConfigMergeError:()=>Ta,ConfigLoader:()=>ja,ConfigLoadError:()=>jr,ConfigFileLoader:()=>Po,ConfigCache:()=>Na,CacheUtils:()=>wu,BunfigError:()=>Ot,BrowserConfigError:()=>Pa,ArrayMergeStrategies:()=>bu});dy=dg(async()=>{yu=import.meta.require,cr=new Na,Vr=new Fa,wu={createKey:hg,isEquivalent:pg,estimateMemoryUsage:mg},Bg=wo(xa.cwd(),"config"),_g=wo(xa.cwd(),"src/generated"),Vf=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:Vf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ea=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,Uf=ut.green,Gg=ut.yellow,zf=ut.blue,Vg=ut.magenta,Ug=ut.cyan,ga=ut.white,zg=ut.gray,Kf=ut.bgRed,Hf=ut.bgYellow,ya=ut.bold,Kg=ut.dim,Hg=ut.italic,qg=ut.underline,Jg=ut.reset,ho={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Cu={debug:"\uD83D\uDD0D",info:zf("\u2139"),success:Uf("\u2713"),warning:Hf(ga(ya(" WARN "))),error:Kf(ga(ya(" ERROR ")))},Yg=new $o("stacks"),dt=new $o("bunfig",{showTags:!0}),Xg=wt(_r.cwd(),"config"),Zg=wt(_r.cwd(),"src/generated"),qf=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:qf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Aa=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,Jf=ot.green,ey=ot.yellow,Yf=ot.blue,ty=ot.magenta,iy=ot.cyan,wa=ot.white,ry=ot.gray,Xf=ot.bgRed,Zf=ot.bgYellow,ny=ot.bgGray,Ca=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},vu={debug:"\uD83D\uDD0D",info:Yf("\u2139"),success:Jf("\u2713"),warning:Zf(wa(Ca(" WARN "))),error:Xf(wa(Ca(" 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}},ka=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})}},Ta=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})}},Oa=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}},Ra=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})}},Pa=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})}},Ma=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 ka(e,t,i)},configMerge(e,t,i,r){return new Ta(e,t,i,r)},envVar(e,t,i,r){return new Ao(e,t,i,r)},fileSystem(e,t,i){return new Oa(e,t,i)},typeGeneration(e,t,i){return new Ra(e,t,i)},schemaValidation(e,t,i){return new Gr(e,t,i)},browserConfig(e,t,i,r){return new Pa(e,t,i,r)},plugin(e,t,i){return new Ma(e,t,i)}},bu={replace:"replace",concat:"concat",smart:"smart"},$u=/^https?:\/\//,_t=new So("bunfig",{showTags:!0}),si=new ja,xu=Ct(Ii.cwd(),"config"),Su=Ct(Ii.cwd(),"src/generated")});py=Co.env.CLARITY_LOG_DIR||Vm(hy(),"logs"),Eu={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={...Eu},Yv=(async()=>{try{let{loadConfig:e}=await dy().then(()=>lu),t=await e({name:"clarity",alias:"logging",defaultConfig:Eu,cwd:Co.cwd()});if(t)Object.assign(ko,t)}catch{}return ko})();ku={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=ku,{red:Xv,green:gy,yellow:Zv,blue:yy,magenta:Qv,cyan:eb,white:Qf,gray:tb,bgRed:wy,bgYellow:Cy,bgGray:ib,bold:eu,dim:rb,italic:nb,underline:ob,strikethrough:sb,reset:ab}=ku,va={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vy={debug:"\uD83D\uDD0D",info:yy("\u2139"),success:gy("\u2713"),warning:Cy(Qf(eu(" WARN "))),error:wy(Qf(eu(" 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}};Tu=class Tu 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})}};Ou=class Ou 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}};Ga=class Ga 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})}};Ru=class Ru 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}};Pu=class Pu 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})}};Mu=class Mu 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})}};Du=class Du 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 Tu(e,t,i)},configMerge(e,t,i,r){return new Ou(e,t,i,r)},envVar(e,t,i,r){return new Ga(e,t,i,r)},fileSystem(e,t,i){return new Ru(e,t,i)},typeGeneration(e,t,i){return new Pu(e,t,i)},schemaValidation(e,t,i){return new To(e,t,i)},browserConfig(e,t,i,r){return new Mu(e,t,i,r)},plugin(e,t,i){return new Du(e,t,i)}};tu=ig(import.meta.url),co=new Map,ba=new Set;ky=/^https?:\/\//;ii=new Mo("bunfig",{showTags:!0});cb=new ju;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},Gu=Oy});import{existsSync as Uu}from"fs";import{basename as Ry,dirname as Py,extname as zu,isAbsolute as Do,relative as ai,resolve as li}from"path";async function Hu(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(!Ua(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 Yc([...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 Ku(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}
|
|
224
228
|
entrypoints: ${e.entrypoints.map((o)=>JSON.stringify(o)).join(", ")||"(none)"}
|
|
225
229
|
`+(e.exclude?.length?` exclude: ${e.exclude.map((o)=>JSON.stringify(o)).join(", ")}
|
|
226
|
-
`:"")+"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)=>
|
|
227
|
-
${r}`)}let n=e.entrypoints.filter((o)=>{if(
|
|
228
|
-
${r}`)}async function Cy(e){let t=[],i=ti(e.cwd,e.root),r=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let o of n)if(bo(o)&&ka(o)){if(!o.includes("node_modules")){if(!Gt(o,i)&&e.outputStructure!=="flat")le.warn(`Skipping entrypoint outside root: ${ei(e.cwd,o)}`);else if(!Wr(o,r,i))t.push(o)}}else{let s=new Tu(o);for await(let l of s.scan({cwd:i,absolute:!0,onlyFiles:!0}))if(ka(l)&&!l.includes("node_modules")){if(!Wr(l,r,i))t.push(l)}}return[...new Set(t.map((o)=>ti(o)))].sort()}function Gt(e,t){let i=ei(t,e);return i!==".."&&!i.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!bo(i)}function vy(e,t){let i=new Map,r=new Map;for(let n of e){let o=er(n,t),s=i.get(o);if(s&&s!==n)throw Error(`Output path collision: ${ei(t.cwd,s)} and ${ei(t.cwd,n)} both emit ${ei(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 er(e,t){let i=ti(t.cwd,t.root),r=ei(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 ti(t.cwd,t.outdir,n);else{let o=hy(n);return ti(t.cwd,t.outdir,o)}}function by(e,t,i=""){let r=ei(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 Ru(e,t,i,r){let n=er(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)&&Wr(s.resolved,t.exclude??[],ti(t.cwd,t.root)))throw Error(`Local reference ${JSON.stringify(o)} from ${e} targets a source excluded from this package build: ${s.resolved}`);let l=s.isAlias?s.suffix??"":o.match(/[?#].*$/)?.[0]??"",a=l?o.slice(0,-l.length):o,f=ku(a),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=er(s.resolved,t);return{kind:"local",specifier:o,resolvedSource:s.resolved,declarationOutput:d,emittedSpecifier:by(n,d,u)+l}}}var Tu,my=50,Fr,yy;var Ta=me(()=>{Dc();In();Wn();({Glob:Tu}=globalThis.Bun);Fr=new Map;yy=/[*?[\]{}!]/});var Pu;var Mu=me(()=>{Pu=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 Du(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(`
|
|
229
|
-
`,r),
|
|
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)&&Uu(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(Iy.test(o))return!1;return!Uu(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 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)&&Ua(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 Ku(o);for await(let a of s.scan({cwd:i,absolute:!0,onlyFiles:!0}))if(Ua(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 Ua(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 qu(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=zu(l),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";if(!u&&t.moduleSpecifierMode==="node"){let h=zu(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 Ku,My=50,Ur,Iy;var za=ye(()=>{Xc();Kn();Jn();({Glob:Ku}=globalThis.Bun);Ur=new Map;Iy=/[*?[\]{}!]/});var Ju;var Yu=ye(()=>{Ju=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 Xu(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
|
+
`,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]===`
|
|
230
234
|
`?`
|
|
231
|
-
`:" ";r=
|
|
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]===`
|
|
232
236
|
`?`
|
|
233
|
-
`:" ",r++}continue}i+=o,r++}return i}function
|
|
237
|
+
`:" ",r++}continue}i+=o,r++}return i}function _y(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 jy(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 Gy(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 Vy(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 Zu(e){let t=Xu(e),i=Xu(e,{strings:!1}),r=new Set([..._y(t),...jy(i),...Gy(t),...Ju,...By]),n=[];for(let[o,s]of Vy(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 By;var Qu=ye(()=>{Yu();By=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 td(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(...zy(e,i)),t.sort((f,u)=>f.line-u.line||f.column-u.column)}function zy(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(!Uy.test(d))i.push({...yi(e,h),message:`Invalid ${n[1]} specifier '${d}'`,code:"DTSX1006"})}f+=u.length+1}}return i}var ed,Uy;var id=ye(()=>{ed=String.raw`(?:[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*|'[^']*'|"[^"]*")`,Uy=new RegExp(`^(?:type\\s+)?${ed}(?:\\s+as\\s+${ed})?$`,"u")});import Ky from"process";import{join as _b,resolve as Hy}from"path";function Ka(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function Io(e,t,i="lf"){let r=t.replace(/\r\n/g,`
|
|
234
238
|
`);if(!r.endsWith(`
|
|
235
239
|
`))r+=`
|
|
236
240
|
`;if(i==="crlf")r=r.replace(/\n/g,`\r
|
|
237
|
-
`);if(await
|
|
241
|
+
`);if(await Ol(e,r)!==Buffer.byteLength(r,"utf8"))throw Error(`Incomplete declaration write: ${e}`)}async function rd(e){try{let t=e?.cwd||Ky.cwd();return(await Mr(Hy(t,e?.tsconfigPath||"tsconfig.json"),{allowCircular:!0}))?.isolatedDeclarations??!1}catch{return!1}}function nd(e,t){let i={isValid:!0,errors:[]};for(let r of td(e))i.errors.push({line:r.line,column:r.column,message:r.message,code:r.code});for(let r of Zu(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 od(e,t,i){if(e===t)return"";let r=e.split(`
|
|
238
242
|
`),n=t.split(`
|
|
239
|
-
`),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
|
|
240
|
-
`)}function
|
|
241
|
-
`),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
|
|
242
|
-
`).length;for(let d=0;d<n.length;d++){if(n[d].trim()===""){o.push("");continue}
|
|
243
|
-
${
|
|
244
|
-
`}var
|
|
245
|
-
`),o=e.location.line-1;if(o>=0&&o<n.length){let s=Math.max(0,o-1),
|
|
246
|
-
`)}var
|
|
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 sd(e,t,i,r){let n=e.split(`
|
|
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 ad(e,t){return`${e}
|
|
247
|
+
${Ka()}${t}
|
|
248
|
+
`}var Ha=ye(()=>{gr();Qu();id();Js()});import{chmod as qy,lstat as Xa,mkdir as No,readdir as Jy,realpath as Yy,rename as qa,rm as ld,rmdir as Xy,stat as cd,writeFile as Zy}from"fs/promises";import{basename as Qy,dirname as Kr,isAbsolute as ud,parse as e1,relative as fd,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 Xa(e)}catch(t){if(Ci(t,"ENOENT"))return;throw t}}async function ur(e){let t=mt(e);try{return await Yy(t)}catch(i){if(!Ci(i,"ENOENT")||Kr(t)===t)throw i;return mt(await ur(Kr(t)),Qy(t))}}async function Qa(e){let t=mt(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(ud(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===e1(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 dd(e){return[".d.ts",".d.mts",".d.cts",".d.ts.map",".d.mts.map",".d.cts.map"].some((t)=>e.endsWith(t))}function Ja(e,t){return e.dev===t.dev&&e.ino===t.ino}async function Za(e,t){try{if(!(await cd(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 Za(i,t);try{await No(e),t.push(e)}catch(r){if(!Ci(r,"EEXIST")||!(await cd(e)).isDirectory())throw r}}async function hd(e,t,i){for(let r of(await Jy(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 hd(n,t,i);else if(dd(r.name)){let o=await wi(n);if(!o)throw Error(`Declaration output changed during inventory: ${n}`);i.set(n,o)}}}function Ya(e,t,i,r,n){return Object.assign(AggregateError(t,e),{code:"DTSX_PUBLICATION_FAILED",phase:i,recoveryDirectory:r,outputsCommitted:n})}async function pd(e,t){if(e.dryRun||t.size===0&&!e.clean)return;await Qa(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(!ud(m)||C===i||!Yt(C,i)||Yt(C,r)||!dd(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||!Ja(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 ld(r,{recursive:!0})}try{await Za(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 Xa(r),u=await ur(i);let m=new Map;if(e.clean)await hd(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 Zy(mt(r,"manifest.json"),JSON.stringify({version:1,outdir:i,targets:[...g.values()].map((C)=>({path:fd(i,C.path),backup:fd(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 qy(A,c.existing.mode&511);c.stagedIdentity=await Xa(A)}for(let C of g.values()){if(!C.existing)continue;await h(C.path,u);let b=await wi(C.path);if(!b||!Ja(b,C.existing))throw Error(`Declaration output changed before commit: ${C.path}`);await qa(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 Za(Kr(C.path),o),await h(C.path,u),await wi(C.path))throw Error(`Declaration output appeared during commit: ${C.path}`);await qa(C.staged,C.path),a.push({path:C.path,identity:C.stagedIdentity})}d=!0;try{await p()}catch(C){throw Ya(`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(!Ja(c,b.identity))throw Error(`Installed declaration changed before rollback: ${b.path}`);await ld(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 qa(b.backup,b.path)}catch(c){g.push(c)}if(g.length>0)throw Ya(`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 Xy(b)}catch(c){if(!Ci(c,"ENOENT")&&!Ci(c,"ENOTEMPTY")&&!Ci(c,"EEXIST"))C.push(c)}if(C.length>0)throw Ya(`Prior declarations retained, but publication cleanup failed at ${r}`,[m,...C],"cleanup",l?r:void 0,!1);throw m}}var md=ye(()=>{za();Ha()});function gd(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 yd(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
|
+
`),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 wd=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 t1(){if(Fo!==null)return Fo;try{return vi=await import("prettier"),Fo=!0,!0}catch{return Fo=!1,!1}}async function i1(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 r1(e,t){if(!vi)throw Error("Prettier is not available");let i={...t,parser:t.parser||"typescript"};return vi.format(e,i)}function n1(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
|
|
247
251
|
`)!==-1)f=f.replace(/\r\n/g,`
|
|
248
252
|
`);if(s){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
|
|
249
253
|
|
|
250
254
|
|
|
251
255
|
`)!==-1)f=f.replace(/\n{3,}/g,`
|
|
252
256
|
|
|
253
|
-
`);f=
|
|
257
|
+
`);f=o1(f,u)}if(a||l)f=s1(f,{sort:a,group:l});if(n>0)f=l1(f,n,u);if(o&&!f.endsWith(`
|
|
254
258
|
`))f+=`
|
|
255
|
-
`;return f}function
|
|
256
|
-
`),r=[];for(let n of i){let o=n.match(/^(\s*)(.*)$/);if(!o){r.push(n);continue}let[,s,
|
|
257
|
-
`)}function
|
|
258
|
-
`),r=[],n=[],o=!1,s=0;for(let
|
|
259
|
-
`)}function
|
|
260
|
-
`),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]||"",
|
|
261
|
-
`)}function
|
|
259
|
+
`;return f}function o1(e,t){let i=e.split(`
|
|
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 s1(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 a1(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 a1(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 l1(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=f1(o,s,a);if(l){n.push(...l);continue}if(o.includes("{")&&o.includes("}")){let f=u1(o,t,s,a);n.push(...f);continue}if(o.includes(" | ")){let f=d1(o,t,s,a);n.push(...f);continue}n.push(o)}return n.join(`
|
|
265
|
+
`)}function f1(e,t,i){let r=e.match(c1);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 u1(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 d1(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 Cd(e,t={},i){let r=[];if(t.usePrettier!==!1){if(await t1())try{let n={...await i1(t.prettierConfigPath,i),...t.prettierOptions,parser:"typescript"};return{content:await r1(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:n1(e,t.builtIn),usedPrettier:!1,warnings:r.length>0?r:void 0}}var Fo=null,vi=null,c1;var vd=ye(()=>{c1=/^\s*(export|import)(\s+type)?\s*\{([^{}]*)\}\s*(from\s*(?:'[^']*'|"[^"]*")(?:\s*(?:with|assert)\s*\{[^{}]*\})?)?\s*;?\s*$/});function bd(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 $d=ye(()=>{Cs();Gn();Pi()});import Ad from"process";import{existsSync as h1}from"fs";import{arch as p1,platform as xd}from"os";import{fileURLToPath as m1}from"url";function Lo(e,t="engine"){if(e===void 0||e===null||e==="")return;if(typeof e==="string"&&g1.includes(e))return e;throw Error(`Invalid ${t} ${JSON.stringify(e)}: expected "native" or "typescript"`)}function w1(e){return Lo(e)??y1??Lo(Ad.env.DTSX_ENGINE,"DTSX_ENGINE")??"native"}function Sd(){return`${xd()==="win32"?"windows":xd()}-${p1()}`}function C1(e){let t=[],i=Ad.env.DTSX_NATIVE_LIBRARY;if(i)t.push(i);for(let r of[`../native/${Sd()}/${e}`,`../../native/${Sd()}/${e}`,`../../zig-dtsx/zig-out/lib/${e}`,`../../zig-dtsx/zig-out/bin/${e}`])try{t.push(m1(new URL(r,import.meta.url)))}catch{}return t}function v1(){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 C1(s)){if(!h1(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 b1(){if(el===void 0)el=v1();return el}function kd(e,t){if(w1(t.engine)==="typescript")return null;let i=b1();if(!i)return null;if(e.length*3>dr.length)dr=new Uint8Array(e.length*3);let{written:r}=Ed.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=Ed.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,tl,il)}else o=i.checked(dr,r,t.keepComments,t.isolatedDeclarations,tl,il);let s=Number(tl[0]);if(il[0]!==0)return i.read(o,s),null;return i.read(o,s)}var g1,y1,el,Ed,dr,tl,il;var Td=ye(()=>{g1=["native","typescript"];Ed=new TextEncoder,dr=new Uint8Array(65536),tl=new BigUint64Array(1),il=new Uint32Array(1)});function Pd(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=S1(h,i),f?.enabled!==!1)h=O1(h,f||{});if(l)h=R1(h,l);if(o)h=E1(h);if(h=A1(h,n),s)h=T1(h,a);if(r||d)h=k1(h);return h}function S1(e,t){let i=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
262
266
|
`)!==-1)i=i.replace(/\r\n/g,`
|
|
263
267
|
`);if(i.indexOf("\r")!==-1)i=i.replace(/\r/g,`
|
|
264
268
|
`)}if(t==="crlf")i=i.replace(/\n/g,`\r
|
|
265
|
-
`);return i}function
|
|
269
|
+
`);return i}function E1(e){return e.split(`
|
|
266
270
|
`).map((t)=>t.replace(/[\t ]+$/,"")).join(`
|
|
267
|
-
`)}function
|
|
268
|
-
`.repeat(t+1))}function
|
|
269
|
-
`}function
|
|
270
|
-
`),s=[];for(let
|
|
271
|
-
`)}function
|
|
272
|
-
`),s=[],
|
|
273
|
-
`)}function
|
|
274
|
-
`),s=[],
|
|
275
|
-
`)}function
|
|
276
|
-
`){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(
|
|
277
|
-
`;n+=
|
|
278
|
-
`;n+=
|
|
279
|
-
`;n+=
|
|
280
|
-
`;n+=
|
|
281
|
-
`;n+=C[
|
|
282
|
-
`;n+=b[
|
|
283
|
-
`:""}export {};`;return n}var
|
|
284
|
-
${
|
|
285
|
-
${
|
|
286
|
-
...`:"")),
|
|
287
|
-
`);if(i.failOnUnresolvedReExport)throw Error(
|
|
288
|
-
--- Generation Statistics ---`),
|
|
289
|
-
Errors:`);for(let
|
|
290
|
-
`)}if(i.plugins&&i.plugins.length>0)await r.runOnEnd(s);return
|
|
291
|
-
`)){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
|
|
271
|
+
`)}function A1(e,t){let i=new RegExp(`\\n{${t+2},}`,"g");return e.replace(i,`
|
|
272
|
+
`.repeat(t+1))}function k1(e){return`${e.replace(/\s+$/,"")}
|
|
273
|
+
`}function T1(e,t){let{style:i="spaces",size:r=2}=t,n=i==="tabs"?"\t":" ".repeat(r),o=e.split(`
|
|
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 O1(e,t){let{groups:i=x1,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=Od(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)=>Od(m)!==null)),p=a;while(p.length>0&&p[0].trim()==="")p.shift();return[...h,...u,"",...p].join(`
|
|
277
|
+
`)}function Od(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:Rd(o[1]),isType:!1};return null}let r=!!i[1],n=i[2];return{source:n,group:r?"type":Rd(n),isType:r}}function Rd(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 R1(e,t){let{kinds:i=$1,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 O=P1(c);if(d&&O&&O.kind!=="import"&&!c.startsWith("//")&&!c.startsWith("/*"))d=!1;if(d){if(p.length>0){if(O?.kind==="import"||!O)a.push(...p),p.length=0}a.push(b);continue}if(O&&u<=1){if(f)s.push(f);f={lines:p.length>0?[...p,b]:[b],kind:O.kind,name:O.name,isExport:O.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 P1(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 $1,x1;var Md=ye(()=>{$1=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],x1=["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 M1(e){return e}var o$,s$;var Dd=ye(()=>{o$=new Bo;s$=M1({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 Id(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(D1.test(s)||I1.test(s)||N1.test(s))t.push(s)}else if(s===""||s.startsWith("//"))continue;else break}return t}var D1,I1,N1;var Nd=ye(()=>{D1=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,I1=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,N1=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/});function Fd(e,t){throw Error(t||`Unexpected value: ${e}`)}function _d(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 O=Id(o);if(O.length>0)for(let N=0;N<O.length;N++){if(n)n+=`
|
|
281
|
+
`;n+=O[N]}}}let s=[],a=[],l=[],f=[],u=[],d=[],h=[],p=[],m=[];for(let S of e){let O=S.kind;switch(O){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:Fd(O,`Unhandled declaration kind: ${O}`)}}let g=[],C=[],b=[],c=new Set;for(let S of m){let O=Kt(S.leadingComments,i);if(S.text.startsWith("export default")){let N=S.text.endsWith(";")?S.text:`${S.text};`;b.push(O+N)}else{let N=S.text.trim();if(!N.endsWith(";"))N+=";";let B=O+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 O=r.length;if(A.length>1){if(Wd!==r)Wd=r,Ld=r.map((K)=>`from '${K}`),Bd=r.map((K)=>`from "${K}`);let N=Ld,B=Bd,ee=new Map;for(let K of A){let te=O;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
|
+
`;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 O=M[S];for(let N=0;N<O.length;N++){let B=O[N],ee="",K=B.kind;switch(K){case"function":ee=Rc(B,i);break;case"variable":ee=Vi(B,i);break;case"interface":ee=Pc(B,i);break;case"type":ee=Mc(B,i);break;case"class":ee=Dc(B,i);break;case"enum":ee=Ic(B,i);break;case"module":case"namespace":ee=Nc(B,i);break;case"import":case"export":case"unknown":break;default:Fd(K,`Unhandled declaration kind in processor: ${K}`)}if(ee){if(n)n+=`
|
|
284
|
+
`;n+=ee}}}for(let S=0;S<C.length;S++){if(n)n+=`
|
|
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(Yl)||!Hl(n)))n+=`${n?`
|
|
287
|
+
`:""}export {};`;return n}var Wd=null,Ld,Bd;var jd=ye(()=>{$r();Nd();kn();Ln();Pi();zs();Ld=[],Bd=[]});function _1(e){switch(e){case"strict":return W1;case"readonly":return L1;case"simplified":return B1;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 Vd{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...F1);if(e.presets)for(let t of e.presets)this.rules.push(..._1(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(j1,"\\$&"),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>=Gd){let s=Math.ceil(Gd*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 Vd(e)}function Ud(e,t,i={}){return e.replace(/:\s*([^;,)\]}]+)/g,(r,n)=>`: ${t.map(n.trim(),i)}`)}var F1,W1,L1,B1,j1,Gd=2048,g$,y$;var zd=ye(()=>{F1=[{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}],W1=[{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}],L1=[{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}],B1=[{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}];j1=/[.*+?^${}()|[\]\\]/g;g$=_o({rules:[]}),y$=_o({rules:[],presets:["strict"]})});import{availableParallelism as G1}from"os";import{basename as qd,dirname as V1,relative as Xt,resolve as U1}from"path";function nl(e){let t=rl.get(e);if(!t)t=qn(e),rl.set(e,t),t.catch(()=>rl.delete(e));return t}async function Kd(e,t,i,r,n,o=Io){let s=qd(e)||"output.d.ts",a=Xt(V1(e),t),l=`${s}.map`,f=i.lastIndexOf(`
|
|
288
|
+
${Ka()}`),u=f===-1?i:i.slice(0,f),d=sd(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 ol(e){let t=Date.now(),i={...Gu,...e};if(i.logLevel)Ks(i.logLevel);else if(i.verbose)Ks("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 Qa(i),i.isolatedDeclarations===void 0)i.isolatedDeclarations=await rd(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 Hu(i,()=>nl(i)),f=l.entryFiles,u=[...l.files],{resolver:d,reachability:h}=l;if(Jd.set(i,new Set(u)),i.incremental){let S=l.getResolutionFingerprint();if(!i.isolatedDeclarations){let O=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")&&!O.has(he))O.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 O=o.getStats();de.debug(`Loaded build cache with ${O.entries} entries`)}else de.debug("No existing build cache found, starting fresh");if(!i.dryRun)kl(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,O,N="lf")=>{m.set(S,{content:O,lineEnding:N})},C=async(S,O)=>{let N;try{let B=fr(S,i),ee=async(D)=>{if(!i.diff)return;try{let qe=await Et(B),X=od(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=nd(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=O??await Et(S),await Kd(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=O??await Et(S);let{content:he,declarationCount:Ae,importCount:Se,exportCount:fe}=await K1(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 Cd(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=`${qd(B)||"output.d.ts"}.map`;re=ad(re,D)}await ee(re);let pe=K(re);if(i.dryRun)te(re);else{if(i.declarationMap&&N)await Kd(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=gd(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=Rl(i.concurrency,G1?.()??8),A=new Map;if(b&&u.length>1){let S=u.map(async(O)=>{try{let N=await Et(O);return{file:O,source:N}}catch{return{file:O,source:null}}});for(let O of await Promise.all(S))if(O.source!==null)A.set(O.file,O.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 O=yd(S.dtsError);if(i.continueOnError)de.warn(O);else throw de.error(O),Error(S.dtsError.message)}};if(b)for(let S=0;S<u.length;S+=c){let O=u.slice(S,S+c),N=await Promise.all(O.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 O=await C(S);if(M(O),i.progress){let N=Math.round(s.filesProcessed/u.length*100),B=O.cached?"[cached]":"";de.info(`[${s.filesProcessed}/${u.length}] ${N}% - ${Xt(i.cwd,S)} ${B}`)}}if(!i.bundle){let S=[];if(h)for(let O of h.unresolved)S.push({from:O.from,specifier:O.specifier,reason:"missing"});if(i.autoIncludeReExports===!1&&u.length>0){let O=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)&&!O.has(K.resolved))S.push({from:N,specifier:ee.specifier,reason:"not-emitted"})}}}if(S.length>0){let O=[];O.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")O.push(` ${ee} \u2192 '${B.specifier}' (path not found on disk)`);else O.push(` ${ee} \u2192 '${B.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let N=O.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 O of f){let N=await Ir([O],{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(O))ee.push(O);let K=df(O,ee,p,{cwd:i.cwd,keepComments:i.keepComments});for(let he of new Set(K.warnings))de.warn(`[bundle] ${he}`);let te=S?U1(i.cwd,i.outdir,i.bundleOutput):fr(O,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 O=S instanceof Error?S.message:String(S);throw de.error(`Bundle failed: ${O}`),S}if(!i.dryRun)await pd(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
|
+
--- 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 O=` - ${S.file}`;if(S.location)O+=`:${S.location.line}:${S.location.column}`;if(S.code)O+=` [${S.code}]`;if(O+=`: ${S.message}`,de.info(O),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 z1(e,t,i){let r=await nl(i),n=qu(t,i,r,Jd.get(i));return ff(e,(o)=>n(o).emittedSpecifier)}async function K1(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 nl(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:q1(s,e,i,a,o);if(l!==null)return Hd(l,e,s,i,r,n,H1(l));let f=a.size?bd(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=_d(u,{filePath:e,sourceCode:s,declarations:u,augmentationImports:o},i.keepComments,i.importOrder);return Hd(p,e,s,i,r,n,{declarationCount:u.length,importCount:d,exportCount:h})}function H1(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 q1(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 kd(s,{keepComments:i.keepComments??!0,isolatedDeclarations:i.isolatedDeclarations??!1,engine:i.engine,sourceFile:t,inferenceSources:r,augmentationImports:n})}async function Hd(e,t,i,r,n,o,s){let a=await z1(e,t,r);if(o)a=Ud(a,o,{filePath:t});if(r.normalizeOutput===!0||r.declarationOrder)a=Pd(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 rl,Jd;var Yd=ye(()=>{gr();Pl();hn();ms();Us();Kn();Jn();hf();Tl();Vu();za();Ha();md();wd();vd();$d();Td();Md();Dd();jd();zd();rl=new WeakMap,Jd=new WeakMap});var Xd=ye(()=>{Yd()});import eh from"process";import{dirname as J1,relative as Zd,resolve as jo,sep as Go}from"path";class th{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 ih(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 th;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=Z1({...u,incremental:n,cacheDir:o},h);if(m.clean){let A=jo(m.cwd??eh.cwd(),m.outdir??"./dist");if(Qd.has(A))m.clean=!1;else Qd.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);ol(m).then((O)=>{clearTimeout(S),A(O)}).catch((O)=>{clearTimeout(S),M(O)})}))(),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=Y1(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 Y1(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 X1(e){let t=e.map((r)=>J1(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 Z1(e,t){let i=e.cwd||eh.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=X1(r.map((l)=>jo(i,l)));o=Zd(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(Zd(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,Qd;var rh=ye(()=>{Xd();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}}};Qd=new Set});import{mkdir as Q1,stat as e0}from"fs/promises";import{bold as sl,dim as al,green as t0,italic as nh,log as i0}from"@stacksjs/cli";import{path as Rt}from"@stacksjs/path";import{glob as oh}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 wh,readdirSync as Ch,readFileSync as bl}from"fs";import{join as es}from"path";function vh(e){return[...Ch(e,{withFileTypes:!0}).filter((i)=>i.isDirectory()).map((i)=>es(e,i.name)),e].filter((i)=>{let r=es(i,"package.json");if(!wh(r))return!1;let n=JSON.parse(bl(r,"utf8"));return!n.private&&!!n.scripts?.build})}async function bh(e){let t=e.map((n)=>{let o=JSON.parse(bl(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 r0(e){let t=await oh([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 n0(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(`
|
|
292
296
|
`).find((s)=>n.test(s))??r.trim().split(`
|
|
293
297
|
`)[0];throw Error(`Built package at ${t} cannot be imported: ${o}
|
|
294
|
-
Fix the generated module at its source before publishing.`)}}async function
|
|
295
|
-
`),await
|
|
298
|
+
Fix the generated module at its source before publishing.`)}}async function cx(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 r0(e.dir),await n0(e.dir);let n=await oh([Rt.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let o of n){let s=await e0(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(`${sl(al(`[${a}]`))} ${al("dist/")}${l}`)}console.log(`${sl(al(`[${i}ms]`))} Built ${nh(sl(t0(r)))}`)}async function fx(e){let t=e.pkgName??`@stacksjs/${Rt.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else i0.info(`Building ${nh(t)}...`);return{startTime:Date.now()}}async function ux(e){await Promise.resolve().then(() => rh());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??s0(),plugins:[ih({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=o0(a);let l=Rt.resolve(r,s.replace(/\.ts$/,".js"));await Q1(Rt.dirname(l),{recursive:!0}),await Bun.write(l,a)}}function o0(e){return e.replace(/(['"])(\.\.?\/[^'"]+?)(?<!\.d)\.tsx?\1/g,"$1$2.js$1")}function s0(e=[]){let t=[];try{let i=yh("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{bh as buildWorkspacePackages,Qo as dependencyLayers,s0 as frameworkExternal,fx as intro,cx as outro,o0 as rewriteRelativeTsSpecifiers,ux as transpilePackage,r0 as validateDeclarations,n0 as validateRuntimeExports,vh as workspaceBuildTargets};
|