@stacksjs/build 0.70.101 → 0.70.103

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 CHANGED
@@ -1,85 +1,85 @@
1
1
  // @bun
2
- var fl=Object.defineProperty;var ul=(e)=>e;function hl(e,t){this[e]=ul.bind(null,t)}var dl=(e,t)=>{for(var r in t)fl(e,r,{get:t[r],enumerable:!0,configurable:!0,set:hl.bind(t,r)})};var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ke=import.meta.require;function As(e,t,r){let i={file:t,message:"Unknown error",code:ir.UNKNOWN_ERROR};if(e instanceof Error){i.message=e.message,i.stack=e.stack;let n=e.message.match(/\((\d+),(\d+)\)/);if(n)i.location={line:Number.parseInt(n[1],10),column:Number.parseInt(n[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))i.code=ir.FILE_NOT_FOUND,i.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))i.code=ir.SYNTAX_ERROR,i.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))i.code=ir.TYPE_INFERENCE_ERROR,i.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))i.code=ir.PARSE_ERROR,i.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")i.message=e;return i}function xs(e,t){let r=[],i=e.file;if(e.location)i+=`:${e.location.line}:${e.location.column}`;if(e.code)i+=` [${e.code}]`;if(r.push(i),r.push(` Error: ${e.message}`),t&&e.location){r.push("");let n=t.split(`
2
+ var ul=Object.defineProperty;var hl=(e)=>e;function dl(e,t){this[e]=hl.bind(null,t)}var ml=(e,t)=>{for(var r in t)ul(e,r,{get:t[r],enumerable:!0,configurable:!0,set:dl.bind(t,r)})};var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ke=import.meta.require;function As(e,t,r){let i={file:t,message:"Unknown error",code:ir.UNKNOWN_ERROR};if(e instanceof Error){i.message=e.message,i.stack=e.stack;let n=e.message.match(/\((\d+),(\d+)\)/);if(n)i.location={line:Number.parseInt(n[1],10),column:Number.parseInt(n[2],10)};if(e.message.includes("Cannot find")||e.message.includes("not found"))i.code=ir.FILE_NOT_FOUND,i.suggestion="Check that the file path is correct and the file exists.";else if(e.message.includes("syntax")||e.message.includes("Unexpected token"))i.code=ir.SYNTAX_ERROR,i.suggestion="Check for syntax errors in your TypeScript code.";else if(e.message.includes("type")&&e.message.includes("cannot"))i.code=ir.TYPE_INFERENCE_ERROR,i.suggestion="Add explicit type annotations to help with type inference.";else if(e.message.includes("parse")||e.message.includes("Parse"))i.code=ir.PARSE_ERROR,i.suggestion="The file contains invalid TypeScript syntax."}else if(typeof e==="string")i.message=e;return i}function xs(e,t){let r=[],i=e.file;if(e.location)i+=`:${e.location.line}:${e.location.column}`;if(e.code)i+=` [${e.code}]`;if(r.push(i),r.push(` Error: ${e.message}`),t&&e.location){r.push("");let n=t.split(`
3
3
  `),s=e.location.line-1;if(s>=0&&s<n.length){let a=Math.max(0,s-1),o=Math.min(n.length-1,s+1);for(let c=a;c<=o;c++){let f=(c+1).toString().padStart(4," "),u=c===s?">":" ";if(r.push(` ${u} ${f} | ${n[c]}`),c===s&&e.location.column>0){let l=" ".repeat(10+e.location.column-1);r.push(` ${l}^`)}}}}if(e.suggestion)r.push(""),r.push(` Suggestion: ${e.suggestion}`);return r.join(`
4
- `)}var ir;var Mi=ce(()=>{ir={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"}});var Cr=()=>{};async function gl(){if(vr!==null)return vr;try{return Ct=await import("prettier"),vr=!0,!0}catch{return vr=!1,!1}}async function pl(e,t){if(!Ct)return null;try{if(t&&Ct.resolveConfig){let r=await Ct.resolveConfig(t);if(r)return r}if(e&&Ct.resolveConfig){let r=await Ct.resolveConfig(e);if(r)return r}return null}catch{return null}}async function yl(e,t){if(!Ct)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Ct.format(e,r)}function wl(e,t={}){let{indentSize:r=2,useTabs:i=!1,maxLineWidth:n=100,trailingNewline:s=!0,normalizeWhitespace:a=!0,sortImports:o=!0,groupImports:c=!0}=t,f=e,u=i?"\t":" ".repeat(r);if(f.indexOf(`\r
4
+ `)}var ir;var Mi=ce(()=>{ir={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"}});var Cr=()=>{};async function pl(){if(vr!==null)return vr;try{return Ct=await import("prettier"),vr=!0,!0}catch{return vr=!1,!1}}async function yl(e,t){if(!Ct)return null;try{if(t&&Ct.resolveConfig){let r=await Ct.resolveConfig(t);if(r)return r}if(e&&Ct.resolveConfig){let r=await Ct.resolveConfig(e);if(r)return r}return null}catch{return null}}async function wl(e,t){if(!Ct)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return Ct.format(e,r)}function $l(e,t={}){let{indentSize:r=2,useTabs:i=!1,maxLineWidth:n=100,trailingNewline:s=!0,normalizeWhitespace:a=!0,sortImports:o=!0,groupImports:c=!0}=t,f=e,u=i?"\t":" ".repeat(r);if(f.indexOf(`\r
5
5
  `)!==-1)f=f.replace(/\r\n/g,`
6
6
  `);if(a){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
7
7
 
8
8
 
9
9
  `)!==-1)f=f.replace(/\n{3,}/g,`
10
10
 
11
- `);f=$l(f,u)}if(o||c)f=Cl(f,{sort:o,group:c});if(n>0)f=bl(f,n,u);if(s&&!f.endsWith(`
11
+ `);f=Cl(f,u)}if(o||c)f=vl(f,{sort:o,group:c});if(n>0)f=Al(f,n,u);if(s&&!f.endsWith(`
12
12
  `))f+=`
13
- `;return f}function $l(e,t){let r=e.split(`
13
+ `;return f}function Cl(e,t){let r=e.split(`
14
14
  `),i=[];for(let n of r){let s=n.match(/^(\s*)(.*)$/);if(!s){i.push(n);continue}let[,a,o]=s;if(!o){i.push("");continue}let c=a.replace(/\t/g," ").length,f=Math.floor(c/2);i.push(t.repeat(f)+o)}return i.join(`
15
- `)}function Cl(e,t){let r=e.split(`
16
- `),i=[],n=[],s=!1,a=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){s=!0,a=c;let l=u[1];i.push({line:f,source:u[2],isType:l.startsWith("import type ")||l.startsWith("import type\t")})}else if(s&&f.trim()==="")continue;else{if(s)s=!1;n.push(f)}}if(i.length===0)return e;if(t.sort)i.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return vl(c.source,f.source)});let o;if(t.group){let c=[],f=[],u=[],l=[],p=[];for(let d=0;d<i.length;d++){let C=i[d],b=C.source;if(b.charCodeAt(0)===46)p.push(C);else if(b.startsWith("node:"))c.push(C);else if(b.charCodeAt(0)===64)l.push(C);else if(b.includes("/"))u.push(C);else f.push(C)}o=[...c.map((d)=>d.line),...c.length>0&&f.length>0?[""]:[],...f.map((d)=>d.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((d)=>d.line),...l.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...l.map((d)=>d.line),...p.length>0?[""]:[],...p.map((d)=>d.line)]}else o=i.map((c)=>c.line);return[...o,"",...n].join(`
17
- `)}function vl(e,t){let r=e.startsWith("node:"),i=t.startsWith("node:");if(r!==i)return r?-1:1;let n=e.startsWith("."),s=t.startsWith(".");if(n!==s)return n?1:-1;return e.localeCompare(t)}function bl(e,t,r){let i=e.split(`
18
- `),n=[];for(let s of i){if(s.length<=t){n.push(s);continue}if(s.trimStart().startsWith("import ")){n.push(s);continue}let a=s.match(/^(\s*)/)?.[1]||"",o=a+r;if(s.includes("{")&&s.includes("}")){let c=Al(s,t,a,o);n.push(...c);continue}if(s.includes(" | ")){let c=xl(s,t,a,o);n.push(...c);continue}n.push(s)}return n.join(`
19
- `)}function Al(e,t,r,i){let n=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!n)return[e];let[,,s,a,o,c]=n,f=o.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${a}`,...f.map((u)=>`${i}${u.trim()};`),`${r}${c.trim()}`]}function xl(e,t,r,i){let n=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!n)return[e];let[,,s,a]=n,o=a.split(/\s*\|\s*/).filter((c)=>c.trim());if(o.length<=2)return[e];return[`${r}${s}`,...o.map((c,f)=>`${i}${f>0?"| ":" "}${c.trim()}`)]}async function Es(e,t={},r){let i=[];if(t.usePrettier!==!1){if(await gl())try{let n={...await pl(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await yl(e,n),usedPrettier:!0}}catch(n){i.push(`Prettier formatting failed: ${n}. Using built-in formatter.`)}else if(t.usePrettier===!0)i.push("Prettier requested but not available. Using built-in formatter.")}return{content:wl(e,t.builtIn),usedPrettier:!1,warnings:i.length>0?i:void 0}}var vr=null,Ct=null;var Bi=ce(()=>{Cr()});function El(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],r=0,i=0,n=e.length;while(i<n)if(e.charCodeAt(i)===47&&i+1<n&&e.charCodeAt(i+1)===42){if(i>r)t.push(e.substring(r,i));i+=2;while(i<n-1){if(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47){i+=2;break}i++}r=i}else i++;if(r<n)t.push(e.substring(r));return t.join("").trim()}function Gi(){xr=!0,Me=null}function Ui(){xr=!1;let e=Me;return Me=null,e}function Yi(e){let t=e.length;if(t===0)return!1;let r=0;if(e.charCodeAt(r)===45)r++;if(r>=t)return!1;let i=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===i)return!1;if(r<t&&e.charCodeAt(r)===46){r++;let n=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===n)return!1}return r===t}function Ol(e){for(let t=0,r=e.length-1;t<r;t++){let i=e.charCodeAt(t);if(i<48||i>57)return!1}return!0}function _i(e,t){let r=0,i=0;while((i=e.indexOf(t,i))!==-1)r++,i+=t.length;return r}function br(e){let t=e.length,r=!1;for(let a=1;a<t;a++)if(e.charCodeAt(a)<=32&&e.charCodeAt(a-1)<=32){r=!0;break}if(!r)for(let a=0;a<t;a++){let o=e.charCodeAt(a);if(o===10||o===13||o===9){r=!0;break}}if(!r)return e;let i=[],n=-1,s=!1;for(let a=0;a<t;a++)if(e.charCodeAt(a)<=32){if(!s){if(n>=0)i.push(e.substring(n,a));i.push(" "),s=!0,n=-1}}else{if(s||n<0)n=a;s=!1}if(n>=0)i.push(e.substring(n));return i.join("")}function Ae(e,t=!1,r=!1,i=0){if(!e||typeof e!=="string")return"unknown";if(i>=20)return"unknown";let n=e.trim();if(n.startsWith("BigInt("))return"bigint";if(n.startsWith("Symbol.for("))return"symbol";if(n.includes(".raw`")||n.includes("String.raw`"))return"string";if(n.startsWith("`")&&n.endsWith("`")){if(!t||n.includes("${")||n.includes(`
20
- `)||n.includes("\r"))return"string";return n}if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")){if(!t)return"string";return n}if(Yi(n)){if(!t)return"number";return n}if(n==="true"||n==="false"){if(!t)return"boolean";return n}if(n==="null")return"null";if(n==="undefined")return"undefined";if(n.startsWith("[")&&n.endsWith("]"))return Zi(n,t,i+1);if(n.startsWith("{")&&n.endsWith("}"))return Il(n,t,i+1);if(n.startsWith("class ")||n.startsWith("class{"))return Fl(n);if(n.startsWith("new "))return Pl(n);if(n.endsWith("as const")){let s=n.slice(0,-8).trim();if(s.startsWith("[")&&s.endsWith("]")){let a=s.slice(1,-1).trim();if(!a)return"readonly []";let o=Ar(a),c=[];for(let f=0;f<o.length;f++)c.push(Ae(o[f].trim(),!0,!1,i+1));return`readonly [${c.join(", ")}]`}return Ae(s,!0,r,i+1)}if(n.includes("=>")||n.startsWith("function")||n.startsWith("async"))return Fs(n,r,i,t);if(n.startsWith("`")&&n.endsWith("`"))return Wl(n,t);if(n.startsWith("Promise."))return Ns(n,t,i);if(n.startsWith("await "))return"unknown";if(n.charCodeAt(n.length-1)===110&&n.length>1&&Ol(n)){if(t)return n;return"bigint"}if(n.startsWith("Symbol(")||n==="Symbol.for")return"symbol";if(Sl(n))return"boolean";return"unknown"}function Sl(e){let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===34||i===39||i===96){r=sr(e,r,i)-1;continue}if(i===40||i===91||i===123){t++;continue}if(i===41||i===93||i===125){t--;continue}if(t!==0)continue;if(e.startsWith("===",r)||e.startsWith("!==",r)||e.startsWith("==",r)||e.startsWith("!=",r)||e.startsWith(">=",r)||e.startsWith("<=",r))return!0;if((i===62||i===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function kl(e,t=!1,r=0){return Ae(e,t,!0,r)}function nr(e,t=!1,r=""){let i=Rs(r),n=[],s=!1,a=0;while(a<e.length){let c=e.charCodeAt(a);if(c===34||c===39||c===96){a=sr(e,a,c);continue}if(c===47&&e.charCodeAt(a+1)===47){a+=2;while(a<e.length&&e.charCodeAt(a)!==10&&e.charCodeAt(a)!==13)a++;continue}if(c===47&&e.charCodeAt(a+1)===42){let f=e.indexOf("*/",a+2);a=f===-1?e.length:f+2;continue}if(e.startsWith("function",a)&&Os(e,a,8)||e.startsWith("class",a)&&Os(e,a,5)){let f=Nl(e,a);if(f!==-1){a=Ss(e,f);continue}}if(c===61&&e.charCodeAt(a+1)===62){let f=a+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){a=Ss(e,f);continue}}if(e.startsWith("return",a)&&(a===0||!rt(e.charCodeAt(a-1)))&&!rt(e.charCodeAt(a+6))){a+=6;let f=!1;while(a<e.length&&e.charCodeAt(a)<=32){let w=e.charCodeAt(a);if(w===10||w===13)f=!0;a++}if(f||a>=e.length||e.charCodeAt(a)===59||e.charCodeAt(a)===125){s=!0;continue}let u=a,l=0,p=0,d=0;while(a<e.length){let w=e.charCodeAt(a);if(w===34||w===39||w===96){a=sr(e,a,w);continue}if(w===47&&e.charCodeAt(a+1)===47)break;if(w===47&&e.charCodeAt(a+1)===42){let A=e.indexOf("*/",a+2);a=A===-1?e.length:A+2;continue}if(w===40)l++;else if(w===41)l--;else if(w===91)p++;else if(w===93)p--;else if(w===123)d++;else if(w===125){if(d===0&&l===0&&p===0)break;d--}else if(w===59&&l===0&&p===0&&d===0)break;a++}let C=e.slice(u,a).trim(),b=Et(C,i);if(!n.includes(b))n.push(b);continue}a++}if(s&&!n.includes("undefined"))n.push("undefined");let o=n.includes("unknown")?"unknown":n.length===0?"void":n.join(" | ");return t&&!o.startsWith("Promise<")?`Promise<${o}>`:o}function Rs(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,i=0,n=0,s=0;for(let a=0;a<=r.length;a++){let o=r.charCodeAt(a);if(o===40||o===91||o===123)n++;else if(o===41||o===93||o===125)n--;else if(o===60)s++;else if(o===62&&r.charCodeAt(a-1)!==61&&s>0)s--;if(a!==r.length&&(o!==44||n!==0||s!==0))continue;let c=r.slice(i,a).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=c.slice(f+1).trim(),p=l.indexOf("=");if(p!==-1)l=l.slice(0,p).trim();if(ar(u)&&l)t.set(u,l)}i=a+1}return t}function Et(e,t){let r=e.trim();while(Tl(r))r=r.slice(1,-1).trim();if(r.startsWith("await ")){let s=Et(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let i=Rl(r);if(i){let s=Et(i.whenTrue,t),a=Et(i.whenFalse,t);return s===a?s:`${s} | ${a}`}if(["===","!==","==","!=",">=","<="].some((s)=>r.includes(s))||r.includes(" > ")||r.includes(" < "))return"boolean";let n=0;for(let s=r.length-1;s>=0;s--){let a=r.charCodeAt(s);if(a===41||a===93||a===125)n++;else if(a===40||a===91||a===123)n--;else if(n===0&&(a===43||a===45||a===42||a===47||a===37)){let o=Et(r.slice(0,s),t),c=Et(r.slice(s+1),t);if(a===43&&(o==="string"||c==="string"))return"string";if(o==="number"&&c==="number")return"number";break}}return Ae(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let a=s.slice(7);return t.get(a)??"unknown"})}function Tl(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===40)t++;else if(i===41&&--t===0)return r===e.length-1}return!1}function Rl(e){let t=0,r=-1;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);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(i+1)!==63)r=i;else if(n===58&&t===0&&r!==-1)return{whenTrue:e.slice(r+1,i),whenFalse:e.slice(i+1)}}return null}function Os(e,t,r){return(t===0||!rt(e.charCodeAt(t-1)))&&!rt(e.charCodeAt(t+r))}function Nl(e,t){for(let r=t;r<e.length;r++){let i=e.charCodeAt(r);if(i===34||i===39||i===96){r=sr(e,r,i)-1;continue}if(i===123)return r;if(i===59)return-1}return-1}function Ss(e,t){let r=1,i=t+1;while(i<e.length&&r>0){let n=e.charCodeAt(i);if(n===34||n===39||n===96){i=sr(e,i,n);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){let s=e.indexOf("*/",i+2);i=s===-1?e.length:s+2;continue}if(n===123)r++;else if(n===125)r--;i++}return i}function sr(e,t,r){let i=t+1;while(i<e.length){let n=e.charCodeAt(i);if(n===92){i+=2;continue}if(i++,n===r)break}return i}function Wl(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
21
- `)||e.includes("\r"))return"string";return e}function Pl(e){let t=4;while(t<e.length&&e.charCodeAt(t)<=32)t++;let r=t,i=e.charCodeAt(t);if(i<65||i>90)return"unknown";while(t<e.length&&(rt(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let n=e.slice(r,t);{let s=e.slice(t),a=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);a=s.slice(f+1);let l=a.indexOf("(");if(l!==-1){let p=0,d=-1;for(let C=l;C<a.length;C++)if(a[C]==="(")p++;else if(a[C]===")"){if(p--,p===0){d=C;break}}if(d!==-1){if(a.slice(d+1).trimStart().startsWith("."))return"unknown"}}return`${n}${u}`}}let o=a.indexOf("(");if(o!==-1){let c=0,f=-1;for(let u=o;u<a.length;u++)if(a[u]==="(")c++;else if(a[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(a.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(n){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return n}}return"unknown"}function Fl(e){let t=e.trimStart(),r=5;while(r<t.length&&t.charCodeAt(r)<=32)r++;let i=r;if(r<t.length&&rt(t.charCodeAt(r))){while(r<t.length&&rt(t.charCodeAt(r)))r++;return`typeof ${t.slice(i,r)}`}return"{ new (...args: any[]): any }"}function Ns(e,t,r=0){if(e.startsWith("Promise.resolve(")){let i=e.indexOf(")",16);if(i!==-1){let n=e.slice(16,i).trim();if(n)return`Promise<${Ae(n,t,!1,r+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let i=e.indexOf("[",12),n=e.lastIndexOf("]");if(i!==-1&&n>i){let s=e.slice(i+1,n).trim(),a=Ar(s),o=[];for(let c=0;c<a.length;c++){let f=a[c].trim();if(f.startsWith("Promise.resolve(")){let u=Ns(f,t,r+1),l=u.indexOf("<"),p=u.lastIndexOf(">");o.push(l!==-1&&p>l?u.slice(l+1,p):"unknown")}else o.push(Ae(f,t,!1,r+1))}return`Promise<[${o.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Zi(e,t,r=0){let i=e.slice(1,-1).trim();if(!i)return"never[]";if(r>=20)return"unknown[]";let n=Ar(i),s=!1;for(let p=0;p<n.length;p++){let d=n[p],C=d.length;while(C>0&&d.charCodeAt(C-1)<=32)C--;if(C>=8&&d.slice(C-8,C)==="as const"){s=!0;break}}if(s){let p=[];for(let d=0;d<n.length;d++){let C=n[d].trim();if(C.endsWith("as const")){let b=C.slice(0,-8).trim();if(b.startsWith("[")&&b.endsWith("]")){let w=b.slice(1,-1).trim(),A=Ar(w),S=[];for(let k=0;k<A.length;k++)S.push(Ae(A[k].trim(),!0,!1,r+1));p.push(`readonly [${S.join(", ")}]`)}else p.push(Ae(b,!0,!1,r+1))}else if(C.startsWith("[")&&C.endsWith("]"))p.push(Zi(C,!0,r+1));else p.push(Ae(C,!0,!1,r+1))}return`readonly [
15
+ `)}function vl(e,t){let r=e.split(`
16
+ `),i=[],n=[],s=!1,a=0;for(let c=0;c<r.length;c++){let f=r[c],u=f.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(u){s=!0,a=c;let l=u[1];i.push({line:f,source:u[2],isType:l.startsWith("import type ")||l.startsWith("import type\t")})}else if(s&&f.trim()==="")continue;else{if(s)s=!1;n.push(f)}}if(i.length===0)return e;if(t.sort)i.sort((c,f)=>{if(c.isType!==f.isType)return c.isType?1:-1;return bl(c.source,f.source)});let o;if(t.group){let c=[],f=[],u=[],l=[],p=[];for(let d=0;d<i.length;d++){let C=i[d],b=C.source;if(b.charCodeAt(0)===46)p.push(C);else if(b.startsWith("node:"))c.push(C);else if(b.charCodeAt(0)===64)l.push(C);else if(b.includes("/"))u.push(C);else f.push(C)}o=[...c.map((d)=>d.line),...c.length>0&&f.length>0?[""]:[],...f.map((d)=>d.line),...(c.length>0||f.length>0)&&u.length>0?[""]:[],...u.map((d)=>d.line),...l.length>0&&(c.length>0||f.length>0||u.length>0)?[""]:[],...l.map((d)=>d.line),...p.length>0?[""]:[],...p.map((d)=>d.line)]}else o=i.map((c)=>c.line);return[...o,"",...n].join(`
17
+ `)}function bl(e,t){let r=e.startsWith("node:"),i=t.startsWith("node:");if(r!==i)return r?-1:1;let n=e.startsWith("."),s=t.startsWith(".");if(n!==s)return n?1:-1;return e.localeCompare(t)}function Al(e,t,r){let i=e.split(`
18
+ `),n=[];for(let s of i){if(s.length<=t){n.push(s);continue}if(s.trimStart().startsWith("import ")){n.push(s);continue}let a=s.match(/^(\s*)/)?.[1]||"",o=a+r;if(s.includes("{")&&s.includes("}")){let c=xl(s,t,a,o);n.push(...c);continue}if(s.includes(" | ")){let c=El(s,t,a,o);n.push(...c);continue}n.push(s)}return n.join(`
19
+ `)}function xl(e,t,r,i){let n=e.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!n)return[e];let[,,s,a,o,c]=n,f=o.split(/;\s*|,\s*/).filter((u)=>u.trim());if(f.length<=1)return[e];return[`${r}${s}${a}`,...f.map((u)=>`${i}${u.trim()};`),`${r}${c.trim()}`]}function El(e,t,r,i){let n=e.match(/^(\s*)(.*?=\s*)(.+)$/);if(!n)return[e];let[,,s,a]=n,o=a.split(/\s*\|\s*/).filter((c)=>c.trim());if(o.length<=2)return[e];return[`${r}${s}`,...o.map((c,f)=>`${i}${f>0?"| ":" "}${c.trim()}`)]}async function Es(e,t={},r){let i=[];if(t.usePrettier!==!1){if(await pl())try{let n={...await yl(t.prettierConfigPath,r),...t.prettierOptions,parser:"typescript"};return{content:await wl(e,n),usedPrettier:!0}}catch(n){i.push(`Prettier formatting failed: ${n}. Using built-in formatter.`)}else if(t.usePrettier===!0)i.push("Prettier requested but not available. Using built-in formatter.")}return{content:$l(e,t.builtIn),usedPrettier:!1,warnings:i.length>0?i:void 0}}var vr=null,Ct=null;var Bi=ce(()=>{Cr()});function Ol(e){if(e.indexOf("/*")===-1)return e.trim();let t=[],r=0,i=0,n=e.length;while(i<n)if(e.charCodeAt(i)===47&&i+1<n&&e.charCodeAt(i+1)===42){if(i>r)t.push(e.substring(r,i));i+=2;while(i<n-1){if(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47){i+=2;break}i++}r=i}else i++;if(r<n)t.push(e.substring(r));return t.join("").trim()}function Gi(){xr=!0,Me=null}function Ui(){xr=!1;let e=Me;return Me=null,e}function Yi(e){let t=e.length;if(t===0)return!1;let r=0;if(e.charCodeAt(r)===45)r++;if(r>=t)return!1;let i=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===i)return!1;if(r<t&&e.charCodeAt(r)===46){r++;let n=r;while(r<t&&e.charCodeAt(r)>=48&&e.charCodeAt(r)<=57)r++;if(r===n)return!1}return r===t}function Sl(e){for(let t=0,r=e.length-1;t<r;t++){let i=e.charCodeAt(t);if(i<48||i>57)return!1}return!0}function _i(e,t){let r=0,i=0;while((i=e.indexOf(t,i))!==-1)r++,i+=t.length;return r}function br(e){let t=e.length,r=!1;for(let a=1;a<t;a++)if(e.charCodeAt(a)<=32&&e.charCodeAt(a-1)<=32){r=!0;break}if(!r)for(let a=0;a<t;a++){let o=e.charCodeAt(a);if(o===10||o===13||o===9){r=!0;break}}if(!r)return e;let i=[],n=-1,s=!1;for(let a=0;a<t;a++)if(e.charCodeAt(a)<=32){if(!s){if(n>=0)i.push(e.substring(n,a));i.push(" "),s=!0,n=-1}}else{if(s||n<0)n=a;s=!1}if(n>=0)i.push(e.substring(n));return i.join("")}function Ae(e,t=!1,r=!1,i=0){if(!e||typeof e!=="string")return"unknown";if(i>=20)return"unknown";let n=e.trim();if(n.startsWith("BigInt("))return"bigint";if(n.startsWith("Symbol.for("))return"symbol";if(n.includes(".raw`")||n.includes("String.raw`"))return"string";if(n.startsWith("`")&&n.endsWith("`")){if(!t||n.includes("${")||n.includes(`
20
+ `)||n.includes("\r"))return"string";return n}if(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")){if(!t)return"string";return n}if(Yi(n)){if(!t)return"number";return n}if(n==="true"||n==="false"){if(!t)return"boolean";return n}if(n==="null")return"null";if(n==="undefined")return"undefined";if(n.startsWith("[")&&n.endsWith("]"))return Zi(n,t,i+1);if(n.startsWith("{")&&n.endsWith("}"))return Ll(n,t,i+1);if(n.startsWith("class ")||n.startsWith("class{"))return Dl(n);if(n.startsWith("new "))return Fl(n);if(n.endsWith("as const")){let s=n.slice(0,-8).trim();if(s.startsWith("[")&&s.endsWith("]")){let a=s.slice(1,-1).trim();if(!a)return"readonly []";let o=Ar(a),c=[];for(let f=0;f<o.length;f++)c.push(Ae(o[f].trim(),!0,!1,i+1));return`readonly [${c.join(", ")}]`}return Ae(s,!0,r,i+1)}if(n.includes("=>")||n.startsWith("function")||n.startsWith("async"))return Fs(n,r,i,t);if(n.startsWith("`")&&n.endsWith("`"))return Pl(n,t);if(n.startsWith("Promise."))return Ns(n,t,i);if(n.startsWith("await "))return"unknown";if(n.charCodeAt(n.length-1)===110&&n.length>1&&Sl(n)){if(t)return n;return"bigint"}if(n.startsWith("Symbol(")||n==="Symbol.for")return"symbol";if(kl(n))return"boolean";return"unknown"}function kl(e){let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===34||i===39||i===96){r=sr(e,r,i)-1;continue}if(i===40||i===91||i===123){t++;continue}if(i===41||i===93||i===125){t--;continue}if(t!==0)continue;if(e.startsWith("===",r)||e.startsWith("!==",r)||e.startsWith("==",r)||e.startsWith("!=",r)||e.startsWith(">=",r)||e.startsWith("<=",r))return!0;if((i===62||i===60)&&e.charCodeAt(r-1)!==61&&e.charCodeAt(r+1)!==61)return!0}return!1}function Tl(e,t=!1,r=0){return Ae(e,t,!0,r)}function nr(e,t=!1,r=""){let i=Rs(r),n=[],s=!1,a=0;while(a<e.length){let c=e.charCodeAt(a);if(c===34||c===39||c===96){a=sr(e,a,c);continue}if(c===47&&e.charCodeAt(a+1)===47){a+=2;while(a<e.length&&e.charCodeAt(a)!==10&&e.charCodeAt(a)!==13)a++;continue}if(c===47&&e.charCodeAt(a+1)===42){let f=e.indexOf("*/",a+2);a=f===-1?e.length:f+2;continue}if(e.startsWith("function",a)&&Os(e,a,8)||e.startsWith("class",a)&&Os(e,a,5)){let f=Wl(e,a);if(f!==-1){a=Ss(e,f);continue}}if(c===61&&e.charCodeAt(a+1)===62){let f=a+2;while(f<e.length&&e.charCodeAt(f)<=32)f++;if(e.charCodeAt(f)===123){a=Ss(e,f);continue}}if(e.startsWith("return",a)&&(a===0||!it(e.charCodeAt(a-1)))&&!it(e.charCodeAt(a+6))){a+=6;let f=!1;while(a<e.length&&e.charCodeAt(a)<=32){let w=e.charCodeAt(a);if(w===10||w===13)f=!0;a++}if(f||a>=e.length||e.charCodeAt(a)===59||e.charCodeAt(a)===125){s=!0;continue}let u=a,l=0,p=0,d=0;while(a<e.length){let w=e.charCodeAt(a);if(w===34||w===39||w===96){a=sr(e,a,w);continue}if(w===47&&e.charCodeAt(a+1)===47)break;if(w===47&&e.charCodeAt(a+1)===42){let A=e.indexOf("*/",a+2);a=A===-1?e.length:A+2;continue}if(w===40)l++;else if(w===41)l--;else if(w===91)p++;else if(w===93)p--;else if(w===123)d++;else if(w===125){if(d===0&&l===0&&p===0)break;d--}else if(w===59&&l===0&&p===0&&d===0)break;a++}let C=e.slice(u,a).trim(),b=Et(C,i);if(!n.includes(b))n.push(b);continue}a++}if(s&&!n.includes("undefined"))n.push("undefined");let o=n.includes("unknown")?"unknown":n.length===0?"void":n.join(" | ");return t&&!o.startsWith("Promise<")?`Promise<${o}>`:o}function Rs(e){let t=new Map,r=e.startsWith("(")&&e.endsWith(")")?e.slice(1,-1):e,i=0,n=0,s=0;for(let a=0;a<=r.length;a++){let o=r.charCodeAt(a);if(o===40||o===91||o===123)n++;else if(o===41||o===93||o===125)n--;else if(o===60)s++;else if(o===62&&r.charCodeAt(a-1)!==61&&s>0)s--;if(a!==r.length&&(o!==44||n!==0||s!==0))continue;let c=r.slice(i,a).trim(),f=c.indexOf(":");if(f!==-1){let u=c.slice(0,f).trim().replace(/^\.\.\./,"").replace(/\?$/,""),l=c.slice(f+1).trim(),p=l.indexOf("=");if(p!==-1)l=l.slice(0,p).trim();if(ar(u)&&l)t.set(u,l)}i=a+1}return t}function Et(e,t){let r=e.trim();while(Rl(r))r=r.slice(1,-1).trim();if(r.startsWith("await ")){let s=Et(r.slice(6),t);return s.startsWith("Promise<")&&s.endsWith(">")?s.slice(8,-1):s}if(t.has(r))return t.get(r);if(r.startsWith("!"))return"boolean";if(r.startsWith("fetch("))return"Promise<Response>";let i=Nl(r);if(i){let s=Et(i.whenTrue,t),a=Et(i.whenFalse,t);return s===a?s:`${s} | ${a}`}if(["===","!==","==","!=",">=","<="].some((s)=>r.includes(s))||r.includes(" > ")||r.includes(" < "))return"boolean";let n=0;for(let s=r.length-1;s>=0;s--){let a=r.charCodeAt(s);if(a===41||a===93||a===125)n++;else if(a===40||a===91||a===123)n--;else if(n===0&&(a===43||a===45||a===42||a===47||a===37)){let o=Et(r.slice(0,s),t),c=Et(r.slice(s+1),t);if(a===43&&(o==="string"||c==="string"))return"string";if(o==="number"&&c==="number")return"number";break}}return Ae(r,!1).replace(/\btypeof\s+[$A-Z_a-z][$\w]*/g,(s)=>{let a=s.slice(7);return t.get(a)??"unknown"})}function Rl(e){if(!e.startsWith("(")||!e.endsWith(")"))return!1;let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===40)t++;else if(i===41&&--t===0)return r===e.length-1}return!1}function Nl(e){let t=0,r=-1;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);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(i+1)!==63)r=i;else if(n===58&&t===0&&r!==-1)return{whenTrue:e.slice(r+1,i),whenFalse:e.slice(i+1)}}return null}function Os(e,t,r){return(t===0||!it(e.charCodeAt(t-1)))&&!it(e.charCodeAt(t+r))}function Wl(e,t){for(let r=t;r<e.length;r++){let i=e.charCodeAt(r);if(i===34||i===39||i===96){r=sr(e,r,i)-1;continue}if(i===123)return r;if(i===59)return-1}return-1}function Ss(e,t){let r=1,i=t+1;while(i<e.length&&r>0){let n=e.charCodeAt(i);if(n===34||n===39||n===96){i=sr(e,i,n);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){let s=e.indexOf("*/",i+2);i=s===-1?e.length:s+2;continue}if(n===123)r++;else if(n===125)r--;i++}return i}function sr(e,t,r){let i=t+1;while(i<e.length){let n=e.charCodeAt(i);if(n===92){i+=2;continue}if(i++,n===r)break}return i}function Pl(e,t){if(e.includes(".raw`")||e.includes("String.raw`"))return"string";if(!t||e.includes("${")||e.includes(`
21
+ `)||e.includes("\r"))return"string";return e}function Fl(e){let t=4;while(t<e.length&&e.charCodeAt(t)<=32)t++;let r=t,i=e.charCodeAt(t);if(i<65||i>90)return"unknown";while(t<e.length&&(it(e.charCodeAt(t))||e.charCodeAt(t)===46))t++;if(t===r)return"unknown";let n=e.slice(r,t);{let s=e.slice(t),a=s;if(s.startsWith("<")){let c=0,f=-1;for(let u=0;u<s.length;u++)if(s[u]==="<")c++;else if(s[u]===">"){if(c--,c===0){f=u;break}}if(f!==-1){let u=s.slice(0,f+1);a=s.slice(f+1);let l=a.indexOf("(");if(l!==-1){let p=0,d=-1;for(let C=l;C<a.length;C++)if(a[C]==="(")p++;else if(a[C]===")"){if(p--,p===0){d=C;break}}if(d!==-1){if(a.slice(d+1).trimStart().startsWith("."))return"unknown"}}return`${n}${u}`}}let o=a.indexOf("(");if(o!==-1){let c=0,f=-1;for(let u=o;u<a.length;u++)if(a[u]==="(")c++;else if(a[u]===")"){if(c--,c===0){f=u;break}}if(f!==-1){if(a.slice(f+1).trimStart().startsWith("."))return"unknown"}}switch(n){case"Date":return"Date";case"Map":return"Map<any, any>";case"Set":return"Set<any>";case"WeakMap":return"WeakMap<any, any>";case"WeakSet":return"WeakSet<any>";case"RegExp":return"RegExp";case"Error":return"Error";case"Array":return"any[]";case"Object":return"object";case"Function":return"Function";case"Promise":return"Promise<any>";default:return n}}return"unknown"}function Dl(e){let t=e.trimStart(),r=5;while(r<t.length&&t.charCodeAt(r)<=32)r++;let i=r;if(r<t.length&&it(t.charCodeAt(r))){while(r<t.length&&it(t.charCodeAt(r)))r++;return`typeof ${t.slice(i,r)}`}return"{ new (...args: any[]): any }"}function Ns(e,t,r=0){if(e.startsWith("Promise.resolve(")){let i=e.indexOf(")",16);if(i!==-1){let n=e.slice(16,i).trim();if(n)return`Promise<${Ae(n,t,!1,r+1)}>`}return"Promise<unknown>"}if(e.startsWith("Promise.reject("))return"Promise<never>";if(e.startsWith("Promise.all(")){let i=e.indexOf("[",12),n=e.lastIndexOf("]");if(i!==-1&&n>i){let s=e.slice(i+1,n).trim(),a=Ar(s),o=[];for(let c=0;c<a.length;c++){let f=a[c].trim();if(f.startsWith("Promise.resolve(")){let u=Ns(f,t,r+1),l=u.indexOf("<"),p=u.lastIndexOf(">");o.push(l!==-1&&p>l?u.slice(l+1,p):"unknown")}else o.push(Ae(f,t,!1,r+1))}return`Promise<[${o.join(", ")}]>`}return"Promise<unknown[]>"}return"Promise<unknown>"}function Zi(e,t,r=0){let i=e.slice(1,-1).trim();if(!i)return"never[]";if(r>=20)return"unknown[]";let n=Ar(i),s=!1;for(let p=0;p<n.length;p++){let d=n[p],C=d.length;while(C>0&&d.charCodeAt(C-1)<=32)C--;if(C>=8&&d.slice(C-8,C)==="as const"){s=!0;break}}if(s){let p=[];for(let d=0;d<n.length;d++){let C=n[d].trim();if(C.endsWith("as const")){let b=C.slice(0,-8).trim();if(b.startsWith("[")&&b.endsWith("]")){let w=b.slice(1,-1).trim(),A=Ar(w),S=[];for(let k=0;k<A.length;k++)S.push(Ae(A[k].trim(),!0,!1,r+1));p.push(`readonly [${S.join(", ")}]`)}else p.push(Ae(b,!0,!1,r+1))}else if(C.startsWith("[")&&C.endsWith("]"))p.push(Zi(C,!0,r+1));else p.push(Ae(C,!0,!1,r+1))}return`readonly [
22
22
  ${p.join(` |
23
23
  `)}
24
- ]`}let a=xr&&!t,o=[],c=[];for(let p of n){let d=p.trim(),C=Me;if(Me=null,d.startsWith("...")){let b=d.slice(3).trim(),w=Ae(b,!1,!1,r+1);if(w.endsWith("[]"))o.push(w.slice(0,-2));else if(w.startsWith("readonly [")&&w.endsWith("]"))o.push(w.slice(10,-1));else if(Ji(b))o.push(`(typeof ${b})[number]`);else o.push("unknown")}else if(d.startsWith("[")&&d.endsWith("]"))o.push(Zi(d,t,r+1));else o.push(kl(d,t,r+1));if(a)c.push(Me);Me=C}if(a)if(Ki(e))Me=br(e);else{let p=[];for(let d=0;d<n.length;d++){let C=n[d].trim();if(C.endsWith("as const"))continue;if(Vi(C)||C==="null"||C==="undefined")p.push(C);else if(C.startsWith("[")&&Ki(C))p.push(br(C));else if(C.startsWith("{")){if(c[d])p.push(c[d])}else{let b=Ae(C,!1,!1,0);if(b!=="unknown")p.push(b)}}if(p.length>0)Me=`[${p.join(", ")}]`}if(t)return`readonly [${o.join(", ")}]`;let f=new Set,u=[],l=!0;for(let p of o){if(!f.has(p))f.add(p),u.push(p);if(l){if(!(Yi(p)||p==="true"||p==="false"||p.charCodeAt(0)===34&&p.charCodeAt(p.length-1)===34||p.charCodeAt(0)===39&&p.charCodeAt(p.length-1)===39))l=!1}}if(l&&o.length<=10)return`readonly [${o.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Ar(e){let t=[],r=0,i=0,n=!1,s=0;for(let o=0;o<e.length;o++){let c=e.charCodeAt(o);if(!n&&(c===34||c===39||c===96))n=!0,s=c;else if(n&&c===s&&(o===0||e.charCodeAt(o-1)!==92))n=!1;if(!n){if(c===91||c===123||c===40)i++;else if(c===93||c===125||c===41)i--;else if(c===44&&i===0){let f=e.substring(r,o).trim();if(f)t.push(f);r=o+1;continue}}}let a=e.substring(r).trim();if(a)t.push(a);return t}function Vi(e){if(Yi(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Dl(e){return e==="number"||e==="string"||e==="boolean"}function Ki(e){let t=!1,r=0,i=e.length;for(let n=0;n<i;n++){let s=e.charCodeAt(n);if(t){if(s===92){n++;continue}if(s===r)t=!1;continue}if(s===34||s===39||s===96){t=!0,r=s;continue}if(s===61&&n+1<i&&e.charCodeAt(n+1)===62)return!1;if(s>=97&&s<=122){let a=n;while(n<i&&(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 o=e.slice(a,n);if(o==="new"||o==="async"||o==="await"||o==="function"||o==="yield"||o==="console"||o==="process")return!1;let c=n;while(c<i&&e.charCodeAt(c)<=32)c++;if(c<i&&e.charCodeAt(c)===40)return!1;n--}}return!0}function Il(e,t,r=0){let i=e.slice(1,-1).trim();if(!i)return"{}";if(r>=20)return"Record<string, unknown>";let n=_l(i),s=[],a=[],o=xr&&!t,c=[];for(let[l,p]of n){let{comments:d,key:C}=Bl(l),b=d?`${d}
25
- `:"";if(C==="..."){let M=p.trim(),te=Ji(M)?`typeof ${M}`:Ae(M,t,!1,r+1);if(te!=="unknown")a.push(te);if(o&&(Ji(M)||M.startsWith("{")))c.push(`...${br(M)}`);continue}let w=Me;Me=null;let A,S=p.trim();if(S===C&&ar(S))A=`typeof ${S}`;else if(Kl(S))A=Jl(C,S);else if(A=Ae(p,t,!1,r+1),A.includes("=>")||A.includes("function")||A.includes("async"))A=Ll(A);let k=Me;Me=w;let T=p.trim(),v=Zl(C);if(v){let M=Vl(v.kind,v.name,A);if(M){s.push(`${b}${M}`);continue}}if(!t&&Dl(A)&&Vi(T))s.push(`${b}/** @defaultValue ${T} */
26
- ${C}: ${A}`);else s.push(`${b}${C}: ${A}`);if(o){let M=El(C);if(T.endsWith("as const"));else if(Vi(T))c.push(`${M}: ${T}`);else if(T.startsWith("[")&&Ki(T))c.push(`${M}: ${br(T)}`);else if(T.startsWith("{")){if(k)c.push(`${M}: ${k}`)}else if(!T.startsWith("[")&&(T.includes("=>")||T.startsWith("function")||T.startsWith("async"))){let te=Fs(T,!1,0,!0);c.push(`${M}: ${te}`)}}}if(o&&c.length>0){let l=r>0?(r-1)/2:0,p=`{ ${c.join(", ")} }`;if(p.length<=80)Me=p;else{let d=" ".repeat((l+1)*2),C=" ".repeat(l*2);Me=`{
24
+ ]`}let a=xr&&!t,o=[],c=[];for(let p of n){let d=p.trim(),C=Me;if(Me=null,d.startsWith("...")){let b=d.slice(3).trim(),w=Ae(b,!1,!1,r+1);if(w.endsWith("[]"))o.push(w.slice(0,-2));else if(w.startsWith("readonly [")&&w.endsWith("]"))o.push(w.slice(10,-1));else if(Ji(b))o.push(`(typeof ${b})[number]`);else o.push("unknown")}else if(d.startsWith("[")&&d.endsWith("]"))o.push(Zi(d,t,r+1));else o.push(Tl(d,t,r+1));if(a)c.push(Me);Me=C}if(a)if(Ki(e))Me=br(e);else{let p=[];for(let d=0;d<n.length;d++){let C=n[d].trim();if(C.endsWith("as const"))continue;if(Vi(C)||C==="null"||C==="undefined")p.push(C);else if(C.startsWith("[")&&Ki(C))p.push(br(C));else if(C.startsWith("{")){if(c[d])p.push(c[d])}else{let b=Ae(C,!1,!1,0);if(b!=="unknown")p.push(b)}}if(p.length>0)Me=`[${p.join(", ")}]`}if(t)return`readonly [${o.join(", ")}]`;let f=new Set,u=[],l=!0;for(let p of o){if(!f.has(p))f.add(p),u.push(p);if(l){if(!(Yi(p)||p==="true"||p==="false"||p.charCodeAt(0)===34&&p.charCodeAt(p.length-1)===34||p.charCodeAt(0)===39&&p.charCodeAt(p.length-1)===39))l=!1}}if(l&&o.length<=10)return`readonly [${o.join(", ")}]`;if(u.length===1)return`${u[0]}[]`;return`(${u.join(" | ")})[]`}function Ar(e){let t=[],r=0,i=0,n=!1,s=0;for(let o=0;o<e.length;o++){let c=e.charCodeAt(o);if(!n&&(c===34||c===39||c===96))n=!0,s=c;else if(n&&c===s&&(o===0||e.charCodeAt(o-1)!==92))n=!1;if(!n){if(c===91||c===123||c===40)i++;else if(c===93||c===125||c===41)i--;else if(c===44&&i===0){let f=e.substring(r,o).trim();if(f)t.push(f);r=o+1;continue}}}let a=e.substring(r).trim();if(a)t.push(a);return t}function Vi(e){if(Yi(e))return!0;if(e==="true"||e==="false")return!0;if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return!0;return!1}function Il(e){return e==="number"||e==="string"||e==="boolean"}function Ki(e){let t=!1,r=0,i=e.length;for(let n=0;n<i;n++){let s=e.charCodeAt(n);if(t){if(s===92){n++;continue}if(s===r)t=!1;continue}if(s===34||s===39||s===96){t=!0,r=s;continue}if(s===61&&n+1<i&&e.charCodeAt(n+1)===62)return!1;if(s>=97&&s<=122){let a=n;while(n<i&&(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 o=e.slice(a,n);if(o==="new"||o==="async"||o==="await"||o==="function"||o==="yield"||o==="console"||o==="process")return!1;let c=n;while(c<i&&e.charCodeAt(c)<=32)c++;if(c<i&&e.charCodeAt(c)===40)return!1;n--}}return!0}function Ll(e,t,r=0){let i=e.slice(1,-1).trim();if(!i)return"{}";if(r>=20)return"Record<string, unknown>";let n=Zl(i),s=[],a=[],o=xr&&!t,c=[];for(let[l,p]of n){let{comments:d,key:C}=_l(l),b=d?`${d}
25
+ `:"";if(C==="..."){let M=p.trim(),te=Ji(M)?`typeof ${M}`:Ae(M,t,!1,r+1);if(te!=="unknown")a.push(te);if(o&&(Ji(M)||M.startsWith("{")))c.push(`...${br(M)}`);continue}let w=Me;Me=null;let A,S=p.trim();if(S===C&&ar(S))A=`typeof ${S}`;else if(Jl(S))A=Gl(C,S);else if(A=Ae(p,t,!1,r+1),A.includes("=>")||A.includes("function")||A.includes("async"))A=jl(A);let k=Me;Me=w;let T=p.trim(),v=Vl(C);if(v){let M=Kl(v.kind,v.name,A);if(M){s.push(`${b}${M}`);continue}}if(!t&&Il(A)&&Vi(T))s.push(`${b}/** @defaultValue ${T} */
26
+ ${C}: ${A}`);else s.push(`${b}${C}: ${A}`);if(o){let M=Ol(C);if(T.endsWith("as const"));else if(Vi(T))c.push(`${M}: ${T}`);else if(T.startsWith("[")&&Ki(T))c.push(`${M}: ${br(T)}`);else if(T.startsWith("{")){if(k)c.push(`${M}: ${k}`)}else if(!T.startsWith("[")&&(T.includes("=>")||T.startsWith("function")||T.startsWith("async"))){let te=Fs(T,!1,0,!0);c.push(`${M}: ${te}`)}}}if(o&&c.length>0){let l=r>0?(r-1)/2:0,p=`{ ${c.join(", ")} }`;if(p.length<=80)Me=p;else{let d=" ".repeat((l+1)*2),C=" ".repeat(l*2);Me=`{
27
27
  ${d}${c.join(`,
28
28
  ${d}`)}
29
29
  ${C}}`}}let f=s.length>0?`{
30
30
  ${s.join(`;
31
31
  `)}
32
- }`:"{}";if(a.length===0)return f;let u=a[0];for(let l=1;l<a.length;l++)u=`Omit<${u}, keyof ${a[l]}> & ${a[l]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function ar(e){if(!e)return!1;let t=e.charCodeAt(0);if(!(t>=65&&t<=90||t>=97&&t<=122||t===95||t===36||t>127))return!1;for(let r=1;r<e.length;r++)if(!rt(e.charCodeAt(r)))return!1;return!0}function Ji(e){let t=e.split(".");return t.length>0&&t.every(ar)}function Ll(e){let t=e.split(`
32
+ }`:"{}";if(a.length===0)return f;let u=a[0];for(let l=1;l<a.length;l++)u=`Omit<${u}, keyof ${a[l]}> & ${a[l]}`;return s.length>0?`Omit<${u}, keyof ${f}> & ${f}`:u}function ar(e){if(!e)return!1;let t=e.charCodeAt(0);if(!(t>=65&&t<=90||t>=97&&t<=122||t===95||t===36||t>127))return!1;for(let r=1;r<e.length;r++)if(!it(e.charCodeAt(r)))return!1;return!0}function Ji(e){let t=e.split(".");return t.length>0&&t.every(ar)}function jl(e){let t=e.split(`
33
33
  `).map((f)=>Ws(f)).join(`
34
- `),r=t.indexOf("async");if(r!==-1){let f=r>0?t.charCodeAt(r-1):32,u=r+5<t.length?t.charCodeAt(r+5):32;if(!rt(f)&&!rt(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let i=t.indexOf("(");if(i!==-1){let f=vt(t,i,"(",")");if(f!==-1){let u=t.slice(i,f+1),l=Pt(u);t=t.slice(0,i)+l+t.slice(f+1)}}let n=t.length,s="",a=[],o=!1,c=!1;for(let f=0;f<n;f++){let u=t.charCodeAt(f);if(u===123||u===40)a.push(u);else if(u===125||u===41)a.pop();if(u<=32){if(o=!0,u===10||u===13)c=!0;continue}if(o&&s.length>0){let l=(a.length>0?a[a.length-1]:0)===123;if(c&&l){let p=s.charCodeAt(s.length-1),d=p===59||p===44||p===123||u===125,C=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!d&&!C)s+="; ";else s+=" "}else s+=" "}o=!1,c=!1,s+=t[f]}return s.trim()}function rt(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Pt(e){let t=e.trim(),r,i=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),i=!0;else r=t;let n=r.trim();if(!n)return i?"()":"";let s=!1;{let C=0;for(let b=0;b<n.length;b++){let w=n.charCodeAt(b);if(w===40||w===60||w===91||w===123)C++;else if(w===41||w===62||w===93||w===125)C--;else if(C===0&&w===61){let A=b>0?n.charCodeAt(b-1):0,S=b+1<n.length?n.charCodeAt(b+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&S!==61&&S!==62){s=!0;break}}}}if(!s)return t;let a=[],o=[],c=0,f=0,u=!1,l=0;for(let C=0;C<=n.length;C++){if(C===n.length){a.push(n.slice(c));break}let b=n.charCodeAt(C);if(u){if(b===92){C++;continue}if(b===l)u=!1;continue}if(b===47&&C+1<n.length){let w=n.charCodeAt(C+1);if(w===42){C+=2;while(C+1<n.length&&!(n.charCodeAt(C)===42&&n.charCodeAt(C+1)===47))C++;C++;continue}if(w===47){while(C<n.length&&n.charCodeAt(C)!==10)C++;continue}}if(b===39||b===34||b===96){u=!0,l=b;continue}if(b===40||b===60||b===91||b===123)f++;else if(b===41||b===62||b===93||b===125)f--;else if(b===44&&f===0){a.push(n.slice(c,C));let w=",",A=C+1;while(A<n.length&&n.charCodeAt(A)<=32)w+=n[A],A++;o.push(w),c=A}}let p=[];for(let C of a){let b=C.trim();if(!b){p.push(C);continue}if(b.startsWith("//"))continue;let w=Ws(b),A=C.slice(0,C.length-C.trimStart().length);p.push(A+jl(w))}let d=p[0]||"";for(let C=1;C<p.length;C++)d+=(o[C-1]||", ")+p[C];return i?`(${d})`:d}function Ws(e){let t=!1,r=0;for(let i=0;i<e.length-1;i++){let n=e.charCodeAt(i);if(t){if(n===92){i++;continue}if(n===r)t=!1;continue}if(n===39||n===34||n===96){t=!0,r=n;continue}if(n===47&&e.charCodeAt(i+1)===47)return e.slice(0,i).trimEnd()}return e}function jl(e){if(e.startsWith("..."))return e;let t=-1,r=-1,i=0,n=!1,s=0;for(let o=0;o<e.length;o++){let c=e.charCodeAt(o);if(n){if(c===92){o++;continue}if(c===s)n=!1;continue}if(c===47&&o+1<e.length){let f=e.charCodeAt(o+1);if(f===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o++;continue}if(f===47){while(o<e.length&&e.charCodeAt(o)!==10)o++;continue}}if(c===39||c===34||c===96){n=!0,s=c;continue}if(c===40||c===60||c===91||c===123)i++;else if(c===41||c===62||c===93||c===125)i--;else if(i===0){if(c===58&&t===-1)t=o;else if(c===61&&r===-1&&(o===0||e.charCodeAt(o-1)!==61)&&(o+1>=e.length||e.charCodeAt(o+1)!==61&&e.charCodeAt(o+1)!==62))r=o}}let a=r!==-1;if(t!==-1&&(r===-1||t<r)){let o=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=a&&!o.endsWith("?")?"?":"";return`${o}${f}: ${c}`}else if(r!==-1){let o=e.slice(0,r).trim(),c=!o.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${o}${c}: ${u}`}return e}function Ml(e){let t=0,r=e.length;while(t<r){while(t<r&&(e.charCodeAt(t)===32||e.charCodeAt(t)===9||e.charCodeAt(t)===10||e.charCodeAt(t)===13))t++;if(t+1<r&&e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42){t+=2;while(t+1<r&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t+=2;continue}break}return t}function Bl(e){let t=[],r=0,i=e.length;while(r<i){while(r<i&&e.charCodeAt(r)<=32)r++;if(r+1>=i||e.charCodeAt(r)!==47||e.charCodeAt(r+1)!==42)break;let n=r;r+=2;while(r+1<i&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47))r++;r=Math.min(r+2,i),t.push(e.slice(n,r).trim())}return{comments:t.join(`
35
- `),key:e.slice(r).trim()}}function _l(e){let t=[],r="",i="",n=0,s=!1,a="",o=!0,c=!1,f=0,u=!1,l=!1,p=0,d=!1,C=!1;for(let b=0;b<e.length;b++){let w=e.charCodeAt(b),A=b>0?e.charCodeAt(b-1):0,S=b<e.length-1?e.charCodeAt(b+1):0;if(!s&&!c&&w===47&&S===47){b+=2;while(b<e.length&&e.charCodeAt(b)!==10)b++;continue}if(!s&&!c&&w===47&&S===42){c=!0,f=1,r+="/*",b++;continue}else if(c&&w===42&&S===47){if(f--,r+="*/",b++,f===0)c=!1;continue}else if(c&&w===47&&S===42){f++,r+="/*",b++;continue}let k=e[b];if(!s&&(w===34||w===39||w===96))s=!0,a=k,r+=k;else if(s&&k===a&&A!==92)s=!1,r+=k;else if(!s&&!c)if(w===40&&n===0&&o){i=r.trim();let T=Ml(i),v=T>0?i.slice(0,T):"",M=i.slice(T),te="";if(M.startsWith("async ")||M.startsWith("async\t")||M.startsWith(`async
36
- `))M=M.slice(6).trimStart(),te="async ";if(M.startsWith("*"))M=M.slice(1).trimStart(),te+="*";i=v+M,r=te+k,o=!1,d=!0,C=!1,n=1}else if(w===123||w===91||w===40){if(n++,r+=k,C&&w===123)C=!1}else if(w===125||w===93||w===41){if(n--,r+=k,w===41&&n===0&&!o&&!d)u=!0;if(d){if(w===41&&n===0&&!C)C=!0;else if(w===125&&n===0)d=!1,C=!1}}else if(w===58&&n===0&&o)i=r.trim(),r="",o=!1;else if(w===58&&n===0&&u)l=!0,r+=k;else if(w===60&&l)p++,r+=k;else if(w===62&&p>0&&A!==61)p--,r+=k;else if(w===61&&S===62&&l&&p===0)l=!1,u=!1,r+=k;else if(w===44&&n===0&&p===0&&!C){if(i&&r.trim()){let T=r.trim();t.push([i,T])}else if(o&&r.trim()){let T=r.trim();if(ar(T))t.push([T,T]);else if(T.startsWith("...")&&T.length>3)t.push(["...",T.slice(3).trim()])}r="",i="",o=!0,u=!1,l=!1,p=0}else r+=k;else r+=k}if(i&&r.trim()){let b=r.trim();t.push([i,b])}else if(o&&r.trim()){let b=r.trim();if(ar(b))t.push([b,b]);else if(b.startsWith("...")&&b.length>3)t.push(["...",b.slice(3).trim()])}return t}function Zl(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"get",name:r}}if(t.startsWith("set ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"set",name:r}}return null}function Vl(e,t,r){let i=r.trim();if(i.charCodeAt(0)!==40)return null;let n=vt(i,0,"(",")");if(n===-1)return null;let s=i.slice(1,n).trim(),a=i.slice(n+1).trimStart();if(!a.startsWith("=>"))return null;let o=a.slice(2).trim();if(e==="get")return`get ${t}(): ${o||"unknown"}`;return`set ${t}(${s})`}function Kl(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n===40)r++;else if(n===41){if(r--,r===0){let s=t.slice(i+1).trimStart();if(s.startsWith("{"))return!0;if(s.startsWith(":")){let a=Ps(s,1);if(a?.kind==="arrow")return!1;if(a?.kind==="body")return!0}return!1}}}return!1}function Jl(e,t){let r=t.trimStart(),i=!1,n=!1;if(r.startsWith("async ")||r.startsWith("async\t"))i=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))n=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let p=0,d=-1;for(let C=0;C<r.length;C++)if(r.charCodeAt(C)===60)p++;else if(r.charCodeAt(C)===62){if(p--,p===0){d=C;break}}if(d!==-1)s=r.slice(0,d+1),r=r.slice(d+1).trimStart()}let a=r.indexOf("("),o=vt(r,a,"(",")");if(a===-1||o===-1)return"() => unknown";let c=r.slice(a,o+1),f="unknown",u=r.slice(o+1).trimStart();if(u.charCodeAt(0)===58){let p=u.slice(1),d=Ps(p,0);if(d)f=p.slice(0,d.index).trim();else f=p.trim()}if(f==="unknown"){if(i&&n)f="AsyncGenerator<unknown, void, unknown>";else if(n)f="Generator<unknown, void, unknown>";else if(i)f="Promise<void>"}else if(i&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let l=Pt(c);return`${s}${l} => ${f}`}function Ps(e,t){let r=0,i=0,n=0,s=0,a=!1,o=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(a){if(f===92)c++;else if(f===o)a=!1;continue}if(f===34||f===39||f===96){a=!0,o=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)i++;else if(f===93&&i>0)i--;else if(f===60)n++;else if(f===62&&n>0)n--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||i>0||n>0||s>0,l=e.slice(t,c).trimEnd(),p=l.charCodeAt(l.length-1),d=l.length===0||p===38||p===124||p===40||p===44||p===58||p===61||p===91;if(u||d)s++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&i===0&&n===0&&s===0)return{index:c,kind:"arrow"}}return null}function vt(e,t,r,i){let n=0;for(let s=t;s<e.length;s++)if(e[s]===r)n++;else if(e[s]===i){if(n--,n===0)return s}return-1}function ks(e){let t=0,r=0,i=!1,n="";for(let s=0;s<e.length-1;s++){let a=e[s],o=e[s+1],c=s>0?e[s-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,n=a;else if(i&&a===n&&c!=="\\")i=!1;if(!i){if(a==="(")t++;else if(a===")")t--;else if(a==="[")r++;else if(a==="]")r--;if(a==="="&&o===">"&&t===0&&r===0)return s}}return-1}function Fs(e,t=!1,r=0,i=!0){let n=e.trim();if(n.length>200&&_i(n,"=>")>2&&_i(n,"<")>5&&!n.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(n.startsWith("async ")&&n.includes("=>")){let a=n.slice(5).trim(),o=ks(a);if(o===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=a.substring(0,o).trim(),f=a.substring(o+2).trim(),u=Ts(c),l=u.params,p=u.returnType;if(l=Pt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let d=p;if(d);else if(f.startsWith("{"))d=nr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else d=Ae(f,i,!1,r+1);let C=`${l} => ${p||d.startsWith("Promise<")?d:`Promise<${d}>`}`;return t?`(${C})`:C}if(n.includes("=>")){let a="",o=n;if(n.startsWith("<")){let w=vt(n,0,"<",">");if(w!==-1)a=n.substring(0,w+1),o=n.substring(w+1).trim()}let c=ks(o);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=o.substring(0,c).trim(),u=o.substring(c+2).trim(),l=Ts(f),p=l.params,d=l.returnType;if(p=Pt(p),p==="()"||p==="")p="()";else if(!p.startsWith("("))p=`(${p})`;let C="unknown";if(d)C=d;else if(u.startsWith("{"))C=nr(u.slice(1,u.endsWith("}")?-1:void 0),!1,p);else if(u.includes("=>")){let w=u.trimStart(),A=w.indexOf("("),S=A!==-1?vt(w,A,"(",")"):-1,k=S!==-1?w.indexOf("=>",S):-1;if(A===0&&S!==-1&&k!==-1){let T=w.substring(A+1,S).trim(),v=Pt(T);if(a.includes("T")&&v.includes("T"))C=`(${v}) => T`;else C=`(${v}) => any`}else C="any"}else if(t)C="unknown";else C=Et(u,Rs(p));let b=`${a}${p} => ${C}`;return t?`(${b})`:b}if(n.startsWith("function")){let a=8,o=n.length;while(a<o&&n.charCodeAt(a)<=32)a++;let c=!1;if(a<o&&n.charCodeAt(a)===42){c=!0,a++;while(a<o&&n.charCodeAt(a)<=32)a++}let f="";if(a<o&&n.charCodeAt(a)===60){let p=a,d=1;a++;while(a<o&&d>0){let C=n.charCodeAt(a);if(C===60)d++;else if(C===62)d--;a++}f=n.substring(p,a);while(a<o&&n.charCodeAt(a)<=32)a++}let u=n.indexOf("(",a);if(u!==-1){let p=1,d=u+1;while(d<o&&p>0){let A=n.charCodeAt(d);if(A===40)p++;else if(A===41)p--;d++}let C=n.substring(u+1,d-1).trim(),b=C?`(${C})`:"()";if(c){let A=n.substring(d).trim(),S=A.indexOf("Generator<");if(S!==-1){let T=S+10,v=A.indexOf(">",T);if(v!==-1){let M=A.substring(T,v),te=`${f}${b} => Generator<${M}>`;return t?`(${te})`:te}}let k=`${f}${b} => Generator<any, any, any>`;return t?`(${k})`:k}let w=`${f}${b} => unknown`;return t?`(${w})`:w}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(n.includes("=>")&&n.includes("(")&&n.includes(")")){if(n.length>100||_i(n,"=>")>2){let a="";if(n.charCodeAt(0)===60){let l=vt(n,0,"<",">");if(l!==-1)a=n.substring(0,l+1)}let o=n.indexOf("("),c=o!==-1?vt(n,o,"(",")"):-1,f=o!==-1&&c!==-1?n.substring(o,c+1):"(...args: any[])";f=Pt(f);let u=`${a}${f} => any`;return t?`(${u})`:u}return t?`(${n})`:n}let s="() => unknown";return t?`(${s})`:s}function Ts(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=vt(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let i=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:i.startsWith(":")?i.slice(1).trim():""}}function Ds(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 Is(e){let t=e.lastIndexOf(" satisfies ");if(t===-1)return null;let r=e.slice(t+11).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var xr=!1,Me=null;var Er=()=>{};function Se(e){return e===We||e===Pe||e===he||e===Ce}function Ft(e){return e>=65&&e<=90||e>=97&&e<=122||e===Ul||e===Ms||e>127}function Ze(e){return Ft(e)||e>=48&&e<=57}function Yl(e){let t=!0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===st){if(t)return!1;t=!0}else if(t){if(!Ft(i))return!1;t=!1}else if(!Ze(i))return!1}return e.length>0&&!t}function Hl(e,t,r){let i=t+1;while(i<e.length){let n=e.charCodeAt(i);if(n===Ue){i+=2;continue}if(i++,n===r)break}return i}function ql(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===_&&e.includes("[")&&e.includes("]:")}function qi(e,t,r=!0){return Bs(e,t,r,!0)}function zi(e,t,r=!0){return Bs(e,t,r,!1)}function Bs(e,t,r,i){let n=e,s=r,a=i,o=n.length,c=[],f=new Map,u=new Set,l=0;if(l<o&&n.charCodeAt(l)===65279)l++;function p(m,h){if(m<h){let g=n.charCodeAt(m),y=n.charCodeAt(h-1);if(g!==We&&g!==Pe&&g!==he&&g!==Ce&&y!==We&&y!==Pe&&y!==he&&y!==Ce)return n.slice(m,h)}while(m<h&&Se(n.charCodeAt(m)))m++;while(h>m&&Se(n.charCodeAt(h-1)))h--;return n.slice(m,h)}function d(){if(l>=o)return;let m=n.charCodeAt(l);if(m!==We&&m!==Pe&&m!==he&&m!==Ce&&m!==z)return;while(l<o){let h=n.charCodeAt(l);if(h===We||h===Pe||h===he||h===Ce){l++;continue}if(h===z&&l+1<o){let g=n.charCodeAt(l+1);if(g===z){let y=n.indexOf(`
34
+ `),r=t.indexOf("async");if(r!==-1){let f=r>0?t.charCodeAt(r-1):32,u=r+5<t.length?t.charCodeAt(r+5):32;if(!it(f)&&!it(u))t=(t.slice(0,r)+t.slice(r+5)).trim()}let i=t.indexOf("(");if(i!==-1){let f=vt(t,i,"(",")");if(f!==-1){let u=t.slice(i,f+1),l=Pt(u);t=t.slice(0,i)+l+t.slice(f+1)}}let n=t.length,s="",a=[],o=!1,c=!1;for(let f=0;f<n;f++){let u=t.charCodeAt(f);if(u===123||u===40)a.push(u);else if(u===125||u===41)a.pop();if(u<=32){if(o=!0,u===10||u===13)c=!0;continue}if(o&&s.length>0){let l=(a.length>0?a[a.length-1]:0)===123;if(c&&l){let p=s.charCodeAt(s.length-1),d=p===59||p===44||p===123||u===125,C=s.length>=2&&s.charCodeAt(s.length-1)===47&&s.charCodeAt(s.length-2)===42;if(!d&&!C)s+="; ";else s+=" "}else s+=" "}o=!1,c=!1,s+=t[f]}return s.trim()}function it(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function Pt(e){let t=e.trim(),r,i=!1;if(t.startsWith("(")&&t.endsWith(")"))r=t.slice(1,-1),i=!0;else r=t;let n=r.trim();if(!n)return i?"()":"";let s=!1;{let C=0;for(let b=0;b<n.length;b++){let w=n.charCodeAt(b);if(w===40||w===60||w===91||w===123)C++;else if(w===41||w===62||w===93||w===125)C--;else if(C===0&&w===61){let A=b>0?n.charCodeAt(b-1):0,S=b+1<n.length?n.charCodeAt(b+1):0;if(A!==61&&A!==33&&A!==60&&A!==62&&S!==61&&S!==62){s=!0;break}}}}if(!s)return t;let a=[],o=[],c=0,f=0,u=!1,l=0;for(let C=0;C<=n.length;C++){if(C===n.length){a.push(n.slice(c));break}let b=n.charCodeAt(C);if(u){if(b===92){C++;continue}if(b===l)u=!1;continue}if(b===47&&C+1<n.length){let w=n.charCodeAt(C+1);if(w===42){C+=2;while(C+1<n.length&&!(n.charCodeAt(C)===42&&n.charCodeAt(C+1)===47))C++;C++;continue}if(w===47){while(C<n.length&&n.charCodeAt(C)!==10)C++;continue}}if(b===39||b===34||b===96){u=!0,l=b;continue}if(b===40||b===60||b===91||b===123)f++;else if(b===41||b===62||b===93||b===125)f--;else if(b===44&&f===0){a.push(n.slice(c,C));let w=",",A=C+1;while(A<n.length&&n.charCodeAt(A)<=32)w+=n[A],A++;o.push(w),c=A}}let p=[];for(let C of a){let b=C.trim();if(!b){p.push(C);continue}if(b.startsWith("//"))continue;let w=Ws(b),A=C.slice(0,C.length-C.trimStart().length);p.push(A+Ml(w))}let d=p[0]||"";for(let C=1;C<p.length;C++)d+=(o[C-1]||", ")+p[C];return i?`(${d})`:d}function Ws(e){let t=!1,r=0;for(let i=0;i<e.length-1;i++){let n=e.charCodeAt(i);if(t){if(n===92){i++;continue}if(n===r)t=!1;continue}if(n===39||n===34||n===96){t=!0,r=n;continue}if(n===47&&e.charCodeAt(i+1)===47)return e.slice(0,i).trimEnd()}return e}function Ml(e){if(e.startsWith("..."))return e;let t=-1,r=-1,i=0,n=!1,s=0;for(let o=0;o<e.length;o++){let c=e.charCodeAt(o);if(n){if(c===92){o++;continue}if(c===s)n=!1;continue}if(c===47&&o+1<e.length){let f=e.charCodeAt(o+1);if(f===42){o+=2;while(o+1<e.length&&!(e.charCodeAt(o)===42&&e.charCodeAt(o+1)===47))o++;o++;continue}if(f===47){while(o<e.length&&e.charCodeAt(o)!==10)o++;continue}}if(c===39||c===34||c===96){n=!0,s=c;continue}if(c===40||c===60||c===91||c===123)i++;else if(c===41||c===62||c===93||c===125)i--;else if(i===0){if(c===58&&t===-1)t=o;else if(c===61&&r===-1&&(o===0||e.charCodeAt(o-1)!==61)&&(o+1>=e.length||e.charCodeAt(o+1)!==61&&e.charCodeAt(o+1)!==62))r=o}}let a=r!==-1;if(t!==-1&&(r===-1||t<r)){let o=e.slice(0,t).trim(),c=r!==-1?e.slice(t+1,r).trim():e.slice(t+1).trim(),f=a&&!o.endsWith("?")?"?":"";return`${o}${f}: ${c}`}else if(r!==-1){let o=e.slice(0,r).trim(),c=!o.endsWith("?")?"?":"",f=e.slice(r+1).trim(),u="unknown";if(f==="true"||f==="false")u="boolean";else if(/^-?\d+(\.\d+)?$/.test(f))u="number";else if(f.startsWith("'")&&f.endsWith("'")||f.startsWith('"')&&f.endsWith('"'))u="string";else if(f.startsWith("["))u="unknown[]";else if(f.startsWith("{"))u="Record<string, unknown>";return`${o}${c}: ${u}`}return e}function Bl(e){let t=0,r=e.length;while(t<r){while(t<r&&(e.charCodeAt(t)===32||e.charCodeAt(t)===9||e.charCodeAt(t)===10||e.charCodeAt(t)===13))t++;if(t+1<r&&e.charCodeAt(t)===47&&e.charCodeAt(t+1)===42){t+=2;while(t+1<r&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t+=2;continue}break}return t}function _l(e){let t=[],r=0,i=e.length;while(r<i){while(r<i&&e.charCodeAt(r)<=32)r++;if(r+1>=i||e.charCodeAt(r)!==47||e.charCodeAt(r+1)!==42)break;let n=r;r+=2;while(r+1<i&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47))r++;r=Math.min(r+2,i),t.push(e.slice(n,r).trim())}return{comments:t.join(`
35
+ `),key:e.slice(r).trim()}}function Zl(e){let t=[],r="",i="",n=0,s=!1,a="",o=!0,c=!1,f=0,u=!1,l=!1,p=0,d=!1,C=!1;for(let b=0;b<e.length;b++){let w=e.charCodeAt(b),A=b>0?e.charCodeAt(b-1):0,S=b<e.length-1?e.charCodeAt(b+1):0;if(!s&&!c&&w===47&&S===47){b+=2;while(b<e.length&&e.charCodeAt(b)!==10)b++;continue}if(!s&&!c&&w===47&&S===42){c=!0,f=1,r+="/*",b++;continue}else if(c&&w===42&&S===47){if(f--,r+="*/",b++,f===0)c=!1;continue}else if(c&&w===47&&S===42){f++,r+="/*",b++;continue}let k=e[b];if(!s&&(w===34||w===39||w===96))s=!0,a=k,r+=k;else if(s&&k===a&&A!==92)s=!1,r+=k;else if(!s&&!c)if(w===40&&n===0&&o){i=r.trim();let T=Bl(i),v=T>0?i.slice(0,T):"",M=i.slice(T),te="";if(M.startsWith("async ")||M.startsWith("async\t")||M.startsWith(`async
36
+ `))M=M.slice(6).trimStart(),te="async ";if(M.startsWith("*"))M=M.slice(1).trimStart(),te+="*";i=v+M,r=te+k,o=!1,d=!0,C=!1,n=1}else if(w===123||w===91||w===40){if(n++,r+=k,C&&w===123)C=!1}else if(w===125||w===93||w===41){if(n--,r+=k,w===41&&n===0&&!o&&!d)u=!0;if(d){if(w===41&&n===0&&!C)C=!0;else if(w===125&&n===0)d=!1,C=!1}}else if(w===58&&n===0&&o)i=r.trim(),r="",o=!1;else if(w===58&&n===0&&u)l=!0,r+=k;else if(w===60&&l)p++,r+=k;else if(w===62&&p>0&&A!==61)p--,r+=k;else if(w===61&&S===62&&l&&p===0)l=!1,u=!1,r+=k;else if(w===44&&n===0&&p===0&&!C){if(i&&r.trim()){let T=r.trim();t.push([i,T])}else if(o&&r.trim()){let T=r.trim();if(ar(T))t.push([T,T]);else if(T.startsWith("...")&&T.length>3)t.push(["...",T.slice(3).trim()])}r="",i="",o=!0,u=!1,l=!1,p=0}else r+=k;else r+=k}if(i&&r.trim()){let b=r.trim();t.push([i,b])}else if(o&&r.trim()){let b=r.trim();if(ar(b))t.push([b,b]);else if(b.startsWith("...")&&b.length>3)t.push(["...",b.slice(3).trim()])}return t}function Vl(e){let t=e.trim();if(t.startsWith("get ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"get",name:r}}if(t.startsWith("set ")&&t.length>4){let r=t.slice(4).trim();if(r)return{kind:"set",name:r}}return null}function Kl(e,t,r){let i=r.trim();if(i.charCodeAt(0)!==40)return null;let n=vt(i,0,"(",")");if(n===-1)return null;let s=i.slice(1,n).trim(),a=i.slice(n+1).trimStart();if(!a.startsWith("=>"))return null;let o=a.slice(2).trim();if(e==="get")return`get ${t}(): ${o||"unknown"}`;return`set ${t}(${s})`}function Jl(e){let t=e;if(t.startsWith("async ")||t.startsWith("async\t"))t=t.slice(5).trimStart();if(t.startsWith("*"))t=t.slice(1).trimStart();if(!t.startsWith("("))return!1;let r=0;for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n===40)r++;else if(n===41){if(r--,r===0){let s=t.slice(i+1).trimStart();if(s.startsWith("{"))return!0;if(s.startsWith(":")){let a=Ps(s,1);if(a?.kind==="arrow")return!1;if(a?.kind==="body")return!0}return!1}}}return!1}function Gl(e,t){let r=t.trimStart(),i=!1,n=!1;if(r.startsWith("async ")||r.startsWith("async\t"))i=!0,r=r.slice(5).trimStart();if(r.startsWith("*"))n=!0,r=r.slice(1).trimStart();let s="";if(r.charCodeAt(0)===60){let p=0,d=-1;for(let C=0;C<r.length;C++)if(r.charCodeAt(C)===60)p++;else if(r.charCodeAt(C)===62){if(p--,p===0){d=C;break}}if(d!==-1)s=r.slice(0,d+1),r=r.slice(d+1).trimStart()}let a=r.indexOf("("),o=vt(r,a,"(",")");if(a===-1||o===-1)return"() => unknown";let c=r.slice(a,o+1),f="unknown",u=r.slice(o+1).trimStart();if(u.charCodeAt(0)===58){let p=u.slice(1),d=Ps(p,0);if(d)f=p.slice(0,d.index).trim();else f=p.trim()}if(f==="unknown"){if(i&&n)f="AsyncGenerator<unknown, void, unknown>";else if(n)f="Generator<unknown, void, unknown>";else if(i)f="Promise<void>"}else if(i&&!f.startsWith("Promise<")&&!f.startsWith("AsyncGenerator<"))f=`Promise<${f}>`;let l=Pt(c);return`${s}${l} => ${f}`}function Ps(e,t){let r=0,i=0,n=0,s=0,a=!1,o=0;for(let c=t;c<e.length;c++){let f=e.charCodeAt(c);if(a){if(f===92)c++;else if(f===o)a=!1;continue}if(f===34||f===39||f===96){a=!0,o=f;continue}if(f===40)r++;else if(f===41&&r>0)r--;else if(f===91)i++;else if(f===93&&i>0)i--;else if(f===60)n++;else if(f===62&&n>0)n--;else if(f===125&&s>0)s--;else if(f===123){let u=r>0||i>0||n>0||s>0,l=e.slice(t,c).trimEnd(),p=l.charCodeAt(l.length-1),d=l.length===0||p===38||p===124||p===40||p===44||p===58||p===61||p===91;if(u||d)s++;else return{index:c,kind:"body"}}else if(f===61&&c+1<e.length&&e.charCodeAt(c+1)===62&&r===0&&i===0&&n===0&&s===0)return{index:c,kind:"arrow"}}return null}function vt(e,t,r,i){let n=0;for(let s=t;s<e.length;s++)if(e[s]===r)n++;else if(e[s]===i){if(n--,n===0)return s}return-1}function ks(e){let t=0,r=0,i=!1,n="";for(let s=0;s<e.length-1;s++){let a=e[s],o=e[s+1],c=s>0?e[s-1]:"";if(!i&&(a==='"'||a==="'"||a==="`"))i=!0,n=a;else if(i&&a===n&&c!=="\\")i=!1;if(!i){if(a==="(")t++;else if(a===")")t--;else if(a==="[")r++;else if(a==="]")r--;if(a==="="&&o===">"&&t===0&&r===0)return s}}return-1}function Fs(e,t=!1,r=0,i=!0){let n=e.trim();if(n.length>200&&_i(n,"=>")>2&&_i(n,"<")>5&&!n.startsWith("function"))return t?"((...args: any[]) => any)":"(...args: any[]) => any";if(n.startsWith("async ")&&n.includes("=>")){let a=n.slice(5).trim(),o=ks(a);if(o===-1)return t?"(() => Promise<unknown>)":"() => Promise<unknown>";let c=a.substring(0,o).trim(),f=a.substring(o+2).trim(),u=Ts(c),l=u.params,p=u.returnType;if(l=Pt(l),l==="()"||l==="")l="()";else if(!l.startsWith("("))l=`(${l})`;let d=p;if(d);else if(f.startsWith("{"))d=nr(f.slice(1,f.endsWith("}")?-1:void 0),!0,l);else d=Ae(f,i,!1,r+1);let C=`${l} => ${p||d.startsWith("Promise<")?d:`Promise<${d}>`}`;return t?`(${C})`:C}if(n.includes("=>")){let a="",o=n;if(n.startsWith("<")){let w=vt(n,0,"<",">");if(w!==-1)a=n.substring(0,w+1),o=n.substring(w+1).trim()}let c=ks(o);if(c===-1)return t?"(() => unknown)":"() => unknown";let f=o.substring(0,c).trim(),u=o.substring(c+2).trim(),l=Ts(f),p=l.params,d=l.returnType;if(p=Pt(p),p==="()"||p==="")p="()";else if(!p.startsWith("("))p=`(${p})`;let C="unknown";if(d)C=d;else if(u.startsWith("{"))C=nr(u.slice(1,u.endsWith("}")?-1:void 0),!1,p);else if(u.includes("=>")){let w=u.trimStart(),A=w.indexOf("("),S=A!==-1?vt(w,A,"(",")"):-1,k=S!==-1?w.indexOf("=>",S):-1;if(A===0&&S!==-1&&k!==-1){let T=w.substring(A+1,S).trim(),v=Pt(T);if(a.includes("T")&&v.includes("T"))C=`(${v}) => T`;else C=`(${v}) => any`}else C="any"}else if(t)C="unknown";else C=Et(u,Rs(p));let b=`${a}${p} => ${C}`;return t?`(${b})`:b}if(n.startsWith("function")){let a=8,o=n.length;while(a<o&&n.charCodeAt(a)<=32)a++;let c=!1;if(a<o&&n.charCodeAt(a)===42){c=!0,a++;while(a<o&&n.charCodeAt(a)<=32)a++}let f="";if(a<o&&n.charCodeAt(a)===60){let p=a,d=1;a++;while(a<o&&d>0){let C=n.charCodeAt(a);if(C===60)d++;else if(C===62)d--;a++}f=n.substring(p,a);while(a<o&&n.charCodeAt(a)<=32)a++}let u=n.indexOf("(",a);if(u!==-1){let p=1,d=u+1;while(d<o&&p>0){let A=n.charCodeAt(d);if(A===40)p++;else if(A===41)p--;d++}let C=n.substring(u+1,d-1).trim(),b=C?`(${C})`:"()";if(c){let A=n.substring(d).trim(),S=A.indexOf("Generator<");if(S!==-1){let T=S+10,v=A.indexOf(">",T);if(v!==-1){let M=A.substring(T,v),te=`${f}${b} => Generator<${M}>`;return t?`(${te})`:te}}let k=`${f}${b} => Generator<any, any, any>`;return t?`(${k})`:k}let w=`${f}${b} => unknown`;return t?`(${w})`:w}let l="(...args: any[]) => unknown";return t?`(${l})`:l}if(n.includes("=>")&&n.includes("(")&&n.includes(")")){if(n.length>100||_i(n,"=>")>2){let a="";if(n.charCodeAt(0)===60){let l=vt(n,0,"<",">");if(l!==-1)a=n.substring(0,l+1)}let o=n.indexOf("("),c=o!==-1?vt(n,o,"(",")"):-1,f=o!==-1&&c!==-1?n.substring(o,c+1):"(...args: any[])";f=Pt(f);let u=`${a}${f} => any`;return t?`(${u})`:u}return t?`(${n})`:n}let s="() => unknown";return t?`(${s})`:s}function Ts(e){let t=e.trim();if(!t.startsWith("("))return{params:t,returnType:""};let r=vt(t,0,"(",")");if(r===-1)return{params:t,returnType:""};let i=t.slice(r+1).trim();return{params:t.slice(0,r+1),returnType:i.startsWith(":")?i.slice(1).trim():""}}function Ds(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 Is(e){let t=e.lastIndexOf(" satisfies ");if(t===-1)return null;let r=e.slice(t+11).trim();if(r.endsWith(";"))r=r.slice(0,-1).trim();return r||null}var xr=!1,Me=null;var Er=()=>{};function Se(e){return e===We||e===Pe||e===he||e===Ce}function Ft(e){return e>=65&&e<=90||e>=97&&e<=122||e===Yl||e===Ms||e>127}function Ze(e){return Ft(e)||e>=48&&e<=57}function Hl(e){let t=!0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===st){if(t)return!1;t=!0}else if(t){if(!Ft(i))return!1;t=!1}else if(!Ze(i))return!1}return e.length>0&&!t}function ql(e,t,r){let i=t+1;while(i<e.length){let n=e.charCodeAt(i);if(n===Ue){i+=2;continue}if(i++,n===r)break}return i}function zl(e){if(e==="any"||e==="object"||e==="unknown")return!0;if(e.startsWith("Record<")||e.startsWith("Array<"))return!0;return e.charCodeAt(0)===_&&e.includes("[")&&e.includes("]:")}function qi(e,t,r=!0){return Bs(e,t,r,!0)}function zi(e,t,r=!0){return Bs(e,t,r,!1)}function Bs(e,t,r,i){let n=e,s=r,a=i,o=n.length,c=[],f=new Map,u=new Set,l=0;if(l<o&&n.charCodeAt(l)===65279)l++;function p(m,h){if(m<h){let g=n.charCodeAt(m),y=n.charCodeAt(h-1);if(g!==We&&g!==Pe&&g!==he&&g!==Ce&&y!==We&&y!==Pe&&y!==he&&y!==Ce)return n.slice(m,h)}while(m<h&&Se(n.charCodeAt(m)))m++;while(h>m&&Se(n.charCodeAt(h-1)))h--;return n.slice(m,h)}function d(){if(l>=o)return;let m=n.charCodeAt(l);if(m!==We&&m!==Pe&&m!==he&&m!==Ce&&m!==z)return;while(l<o){let h=n.charCodeAt(l);if(h===We||h===Pe||h===he||h===Ce){l++;continue}if(h===z&&l+1<o){let g=n.charCodeAt(l+1);if(g===z){let y=n.indexOf(`
37
37
  `,l+2);l=y===-1?o:y+1;continue}if(g===Ee){let y=n.indexOf("*/",l+2);l=y===-1?o:y+2;continue}}break}}function C(m){let h=m.length,g=0,y=h;for(let $=0;$<h;$++){let x=m.charCodeAt($);if(g){if(x===Ue){$++;continue}if(x===g)g=0;continue}if(x===pe||x===$e||x===je){g=x;continue}if(x===z&&$+1<h){let R=m.charCodeAt($+1);if(R===z){y=$;while(y>0&&(m.charCodeAt(y-1)===We||m.charCodeAt(y-1)===Pe))y--;return m.slice(0,y)}if(R===Ee){let P=m.indexOf("*/",$+2);if(P!==-1){m=`${m.slice(0,$)} ${m.slice(P+2)}`,$--;continue}}}}y=h;while(y>0&&(m.charCodeAt(y-1)===We||m.charCodeAt(y-1)===Pe||m.charCodeAt(y-1)===Ce))y--;return y<h?m.slice(0,y):m}function b(m){l++;let h=m===pe?"'":'"';while(l<o){let g=n.indexOf(h,l);if(g===-1){l=o;return}let y=0,$=g-1;while($>=0&&n.charCodeAt($)===Ue)y++,$--;if(y%2===0){l=g+1;return}l=g+1}}function w(){l++;let m=[];while(l<o){let h=n.charCodeAt(l);if(m.length===0){if(h===Ue){l+=2;continue}if(h===je){l++;return}if(h===Ms&&l+1<o&&n.charCodeAt(l+1)===_){l+=2,m.push(0);continue}l++;continue}if(h===pe||h===$e){b(h);continue}if(h===je){w();continue}if(h===z&&l+1<o){let g=n.charCodeAt(l+1);if(g===z){let y=n.indexOf(`
38
38
  `,l+2);l=y===-1?o:y+1;continue}if(g===Ee){let y=n.indexOf("*/",l+2);l=y===-1?o:y+2;continue}if(S()){k();continue}l++;continue}if(h===_){m[m.length-1]++,l++;continue}if(h===U){let g=m[m.length-1];if(g===0){m.pop(),l++;continue}m[m.length-1]=g-1,l++;continue}l++}}function A(){let m=n.charCodeAt(l);if(m===pe||m===$e)return b(m),!0;if(m===je)return w(),!0;if(m===z&&l+1<o){let h=n.charCodeAt(l+1);if(h===z){let g=n.indexOf(`
39
39
  `,l+2);return l=g===-1?o:g+1,!0}if(h===Ee){let g=n.indexOf("*/",l+2);return l=g===-1?o:g+2,!0}if(S())return k(),!0}return!1}function S(){let m=l-1;while(m>=0&&(n.charCodeAt(m)===We||n.charCodeAt(m)===Pe||n.charCodeAt(m)===he||n.charCodeAt(m)===Ce))m--;if(m<0)return!0;let h=n.charCodeAt(m);if(h===ge||h===Q||h===fe||h===33||h===38||h===124||h===Or||h===Je||h===Ge||h===Y||h===_||h===U||h===94||h===126||h===43||h===45||h===Ee||h===37||h===xe||h===we)return!0;if(Ze(h)){let g=m;while(g>=0&&Ze(n.charCodeAt(g)))g--;let y=n.slice(g+1,m+1);if(y==="return"||y==="typeof"||y==="void"||y==="delete"||y==="throw"||y==="new"||y==="in"||y==="of"||y==="case"||y==="instanceof"||y==="yield"||y==="await")return!0}return!1}function k(){l++;let m=!1;while(l<o){let h=n.charCodeAt(l);if(h===Ue){l+=2;continue}if(m){if(h===Oe)m=!1;l++;continue}if(h===fe){m=!0,l++;continue}if(h===z){l++;break}if(h===he||h===Ce)break;l++}while(l<o&&Ze(n.charCodeAt(l)))l++}function T(){let m=l;while(l<o&&Ze(n.charCodeAt(l)))l++;return n.slice(m,l)}function v(m){if(l+m.length>o)return!1;for(let h=0;h<m.length;h++)if(n.charCodeAt(l+h)!==m.charCodeAt(h))return!1;if(l+m.length<o&&Ze(n.charCodeAt(l+m.length)))return!1;return!0}function M(m){let h=l+m;while(h<o){let g=n.charCodeAt(h);if(g===We||g===Pe||g===he||g===Ce){h++;continue}return g!==st&&g!==ge}return!1}function te(){if(l>=o)return!1;switch(n.charCodeAt(l)){case 101:return v("export")||v("enum");case 105:return v("import")||v("interface");case 102:return v("function");case 99:return v("class")||v("const");case 116:return v("type");case 108:return v("let");case 118:return v("var");case 100:return v("declare")||v("default");case 109:return v("module");case 110:return v("namespace");case 97:return v("abstract")||v("async");default:return!1}}function F(){let m=n.charCodeAt(l);if(m!==he&&m!==Ce)return!1;let h=l;if(l++,m===Ce&&l<o&&n.charCodeAt(l)===he)l++;while(l<o){let y=n.charCodeAt(l);if(y===We||y===Pe||y===Ce||y===he){l++;continue}if(y===z&&l+1<o){let $=n.charCodeAt(l+1);if($===z){let x=n.indexOf(`
40
40
  `,l+2);l=x===-1?o:x+1;continue}if($===Ee){let x=n.indexOf("*/",l+2);l=x===-1?o:x+2;continue}}break}let g=l>=o||te()||n.charCodeAt(l)===U;return l=h,g}function K(){let m=n.charCodeAt(l);if(m!==he&&m!==Ce)return!1;let h=l;if(l++,m===Ce&&l<o&&n.charCodeAt(l)===he)l++;while(l<o){let y=n.charCodeAt(l);if(y===We||y===Pe||y===Ce||y===he){l++;continue}if(y===z&&l+1<o&&n.charCodeAt(l+1)===z){let $=n.indexOf(`
41
- `,l+2);l=$===-1?o:$+1;continue}break}if(l>=o)return l=h,!0;let g=n.charCodeAt(l);if(g===124||g===38||g===st||g===Or||g===Je)return l=h,!1;if(v("extends")||v("keyof")||v("typeof")||v("infer")||v("is")||v("as")||v("in"))return l=h,!1;return l=h,!0}let q=/[{}'"`\/]/g,ne=/[()'"`\/]/g,V=/[[\]'"`\/]/g,H=/[<>'"`\/]/g;function G(m,h){let g=1;l++;let y=m===_?q:m===Q?ne:m===fe?V:H;y.lastIndex=l;let $;while(($=y.exec(n))!==null){let x=$.index,R=n.charCodeAt(x);if(R===pe||R===$e){l=x,b(R),y.lastIndex=l;continue}if(R===je){l=x,w(),y.lastIndex=l;continue}if(R===z){if(l=x,A()){y.lastIndex=l;continue}y.lastIndex=x+1;continue}if(R===m)g++;else if(R===h){if(h===we&&x>0&&n.charCodeAt(x-1)===ge){y.lastIndex=x+1;continue}if(g--,g===0)return l=x+1,l}y.lastIndex=x+1}return l=o,l}function J(){return l>0&&n.charCodeAt(l-1)===ge}function ye(){return l+1<o&&n.charCodeAt(l+1)===we}let X=/[{};'"`\/\n\r()[\]]/g;function ie(){let m=0,h=0,g=0;X.lastIndex=l;let y;while((y=X.exec(n))!==null){let $=y.index,x=n.charCodeAt($);if(x===pe||x===$e){l=$,b(x),X.lastIndex=l;continue}if(x===je){l=$,w(),X.lastIndex=l;continue}if(x===z){if(l=$,A()){X.lastIndex=l;continue}X.lastIndex=$+1;continue}if(x===Q){h++,X.lastIndex=$+1;continue}if(x===me){h--,X.lastIndex=$+1;continue}if(x===fe){g++,X.lastIndex=$+1;continue}if(x===Oe){g--,X.lastIndex=$+1;continue}if(x===_){m++,X.lastIndex=$+1;continue}if(x===U){if(m--,m<=0&&h<=0&&g<=0){l=$+1;return}X.lastIndex=$+1;continue}if(x===Y&&m===0&&h===0&&g===0){l=$+1;return}if((x===he||x===Ce)&&m===0&&h===0&&g===0){if(l=$,F())return}X.lastIndex=$+1}l=o}function er(){G(_,U);while(l<o&&Se(n.charCodeAt(l)))l++;if(v("from")){l+=4;while(l<o&&Se(n.charCodeAt(l)))l++;if(l<o){let m=n.charCodeAt(l);if(m===pe||m===$e)b(m)}}while(l<o&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Pe))l++;if(l<o&&n.charCodeAt(l)===Y)l++}function xt(){l++;while(l<o&&Se(n.charCodeAt(l)))l++;if(v("as")){l+=2;while(l<o&&Se(n.charCodeAt(l)))l++;T();while(l<o&&Se(n.charCodeAt(l)))l++}if(v("from")){l+=4;while(l<o&&Se(n.charCodeAt(l)))l++;if(l<o){let m=n.charCodeAt(l);if(m===pe||m===$e)b(m)}}while(l<o&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Pe))l++;if(l<o&&n.charCodeAt(l)===Y)l++}function et(m){let h=m.indexOf("from ");if(h===-1)return;let g=h+5;while(g<m.length&&(m.charCodeAt(g)===32||m.charCodeAt(g)===9))g++;if(g>=m.length)return;let y=m.charCodeAt(g);if(y!==39&&y!==34)return;let $=m.indexOf(m[g],g+1);if($===-1)return;return m.slice(g+1,$)}function le(m){if(!s)return;let h=m-1;while(h>=0&&Se(n.charCodeAt(h)))h--;if(h<0)return;let g=[],y=!1;while(h>=0){if(h>=1&&n.charCodeAt(h)===z&&n.charCodeAt(h-1)===Ee){let R=n.lastIndexOf("/*",h-2);if(R>=0){g.push(n.slice(R,h+1)),y=!0,h=R-1;while(h>=0&&Se(n.charCodeAt(h)))h--;continue}break}let $=h;while($>0&&n.charCodeAt($-1)!==he)$--;let x=p($,h+1);if(x.startsWith("//")){if(y)break;let R=[x];h=$-1;while(h>=0&&(n.charCodeAt(h)===he||n.charCodeAt(h)===Ce))h--;while(h>=0){let P=h;while(P>0&&n.charCodeAt(P-1)!==he)P--;let E=p(P,h+1);if(E.startsWith("//")){R.push(E),h=P-1;while(h>=0&&(n.charCodeAt(h)===he||n.charCodeAt(h)===Ce))h--}else if(E===""){h=P-1;while(h>=0&&(n.charCodeAt(h)===he||n.charCodeAt(h)===Ce))h--}else break}R.reverse(),g.push(R.join(`
41
+ `,l+2);l=$===-1?o:$+1;continue}break}if(l>=o)return l=h,!0;let g=n.charCodeAt(l);if(g===124||g===38||g===st||g===Or||g===Je)return l=h,!1;if(v("extends")||v("keyof")||v("typeof")||v("infer")||v("is")||v("as")||v("in"))return l=h,!1;return l=h,!0}let q=/[{}'"`\/]/g,ne=/[()'"`\/]/g,V=/[[\]'"`\/]/g,H=/[<>'"`\/]/g;function G(m,h){let g=1;l++;let y=m===_?q:m===Q?ne:m===fe?V:H;y.lastIndex=l;let $;while(($=y.exec(n))!==null){let x=$.index,R=n.charCodeAt(x);if(R===pe||R===$e){l=x,b(R),y.lastIndex=l;continue}if(R===je){l=x,w(),y.lastIndex=l;continue}if(R===z){if(l=x,A()){y.lastIndex=l;continue}y.lastIndex=x+1;continue}if(R===m)g++;else if(R===h){if(h===we&&x>0&&n.charCodeAt(x-1)===ge){y.lastIndex=x+1;continue}if(g--,g===0)return l=x+1,l}y.lastIndex=x+1}return l=o,l}function J(){return l>0&&n.charCodeAt(l-1)===ge}function ye(){return l+1<o&&n.charCodeAt(l+1)===we}let X=/[{};'"`\/\n\r()[\]]/g;function ie(){let m=0,h=0,g=0;X.lastIndex=l;let y;while((y=X.exec(n))!==null){let $=y.index,x=n.charCodeAt($);if(x===pe||x===$e){l=$,b(x),X.lastIndex=l;continue}if(x===je){l=$,w(),X.lastIndex=l;continue}if(x===z){if(l=$,A()){X.lastIndex=l;continue}X.lastIndex=$+1;continue}if(x===Q){h++,X.lastIndex=$+1;continue}if(x===me){h--,X.lastIndex=$+1;continue}if(x===fe){g++,X.lastIndex=$+1;continue}if(x===Oe){g--,X.lastIndex=$+1;continue}if(x===_){m++,X.lastIndex=$+1;continue}if(x===U){if(m--,m<=0&&h<=0&&g<=0){l=$+1;return}X.lastIndex=$+1;continue}if(x===Y&&m===0&&h===0&&g===0){l=$+1;return}if((x===he||x===Ce)&&m===0&&h===0&&g===0){if(l=$,F())return}X.lastIndex=$+1}l=o}function er(){G(_,U);while(l<o&&Se(n.charCodeAt(l)))l++;if(v("from")){l+=4;while(l<o&&Se(n.charCodeAt(l)))l++;if(l<o){let m=n.charCodeAt(l);if(m===pe||m===$e)b(m)}}while(l<o&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Pe))l++;if(l<o&&n.charCodeAt(l)===Y)l++}function xt(){l++;while(l<o&&Se(n.charCodeAt(l)))l++;if(v("as")){l+=2;while(l<o&&Se(n.charCodeAt(l)))l++;T();while(l<o&&Se(n.charCodeAt(l)))l++}if(v("from")){l+=4;while(l<o&&Se(n.charCodeAt(l)))l++;if(l<o){let m=n.charCodeAt(l);if(m===pe||m===$e)b(m)}}while(l<o&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Pe))l++;if(l<o&&n.charCodeAt(l)===Y)l++}function tt(m){let h=m.indexOf("from ");if(h===-1)return;let g=h+5;while(g<m.length&&(m.charCodeAt(g)===32||m.charCodeAt(g)===9))g++;if(g>=m.length)return;let y=m.charCodeAt(g);if(y!==39&&y!==34)return;let $=m.indexOf(m[g],g+1);if($===-1)return;return m.slice(g+1,$)}function le(m){if(!s)return;let h=m-1;while(h>=0&&Se(n.charCodeAt(h)))h--;if(h<0)return;let g=[],y=!1;while(h>=0){if(h>=1&&n.charCodeAt(h)===z&&n.charCodeAt(h-1)===Ee){let R=n.lastIndexOf("/*",h-2);if(R>=0){g.push(n.slice(R,h+1)),y=!0,h=R-1;while(h>=0&&Se(n.charCodeAt(h)))h--;continue}break}let $=h;while($>0&&n.charCodeAt($-1)!==he)$--;let x=p($,h+1);if(x.startsWith("//")){if(y)break;let R=[x];h=$-1;while(h>=0&&(n.charCodeAt(h)===he||n.charCodeAt(h)===Ce))h--;while(h>=0){let P=h;while(P>0&&n.charCodeAt(P-1)!==he)P--;let E=p(P,h+1);if(E.startsWith("//")){R.push(E),h=P-1;while(h>=0&&(n.charCodeAt(h)===he||n.charCodeAt(h)===Ce))h--}else if(E===""){h=P-1;while(h>=0&&(n.charCodeAt(h)===he||n.charCodeAt(h)===Ce))h--}else break}R.reverse(),g.push(R.join(`
42
42
  `));continue}break}if(g.length===0)return;return g.reverse(),g}function nt(m){let h=m,g=!1;while(l<o){let E=n.charCodeAt(l);if(E===Y){l++;break}if(E===pe||E===$e){b(E),g=!0;while(l<o&&(n.charCodeAt(l)===We||n.charCodeAt(l)===Pe))l++;if(l<o&&n.charCodeAt(l)===Y)l++;break}if(E===he&&g)break;l++}let y=p(h,l),$=y.charCodeAt(7)===116&&(y.startsWith("import type ")||y.startsWith("import type{")),x=!1;{let E=6;while(E<y.length&&(y.charCodeAt(E)===We||y.charCodeAt(E)===Pe))E++;if(E<y.length&&y.charCodeAt(E)===116&&y.startsWith("type",E)){E+=4;while(E<y.length&&(y.charCodeAt(E)===We||y.charCodeAt(E)===Pe))E++}if(E<y.length){let O=y.charCodeAt(E);x=O===pe||O===$e}}let R="";{let E=y.indexOf("from ");if(E!==-1){let O=E+5;while(O<y.length&&(y.charCodeAt(O)===We||y.charCodeAt(O)===Pe))O++;if(O<y.length){let W=y.charCodeAt(O);if(W===pe||W===$e){let j=y.indexOf(String.fromCharCode(W),O+1);if(j!==-1)R=y.slice(O+1,j)}}}else if(x){let O=6;while(O<y.length&&y.charCodeAt(O)!==pe&&y.charCodeAt(O)!==$e)O++;if(O<y.length){let W=y.charCodeAt(O),j=y.indexOf(String.fromCharCode(W),O+1);if(j!==-1)R=y.slice(O+1,j)}}}let P=le(h);return{kind:"import",name:"",text:y,isExported:!1,isTypeOnly:$,isSideEffect:x,source:R,leadingComments:P,start:h,end:l}}function gt(){let m=l;return G(_,U),n.slice(m,l)}function tr(m){let h=m.indexOf("(");if(h===-1)return m;let g=m.slice(h);if(g.indexOf("=")===-1)return m;let y=!1;for(let E=0;E<g.length;E++)if(g.charCodeAt(E)===61){let O=E>0?g.charCodeAt(E-1):0,W=E+1<g.length?g.charCodeAt(E+1):0;if(O!==61&&O!==33&&O!==60&&O!==62&&W!==61&&W!==62){y=!0;break}}if(!y)return m;let $=0,x=-1;for(let E=h;E<m.length;E++){let O=m.charCodeAt(E);if(O===40)$++;else if(O===41){if($--,$===0){x=E;break}}}if(x===-1)return m;let R=m.slice(h,x+1),P=Tt(R);return m.slice(0,h)+P+m.slice(x+1)}function gs(m){let h=m.indexOf("//")!==-1||m.indexOf("/*")!==-1,g=m.split(`
43
43
  `),y=[],$=[],x=[],R=!1,P=1/0;for(let W=0;W<g.length;W++){let j=g[W];if(h){if(R){if(j.includes("*/"))R=!1;continue}let L=j.trim();if(L.length===0)continue;let I=L.charCodeAt(0);if(I===z){let be=L.charCodeAt(1);if(be===z)continue;if(be===Ee){if(!L.includes("*/"))R=!0;continue}}if(I===Ee)continue;let N=C(j);if(N.charCodeAt(N.length-1)===Y)N=N.slice(0,-1);N=tr(N);let D=N.trim();if(!D)continue;y.push(N),$.push(D);let B=0;while(B<N.length&&Se(N.charCodeAt(B)))B++;if(D!=="{"&&D!=="}"){if(B<P)P=B}x.push(B)}else{let L=j.length;while(L>0&&(j.charCodeAt(L-1)===We||j.charCodeAt(L-1)===Pe||j.charCodeAt(L-1)===Ce))L--;if(L===0)continue;let I=L<j.length?j.slice(0,L):j;if(I.charCodeAt(I.length-1)===Y)I=I.slice(0,-1);I=tr(I);let N=I.trim();if(!N)continue;y.push(I),$.push(N);let D=0;while(D<I.length&&Se(I.charCodeAt(D)))D++;if(N!=="{"&&N!=="}"){if(D<P)P=D}x.push(D)}}if(y.length===0)return"{}";if(P===1/0||P<=2)return y.join(`
44
44
  `);let E=P-2,O=Array(y.length);for(let W=0;W<y.length;W++){let j=$[W];if(j==="{"){O[W]=j;continue}let L=x[W];if(L>P)O[W]=y[W];else if(L===P&&(j.charCodeAt(0)===U||j.charCodeAt(0)===Oe||j.charCodeAt(0)===me))O[W]=y[W];else{let I=Math.max(0,L-E);O[W]=" ".repeat(I)+j}}return O.join(`
45
- `)}function tt(){if(l>=o||n.charCodeAt(l)!==xe)return"";let m=l;G(xe,we);let h=n.slice(m,l);if(h.includes(`
45
+ `)}function rt(){if(l>=o||n.charCodeAt(l)!==xe)return"";let m=l;G(xe,we);let h=n.slice(m,l);if(h.includes(`
46
46
  `)){let g="",y=!1;for(let $=0;$<h.length;$++){let x=h.charCodeAt($);if(x===32||x===9||x===10||x===13){if(!y&&g.length>0)g+=" ",y=!0}else g+=h[$],y=!1}if(g.charCodeAt(1)===32)g=`<${g.slice(2)}`;if(g.charCodeAt(g.length-2)===32)g=`${g.slice(0,-2)}>`;return g}return h}function pt(){if(l>=o||n.charCodeAt(l)!==Q)return"()";let m=l;return G(Q,me),n.slice(m,l)}function Tt(m){let h=m.slice(1,-1).trim();if(!h)return"()";if(m.indexOf(`
47
47
  `)===-1&&h.indexOf(":")!==-1&&h.indexOf("{")===-1&&h.indexOf("[")===-1&&h.indexOf("=")===-1&&h.indexOf("@")===-1&&h.indexOf("...")===-1){let E=0,O=0,W=0;for(let j=0;j<h.length;j++){let L=h.charCodeAt(j);if(L===Q||L===xe||L===_)W++;else if(L===me||L===we||L===U)W--;else if(W===0){if(L===Je)E++;else if(L===Ge)O++}}if(E>=O+1){let j=!1;for(let L=0;L<Hi.length;L++){let I=Hi[L],N=h.indexOf(I);if(N!==-1){let D=N+I.length;if((N===0||!Ze(h.charCodeAt(N-1)))&&(D>=h.length||!Ze(h.charCodeAt(D)))){j=!0;break}}}if(!j)return m}}let g=[],y=0,$=0,x=!1,R=0;for(let E=0;E<=h.length;E++){if(E===h.length){g.push(h.slice(y).trim());break}let O=h.charCodeAt(E);if(x){if(O===Ue){E++;continue}if(O===R)x=!1;continue}if(O===z&&E+1<h.length){let W=h.charCodeAt(E+1);if(W===Ee){E+=2;while(E+1<h.length&&!(h.charCodeAt(E)===Ee&&h.charCodeAt(E+1)===z))E++;E++;continue}if(W===z){while(E<h.length&&h.charCodeAt(E)!==10)E++;continue}}if(O===pe||O===$e||O===je){x=!0,R=O;continue}if(O===Q||O===_||O===fe||O===xe)$++;else if(O===me||O===U||O===Oe||O===we&&!(E>0&&h.charCodeAt(E-1)===ge))$--;else if(O===Ge&&$===0)g.push(h.slice(y,E).trim()),y=E+1}let P=[];for(let E of g){if(!E)continue;let O=E.trim();if(O.startsWith("//")||O.startsWith("/*"))continue;let W=E;{let j=!1,L=0,I=0,N=0;for(let D=0;D<W.length-1;D++){let B=W.charCodeAt(D);if(B===he){N=D+1;continue}if(j){if(B===Ue){D++;continue}if(B===L)j=!1;continue}if(B===pe||B===$e||B===je){j=!0,L=B;continue}if(B===_||B===fe||B===Q||B===xe){I++;continue}if(B===U||B===Oe||B===me||B===we){if(I>0)I--;continue}if(B===z&&W.charCodeAt(D+1)===z){if(I===0){W=W.slice(0,D).trimEnd();break}let be=W.indexOf(`
48
- `,D);if(be===-1){W=W.slice(0,N).trimEnd();break}let $t=W.slice(0,N),cl=W.slice(be+1);W=`${$t}${cl}`,D=N-1}}}if(!W.trim())continue;P.push(ps(W))}return`(${P.join(", ")})`}function al(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let h="",g=0,y=0,$=!1,x=0;while(g<m.length){let R=m.charCodeAt(g);if($){if(R===Ue&&g+1<m.length){h+=m[g]+m[g+1],g+=2;continue}if(R===x)$=!1;h+=m[g],g++;continue}if(R===z&&g+1<m.length){let P=m.charCodeAt(g+1);if(P===Ee){let E=g;g+=2;while(g+1<m.length&&!(m.charCodeAt(g)===Ee&&m.charCodeAt(g+1)===z))g++;g=Math.min(g+2,m.length),h+=m.slice(E,g);continue}if(P===z){let E=g;while(g<m.length&&m.charCodeAt(g)!==10)g++;h+=m.slice(E,g);continue}}if(R===pe||R===$e||R===je){$=!0,x=R,h+=m[g],g++;continue}if(R===_||R===fe||R===Q)y++;else if(R===U||R===Oe||R===me)y--;if(y>=1&&R===ge&&(g+1>=m.length||m.charCodeAt(g+1)!==ge&&m.charCodeAt(g+1)!==we)){while(h.length>0&&(h[h.length-1]===" "||h[h.length-1]==="\t"||h[h.length-1]===`
49
- `))h=h.slice(0,-1);g++;let P=0;while(g<m.length){let E=m.charCodeAt(g);if(E===pe||E===$e||E===je){let O=E;g++;while(g<m.length){if(m.charCodeAt(g)===Ue){g+=2;continue}if(m.charCodeAt(g)===O){g++;break}g++}continue}if(E===_||E===fe||E===Q)P++;else if(E===U||E===Oe||E===me){if(P===0)break;P--}else if(E===Ge&&P===0)break;g++}continue}if(y===1&&R===st&&g+2<m.length&&m.charCodeAt(g+1)===st&&m.charCodeAt(g+2)===st){g+=3;continue}h+=m[g],g++}return h}function ps(m){let h=m.trim(),g=h.startsWith("...");if(g)h=h.slice(3).trim();while(h.startsWith("@")){let N=1;while(N<h.length&&Ze(h.charCodeAt(N)))N++;if(N<h.length&&h.charCodeAt(N)===Q){let D=1;N++;while(N<h.length&&D>0){if(h.charCodeAt(N)===Q)D++;else if(h.charCodeAt(N)===me)D--;N++}}h=h.slice(N).trim()}let y=!0;while(y){y=!1;for(let N of Hi)if(h.startsWith(N)&&h.length>N.length&&!Ze(h.charCodeAt(N.length))){let D=h.slice(N.length).trim();if(D.charCodeAt(0)===Je||D.charCodeAt(0)===Or&&D.length>1&&D.charCodeAt(1)===Je)break;h=D,y=!0;break}}let $=-1,x=-1,R=0,P=!1,E=0;for(let N=0;N<h.length;N++){let D=h.charCodeAt(N);if(P){if(D===Ue){N++;continue}if(D===E)P=!1;continue}if(D===z&&N+1<h.length){let B=h.charCodeAt(N+1);if(B===Ee){N+=2;while(N+1<h.length&&!(h.charCodeAt(N)===Ee&&h.charCodeAt(N+1)===z))N++;N++;continue}if(B===z){while(N<h.length&&h.charCodeAt(N)!==10)N++;continue}}if(D===pe||D===$e||D===je){P=!0,E=D;continue}if(D===Q||D===_||D===fe||D===xe)R++;else if(D===me||D===U||D===Oe||D===we&&!(N>0&&h.charCodeAt(N-1)===ge))R--;else if(R===0){if(D===Je&&$===-1)$=N;else if(D===ge&&x===-1&&(N===0||h.charCodeAt(N-1)!==ge)&&(N+1>=h.length||h.charCodeAt(N+1)!==ge&&h.charCodeAt(N+1)!==we))x=N}}let O,W,j=x!==-1;if($!==-1&&(x===-1||$<x))if(O=h.slice(0,$).trim(),x!==-1)W=h.slice($+1,x).trim();else W=h.slice($+1).trim();else if(x!==-1)O=h.slice(0,x).trim(),W=Ri(h.slice(x+1).trim());else O=h,W="unknown";if(O=al(O),(O.startsWith("{")||O.startsWith("["))&&O.includes(`
48
+ `,D);if(be===-1){W=W.slice(0,N).trimEnd();break}let $t=W.slice(0,N),fl=W.slice(be+1);W=`${$t}${fl}`,D=N-1}}}if(!W.trim())continue;P.push(ps(W))}return`(${P.join(", ")})`}function ol(m){if(!m.startsWith("{")&&!m.startsWith("["))return m;let h="",g=0,y=0,$=!1,x=0;while(g<m.length){let R=m.charCodeAt(g);if($){if(R===Ue&&g+1<m.length){h+=m[g]+m[g+1],g+=2;continue}if(R===x)$=!1;h+=m[g],g++;continue}if(R===z&&g+1<m.length){let P=m.charCodeAt(g+1);if(P===Ee){let E=g;g+=2;while(g+1<m.length&&!(m.charCodeAt(g)===Ee&&m.charCodeAt(g+1)===z))g++;g=Math.min(g+2,m.length),h+=m.slice(E,g);continue}if(P===z){let E=g;while(g<m.length&&m.charCodeAt(g)!==10)g++;h+=m.slice(E,g);continue}}if(R===pe||R===$e||R===je){$=!0,x=R,h+=m[g],g++;continue}if(R===_||R===fe||R===Q)y++;else if(R===U||R===Oe||R===me)y--;if(y>=1&&R===ge&&(g+1>=m.length||m.charCodeAt(g+1)!==ge&&m.charCodeAt(g+1)!==we)){while(h.length>0&&(h[h.length-1]===" "||h[h.length-1]==="\t"||h[h.length-1]===`
49
+ `))h=h.slice(0,-1);g++;let P=0;while(g<m.length){let E=m.charCodeAt(g);if(E===pe||E===$e||E===je){let O=E;g++;while(g<m.length){if(m.charCodeAt(g)===Ue){g+=2;continue}if(m.charCodeAt(g)===O){g++;break}g++}continue}if(E===_||E===fe||E===Q)P++;else if(E===U||E===Oe||E===me){if(P===0)break;P--}else if(E===Ge&&P===0)break;g++}continue}if(y===1&&R===st&&g+2<m.length&&m.charCodeAt(g+1)===st&&m.charCodeAt(g+2)===st){g+=3;continue}h+=m[g],g++}return h}function ps(m){let h=m.trim(),g=h.startsWith("...");if(g)h=h.slice(3).trim();while(h.startsWith("@")){let N=1;while(N<h.length&&Ze(h.charCodeAt(N)))N++;if(N<h.length&&h.charCodeAt(N)===Q){let D=1;N++;while(N<h.length&&D>0){if(h.charCodeAt(N)===Q)D++;else if(h.charCodeAt(N)===me)D--;N++}}h=h.slice(N).trim()}let y=!0;while(y){y=!1;for(let N of Hi)if(h.startsWith(N)&&h.length>N.length&&!Ze(h.charCodeAt(N.length))){let D=h.slice(N.length).trim();if(D.charCodeAt(0)===Je||D.charCodeAt(0)===Or&&D.length>1&&D.charCodeAt(1)===Je)break;h=D,y=!0;break}}let $=-1,x=-1,R=0,P=!1,E=0;for(let N=0;N<h.length;N++){let D=h.charCodeAt(N);if(P){if(D===Ue){N++;continue}if(D===E)P=!1;continue}if(D===z&&N+1<h.length){let B=h.charCodeAt(N+1);if(B===Ee){N+=2;while(N+1<h.length&&!(h.charCodeAt(N)===Ee&&h.charCodeAt(N+1)===z))N++;N++;continue}if(B===z){while(N<h.length&&h.charCodeAt(N)!==10)N++;continue}}if(D===pe||D===$e||D===je){P=!0,E=D;continue}if(D===Q||D===_||D===fe||D===xe)R++;else if(D===me||D===U||D===Oe||D===we&&!(N>0&&h.charCodeAt(N-1)===ge))R--;else if(R===0){if(D===Je&&$===-1)$=N;else if(D===ge&&x===-1&&(N===0||h.charCodeAt(N-1)!==ge)&&(N+1>=h.length||h.charCodeAt(N+1)!==ge&&h.charCodeAt(N+1)!==we))x=N}}let O,W,j=x!==-1;if($!==-1&&(x===-1||$<x))if(O=h.slice(0,$).trim(),x!==-1)W=h.slice($+1,x).trim();else W=h.slice($+1).trim();else if(x!==-1)O=h.slice(0,x).trim(),W=Ri(h.slice(x+1).trim());else O=h,W="unknown";if(O=ol(O),(O.startsWith("{")||O.startsWith("["))&&O.includes(`
50
50
  `)){let N=O.replace(/\s*\n\s*/g," ").replace(/\s+/g," ");if(N.length<=40)O=N;else O=O.split(`
51
51
  `).map((D)=>{let B=D.trim();if(!B)return"";if(B==="{"||B==="}"||B==="["||B==="]"||B.startsWith("}")||B.startsWith("]"))return B;return` ${B}`}).join(`
52
- `)}let L=O.endsWith("?")||j;if(O.endsWith("?"))O=O.slice(0,-1).trim();let I=L&&!g?"?":"";if(g)return`...${O}: ${W}`;return`${O}${I}: ${W}`}function ys(m){let h=0;if(h<m.length&&m.charCodeAt(h)===45)h++;if(h>=m.length)return!1;let g=m.charCodeAt(h);if(g<48||g>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++;if(h<m.length&&m.charCodeAt(h)===46){if(h++,h>=m.length||m.charCodeAt(h)<48||m.charCodeAt(h)>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++}return h===m.length}function Ri(m){let h=m.trim();if(h==="true"||h==="false")return"boolean";if(ys(h))return"number";if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return"string";if(h.startsWith("["))return"unknown[]";if(h.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Ni(m){let h=m.trim();if(h.endsWith("as const"))h=h.slice(0,-8).trim();if(h==="true"||h==="false")return h;if(ys(h))return h;if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return h;return"unknown"}function Wi(m){if(m.endsWith("as const"))return null;let h=0,g=-1;for(let y=0;y<m.length;y++){let $=m.charCodeAt(y);if($===pe||$===$e||$===je)y=Hl(m,y,$)-1;else if($===123||$===91||$===40)h++;else if($===125||$===93||$===41)h--;else if(h===0&&$===32&&y+4<=m.length&&m.substring(y,y+4)===" as ")g=y}if(g===-1)return null;return m.slice(g+4).trim()||null}function rr(){if(d(),l<o&&n.charCodeAt(l)===Je){l++,d();let m=l,h=0;while(l<o){if(A())continue;let g=n.charCodeAt(l);if(g===Q||g===fe||g===xe)h++;else if(g===me||g===Oe||g===we&&!J())h--;else if(g===_)if(h>0)h++;else{let y=p(m,l),$=(x)=>{let R=y.length-x.length;return R>=0&&y.endsWith(x)&&(R===0||!Ze(y.charCodeAt(R-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||$("is")||$("extends"))h++;else break}else if(g===U){if(h===0)break;h--}else if(h===0&&g===Y)break;if(h===0&&K())break;l++}return p(m,l)}return""}function yt(m,h,g,y){l+=8,d();let $=l<o&&n.charCodeAt(l)===Ee;if($)l++,d();let x=T();if(!x&&!y)return null;d();let R=tt();d();let P=pt();d();let E=rr(),O=E.length>0;if(!E)if(g&&$)E="AsyncGenerator<unknown, void, unknown>";else if($)E="Generator<unknown, void, unknown>";else if(g)E="Promise<void>";else E="void";d();let W=!1;if(l<o&&n.charCodeAt(l)===_){W=!0;let N=l+1;if(G(_,U),!a&&!O&&!$)E=nr(n.slice(N,l-1),g,P)}else if(l<o&&n.charCodeAt(l)===Y)l++;let j=Tt(P),L=`${h?y?"export default function ":"export declare function ":"declare function "}${x||"default"}${R}${j}: ${E};`,I=le(m);if(W)u.add(c.length);return{kind:"function",name:x||"default",text:L,isExported:h,isDefault:y,isAsync:g,isGenerator:$,returnType:E,generics:R||void 0,leadingComments:I,start:m,end:l}}function Rt(m,h,g){l+=h.length,d();let y=[];do{if(d(),l>=o)break;let $=n.charCodeAt(l);if($===_||$===fe)return ie(),y;let x=T();if(!x)return ie(),y;d();let R,P,E=!1;if(l<o&&n.charCodeAt(l)===Je){l++,d();let j=l,L=0;while(l<o){if(A())continue;let I=n.charCodeAt(l);if(I===Q||I===_||I===fe||I===xe)L++;else if(I===me||I===U||I===Oe||I===we&&!J())L--;else if(L===0&&(I===Y||I===Ge))break;else if(L===0&&I===ge&&!ye())break;if(L===0&&F())break;l++}R=p(j,l)}if(l<o&&n.charCodeAt(l)===ge)if(a&&R&&(!s||!ql(R)))ie();else{l++,d();let j=l,L=0,I=0;while(l<o){if(A())continue;let N=n.charCodeAt(l);if(N===Q||N===_||N===fe)L++;else if(N===me||N===U||N===Oe)L--;else if(N===xe&&L===0){if(l+1>=o||n.charCodeAt(l+1)!==ge)I++}else if(N===we&&L===0&&!J()){if(I>0&&(l+1>=o||n.charCodeAt(l+1)!==ge))I--}else if(L===0&&I===0&&(N===Y||N===Ge))break;if(L===0&&I===0&&F())break;l++}if(P=p(j,l),P.endsWith(" as const")||P==="const"){if(E=!0,!R){let N=P.endsWith(" as const")?P.slice(0,-9).trim():P,D=Ni(N);R=D!=="unknown"?D:void 0}}else if(!R){let N=Wi(P);if(N)R=N}}if(l<o){let j=n.charCodeAt(l);if(j===Ge){l++;continue}if(j===Y)l++}let O=le(m),W=`${g?"export ":""}declare ${h} ${x}: ${R||"unknown"};`;y.push({kind:"variable",name:x,text:W,isExported:g,typeAnnotation:R,value:P,modifiers:E?[h,"const assertion"]:[h],leadingComments:O,start:m,end:l});break}while(l<o);return y}function Pi(m,h){l+=9,d();let g=T();d();let y=tt();d();let $="";if(v("extends")){l+=7,d();let O=l,W=0;while(l<o){if(A())continue;let j=n.charCodeAt(l);if(j===xe)W++;else if(j===we&&!J())W--;else if(j===_&&W===0)break;l++}$=p(O,l)}d();let x=l<o&&n.charCodeAt(l)===_?gt():"{}",R=gs(x),P=`${h?"export ":""}declare interface ${g}${y}${$?` extends ${$}`:""} ${R}`,E=le(m);return{kind:"interface",name:g,text:P,isExported:h,extends:$||void 0,generics:y||void 0,leadingComments:E,start:m,end:l}}function Fi(m,h){l+=4,d();let g=T();d();let y=tt();if(d(),l<o&&n.charCodeAt(l)===ge)l++;d();let $=l,x=0;while(l<o){if(A())continue;let O=n.charCodeAt(l);if(O===Q||O===_||O===fe||O===xe)x++;else if(O===me||O===U||O===Oe||O===we&&!J())x--;else if(x===0&&O===Y)break;if(x===0&&F())break;l++}let R=p($,l);if(l<o&&n.charCodeAt(l)===Y)l++;let P=`${h?"export ":""}type ${g}${y} = ${R}`,E=le(m);return{kind:"type",name:g,text:P,isExported:h,generics:y||void 0,leadingComments:E,start:m,end:l}}function Nt(m,h,g){l+=4,d();let y=T();d();let $=l;if(l<o&&n.charCodeAt(l)===_)G(_,U);let x=p(m,l),R=le(m);return{kind:"enum",name:y,text:x,isExported:h,modifiers:g?["const"]:void 0,leadingComments:R,start:m,end:l}}function wt(m,h,g,y=!1){l+=5,d();let $=T()||"AnonymousClass";d();let x=tt();d();let R="";if(v("extends")){l+=7,d();let j=l,L=0;while(l<o){if(A())continue;let I=n.charCodeAt(l);if(I===xe)L++;else if(I===we&&!J())L--;else if(L===0&&(I===_||v("implements")))break;l++}R=p(j,l)}let P;if(v("implements")){l+=10,d();let j=l,L=0;while(l<o){if(A())continue;let N=n.charCodeAt(l);if(N===xe)L++;else if(N===we&&!J())L--;else if(L===0&&N===_)break;l++}let I=p(j,l);if(I)P=I.split(",").map((N)=>N.trim())}d();let E=Di(),O=`${h?y?"export default ":"export declare ":"declare "}${g?"abstract ":""}class ${$}${x}${R?` extends ${R}`:""}${P&&P.length>0?` implements ${P.join(", ")}`:""} ${E}`,W=le(m);return{kind:"class",name:$,text:O,isExported:h,isDefault:y,extends:R||void 0,implements:P,generics:x||void 0,modifiers:g?["abstract"]:void 0,leadingComments:W,start:m,end:l}}function Di(){if(l>=o||n.charCodeAt(l)!==_)return"{}";l++;let m=[];while(l<o){if(d(),l>=o)break;if(n.charCodeAt(l)===U){l++;break}if(n.charCodeAt(l)===Y){l++;continue}if(v("static")&&ws("static")===_){l+=6,d(),G(_,U);continue}let h=!1,g=!1,y=!1,$=!1,x=!1,R=!1,P=!1,E=!1,O=!0;while(O){if(d(),v("private")){h=!0,l+=7;continue}if(v("protected")){g=!0,l+=9;continue}if(v("public")){l+=6;continue}if(v("static")){y=!0,l+=6;continue}if(v("abstract")){$=!0,l+=8;continue}if(v("readonly")){x=!0,l+=8;continue}if(v("override")){R=!0,l+=8;continue}if(v("accessor")){P=!0,l+=8;continue}if(v("async")){E=!0,l+=5;continue}if(v("declare")){l+=7;continue}break}if(d(),l>=o||n.charCodeAt(l)===U)break;if(n.charCodeAt(l)===Sr)h=!0;if(h){Li();continue}let W=" ";if(g)W+="protected ";if(y)W+="static ";if($)W+="abstract ";if(x)W+="readonly ";if(v("constructor")){l+=11,d();let j=pt();if(d(),ol(j,m),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;let L=Tt(j);m.push(` constructor${L};`)}else if(v("get"))if(l+=3,d(),l<o&&(Ft(n.charCodeAt(l))||n.charCodeAt(l)===fe||n.charCodeAt(l)===Sr)){let j=Ii();if(j.startsWith("#")){if(d(),l<o&&n.charCodeAt(l)===Q)pt();if(d(),rr(),d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;continue}d(),pt(),d();let L=rr()||"unknown";if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;m.push(`${W}get ${j}(): ${L};`)}else $s("get",W,y,x,E,m);else if(v("set"))if(l+=3,d(),l<o&&(Ft(n.charCodeAt(l))||n.charCodeAt(l)===fe||n.charCodeAt(l)===Sr)){let j=Ii();if(j.startsWith("#")){if(d(),l<o&&n.charCodeAt(l)===Q)pt();if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;continue}d();let L=pt();if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;let I=Tt(L);m.push(`${W}set ${j}${I};`)}else $s("set",W,y,x,E,m);else{let j=n.charCodeAt(l)===Ee;if(j)l++,d();let L=Ii();if(!L){Li();continue}Cs(L,W,y,x,j,$,E,m)}}return`{
52
+ `)}let L=O.endsWith("?")||j;if(O.endsWith("?"))O=O.slice(0,-1).trim();let I=L&&!g?"?":"";if(g)return`...${O}: ${W}`;return`${O}${I}: ${W}`}function ys(m){let h=0;if(h<m.length&&m.charCodeAt(h)===45)h++;if(h>=m.length)return!1;let g=m.charCodeAt(h);if(g<48||g>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++;if(h<m.length&&m.charCodeAt(h)===46){if(h++,h>=m.length||m.charCodeAt(h)<48||m.charCodeAt(h)>57)return!1;while(h<m.length&&m.charCodeAt(h)>=48&&m.charCodeAt(h)<=57)h++}return h===m.length}function Ri(m){let h=m.trim();if(h==="true"||h==="false")return"boolean";if(ys(h))return"number";if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return"string";if(h.startsWith("["))return"unknown[]";if(h.startsWith("{"))return"Record<string, unknown>";return"unknown"}function Ni(m){let h=m.trim();if(h.endsWith("as const"))h=h.slice(0,-8).trim();if(h==="true"||h==="false")return h;if(ys(h))return h;if(h.startsWith("'")&&h.endsWith("'")||h.startsWith('"')&&h.endsWith('"'))return h;return"unknown"}function Wi(m){if(m.endsWith("as const"))return null;let h=0,g=-1;for(let y=0;y<m.length;y++){let $=m.charCodeAt(y);if($===pe||$===$e||$===je)y=ql(m,y,$)-1;else if($===123||$===91||$===40)h++;else if($===125||$===93||$===41)h--;else if(h===0&&$===32&&y+4<=m.length&&m.substring(y,y+4)===" as ")g=y}if(g===-1)return null;return m.slice(g+4).trim()||null}function rr(){if(d(),l<o&&n.charCodeAt(l)===Je){l++,d();let m=l,h=0;while(l<o){if(A())continue;let g=n.charCodeAt(l);if(g===Q||g===fe||g===xe)h++;else if(g===me||g===Oe||g===we&&!J())h--;else if(g===_)if(h>0)h++;else{let y=p(m,l),$=(x)=>{let R=y.length-x.length;return R>=0&&y.endsWith(x)&&(R===0||!Ze(y.charCodeAt(R-1)))};if(y.length===0||y.endsWith("|")||y.endsWith("&")||$("is")||$("extends"))h++;else break}else if(g===U){if(h===0)break;h--}else if(h===0&&g===Y)break;if(h===0&&K())break;l++}return p(m,l)}return""}function yt(m,h,g,y){l+=8,d();let $=l<o&&n.charCodeAt(l)===Ee;if($)l++,d();let x=T();if(!x&&!y)return null;d();let R=rt();d();let P=pt();d();let E=rr(),O=E.length>0;if(!E)if(g&&$)E="AsyncGenerator<unknown, void, unknown>";else if($)E="Generator<unknown, void, unknown>";else if(g)E="Promise<void>";else E="void";d();let W=!1;if(l<o&&n.charCodeAt(l)===_){W=!0;let N=l+1;if(G(_,U),!a&&!O&&!$)E=nr(n.slice(N,l-1),g,P)}else if(l<o&&n.charCodeAt(l)===Y)l++;let j=Tt(P),L=`${h?y?"export default function ":"export declare function ":"declare function "}${x||"default"}${R}${j}: ${E};`,I=le(m);if(W)u.add(c.length);return{kind:"function",name:x||"default",text:L,isExported:h,isDefault:y,isAsync:g,isGenerator:$,returnType:E,generics:R||void 0,leadingComments:I,start:m,end:l}}function Rt(m,h,g){l+=h.length,d();let y=[];do{if(d(),l>=o)break;let $=n.charCodeAt(l);if($===_||$===fe)return ie(),y;let x=T();if(!x)return ie(),y;d();let R,P,E=!1;if(l<o&&n.charCodeAt(l)===Je){l++,d();let j=l,L=0;while(l<o){if(A())continue;let I=n.charCodeAt(l);if(I===Q||I===_||I===fe||I===xe)L++;else if(I===me||I===U||I===Oe||I===we&&!J())L--;else if(L===0&&(I===Y||I===Ge))break;else if(L===0&&I===ge&&!ye())break;if(L===0&&F())break;l++}R=p(j,l)}if(l<o&&n.charCodeAt(l)===ge)if(a&&R&&(!s||!zl(R)))ie();else{l++,d();let j=l,L=0,I=0;while(l<o){if(A())continue;let N=n.charCodeAt(l);if(N===Q||N===_||N===fe)L++;else if(N===me||N===U||N===Oe)L--;else if(N===xe&&L===0){if(l+1>=o||n.charCodeAt(l+1)!==ge)I++}else if(N===we&&L===0&&!J()){if(I>0&&(l+1>=o||n.charCodeAt(l+1)!==ge))I--}else if(L===0&&I===0&&(N===Y||N===Ge))break;if(L===0&&I===0&&F())break;l++}if(P=p(j,l),P.endsWith(" as const")||P==="const"){if(E=!0,!R){let N=P.endsWith(" as const")?P.slice(0,-9).trim():P,D=Ni(N);R=D!=="unknown"?D:void 0}}else if(!R){let N=Wi(P);if(N)R=N}}if(l<o){let j=n.charCodeAt(l);if(j===Ge){l++;continue}if(j===Y)l++}let O=le(m),W=`${g?"export ":""}declare ${h} ${x}: ${R||"unknown"};`;y.push({kind:"variable",name:x,text:W,isExported:g,typeAnnotation:R,value:P,modifiers:E?[h,"const assertion"]:[h],leadingComments:O,start:m,end:l});break}while(l<o);return y}function Pi(m,h){l+=9,d();let g=T();d();let y=rt();d();let $="";if(v("extends")){l+=7,d();let O=l,W=0;while(l<o){if(A())continue;let j=n.charCodeAt(l);if(j===xe)W++;else if(j===we&&!J())W--;else if(j===_&&W===0)break;l++}$=p(O,l)}d();let x=l<o&&n.charCodeAt(l)===_?gt():"{}",R=gs(x),P=`${h?"export ":""}declare interface ${g}${y}${$?` extends ${$}`:""} ${R}`,E=le(m);return{kind:"interface",name:g,text:P,isExported:h,extends:$||void 0,generics:y||void 0,leadingComments:E,start:m,end:l}}function Fi(m,h){l+=4,d();let g=T();d();let y=rt();if(d(),l<o&&n.charCodeAt(l)===ge)l++;d();let $=l,x=0;while(l<o){if(A())continue;let O=n.charCodeAt(l);if(O===Q||O===_||O===fe||O===xe)x++;else if(O===me||O===U||O===Oe||O===we&&!J())x--;else if(x===0&&O===Y)break;if(x===0&&F())break;l++}let R=p($,l);if(l<o&&n.charCodeAt(l)===Y)l++;let P=`${h?"export ":""}type ${g}${y} = ${R}`,E=le(m);return{kind:"type",name:g,text:P,isExported:h,generics:y||void 0,leadingComments:E,start:m,end:l}}function Nt(m,h,g){l+=4,d();let y=T();d();let $=l;if(l<o&&n.charCodeAt(l)===_)G(_,U);let x=p(m,l),R=le(m);return{kind:"enum",name:y,text:x,isExported:h,modifiers:g?["const"]:void 0,leadingComments:R,start:m,end:l}}function wt(m,h,g,y=!1){l+=5,d();let $=T()||"AnonymousClass";d();let x=rt();d();let R="";if(v("extends")){l+=7,d();let j=l,L=0;while(l<o){if(A())continue;let I=n.charCodeAt(l);if(I===xe)L++;else if(I===we&&!J())L--;else if(L===0&&(I===_||v("implements")))break;l++}R=p(j,l)}let P;if(v("implements")){l+=10,d();let j=l,L=0;while(l<o){if(A())continue;let N=n.charCodeAt(l);if(N===xe)L++;else if(N===we&&!J())L--;else if(L===0&&N===_)break;l++}let I=p(j,l);if(I)P=I.split(",").map((N)=>N.trim())}d();let E=Di(),O=`${h?y?"export default ":"export declare ":"declare "}${g?"abstract ":""}class ${$}${x}${R?` extends ${R}`:""}${P&&P.length>0?` implements ${P.join(", ")}`:""} ${E}`,W=le(m);return{kind:"class",name:$,text:O,isExported:h,isDefault:y,extends:R||void 0,implements:P,generics:x||void 0,modifiers:g?["abstract"]:void 0,leadingComments:W,start:m,end:l}}function Di(){if(l>=o||n.charCodeAt(l)!==_)return"{}";l++;let m=[];while(l<o){if(d(),l>=o)break;if(n.charCodeAt(l)===U){l++;break}if(n.charCodeAt(l)===Y){l++;continue}if(v("static")&&ws("static")===_){l+=6,d(),G(_,U);continue}let h=!1,g=!1,y=!1,$=!1,x=!1,R=!1,P=!1,E=!1,O=!0;while(O){if(d(),v("private")){h=!0,l+=7;continue}if(v("protected")){g=!0,l+=9;continue}if(v("public")){l+=6;continue}if(v("static")){y=!0,l+=6;continue}if(v("abstract")){$=!0,l+=8;continue}if(v("readonly")){x=!0,l+=8;continue}if(v("override")){R=!0,l+=8;continue}if(v("accessor")){P=!0,l+=8;continue}if(v("async")){E=!0,l+=5;continue}if(v("declare")){l+=7;continue}break}if(d(),l>=o||n.charCodeAt(l)===U)break;if(n.charCodeAt(l)===Sr)h=!0;if(h){Li();continue}let W=" ";if(g)W+="protected ";if(y)W+="static ";if($)W+="abstract ";if(x)W+="readonly ";if(v("constructor")){l+=11,d();let j=pt();if(d(),ll(j,m),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;let L=Tt(j);m.push(` constructor${L};`)}else if(v("get"))if(l+=3,d(),l<o&&(Ft(n.charCodeAt(l))||n.charCodeAt(l)===fe||n.charCodeAt(l)===Sr)){let j=Ii();if(j.startsWith("#")){if(d(),l<o&&n.charCodeAt(l)===Q)pt();if(d(),rr(),d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;continue}d(),pt(),d();let L=rr()||"unknown";if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;m.push(`${W}get ${j}(): ${L};`)}else $s("get",W,y,x,E,m);else if(v("set"))if(l+=3,d(),l<o&&(Ft(n.charCodeAt(l))||n.charCodeAt(l)===fe||n.charCodeAt(l)===Sr)){let j=Ii();if(j.startsWith("#")){if(d(),l<o&&n.charCodeAt(l)===Q)pt();if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;continue}d();let L=pt();if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;let I=Tt(L);m.push(`${W}set ${j}${I};`)}else $s("set",W,y,x,E,m);else{let j=n.charCodeAt(l)===Ee;if(j)l++,d();let L=Ii();if(!L){Li();continue}Cs(L,W,y,x,j,$,E,m)}}return`{
53
53
  ${m.join(`
54
54
  `)}
55
- }`}function Ii(){if(l>=o)return"";let m=n.charCodeAt(l);if(m===fe){let h=l;return G(fe,Oe),n.slice(h,l)}if(m===Sr)return l++,`#${T()}`;return T()}function ws(m){let h=l+m.length;while(h<o&&Se(n.charCodeAt(h)))h++;return h<o?n.charCodeAt(h):0}function Li(){let m=0;while(l<o){if(A())continue;let h=n.charCodeAt(l);if(h===_||h===Q)m++;else if(h===U||h===me){if(m===0)return;m--}else if(h===Y&&m===0){l++;return}if(m===0&&K())return;l++}}function $s(m,h,g,y,$,x){Cs(m,h,g,y,!1,!1,$,x)}function Cs(m,h,g,y,$,x,R,P){if(d(),l>=o)return;let E=n.charCodeAt(l),O=!1;if(E===Or)O=!0,l++,d();if(l<o&&n.charCodeAt(l)===33)l++,d();let W=l<o?n.charCodeAt(l):0;if(W===Q||W===xe){let j=W===xe?tt():"";d();let L=pt();d();let I=rr(),N=I.length>0;if(!I)if(R&&$)I="AsyncGenerator<unknown, void, unknown>";else if($)I="Generator<unknown, void, unknown>";else if(R)I="Promise<void>";else I="void";if(d(),l<o&&n.charCodeAt(l)===_){let $t=l+1;if(G(_,U),!a&&!N&&!$)I=nr(n.slice($t,l-1),R,L)}else if(l<o&&n.charCodeAt(l)===Y)l++;let D=Tt(L),B=O?"?":"",be=$?"*":"";P.push(`${h}${be}${m}${B}${j}${D}: ${I};`)}else if(W===Je||W===ge||W===Y||W===U||W===he||W===Ce){let j="";if(W===Je){l++,d();let N=l,D=0;while(l<o){if(A())continue;let B=n.charCodeAt(l);if(B===Q||B===_||B===fe||B===xe)D++;else if(B===me||B===U||B===Oe||B===we&&!J()){if(D===0)break;D--}else if(D===0&&(B===Y||B===Ge))break;else if(D===0&&B===ge&&!ye())break;if(D===0&&K())break;l++}j=p(N,l)}let L="";if(l<o&&n.charCodeAt(l)===ge)if(a&&j){l++;let N=0;while(l<o){if(A())continue;let D=n.charCodeAt(l);if(D===Q||D===_||D===fe)N++;else if(D===me||D===U||D===Oe){if(N===0&&D===U)break;N--}else if(N===0&&D===Y)break;if(N===0&&K())break;l++}}else{l++,d();let N=l,D=0;while(l<o){if(A())continue;let B=n.charCodeAt(l);if(B===Q||B===_||B===fe)D++;else if(B===me||B===U||B===Oe){if(D===0&&B===U)break;D--}else if(D===0&&B===Y)break;if(D===0&&K())break;l++}L=p(N,l)}if(l<o&&n.charCodeAt(l)===Y)l++;if(!j)if(L){let N=Wi(L);if(N)j=N;else j=L.endsWith("as const")||g&&y?Ni(L):Ri(L)}else j="unknown";let I=O?"?":"";P.push(`${h}${m}${I}: ${j};`)}else Li()}function ol(m,h){let g=m.slice(1,-1).trim();if(!g)return;let y=[],$=0,x=0,R=!1,P=0;for(let E=0;E<=g.length;E++){if(E===g.length){y.push(g.slice($).trim());break}let O=g.charCodeAt(E);if(R){if(O===Ue){E++;continue}if(O===P)R=!1;continue}if(O===pe||O===$e||O===je){R=!0,P=O;continue}if(O===Q||O===_||O===fe||O===xe)x++;else if(O===me||O===U||O===Oe||O===we&&!(E>0&&g.charCodeAt(E-1)===ge))x--;else if(O===Ge&&x===0)y.push(g.slice($,E).trim()),$=E+1}for(let E of y){let O=E.startsWith("public ")||E.startsWith("public\t"),W=E.startsWith("protected ")||E.startsWith("protected\t"),j=E.startsWith("private ")||E.startsWith("private\t"),L=E.includes("readonly ");if(!O&&!W&&!j&&!L)continue;if(j)continue;let I=E,N=[];if(O){let be=6;while(be<I.length&&Se(I.charCodeAt(be)))be++;I=I.slice(be),N.push("public")}if(W){let be=9;while(be<I.length&&Se(I.charCodeAt(be)))be++;I=I.slice(be),N.push("protected")}if(L){let be=I.indexOf("readonly ");if(be!==-1){let $t=be+8;while($t<I.length&&Se(I.charCodeAt($t)))$t++;I=I.slice(0,be)+I.slice($t)}N.push("readonly")}let D=N.length>0?`${N.join(" ")} `:"",B=ps(I);h.push(` ${D}${B};`)}}function ji(m=" "){if(l>=o||n.charCodeAt(l)!==_)return"{}";l++;let h=[];while(l<o){if(d(),l>=o)break;if(n.charCodeAt(l)===U){l++;break}if(n.charCodeAt(l)===Y){l++;continue}let g=!1;if(v("export"))g=!0,l+=6,d();if(v("declare"))l+=7,d();let y=g?"export ":"";if(v("function")||v("async")&&ll("async","function")){let $=!1;if(v("async"))$=!0,l+=5,d();if(l+=8,d(),l<o&&n.charCodeAt(l)===Ee)l++,d();let x=T();d();let R=tt();d();let P=pt();d();let E=rr();if(!E)E=$?"Promise<void>":"void";if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;let O=Tt(P);h.push(`${m}${y}function ${x}${R}${O}: ${E};`)}else if(v("const")||v("let")||v("var")){let $=v("const")?"const":v("let")?"let":"var";l+=$.length,d();let x=T();if(!x){ie();continue}d();let R="";if(l<o&&n.charCodeAt(l)===Je){l++,d();let E=l,O=0;while(l<o){if(A())continue;let W=n.charCodeAt(l);if(W===Q||W===_||W===fe||W===xe)O++;else if(W===me||W===U||W===Oe||W===we&&!J())O--;else if(O===0&&(W===Y||W===Ge))break;else if(O===0&&W===ge&&!ye())break;if(O===0&&F())break;l++}R=p(E,l)}let P="";if(l<o&&n.charCodeAt(l)===ge){l++,d();let E=l,O=0;while(l<o){if(A())continue;let W=n.charCodeAt(l);if(W===Q||W===_||W===fe||W===xe)O++;else if(W===me||W===U||W===Oe||W===we&&!J())O--;else if(O===0&&(W===Y||W===Ge))break;if(O===0&&F())break;l++}P=p(E,l)}if(l<o&&n.charCodeAt(l)===Y)l++;if(!R&&P){let E=Wi(P);if(E)R=E;else if($==="const")R=Ni(P);else R=Ri(P)}if(!R)R="unknown";h.push(`${m}${y}${$} ${x}: ${R};`)}else if(v("interface")){l+=9,d();let $=T();d();let x=tt();d();let R="";if(v("extends")){let E=l;while(l<o&&n.charCodeAt(l)!==_){if(A())continue;l++}R=n.slice(E,l)}let P=gs(gt());h.push(`${m}${y}interface ${$}${x}${R} ${P}`)}else if(v("type")){l+=4,d();let $=T();d();let x=tt();if(d(),l<o&&n.charCodeAt(l)===ge){l++,d();let R=l,P=0;while(l<o){if(A())continue;let O=n.charCodeAt(l);if(O===Q||O===_||O===fe||O===xe)P++;else if(O===me||O===U||O===Oe||O===we&&!J())P--;else if(P===0&&O===Y)break;if(P===0&&F())break;l++}let E=p(R,l);if(l<o&&n.charCodeAt(l)===Y)l++;h.push(`${m}${y}type ${$}${x} = ${E}`)}}else if(v("class")){l+=5,d();let $=T();d();let x=tt();d();let R=l;while(l<o&&n.charCodeAt(l)!==_){if(A())continue;l++}let P=p(R,l),E=P?` ${P}`:"",O=Di();h.push(`${m}${y}class ${$}${x}${E} ${O}`)}else if(v("enum")){l+=4,d();let $=T();d();let x=gt();h.push(`${m}${y}enum ${$} ${x}`)}else if(v("namespace")||v("module")){let $=v("namespace")?"namespace":"module";l+=$.length,d();let x=T();d();let R=ji(m);h.push(`${m}${y}${$} ${x} ${R}`)}else if(v("abstract"))if(l+=8,d(),v("class")){l+=5,d();let $=T();d();let x=tt();d();let R=l;while(l<o&&n.charCodeAt(l)!==_){if(A())continue;l++}let P=p(R,l),E=P?` ${P}`:"",O=Di();h.push(`${m}${y}abstract class ${$}${x}${E} ${O}`)}else ie();else if(g&&v("default")){l+=7,d();let $=l;ie();let x=p($,l);if(x.charCodeAt(x.length-1)===Y)x=x.slice(0,-1);if(x)h.push(`${m}export default ${x};`)}else if(!g&&(n.charCodeAt(l)===pe||n.charCodeAt(l)===$e||n.charCodeAt(l)===je))ie();else ie()}if(h.length===0)return"{}";return`{
55
+ }`}function Ii(){if(l>=o)return"";let m=n.charCodeAt(l);if(m===fe){let h=l;return G(fe,Oe),n.slice(h,l)}if(m===Sr)return l++,`#${T()}`;return T()}function ws(m){let h=l+m.length;while(h<o&&Se(n.charCodeAt(h)))h++;return h<o?n.charCodeAt(h):0}function Li(){let m=0;while(l<o){if(A())continue;let h=n.charCodeAt(l);if(h===_||h===Q)m++;else if(h===U||h===me){if(m===0)return;m--}else if(h===Y&&m===0){l++;return}if(m===0&&K())return;l++}}function $s(m,h,g,y,$,x){Cs(m,h,g,y,!1,!1,$,x)}function Cs(m,h,g,y,$,x,R,P){if(d(),l>=o)return;let E=n.charCodeAt(l),O=!1;if(E===Or)O=!0,l++,d();if(l<o&&n.charCodeAt(l)===33)l++,d();let W=l<o?n.charCodeAt(l):0;if(W===Q||W===xe){let j=W===xe?rt():"";d();let L=pt();d();let I=rr(),N=I.length>0;if(!I)if(R&&$)I="AsyncGenerator<unknown, void, unknown>";else if($)I="Generator<unknown, void, unknown>";else if(R)I="Promise<void>";else I="void";if(d(),l<o&&n.charCodeAt(l)===_){let $t=l+1;if(G(_,U),!a&&!N&&!$)I=nr(n.slice($t,l-1),R,L)}else if(l<o&&n.charCodeAt(l)===Y)l++;let D=Tt(L),B=O?"?":"",be=$?"*":"";P.push(`${h}${be}${m}${B}${j}${D}: ${I};`)}else if(W===Je||W===ge||W===Y||W===U||W===he||W===Ce){let j="";if(W===Je){l++,d();let N=l,D=0;while(l<o){if(A())continue;let B=n.charCodeAt(l);if(B===Q||B===_||B===fe||B===xe)D++;else if(B===me||B===U||B===Oe||B===we&&!J()){if(D===0)break;D--}else if(D===0&&(B===Y||B===Ge))break;else if(D===0&&B===ge&&!ye())break;if(D===0&&K())break;l++}j=p(N,l)}let L="";if(l<o&&n.charCodeAt(l)===ge)if(a&&j){l++;let N=0;while(l<o){if(A())continue;let D=n.charCodeAt(l);if(D===Q||D===_||D===fe)N++;else if(D===me||D===U||D===Oe){if(N===0&&D===U)break;N--}else if(N===0&&D===Y)break;if(N===0&&K())break;l++}}else{l++,d();let N=l,D=0;while(l<o){if(A())continue;let B=n.charCodeAt(l);if(B===Q||B===_||B===fe)D++;else if(B===me||B===U||B===Oe){if(D===0&&B===U)break;D--}else if(D===0&&B===Y)break;if(D===0&&K())break;l++}L=p(N,l)}if(l<o&&n.charCodeAt(l)===Y)l++;if(!j)if(L){let N=Wi(L);if(N)j=N;else j=L.endsWith("as const")||g&&y?Ni(L):Ri(L)}else j="unknown";let I=O?"?":"";P.push(`${h}${m}${I}: ${j};`)}else Li()}function ll(m,h){let g=m.slice(1,-1).trim();if(!g)return;let y=[],$=0,x=0,R=!1,P=0;for(let E=0;E<=g.length;E++){if(E===g.length){y.push(g.slice($).trim());break}let O=g.charCodeAt(E);if(R){if(O===Ue){E++;continue}if(O===P)R=!1;continue}if(O===pe||O===$e||O===je){R=!0,P=O;continue}if(O===Q||O===_||O===fe||O===xe)x++;else if(O===me||O===U||O===Oe||O===we&&!(E>0&&g.charCodeAt(E-1)===ge))x--;else if(O===Ge&&x===0)y.push(g.slice($,E).trim()),$=E+1}for(let E of y){let O=E.startsWith("public ")||E.startsWith("public\t"),W=E.startsWith("protected ")||E.startsWith("protected\t"),j=E.startsWith("private ")||E.startsWith("private\t"),L=E.includes("readonly ");if(!O&&!W&&!j&&!L)continue;if(j)continue;let I=E,N=[];if(O){let be=6;while(be<I.length&&Se(I.charCodeAt(be)))be++;I=I.slice(be),N.push("public")}if(W){let be=9;while(be<I.length&&Se(I.charCodeAt(be)))be++;I=I.slice(be),N.push("protected")}if(L){let be=I.indexOf("readonly ");if(be!==-1){let $t=be+8;while($t<I.length&&Se(I.charCodeAt($t)))$t++;I=I.slice(0,be)+I.slice($t)}N.push("readonly")}let D=N.length>0?`${N.join(" ")} `:"",B=ps(I);h.push(` ${D}${B};`)}}function ji(m=" "){if(l>=o||n.charCodeAt(l)!==_)return"{}";l++;let h=[];while(l<o){if(d(),l>=o)break;if(n.charCodeAt(l)===U){l++;break}if(n.charCodeAt(l)===Y){l++;continue}let g=!1;if(v("export"))g=!0,l+=6,d();if(v("declare"))l+=7,d();let y=g?"export ":"";if(v("function")||v("async")&&cl("async","function")){let $=!1;if(v("async"))$=!0,l+=5,d();if(l+=8,d(),l<o&&n.charCodeAt(l)===Ee)l++,d();let x=T();d();let R=rt();d();let P=pt();d();let E=rr();if(!E)E=$?"Promise<void>":"void";if(d(),l<o&&n.charCodeAt(l)===_)G(_,U);else if(l<o&&n.charCodeAt(l)===Y)l++;let O=Tt(P);h.push(`${m}${y}function ${x}${R}${O}: ${E};`)}else if(v("const")||v("let")||v("var")){let $=v("const")?"const":v("let")?"let":"var";l+=$.length,d();let x=T();if(!x){ie();continue}d();let R="";if(l<o&&n.charCodeAt(l)===Je){l++,d();let E=l,O=0;while(l<o){if(A())continue;let W=n.charCodeAt(l);if(W===Q||W===_||W===fe||W===xe)O++;else if(W===me||W===U||W===Oe||W===we&&!J())O--;else if(O===0&&(W===Y||W===Ge))break;else if(O===0&&W===ge&&!ye())break;if(O===0&&F())break;l++}R=p(E,l)}let P="";if(l<o&&n.charCodeAt(l)===ge){l++,d();let E=l,O=0;while(l<o){if(A())continue;let W=n.charCodeAt(l);if(W===Q||W===_||W===fe||W===xe)O++;else if(W===me||W===U||W===Oe||W===we&&!J())O--;else if(O===0&&(W===Y||W===Ge))break;if(O===0&&F())break;l++}P=p(E,l)}if(l<o&&n.charCodeAt(l)===Y)l++;if(!R&&P){let E=Wi(P);if(E)R=E;else if($==="const")R=Ni(P);else R=Ri(P)}if(!R)R="unknown";h.push(`${m}${y}${$} ${x}: ${R};`)}else if(v("interface")){l+=9,d();let $=T();d();let x=rt();d();let R="";if(v("extends")){let E=l;while(l<o&&n.charCodeAt(l)!==_){if(A())continue;l++}R=n.slice(E,l)}let P=gs(gt());h.push(`${m}${y}interface ${$}${x}${R} ${P}`)}else if(v("type")){l+=4,d();let $=T();d();let x=rt();if(d(),l<o&&n.charCodeAt(l)===ge){l++,d();let R=l,P=0;while(l<o){if(A())continue;let O=n.charCodeAt(l);if(O===Q||O===_||O===fe||O===xe)P++;else if(O===me||O===U||O===Oe||O===we&&!J())P--;else if(P===0&&O===Y)break;if(P===0&&F())break;l++}let E=p(R,l);if(l<o&&n.charCodeAt(l)===Y)l++;h.push(`${m}${y}type ${$}${x} = ${E}`)}}else if(v("class")){l+=5,d();let $=T();d();let x=rt();d();let R=l;while(l<o&&n.charCodeAt(l)!==_){if(A())continue;l++}let P=p(R,l),E=P?` ${P}`:"",O=Di();h.push(`${m}${y}class ${$}${x}${E} ${O}`)}else if(v("enum")){l+=4,d();let $=T();d();let x=gt();h.push(`${m}${y}enum ${$} ${x}`)}else if(v("namespace")||v("module")){let $=v("namespace")?"namespace":"module";l+=$.length,d();let x=T();d();let R=ji(m);h.push(`${m}${y}${$} ${x} ${R}`)}else if(v("abstract"))if(l+=8,d(),v("class")){l+=5,d();let $=T();d();let x=rt();d();let R=l;while(l<o&&n.charCodeAt(l)!==_){if(A())continue;l++}let P=p(R,l),E=P?` ${P}`:"",O=Di();h.push(`${m}${y}abstract class ${$}${x}${E} ${O}`)}else ie();else if(g&&v("default")){l+=7,d();let $=l;ie();let x=p($,l);if(x.charCodeAt(x.length-1)===Y)x=x.slice(0,-1);if(x)h.push(`${m}export default ${x};`)}else if(!g&&(n.charCodeAt(l)===pe||n.charCodeAt(l)===$e||n.charCodeAt(l)===je))ie();else ie()}if(h.length===0)return"{}";return`{
56
56
  ${h.join(`
57
57
  `)}
58
- }`}function ll(m,h){let g=l+m.length;while(g<o&&Se(n.charCodeAt(g)))g++;for(let y=0;y<h.length;y++)if(g+y>=o||n.charCodeAt(g+y)!==h.charCodeAt(y))return!1;return g+h.length>=o||!Ze(n.charCodeAt(g+h.length))}function Wt(m,h,g){l+=g.length,d();let y="",$=n.charCodeAt(l);if($===pe||$===$e){let O=l;b($),y=n.slice(O,l)}else{y=T();while(l<o&&n.charCodeAt(l)===st)l++,y+=`.${T()}`}d();let x=l<o&&n.charCodeAt(l)===_?ji():"{}",R=`${h?"export ":""}declare ${g} ${y} ${x}`,P=le(m),E=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:R,isExported:h,source:E?y.slice(1,-1):void 0,leadingComments:P,start:m,end:l}}function vs(m,h){ie();let g=p(h,l);if(g.charCodeAt(g.length-1)===Y)g=g.slice(0,-1).trimEnd();if(!g)return;let y=Ft(g.charCodeAt(0));for(let O=1;y&&O<g.length;O++)y=Ze(g.charCodeAt(O));let $=le(m);if(y){c.push({kind:"export",name:"default",text:`export default ${g};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l});return}let x="__dtsx_default_export__",R=1;while(n.includes(x))x=`__dtsx_default_export_${R++}__`;let P=Ae(g,!1),E=P==="unknown"&&Yl(g)?`typeof ${g}`:P;c.push({kind:"variable",name:x,text:`declare const ${x}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${x};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l})}while(l<o){if(d(),l>=o)break;let m=l,h=n.charCodeAt(l);if(h===105&&v("import"))c.push(nt(m));else if(h===101&&v("export")){l+=6,d();let g=n.charCodeAt(l);if(g===100&&v("default")){l+=7,d();let y=l,$=n.charCodeAt(l);if($===102&&v("function")){let x=yt(m,!0,!1,!0);if(x)c.push(x)}else if($===97&&v("async")&&ws("async")!==Y)if(l+=5,d(),v("function")){let x=yt(m,!0,!0,!0);if(x)c.push(x)}else vs(m,y);else if($===99&&v("class")){let x=wt(m,!0,!1,!0);c.push(x)}else if($===97&&v("abstract")){if(l+=8,d(),v("class")){let x=wt(m,!0,!0,!0);c.push(x)}}else vs(m,y)}else if(g===116&&v("type")){let y=l;if(l+=4,d(),l<o&&n.charCodeAt(l)===_){er();let $=p(m,l),x=le(m);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:et($),leadingComments:x,start:m,end:l})}else if(l<o&&n.charCodeAt(l)===Ee){xt();let $=p(m,l);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:et($),start:m,end:l})}else{l=y;let $=Fi(m,!0);c.push($)}}else if(g===105&&v("interface")){let y=Pi(m,!0);c.push(y)}else if(g===102&&v("function")){let y=yt(m,!0,!1,!1);if(y)c.push(y)}else if(g===97&&v("async"))if(l+=5,d(),v("function")){let y=yt(m,!0,!0,!1);if(y)c.push(y)}else ie();else if(g===99)if(v("class")){let y=wt(m,!0,!1);c.push(y)}else if(v("const")){let y=l;if(l+=5,d(),v("enum")){l=y+5,d();let $=Nt(m,!0,!0);c.push($)}else{l=y;let $=Rt(m,"const",!0);for(let x=0;x<$.length;x++)c.push($[x])}}else ie();else if(g===97&&v("abstract")){if(l+=8,d(),v("class")){let y=wt(m,!0,!0);c.push(y)}}else if(g===108&&v("let")){let y=Rt(m,"let",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(g===118&&v("var")){let y=Rt(m,"var",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(g===101&&v("enum")){let y=Nt(m,!0,!1);c.push(y)}else if(g===100&&v("declare"))l+=7,d(),bs(m,!0);else if(g===110&&v("namespace")&&M(9)){let y=Wt(m,!0,"namespace");c.push(y)}else if(g===109&&v("module")&&M(6)){let y=Wt(m,!0,"module");c.push(y)}else if(g===_){er();let y=p(m,l),$=y.includes("export type"),x=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:$,source:et(y),leadingComments:x,start:m,end:l})}else if(g===Ee){xt();let y=p(m,l),$=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:et(y),leadingComments:$,start:m,end:l})}else{ie();let y=p(m,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:m,end:l})}}else if(h===100&&v("declare"))l+=7,d(),bs(m,!1);else if(h===105&&v("interface")){let g=Pi(m,!1);f.set(g.name,g)}else if(h===116&&v("type")){let g=Fi(m,!1);f.set(g.name,g),c.push(g)}else if(h===102&&v("function")){let g=yt(m,!1,!1,!1);if(g)f.set(g.name,g);else ie()}else if(h===97)if(v("async")){let g=l;if(l+=5,d(),v("function")){let y=yt(m,!1,!0,!1);if(y)f.set(y.name,y);else l=g,ie()}else l=g,ie()}else if(v("abstract"))if(l+=8,d(),v("class")){let g=wt(m,!1,!1);f.set(g.name,g),c.push(g)}else ie();else l++,ie();else if(h===99)if(v("class")){let g=wt(m,!1,!1);f.set(g.name,g),c.push(g)}else if(v("const")){let g=l;if(l+=5,d(),v("enum")){l=g+5,d();let y=Nt(m,!1,!0);f.set(y.name,y),c.push(y)}else{l=g;let y=Rt(m,"const",!1);for(let $=0;$<y.length;$++)f.set(y[$].name,y[$])}}else l++,ie();else if(h===101&&v("enum")){let g=Nt(m,!1,!1);f.set(g.name,g),c.push(g)}else if(h===108&&v("let"))ie();else if(h===118&&v("var"))ie();else if(h===109&&v("module")&&M(6)){let g=Wt(m,!1,"module");c.push(g)}else if(h===110&&v("namespace")&&M(9)){let g=Wt(m,!1,"namespace");c.push(g)}else{let g=n.charCodeAt(l);if(g===pe||g===$e){if(b(g),l<o&&n.charCodeAt(l)===Y)l++}else if(g===je){if(w(),l<o&&n.charCodeAt(l)===Y)l++}else if(g===Gl){if(l++,T(),d(),l<o&&n.charCodeAt(l)===st)l++,T(),d();if(l<o&&n.charCodeAt(l)===Q)G(Q,me)}else l++,ie()}}if(f.size>0)zl(c,f);if(u.size>0){let m=new Map;for(let g of c)if(g.kind==="function")m.set(g.name,(m.get(g.name)||0)+1);let h=new Set;for(let[g,y]of m)if(y>1)h.add(g);if(h.size>0){let g=new Set;for(let y of h)for(let $=c.length-1;$>=0;$--)if(c[$].kind==="function"&&c[$].name===y&&u.has($)){g.add($);break}if(g.size>0){let y=[...g].sort(($,x)=>x-$);for(let $ of y)c.splice($,1)}}}return c;function bs(m,h){if(v("function")){let g=yt(m,h,!1,!1);if(g)c.push(g)}else if(v("async")){if(l+=5,d(),v("function")){let g=yt(m,h,!0,!1);if(g)c.push(g)}}else if(v("class")){let g=wt(m,h,!1);c.push(g)}else if(v("abstract")){if(l+=8,d(),v("class")){let g=wt(m,h,!0);c.push(g)}}else if(v("interface")){let g=Pi(m,h);c.push(g)}else if(v("type")){let g=Fi(m,h);c.push(g)}else if(v("enum")){let g=Nt(m,h,!1);c.push(g)}else if(v("const")){let g=l;if(l+=5,d(),v("enum")){l=g+5,d();let y=Nt(m,h,!0);c.push(y)}else if(h){l=g;let y=Rt(m,"const",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie()}else if(v("let")||v("var"))if(h){let g=v("let")?"let":"var",y=Rt(m,g,!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie();else if(v("module")){let g=Wt(m,h,"module");c.push(g)}else if(v("namespace")){let g=Wt(m,h,"namespace");c.push(g)}else if(v("global")){l+=6,d();let g=`declare global ${l<o&&n.charCodeAt(l)===_?ji():"{}"}`,y=le(m);c.push({kind:"module",name:"global",text:g,isExported:!1,leadingComments:y,start:m,end:l})}else ie()}}function Ls(e,t){let r=0,i=e.length;while(r<i){let n=e.charCodeAt(r);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let s=r;r++;while(r<i){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}t.add(e.substring(s,r))}else r++}}function js(e,t){let r=0;while(r<e.length){let i=e.charCodeAt(r);if(i===pe||i===$e||i===je){let u=i;r++;while(r<e.length)if(e.charCodeAt(r)===Ue)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(i===z&&e.charCodeAt(r+1)===z){r+=2;while(r<e.length&&e.charCodeAt(r)!==he&&e.charCodeAt(r)!==Ce)r++;continue}if(i===z&&e.charCodeAt(r+1)===Ee){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Ft(i)){r++;continue}let n=r++;while(r<e.length&&Ze(e.charCodeAt(r)))r++;let s=n-1,a=r;while(s>=0&&Se(e.charCodeAt(s)))s--;while(a<e.length&&Se(e.charCodeAt(a)))a++;let o=s>=0?e.charCodeAt(s):0,c=a<e.length?e.charCodeAt(a):0,f=n>=3&&e.slice(n-3,n)==="...";if(c===Je||o===st&&!f)continue;if(c===Q&&(o===_||o===Ge))continue;t.add(e.slice(n,r))}}function zl(e,t){let r=new Set,i=new Set;for(let a of e)i.add(a.name);let n=new Set,s=[];for(let a=0;a<e.length;a++){let o=e[a];if(o.kind!=="import"){if(s.push(o.text),Ls(o.text,n),typeof o.value==="string")js(o.value,n)}}for(;;){let a=[];for(let[f,u]of t){if(r.has(f))continue;if(n.has(f)){if(!i.has(f))a.push(u),i.add(f);r.add(f)}}if(a.length===0)break;a.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let o=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<a.length&&(a[c].start??1/0)<=u)o.push(a[c++]);o.push(e[f])}while(c<a.length)o.push(a[c++]);e.length=0;for(let f=0;f<o.length;f++)e.push(o[f]);for(let f of a)if(f.kind!=="import"){if(s.push(f.text),Ls(f.text,n),typeof f.value==="string")js(f.value,n)}}}var We=32,Pe=9,he=10,Ce=13,z=47,Ee=42,pe=39,$e=34,je=96,Ue=92,_=123,U=125,Q=40,me=41,fe=91,Oe=93,xe=60,we=62,Y=59,Je=58,ge=61,Ge=44,st=46,Or=63,Sr=35,Gl=64,Ms=36,Ul=95,Hi;var kr=ce(()=>{Er();Hi=["public","protected","private","readonly","override"]});function Ot(e){if(Xl)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=(t<<5)-t+i,t=t&t}return t}var Xl;var Dt=ce(()=>{Xl=typeof globalThis.Bun?.hash==="function"});function Xi(e,t,r=!0,i=!1){let n=Ot(e),s=`${t}:${r?1:0}:${i?1:0}`,a=It.get(s);if(a&&a.contentHash===n)return a.lastAccess=++_s,a.declarations;let o=i?qi(e,t,r):zi(e,t,r);if(It.set(s,{declarations:o,contentHash:n,lastAccess:++_s}),It.size>Ql){let c=Math.max(1,Math.ceil(It.size*0.1)),f=[];for(let[u,l]of It)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)It.delete(f[u][0])}return o}var Ql=100,_s=0,It;var Tr=ce(()=>{kr();Dt();It=new Map});function Rr(e,t){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):1;if(e===void 0||!Number.isFinite(e))return r;return Math.max(1,Math.floor(e))}var or=()=>{};var Qi=ce(()=>{or();Dt()});function Nr(e,t,r=!0,i=!1){return Xi(e,t,r,i)}var Wr=ce(()=>{Tr();Qi();or()});import{dirname as Sd,relative as ec,resolve as kd}from"path";async function Zs(e,t,r){let i=new Map,n=[],s=new Set,a=0,o=0,c=0,f=[];for(let S of e){let k=t.get(S);if(!k)continue;f.push({file:S,decls:Nr(k,S,r.keepComments)})}for(let{file:S,decls:k}of f){a+=k.length;for(let T of k)if(T.kind==="import"){o++;let v=T.source||"";if(v.startsWith("."))continue;if(!i.has(v))i.set(v,{source:v,specifiers:new Map,isTypeOnly:T.isTypeOnly||!1,isSideEffect:T.isSideEffect||!1});let M=i.get(v);if(T.specifiers)for(let te of T.specifiers){let F=te.alias||te.name;if(!M.specifiers.has(F))M.specifiers.set(F,{name:te.name,alias:te.alias,isType:te.isType||!1})}if(!T.isTypeOnly)M.isTypeOnly=!1}else if(T.isExported||T.kind==="export"){if(c++,T.kind==="export"&&T.source&&(T.source.startsWith(".")||T.source.startsWith("/")))continue;if(T.name&&s.has(T.name))continue;if(T.name)s.add(T.name);n.push({declaration:T,file:S})}}let u=[];u.push("/**"),u.push(" * Bundled TypeScript declarations"),u.push(` * Generated from ${e.length} source files`),u.push(" */"),u.push("");let l=r.importOrder||["bun"],p=Array.from(i.values()),d=Array(p.length);for(let S=0;S<p.length;S++){let k=p[S].source,T=l.length;for(let v=0;v<l.length;v++)if(k.startsWith(l[v])){T=v;break}d[S]=T}let C=p.map((S,k)=>k);C.sort((S,k)=>{let T=d[S],v=d[k];if(T!==v)return T-v;return p[S].source.localeCompare(p[k].source)});let b=C.map((S)=>p[S]);for(let S of b)if(S.isSideEffect)u.push(`import '${S.source}';`);else if(S.specifiers.size>0){let k=Array.from(S.specifiers.values()).map((v)=>{let M=v.isType?"type ":"";return v.alias?`${M}${v.name} as ${v.alias}`:`${M}${v.name}`}),T=S.isTypeOnly?"type ":"";u.push(`import ${T}{ ${k.join(", ")} } from '${S.source}';`)}if(b.length>0)u.push("");let w=new Map;for(let{declaration:S,file:k}of n){if(!w.has(k))w.set(k,[]);w.get(k).push(S)}for(let[S,k]of w){let T=ec(r.cwd,S);u.push(`// From: ${T}`);for(let v of k){if(r.keepComments&&v.leadingComments)for(let M of v.leadingComments)u.push(M);u.push(Vs(v))}u.push("")}let A=u.join(`
59
- `);return{content:A,files:e,declarationCount:a,importCount:o,exportCount:c,size:Buffer.byteLength(A,"utf8"),warnings:[]}}function Vs(e){if(e.text){let r=e.text.trim();if(e.isExported&&!r.startsWith("export"))r=`export ${r}`;if(!r.endsWith(";")&&!r.endsWith("}"))r+=";";return r}let t=[];if(e.isExported)t.push("export");if(e.isDefault)t.push("default");switch(e.kind){case"function":if(t.push("declare function"),t.push(e.name),e.generics)t.push(e.generics);if(t.push(`(${tc(e.parameters)})`),e.returnType)t.push(`: ${e.returnType}`);break;case"variable":if(t.push("declare const"),t.push(e.name),e.typeAnnotation)t.push(`: ${e.typeAnnotation}`);break;case"interface":if(t.push("interface"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${r.name}${r.typeAnnotation?`: ${r.typeAnnotation}`:""};`);t.push("}");break;case"type":if(t.push("type"),t.push(e.name),e.generics)t.push(e.generics);t.push("="),t.push(e.typeAnnotation||"unknown");break;case"class":if(t.push("declare class"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(e.implements&&e.implements.length>0)t.push(`implements ${e.implements.join(", ")}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${Vs(r)}`);t.push("}");break;case"enum":if(t.push("declare enum"),t.push(e.name),t.push("{"),e.members){let r=e.members.map((i)=>i.value!==void 0?`${i.name} = ${i.value}`:i.name);t.push(` ${r.join(`,
60
- `)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function tc(e){if(!e||e.length===0)return"";return e.map((t)=>{let r="";if(t.rest)r+="...";if(r+=t.name,t.optional)r+="?";if(t.type)r+=`: ${t.type}`;if(t.defaultValue)r+=` = ${t.defaultValue}`;return r}).join(", ")}var en=ce(()=>{Wr()});import{existsSync as lr,mkdirSync as rc,readFileSync as rn,renameSync as ic,rmSync as Ks,statSync as Js,writeFileSync as Gs}from"fs";import{join as Us,relative as Pr,resolve as nc}from"path";class nn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=nc(e.cwd,Fr),this.manifestPath=Us(this.cacheDir,sc),this.configHash=this.hashConfig(e)}hashConfig(e){let t={keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,isolatedDeclarations:e.isolatedDeclarations,declarationMap:e.declarationMap,indentStyle:e.indentStyle,indentSize:e.indentSize,prettier:e.prettier,typeMappings:e.typeMappings?{includeDefaults:e.typeMappings.includeDefaults,presets:e.typeMappings.presets,cacheKey:e.typeMappings.cacheKey,rules:e.typeMappings.rules.map((r)=>({pattern:typeof r.pattern==="string"?{kind:"string",value:r.pattern}:{kind:"regex",source:r.pattern.source,flags:r.pattern.flags},replacement:r.replacement,global:r.global,priority:r.priority,hasCondition:Boolean(r.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((r)=>({name:r.name,version:r.version,cacheKey:r.cacheKey}))};return String(Ot(JSON.stringify(t)))}hashString(e){return String(Ot(e))}load(){try{if(!lr(this.manifestPath))return!1;let e=rn(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==tn)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:tn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!lr(this.cacheDir))rc(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Gs(e,JSON.stringify(this.manifest,null,2)),ic(e,this.manifestPath)}finally{if(lr(e))Ks(e,{force:!0})}}needsRegeneration(e,t){return this.getCachedIfValid(e,t)===null}getCached(e,t){return this.getCachedIfValid(e,t)}getCachedIfValid(e,t){if(!this.manifest)return null;let r=Pr(t,e),i=this.manifest.entries[r];if(!i)return null;if(typeof i.dtsContent!=="string"||typeof i.dtsHash!=="string"||i.configHash!==this.configHash||this.hashString(i.dtsContent)!==i.dtsHash)return null;try{let n=Js(e),s=n.mtimeMs,a=n.ctimeMs;if(n.size!==i.sourceSize)return null;if(s!==i.sourceMtime||a!==i.sourceCtime){let o=rn(e,"utf-8");if(this.hashString(o)!==i.sourceHash)return null;i.sourceMtime=s,i.sourceCtime=a}return i.dtsContent}catch{return null}}update(e,t,r,i){if(!this.manifest)this.manifest={version:tn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let n=Pr(i,e),s,a,o;try{let c=Js(e);s=c.mtimeMs,a=c.ctimeMs,o=c.size}catch{s=Date.now(),a=s,o=Buffer.byteLength(t)}this.manifest.entries[n]={sourcePath:n,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:a,sourceSize:o,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Pr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(lr(this.manifestPath))Ks(this.cacheDir,{recursive:!0,force:!0})}catch{}}getStats(){if(!this.manifest)return{entries:0,size:0};let e=Object.keys(this.manifest.entries).length,t=0;for(let r of Object.values(this.manifest.entries))t+=r.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let r=0,i=new Set(Array.from(e).map((n)=>Pr(t,n)));for(let n of Object.keys(this.manifest.entries))if(!i.has(n))delete this.manifest.entries[n],r++;return r}}function Ys(e){let t=Us(e,".gitignore");try{let r="";if(lr(t))r=rn(t,"utf-8");if(!r.split(/\r?\n/).some((i)=>i.trim()===Fr||i.trim()===`${Fr}/`)){let i=r.trimEnd(),n=`${i}${i?`
58
+ }`}function cl(m,h){let g=l+m.length;while(g<o&&Se(n.charCodeAt(g)))g++;for(let y=0;y<h.length;y++)if(g+y>=o||n.charCodeAt(g+y)!==h.charCodeAt(y))return!1;return g+h.length>=o||!Ze(n.charCodeAt(g+h.length))}function Wt(m,h,g){l+=g.length,d();let y="",$=n.charCodeAt(l);if($===pe||$===$e){let O=l;b($),y=n.slice(O,l)}else{y=T();while(l<o&&n.charCodeAt(l)===st)l++,y+=`.${T()}`}d();let x=l<o&&n.charCodeAt(l)===_?ji():"{}",R=`${h?"export ":""}declare ${g} ${y} ${x}`,P=le(m),E=y.startsWith("'")||y.startsWith('"');return{kind:"module",name:y,text:R,isExported:h,source:E?y.slice(1,-1):void 0,leadingComments:P,start:m,end:l}}function vs(m,h){ie();let g=p(h,l);if(g.charCodeAt(g.length-1)===Y)g=g.slice(0,-1).trimEnd();if(!g)return;let y=Ft(g.charCodeAt(0));for(let O=1;y&&O<g.length;O++)y=Ze(g.charCodeAt(O));let $=le(m);if(y){c.push({kind:"export",name:"default",text:`export default ${g};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l});return}let x="__dtsx_default_export__",R=1;while(n.includes(x))x=`__dtsx_default_export_${R++}__`;let P=Ae(g,!1),E=P==="unknown"&&Hl(g)?`typeof ${g}`:P;c.push({kind:"variable",name:x,text:`declare const ${x}: ${E};`,isExported:!1,typeAnnotation:E,modifiers:["const"],start:m,end:l}),c.push({kind:"export",name:"default",text:`export default ${x};`,isExported:!0,isTypeOnly:!1,leadingComments:$,start:m,end:l})}while(l<o){if(d(),l>=o)break;let m=l,h=n.charCodeAt(l);if(h===105&&v("import"))c.push(nt(m));else if(h===101&&v("export")){l+=6,d();let g=n.charCodeAt(l);if(g===100&&v("default")){l+=7,d();let y=l,$=n.charCodeAt(l);if($===102&&v("function")){let x=yt(m,!0,!1,!0);if(x)c.push(x)}else if($===97&&v("async")&&ws("async")!==Y)if(l+=5,d(),v("function")){let x=yt(m,!0,!0,!0);if(x)c.push(x)}else vs(m,y);else if($===99&&v("class")){let x=wt(m,!0,!1,!0);c.push(x)}else if($===97&&v("abstract")){if(l+=8,d(),v("class")){let x=wt(m,!0,!0,!0);c.push(x)}}else vs(m,y)}else if(g===116&&v("type")){let y=l;if(l+=4,d(),l<o&&n.charCodeAt(l)===_){er();let $=p(m,l),x=le(m);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:tt($),leadingComments:x,start:m,end:l})}else if(l<o&&n.charCodeAt(l)===Ee){xt();let $=p(m,l);c.push({kind:"export",name:"",text:$,isExported:!0,isTypeOnly:!0,source:tt($),start:m,end:l})}else{l=y;let $=Fi(m,!0);c.push($)}}else if(g===105&&v("interface")){let y=Pi(m,!0);c.push(y)}else if(g===102&&v("function")){let y=yt(m,!0,!1,!1);if(y)c.push(y)}else if(g===97&&v("async"))if(l+=5,d(),v("function")){let y=yt(m,!0,!0,!1);if(y)c.push(y)}else ie();else if(g===99)if(v("class")){let y=wt(m,!0,!1);c.push(y)}else if(v("const")){let y=l;if(l+=5,d(),v("enum")){l=y+5,d();let $=Nt(m,!0,!0);c.push($)}else{l=y;let $=Rt(m,"const",!0);for(let x=0;x<$.length;x++)c.push($[x])}}else ie();else if(g===97&&v("abstract")){if(l+=8,d(),v("class")){let y=wt(m,!0,!0);c.push(y)}}else if(g===108&&v("let")){let y=Rt(m,"let",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(g===118&&v("var")){let y=Rt(m,"var",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else if(g===101&&v("enum")){let y=Nt(m,!0,!1);c.push(y)}else if(g===100&&v("declare"))l+=7,d(),bs(m,!0);else if(g===110&&v("namespace")&&M(9)){let y=Wt(m,!0,"namespace");c.push(y)}else if(g===109&&v("module")&&M(6)){let y=Wt(m,!0,"module");c.push(y)}else if(g===_){er();let y=p(m,l),$=y.includes("export type"),x=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:$,source:tt(y),leadingComments:x,start:m,end:l})}else if(g===Ee){xt();let y=p(m,l),$=le(m);c.push({kind:"export",name:"",text:y,isExported:!0,isTypeOnly:!1,source:tt(y),leadingComments:$,start:m,end:l})}else{ie();let y=p(m,l);if(y)c.push({kind:"export",name:"",text:y,isExported:!0,start:m,end:l})}}else if(h===100&&v("declare"))l+=7,d(),bs(m,!1);else if(h===105&&v("interface")){let g=Pi(m,!1);f.set(g.name,g)}else if(h===116&&v("type")){let g=Fi(m,!1);f.set(g.name,g),c.push(g)}else if(h===102&&v("function")){let g=yt(m,!1,!1,!1);if(g)f.set(g.name,g);else ie()}else if(h===97)if(v("async")){let g=l;if(l+=5,d(),v("function")){let y=yt(m,!1,!0,!1);if(y)f.set(y.name,y);else l=g,ie()}else l=g,ie()}else if(v("abstract"))if(l+=8,d(),v("class")){let g=wt(m,!1,!1);f.set(g.name,g),c.push(g)}else ie();else l++,ie();else if(h===99)if(v("class")){let g=wt(m,!1,!1);f.set(g.name,g),c.push(g)}else if(v("const")){let g=l;if(l+=5,d(),v("enum")){l=g+5,d();let y=Nt(m,!1,!0);f.set(y.name,y),c.push(y)}else{l=g;let y=Rt(m,"const",!1);for(let $=0;$<y.length;$++)f.set(y[$].name,y[$])}}else l++,ie();else if(h===101&&v("enum")){let g=Nt(m,!1,!1);f.set(g.name,g),c.push(g)}else if(h===108&&v("let"))ie();else if(h===118&&v("var"))ie();else if(h===109&&v("module")&&M(6)){let g=Wt(m,!1,"module");c.push(g)}else if(h===110&&v("namespace")&&M(9)){let g=Wt(m,!1,"namespace");c.push(g)}else{let g=n.charCodeAt(l);if(g===pe||g===$e){if(b(g),l<o&&n.charCodeAt(l)===Y)l++}else if(g===je){if(w(),l<o&&n.charCodeAt(l)===Y)l++}else if(g===Ul){if(l++,T(),d(),l<o&&n.charCodeAt(l)===st)l++,T(),d();if(l<o&&n.charCodeAt(l)===Q)G(Q,me)}else l++,ie()}}if(f.size>0)Xl(c,f);if(u.size>0){let m=new Map;for(let g of c)if(g.kind==="function")m.set(g.name,(m.get(g.name)||0)+1);let h=new Set;for(let[g,y]of m)if(y>1)h.add(g);if(h.size>0){let g=new Set;for(let y of h)for(let $=c.length-1;$>=0;$--)if(c[$].kind==="function"&&c[$].name===y&&u.has($)){g.add($);break}if(g.size>0){let y=[...g].sort(($,x)=>x-$);for(let $ of y)c.splice($,1)}}}return c;function bs(m,h){if(v("function")){let g=yt(m,h,!1,!1);if(g)c.push(g)}else if(v("async")){if(l+=5,d(),v("function")){let g=yt(m,h,!0,!1);if(g)c.push(g)}}else if(v("class")){let g=wt(m,h,!1);c.push(g)}else if(v("abstract")){if(l+=8,d(),v("class")){let g=wt(m,h,!0);c.push(g)}}else if(v("interface")){let g=Pi(m,h);c.push(g)}else if(v("type")){let g=Fi(m,h);c.push(g)}else if(v("enum")){let g=Nt(m,h,!1);c.push(g)}else if(v("const")){let g=l;if(l+=5,d(),v("enum")){l=g+5,d();let y=Nt(m,h,!0);c.push(y)}else if(h){l=g;let y=Rt(m,"const",!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie()}else if(v("let")||v("var"))if(h){let g=v("let")?"let":"var",y=Rt(m,g,!0);for(let $=0;$<y.length;$++)c.push(y[$])}else ie();else if(v("module")){let g=Wt(m,h,"module");c.push(g)}else if(v("namespace")){let g=Wt(m,h,"namespace");c.push(g)}else if(v("global")){l+=6,d();let g=`declare global ${l<o&&n.charCodeAt(l)===_?ji():"{}"}`,y=le(m);c.push({kind:"module",name:"global",text:g,isExported:!1,leadingComments:y,start:m,end:l})}else ie()}}function Ls(e,t){let r=0,i=e.length;while(r<i){let n=e.charCodeAt(r);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let s=r;r++;while(r<i){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}t.add(e.substring(s,r))}else r++}}function js(e,t){let r=0;while(r<e.length){let i=e.charCodeAt(r);if(i===pe||i===$e||i===je){let u=i;r++;while(r<e.length)if(e.charCodeAt(r)===Ue)r+=2;else if(e.charCodeAt(r++)===u)break;continue}if(i===z&&e.charCodeAt(r+1)===z){r+=2;while(r<e.length&&e.charCodeAt(r)!==he&&e.charCodeAt(r)!==Ce)r++;continue}if(i===z&&e.charCodeAt(r+1)===Ee){let u=e.indexOf("*/",r+2);r=u===-1?e.length:u+2;continue}if(!Ft(i)){r++;continue}let n=r++;while(r<e.length&&Ze(e.charCodeAt(r)))r++;let s=n-1,a=r;while(s>=0&&Se(e.charCodeAt(s)))s--;while(a<e.length&&Se(e.charCodeAt(a)))a++;let o=s>=0?e.charCodeAt(s):0,c=a<e.length?e.charCodeAt(a):0,f=n>=3&&e.slice(n-3,n)==="...";if(c===Je||o===st&&!f)continue;if(c===Q&&(o===_||o===Ge))continue;t.add(e.slice(n,r))}}function Xl(e,t){let r=new Set,i=new Set;for(let a of e)i.add(a.name);let n=new Set,s=[];for(let a=0;a<e.length;a++){let o=e[a];if(o.kind!=="import"){if(s.push(o.text),Ls(o.text,n),typeof o.value==="string")js(o.value,n)}}for(;;){let a=[];for(let[f,u]of t){if(r.has(f))continue;if(n.has(f)){if(!i.has(f))a.push(u),i.add(f);r.add(f)}}if(a.length===0)break;a.sort((f,u)=>(f.start??1/0)-(u.start??1/0));let o=[],c=0;for(let f=0;f<e.length;f++){let u=e[f].start??1/0;while(c<a.length&&(a[c].start??1/0)<=u)o.push(a[c++]);o.push(e[f])}while(c<a.length)o.push(a[c++]);e.length=0;for(let f=0;f<o.length;f++)e.push(o[f]);for(let f of a)if(f.kind!=="import"){if(s.push(f.text),Ls(f.text,n),typeof f.value==="string")js(f.value,n)}}}var We=32,Pe=9,he=10,Ce=13,z=47,Ee=42,pe=39,$e=34,je=96,Ue=92,_=123,U=125,Q=40,me=41,fe=91,Oe=93,xe=60,we=62,Y=59,Je=58,ge=61,Ge=44,st=46,Or=63,Sr=35,Ul=64,Ms=36,Yl=95,Hi;var kr=ce(()=>{Er();Hi=["public","protected","private","readonly","override"]});function Ot(e){if(Ql)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);t=(t<<5)-t+i,t=t&t}return t}var Ql;var Dt=ce(()=>{Ql=typeof globalThis.Bun?.hash==="function"});function Xi(e,t,r=!0,i=!1){let n=Ot(e),s=`${t}:${r?1:0}:${i?1:0}`,a=It.get(s);if(a&&a.contentHash===n)return a.lastAccess=++_s,a.declarations;let o=i?qi(e,t,r):zi(e,t,r);if(It.set(s,{declarations:o,contentHash:n,lastAccess:++_s}),It.size>ec){let c=Math.max(1,Math.ceil(It.size*0.1)),f=[];for(let[u,l]of It)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)It.delete(f[u][0])}return o}var ec=100,_s=0,It;var Tr=ce(()=>{kr();Dt();It=new Map});function Rr(e,t){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):1;if(e===void 0||!Number.isFinite(e))return r;return Math.max(1,Math.floor(e))}var or=()=>{};var Qi=ce(()=>{or();Dt()});function Nr(e,t,r=!0,i=!1){return Xi(e,t,r,i)}var Wr=ce(()=>{Tr();Qi();or()});import{dirname as kd,relative as tc,resolve as Td}from"path";async function Zs(e,t,r){let i=new Map,n=[],s=new Set,a=0,o=0,c=0,f=[];for(let S of e){let k=t.get(S);if(!k)continue;f.push({file:S,decls:Nr(k,S,r.keepComments)})}for(let{file:S,decls:k}of f){a+=k.length;for(let T of k)if(T.kind==="import"){o++;let v=T.source||"";if(v.startsWith("."))continue;if(!i.has(v))i.set(v,{source:v,specifiers:new Map,isTypeOnly:T.isTypeOnly||!1,isSideEffect:T.isSideEffect||!1});let M=i.get(v);if(T.specifiers)for(let te of T.specifiers){let F=te.alias||te.name;if(!M.specifiers.has(F))M.specifiers.set(F,{name:te.name,alias:te.alias,isType:te.isType||!1})}if(!T.isTypeOnly)M.isTypeOnly=!1}else if(T.isExported||T.kind==="export"){if(c++,T.kind==="export"&&T.source&&(T.source.startsWith(".")||T.source.startsWith("/")))continue;if(T.name&&s.has(T.name))continue;if(T.name)s.add(T.name);n.push({declaration:T,file:S})}}let u=[];u.push("/**"),u.push(" * Bundled TypeScript declarations"),u.push(` * Generated from ${e.length} source files`),u.push(" */"),u.push("");let l=r.importOrder||["bun"],p=Array.from(i.values()),d=Array(p.length);for(let S=0;S<p.length;S++){let k=p[S].source,T=l.length;for(let v=0;v<l.length;v++)if(k.startsWith(l[v])){T=v;break}d[S]=T}let C=p.map((S,k)=>k);C.sort((S,k)=>{let T=d[S],v=d[k];if(T!==v)return T-v;return p[S].source.localeCompare(p[k].source)});let b=C.map((S)=>p[S]);for(let S of b)if(S.isSideEffect)u.push(`import '${S.source}';`);else if(S.specifiers.size>0){let k=Array.from(S.specifiers.values()).map((v)=>{let M=v.isType?"type ":"";return v.alias?`${M}${v.name} as ${v.alias}`:`${M}${v.name}`}),T=S.isTypeOnly?"type ":"";u.push(`import ${T}{ ${k.join(", ")} } from '${S.source}';`)}if(b.length>0)u.push("");let w=new Map;for(let{declaration:S,file:k}of n){if(!w.has(k))w.set(k,[]);w.get(k).push(S)}for(let[S,k]of w){let T=tc(r.cwd,S);u.push(`// From: ${T}`);for(let v of k){if(r.keepComments&&v.leadingComments)for(let M of v.leadingComments)u.push(M);u.push(Vs(v))}u.push("")}let A=u.join(`
59
+ `);return{content:A,files:e,declarationCount:a,importCount:o,exportCount:c,size:Buffer.byteLength(A,"utf8"),warnings:[]}}function Vs(e){if(e.text){let r=e.text.trim();if(e.isExported&&!r.startsWith("export"))r=`export ${r}`;if(!r.endsWith(";")&&!r.endsWith("}"))r+=";";return r}let t=[];if(e.isExported)t.push("export");if(e.isDefault)t.push("default");switch(e.kind){case"function":if(t.push("declare function"),t.push(e.name),e.generics)t.push(e.generics);if(t.push(`(${rc(e.parameters)})`),e.returnType)t.push(`: ${e.returnType}`);break;case"variable":if(t.push("declare const"),t.push(e.name),e.typeAnnotation)t.push(`: ${e.typeAnnotation}`);break;case"interface":if(t.push("interface"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${r.name}${r.typeAnnotation?`: ${r.typeAnnotation}`:""};`);t.push("}");break;case"type":if(t.push("type"),t.push(e.name),e.generics)t.push(e.generics);t.push("="),t.push(e.typeAnnotation||"unknown");break;case"class":if(t.push("declare class"),t.push(e.name),e.generics)t.push(e.generics);if(e.extends)t.push(`extends ${e.extends}`);if(e.implements&&e.implements.length>0)t.push(`implements ${e.implements.join(", ")}`);if(t.push("{"),e.members)for(let r of e.members)t.push(` ${Vs(r)}`);t.push("}");break;case"enum":if(t.push("declare enum"),t.push(e.name),t.push("{"),e.members){let r=e.members.map((i)=>i.value!==void 0?`${i.name} = ${i.value}`:i.name);t.push(` ${r.join(`,
60
+ `)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function rc(e){if(!e||e.length===0)return"";return e.map((t)=>{let r="";if(t.rest)r+="...";if(r+=t.name,t.optional)r+="?";if(t.type)r+=`: ${t.type}`;if(t.defaultValue)r+=` = ${t.defaultValue}`;return r}).join(", ")}var en=ce(()=>{Wr()});import{existsSync as lr,mkdirSync as ic,readFileSync as rn,renameSync as nc,rmSync as Ks,statSync as Js,writeFileSync as Gs}from"fs";import{join as Us,relative as Pr,resolve as sc}from"path";class nn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=sc(e.cwd,Fr),this.manifestPath=Us(this.cacheDir,ac),this.configHash=this.hashConfig(e)}hashConfig(e){let t={keepComments:e.keepComments,importOrder:e.importOrder,outputStructure:e.outputStructure,isolatedDeclarations:e.isolatedDeclarations,declarationMap:e.declarationMap,indentStyle:e.indentStyle,indentSize:e.indentSize,prettier:e.prettier,typeMappings:e.typeMappings?{includeDefaults:e.typeMappings.includeDefaults,presets:e.typeMappings.presets,cacheKey:e.typeMappings.cacheKey,rules:e.typeMappings.rules.map((r)=>({pattern:typeof r.pattern==="string"?{kind:"string",value:r.pattern}:{kind:"regex",source:r.pattern.source,flags:r.pattern.flags},replacement:r.replacement,global:r.global,priority:r.priority,hasCondition:Boolean(r.condition)}))}:void 0,lineEnding:e.lineEnding,normalizeOutput:e.normalizeOutput,declarationOrder:e.declarationOrder,plugins:e.plugins?.map((r)=>({name:r.name,version:r.version,cacheKey:r.cacheKey}))};return String(Ot(JSON.stringify(t)))}hashString(e){return String(Ot(e))}load(){try{if(!lr(this.manifestPath))return!1;let e=rn(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==tn)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:tn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!lr(this.cacheDir))ic(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Gs(e,JSON.stringify(this.manifest,null,2)),nc(e,this.manifestPath)}finally{if(lr(e))Ks(e,{force:!0})}}needsRegeneration(e,t){return this.getCachedIfValid(e,t)===null}getCached(e,t){return this.getCachedIfValid(e,t)}getCachedIfValid(e,t){if(!this.manifest)return null;let r=Pr(t,e),i=this.manifest.entries[r];if(!i)return null;if(typeof i.dtsContent!=="string"||typeof i.dtsHash!=="string"||i.configHash!==this.configHash||this.hashString(i.dtsContent)!==i.dtsHash)return null;try{let n=Js(e),s=n.mtimeMs,a=n.ctimeMs;if(n.size!==i.sourceSize)return null;if(s!==i.sourceMtime||a!==i.sourceCtime){let o=rn(e,"utf-8");if(this.hashString(o)!==i.sourceHash)return null;i.sourceMtime=s,i.sourceCtime=a}return i.dtsContent}catch{return null}}update(e,t,r,i){if(!this.manifest)this.manifest={version:tn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let n=Pr(i,e),s,a,o;try{let c=Js(e);s=c.mtimeMs,a=c.ctimeMs,o=c.size}catch{s=Date.now(),a=s,o=Buffer.byteLength(t)}this.manifest.entries[n]={sourcePath:n,sourceHash:this.hashString(t),sourceMtime:s,sourceCtime:a,sourceSize:o,dtsContent:r,dtsHash:this.hashString(r),generatedAt:Date.now(),configHash:this.configHash}}remove(e,t){if(!this.manifest)return;let r=Pr(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(lr(this.manifestPath))Ks(this.cacheDir,{recursive:!0,force:!0})}catch{}}getStats(){if(!this.manifest)return{entries:0,size:0};let e=Object.keys(this.manifest.entries).length,t=0;for(let r of Object.values(this.manifest.entries))t+=r.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let r=0,i=new Set(Array.from(e).map((n)=>Pr(t,n)));for(let n of Object.keys(this.manifest.entries))if(!i.has(n))delete this.manifest.entries[n],r++;return r}}function Ys(e){let t=Us(e,".gitignore");try{let r="";if(lr(t))r=rn(t,"utf-8");if(!r.split(/\r?\n/).some((i)=>i.trim()===Fr||i.trim()===`${Fr}/`)){let i=r.trimEnd(),n=`${i}${i?`
61
61
 
62
62
  `:""}# dtsx cache
63
63
  ${Fr}/
64
- `;Gs(t,n)}}catch{}}var tn=3,Fr=".dtsx-cache",sc="manifest.json";var sn=ce(()=>{Dt()});function fc(e){switch(e){case"strict":return oc;case"readonly":return lc;case"simplified":return cc;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 qs{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...ac);if(e.presets)for(let t of e.presets)this.rules.push(...fc(t));this.rules.push(...e.rules),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let r=this.rules[t],i=typeof r.pattern==="string"?new RegExp(r.pattern.replace(uc,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:i}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,i=this.cache.get(r);if(i!==void 0)return i;let n=e,s=null;for(let a=0;a<this.compiled.length;a++){let{rule:o,regex:c}=this.compiled[a];if(o.condition){if(!s)s={type:e,...t};if(!o.condition(s))continue}if(c.lastIndex=0,c.test(n)){if(c.lastIndex=0,n=n.replace(c,o.replacement),c.lastIndex=0,!o.global)break}}if(this.cache.size>=Hs){let a=Math.ceil(Hs*0.1),o=0;for(let c of this.cache.keys()){if(o++>=a)break;this.cache.delete(c)}}return this.cache.set(r,n),n}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let i=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?i!==e:!e.test(i)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Dr(e={rules:[]}){return new qs(e)}function zs(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(i,n)=>{return`: ${t.map(n.trim(),r)}`})}var ac,oc,lc,cc,uc,Hs=2048,Fd,Dd;var an=ce(()=>{ac=[{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}],oc=[{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}],lc=[{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}],cc=[{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}];uc=/[.*+?^${}()|[\]\\]/g;Fd=Dr({rules:[]}),Dd=Dr({rules:[],presets:["strict"]})});import{readFile as hc,stat as jd,writeFile as dc}from"fs/promises";async function Xs(e,t){if(Ir)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await dc(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function at(e){if(Ir)return globalThis.Bun.file(e).text();return hc(e,"utf-8")}var Ir,Md;var cr=ce(()=>{Ir=typeof globalThis.Bun<"u",Md=!Ir&&typeof process<"u"&&!!process.versions?.node});import{existsSync as mc,statSync as gc}from"fs";import{dirname as pc,extname as yc,isAbsolute as on,resolve as wc}from"path";function Lr(e){try{return gc(e).isFile()}catch{return!1}}function jr(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!on(r))return{resolved:null,isRelative:!1};let i=pc(t),n=on(r)?r:wc(i,r);if(Lr(n))return{resolved:n,isRelative:!0};let s=yc(n),a=$c[s];if(a){let o=n.slice(0,-s.length);for(let c of a){let f=o+c;if(Lr(f))return{resolved:f,isRelative:!0}}}for(let o of Qs){let c=n+o;if(Lr(c))return{resolved:c,isRelative:!0}}if(mc(n))for(let o of Qs){let c=`${n}/index${o}`;if(Lr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function Cc(e){let t=e.length,r="",i=0;while(i<t){let n=e.charCodeAt(i);if(n===34||n===39||n===96){let s=n;r+=e[i++];while(i<t){let a=e.charCodeAt(i),o=e[i++];if(r+=s===96&&a!==s?a===10||a===13?o:" ":o,a===92&&i<t){let c=e[i++];r+=s===96?c===`
65
- `||c==="\r"?c:" ":c;continue}if(a===s)break}continue}if(n===47&&i+1<t){let s=e.charCodeAt(i+1);if(s===47){i+=2;while(i<t&&e.charCodeAt(i)!==10)i++;continue}if(s===42){i+=2;while(i+1<t&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))i++;i+=2;continue}}r+=e[i++]}return r}function ln(e,t={}){let r=[],i=Cc(e);ea.lastIndex=0;let n;while((n=ea.exec(i))!==null){let s=!!n[1],a=n[3],o=n[0],c;if(o.includes("* as "))c="export-star-as";else if(o.includes("*"))c="export-star";else c="export-named";r.push({specifier:a,kind:c,isTypeOnly:s})}if(t.includeImports){ta.lastIndex=0;while((n=ta.exec(i))!==null)r.push({specifier:n[3],kind:"import",isTypeOnly:!!n[1]})}return r}async function cn(e,t={}){let r=new Set,i=new Map,n=[],s=[];for(let a of e)if(!r.has(a))r.add(a),s.push(a);while(s.length>0){let a=s.shift(),o;try{o=await at(a)}catch{continue}let c=ln(o,t);i.set(a,c);for(let f of c){if(!(f.specifier.startsWith(".")||on(f.specifier)))continue;let u=jr(f.specifier,a);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else n.push({from:a,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:i,unresolved:n}}var Qs,$c,ea,ta;var fn=ce(()=>{cr();Qs=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],$c={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};ea=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,ta=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});function Lt(e){return ra[e]>=ra[Mr]}function Ac(){if(!bc)return"";return`[${new Date().toISOString().slice(11,23)}] `}function xc(e,t){let r=Ac();if(e||r)return[`${r}${e}`,...t];return t}function jt(e,t,r){let i=xc(t,r);if(ia){ia(e,...i);return}switch(e){case"debug":console.debug(...i);break;case"info":console.log(...i);break;case"warn":console.warn(...i);break;case"error":console.error(...i);break}}function na(e){return{debug:(...t)=>{if(Lt("debug"))jt("debug",e,t)},info:(...t)=>{if(Lt("info"))jt("info",e,t)},warn:(...t)=>{if(Lt("warn"))jt("warn",e,t)},error:(...t)=>{if(Lt("error"))jt("error",e,t)},setLevel:(t)=>{Mr=t},getLevel:()=>Mr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return na(r)},time:(t)=>{let r=performance.now();return()=>{let i=performance.now()-r;if(Lt("debug"))jt("debug",e,[`${t}: ${i.toFixed(2)}ms`])}},progress:(t)=>{if(Lt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else jt("info",e,[t])}}}function un(e){Mr=e}var ra,Mr="info",vc="[dtsx]",bc=!1,ia=null,Z;var Br=ce(()=>{ra={debug:0,info:1,warn:2,error:3,silent:4};Z=na(vc)});import Ec from"process";import{existsSync as sa,statSync as aa}from"fs";import{existsSync as Oc,mkdirSync as zd,readdirSync as Xd,readFileSync as Sc,writeFileSync as Qd}from"fs";import{homedir as Mt}from"os";import{dirname as rm,resolve as Ye}from"path";import Ci from"process";import{existsSync as oa,statSync as la}from"fs";import{existsSync as Nn,mkdirSync as kc,readdirSync as Tc,writeFileSync as Rc}from"fs";import{homedir as Bt}from"os";import{dirname as ca,resolve as _e}from"path";import St from"process";import{join as Nc,relative as Wc,resolve as fa}from"path";import ai from"process";import{existsSync as Ja,mkdirSync as hm,readdirSync as dm,writeFileSync as mm}from"fs";import{homedir as hn}from"os";import{dirname as ym,resolve as Be}from"path";import ur from"process";import{join as Pc,relative as Fc,resolve as ua}from"path";import oi from"process";import{existsSync as Ga,mkdirSync as bm,readdirSync as Am,writeFileSync as xm}from"fs";import{dirname as Om,resolve as li}from"path";import Wn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as Dc,createDecipheriv as Ic,randomBytes as dn}from"crypto";import{closeSync as mn,createReadStream as ha,createWriteStream as Lc,existsSync as gn,fsyncSync as da,openSync as ma,writeFileSync as jc}from"fs";import{access as Mc,constants as ga,mkdir as Bc,readdir as _r,rename as pa,stat as _t,unlink as Zr,writeFile as pn}from"fs/promises";import{join as Zt}from"path";import De from"process";import{pipeline as _c}from"stream/promises";import{createGzip as ya}from"zlib";import Vt from"process";import ft from"process";import{Buffer as ot}from"buffer";import{createCipheriv as Zc,createDecipheriv as Vc,randomBytes as yn}from"crypto";import{closeSync as wn,createReadStream as wa,createWriteStream as Kc,existsSync as Vr,fsyncSync as $a,openSync as Ca,writeFileSync as Jc}from"fs";import{access as Gc,constants as va,mkdir as Uc,readdir as Kr,rename as ba,stat as Kt,unlink as Jr,writeFile as $n}from"fs/promises";import{isAbsolute as Yc,join as Jt,resolve as Hc}from"path";import se from"process";import{pipeline as qc}from"stream/promises";import{createGzip as Aa}from"zlib";import Gt from"process";import ut from"process";import Gr from"process";import{existsSync as Ur}from"fs";import{resolve as Cn}from"path";import{existsSync as zc}from"fs";import{existsSync as Xc,readdirSync as Qc}from"fs";import{extname as vn,resolve as xa}from"path";import ef from"process";import{join as tf,relative as rf,resolve as Ea}from"path";import ci from"process";import{Buffer as lt}from"buffer";import{createCipheriv as nf,createDecipheriv as sf,randomBytes as bn}from"crypto";import{closeSync as An,createReadStream as Oa,createWriteStream as af,existsSync as Yr,fsyncSync as Sa,openSync as ka,writeFileSync as of}from"fs";import{access as lf,constants as Ta,mkdir as cf,readdir as Hr,rename as Ra,stat as Ut,unlink as qr,writeFile as xn}from"fs/promises";import{isAbsolute as ff,join as Yt,resolve as uf}from"path";import ae from"process";import{pipeline as hf}from"stream/promises";import{createGzip as Na}from"zlib";import Ht from"process";import ht from"process";import zr from"process";import{existsSync as Xr}from"fs";import{resolve as En}from"path";import{existsSync as df}from"fs";class Ua{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!sa(e))return!0;return aa(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=sa(r)?aa(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Ya{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function pf(e,t){this[e]=gf.bind(null,t)}class Kn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!oa(e))return!0;return la(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=oa(r)?la(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Jn{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function $f(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Cf(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function vf(e){return e.getStats().size*2}function Gn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&de(t[0])&&"id"in t[0]&&t[0].id===3&&de(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(de(t)&&de(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(de(e)&&"arr"in e&&Array.isArray(e.arr)&&de(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&de(t[0])&&de(e[0])){let i=[...t];for(let n of e)if(de(n)&&"name"in n){if(!i.find((s)=>de(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(de(n)&&"path"in n){if(!i.find((s)=>de(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>ui(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!de(t)||!de(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(de(n)&&de(r[i]))r[i]=Gn(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&de(n[0])&&de(r[i][0])){let s=[...n];for(let a of r[i])if(de(a)&&"name"in a){if(!s.find((o)=>de(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(de(a)&&"path"in a){if(!s.find((o)=>de(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>ui(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function ui(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ui(e[r],t[r]))return!1;return!0}if(de(e)&&de(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ui(e[n],t[n]))return!1}return!0}return!1}function de(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function bf(e,t){if(!Ga(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Gn(t,i)}catch{return null}}catch{return null}}async function Af({name:e="",cwd:t,defaultConfig:r}){let i=t||Wn.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of s)for(let o of n){let c=li(i,`${a}${o}`),f=await bf(c,r);if(f!==null)return f}try{let a=li(i,"package.json");if(Ga(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return Gn(r,o)}catch{}}}catch{}return r}function xf(e,t={}){let r=oi.cwd();while(r.includes("storage"))r=ua(r,"..");let i=ua(r,e||"");if(t?.relative)return Fc(oi.cwd(),i);return i}async function Ef(){try{let e=await Af({name:"clarity",defaultConfig:ri,cwd:oi.cwd(),endpoint:"",headers:{}});return{...ri,...e}}catch{return ri}}function ve(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Of(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let e=ft.type;if(e==="renderer"||e==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class qa{async format(e){let t=await Of(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Vt.pid,hostname:t(),environment:Vt.env.NODE_ENV||"development",platform:Vt.platform,version:Vt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Vt.env.NODE_ENV||Vt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hi{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={...Fn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new qa,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??De.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ii,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ii};return{...ii,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Fn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await Mc(this.config.logDirectory,ga.F_OK|ga.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Bc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:bt.from(e);try{if(!gn(this.currentLogFile))await pn(this.currentLogFile,"",{mode:420});if(i=ma(this.currentLogFile,"a",420),jc(i,o,{flag:"a"}),da(i),i!==void 0)mn(i),i=void 0;if((await _t(this.currentLogFile)).size===0){if(await pn(this.currentLogFile,o,{flag:"w",mode:420}),(await _t(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),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(i!==void 0)try{mn(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Zt(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 Zt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ve())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return dn(16).toString("hex")}generateKey(){return dn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=dn(16),i=Dc("aes-256-gcm",t,r),n=bt.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:bt.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ya(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(bt.from(bt.concat(n)))),i.on("error",r),i.write(e),i.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(ve())return;let e=await _t(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await _r(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await _t(r).catch(()=>null))try{if(await pa(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Zr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await pn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await _t(r).catch(()=>null))await pa(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await _r(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Zr(Zt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ha(e),i=Lc(t),n=ya();await _c(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),gn(this.currentLogFile))try{let e=ma(this.currentLogFile,"r+");da(e),mn(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(!ve()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await _r(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zr(Zt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?ue.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=De.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${ue.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!ve()){let f=ao[e],u=this.options.showTags!==!1&&this.name?ue.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:ue.gray(a),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:ue.green(a),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.error(l),o){let p=o.split(`
64
+ `;Gs(t,n)}}catch{}}var tn=3,Fr=".dtsx-cache",ac="manifest.json";var sn=ce(()=>{Dt()});function uc(e){switch(e){case"strict":return lc;case"readonly":return cc;case"simplified":return fc;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 qs{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...oc);if(e.presets)for(let t of e.presets)this.rules.push(...uc(t));this.rules.push(...e.rules),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let r=this.rules[t],i=typeof r.pattern==="string"?new RegExp(r.pattern.replace(hc,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:i}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,i=this.cache.get(r);if(i!==void 0)return i;let n=e,s=null;for(let a=0;a<this.compiled.length;a++){let{rule:o,regex:c}=this.compiled[a];if(o.condition){if(!s)s={type:e,...t};if(!o.condition(s))continue}if(c.lastIndex=0,c.test(n)){if(c.lastIndex=0,n=n.replace(c,o.replacement),c.lastIndex=0,!o.global)break}}if(this.cache.size>=Hs){let a=Math.ceil(Hs*0.1),o=0;for(let c of this.cache.keys()){if(o++>=a)break;this.cache.delete(c)}}return this.cache.set(r,n),n}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let i=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?i!==e:!e.test(i)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Dr(e={rules:[]}){return new qs(e)}function zs(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(i,n)=>{return`: ${t.map(n.trim(),r)}`})}var oc,lc,cc,fc,hc,Hs=2048,Dd,Id;var an=ce(()=>{oc=[{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}],lc=[{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}],cc=[{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}],fc=[{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}];hc=/[.*+?^${}()|[\]\\]/g;Dd=Dr({rules:[]}),Id=Dr({rules:[],presets:["strict"]})});import{readFile as dc,stat as Md,writeFile as mc}from"fs/promises";async function Xs(e,t){if(Ir)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await mc(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function at(e){if(Ir)return globalThis.Bun.file(e).text();return dc(e,"utf-8")}var Ir,Bd;var cr=ce(()=>{Ir=typeof globalThis.Bun<"u",Bd=!Ir&&typeof process<"u"&&!!process.versions?.node});import{existsSync as gc,statSync as pc}from"fs";import{dirname as yc,extname as wc,isAbsolute as on,resolve as $c}from"path";function Lr(e){try{return pc(e).isFile()}catch{return!1}}function jr(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!on(r))return{resolved:null,isRelative:!1};let i=yc(t),n=on(r)?r:$c(i,r);if(Lr(n))return{resolved:n,isRelative:!0};let s=wc(n),a=Cc[s];if(a){let o=n.slice(0,-s.length);for(let c of a){let f=o+c;if(Lr(f))return{resolved:f,isRelative:!0}}}for(let o of Qs){let c=n+o;if(Lr(c))return{resolved:c,isRelative:!0}}if(gc(n))for(let o of Qs){let c=`${n}/index${o}`;if(Lr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function vc(e){let t=e.length,r="",i=0;while(i<t){let n=e.charCodeAt(i);if(n===34||n===39||n===96){let s=n;r+=e[i++];while(i<t){let a=e.charCodeAt(i),o=e[i++];if(r+=s===96&&a!==s?a===10||a===13?o:" ":o,a===92&&i<t){let c=e[i++];r+=s===96?c===`
65
+ `||c==="\r"?c:" ":c;continue}if(a===s)break}continue}if(n===47&&i+1<t){let s=e.charCodeAt(i+1);if(s===47){i+=2;while(i<t&&e.charCodeAt(i)!==10)i++;continue}if(s===42){i+=2;while(i+1<t&&!(e.charCodeAt(i)===42&&e.charCodeAt(i+1)===47))i++;i+=2;continue}}r+=e[i++]}return r}function ln(e,t={}){let r=[],i=vc(e);ea.lastIndex=0;let n;while((n=ea.exec(i))!==null){let s=!!n[1],a=n[3],o=n[0],c;if(o.includes("* as "))c="export-star-as";else if(o.includes("*"))c="export-star";else c="export-named";r.push({specifier:a,kind:c,isTypeOnly:s})}if(t.includeImports){ta.lastIndex=0;while((n=ta.exec(i))!==null)r.push({specifier:n[3],kind:"import",isTypeOnly:!!n[1]})}return r}async function cn(e,t={}){let r=new Set,i=new Map,n=[],s=[];for(let a of e)if(!r.has(a))r.add(a),s.push(a);while(s.length>0){let a=s.shift(),o;try{o=await at(a)}catch{continue}let c=ln(o,t);i.set(a,c);for(let f of c){if(!(f.specifier.startsWith(".")||on(f.specifier)))continue;let u=jr(f.specifier,a);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else n.push({from:a,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:i,unresolved:n}}var Qs,Cc,ea,ta;var fn=ce(()=>{cr();Qs=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Cc={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};ea=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,ta=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});function Lt(e){return ra[e]>=ra[Mr]}function xc(){if(!Ac)return"";return`[${new Date().toISOString().slice(11,23)}] `}function Ec(e,t){let r=xc();if(e||r)return[`${r}${e}`,...t];return t}function jt(e,t,r){let i=Ec(t,r);if(ia){ia(e,...i);return}switch(e){case"debug":console.debug(...i);break;case"info":console.log(...i);break;case"warn":console.warn(...i);break;case"error":console.error(...i);break}}function na(e){return{debug:(...t)=>{if(Lt("debug"))jt("debug",e,t)},info:(...t)=>{if(Lt("info"))jt("info",e,t)},warn:(...t)=>{if(Lt("warn"))jt("warn",e,t)},error:(...t)=>{if(Lt("error"))jt("error",e,t)},setLevel:(t)=>{Mr=t},getLevel:()=>Mr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return na(r)},time:(t)=>{let r=performance.now();return()=>{let i=performance.now()-r;if(Lt("debug"))jt("debug",e,[`${t}: ${i.toFixed(2)}ms`])}},progress:(t)=>{if(Lt("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else jt("info",e,[t])}}}function un(e){Mr=e}var ra,Mr="info",bc="[dtsx]",Ac=!1,ia=null,Z;var Br=ce(()=>{ra={debug:0,info:1,warn:2,error:3,silent:4};Z=na(bc)});import Oc from"process";import{existsSync as sa,statSync as aa}from"fs";import{existsSync as Sc,mkdirSync as Xd,readdirSync as Qd,readFileSync as kc,writeFileSync as em}from"fs";import{homedir as Mt}from"os";import{dirname as im,resolve as Ye}from"path";import Ci from"process";import{existsSync as oa,statSync as la}from"fs";import{existsSync as Nn,mkdirSync as Tc,readdirSync as Rc,writeFileSync as Nc}from"fs";import{homedir as Bt}from"os";import{dirname as ca,resolve as _e}from"path";import St from"process";import{join as Wc,relative as Pc,resolve as fa}from"path";import ai from"process";import{existsSync as Ja,mkdirSync as dm,readdirSync as mm,writeFileSync as gm}from"fs";import{homedir as hn}from"os";import{dirname as wm,resolve as Be}from"path";import ur from"process";import{join as Fc,relative as Dc,resolve as ua}from"path";import oi from"process";import{existsSync as Ga,mkdirSync as Am,readdirSync as xm,writeFileSync as Em}from"fs";import{dirname as Sm,resolve as li}from"path";import Wn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as Ic,createDecipheriv as Lc,randomBytes as dn}from"crypto";import{closeSync as mn,createReadStream as ha,createWriteStream as jc,existsSync as gn,fsyncSync as da,openSync as ma,writeFileSync as Mc}from"fs";import{access as Bc,constants as ga,mkdir as _c,readdir as _r,rename as pa,stat as _t,unlink as Zr,writeFile as pn}from"fs/promises";import{join as Zt}from"path";import De from"process";import{pipeline as Zc}from"stream/promises";import{createGzip as ya}from"zlib";import Vt from"process";import ft from"process";import{Buffer as ot}from"buffer";import{createCipheriv as Vc,createDecipheriv as Kc,randomBytes as yn}from"crypto";import{closeSync as wn,createReadStream as wa,createWriteStream as Jc,existsSync as Vr,fsyncSync as $a,openSync as Ca,writeFileSync as Gc}from"fs";import{access as Uc,constants as va,mkdir as Yc,readdir as Kr,rename as ba,stat as Kt,unlink as Jr,writeFile as $n}from"fs/promises";import{isAbsolute as Hc,join as Jt,resolve as qc}from"path";import se from"process";import{pipeline as zc}from"stream/promises";import{createGzip as Aa}from"zlib";import Gt from"process";import ut from"process";import Gr from"process";import{existsSync as Ur}from"fs";import{resolve as Cn}from"path";import{existsSync as Xc}from"fs";import{existsSync as Qc,readdirSync as ef}from"fs";import{extname as vn,resolve as xa}from"path";import tf from"process";import{join as rf,relative as nf,resolve as Ea}from"path";import ci from"process";import{Buffer as lt}from"buffer";import{createCipheriv as sf,createDecipheriv as af,randomBytes as bn}from"crypto";import{closeSync as An,createReadStream as Oa,createWriteStream as of,existsSync as Yr,fsyncSync as Sa,openSync as ka,writeFileSync as lf}from"fs";import{access as cf,constants as Ta,mkdir as ff,readdir as Hr,rename as Ra,stat as Ut,unlink as qr,writeFile as xn}from"fs/promises";import{isAbsolute as uf,join as Yt,resolve as hf}from"path";import ae from"process";import{pipeline as df}from"stream/promises";import{createGzip as Na}from"zlib";import Ht from"process";import ht from"process";import zr from"process";import{existsSync as Xr}from"fs";import{resolve as En}from"path";import{existsSync as mf}from"fs";class Ua{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!sa(e))return!0;return aa(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=sa(r)?aa(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Ya{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function yf(e,t){this[e]=pf.bind(null,t)}class Kn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!oa(e))return!0;return la(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=oa(r)?la(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Jn{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Cf(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function vf(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function bf(e){return e.getStats().size*2}function Gn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&de(t[0])&&"id"in t[0]&&t[0].id===3&&de(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(de(t)&&de(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(de(e)&&"arr"in e&&Array.isArray(e.arr)&&de(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&de(t[0])&&de(e[0])){let i=[...t];for(let n of e)if(de(n)&&"name"in n){if(!i.find((s)=>de(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(de(n)&&"path"in n){if(!i.find((s)=>de(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>ui(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!de(t)||!de(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(de(n)&&de(r[i]))r[i]=Gn(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&de(n[0])&&de(r[i][0])){let s=[...n];for(let a of r[i])if(de(a)&&"name"in a){if(!s.find((o)=>de(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(de(a)&&"path"in a){if(!s.find((o)=>de(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>ui(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function ui(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ui(e[r],t[r]))return!1;return!0}if(de(e)&&de(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ui(e[n],t[n]))return!1}return!0}return!1}function de(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Af(e,t){if(!Ga(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Gn(t,i)}catch{return null}}catch{return null}}async function xf({name:e="",cwd:t,defaultConfig:r}){let i=t||Wn.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of s)for(let o of n){let c=li(i,`${a}${o}`),f=await Af(c,r);if(f!==null)return f}try{let a=li(i,"package.json");if(Ga(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return Gn(r,o)}catch{}}}catch{}return r}function Ef(e,t={}){let r=oi.cwd();while(r.includes("storage"))r=ua(r,"..");let i=ua(r,e||"");if(t?.relative)return Dc(oi.cwd(),i);return i}async function Of(){try{let e=await xf({name:"clarity",defaultConfig:ri,cwd:oi.cwd(),endpoint:"",headers:{}});return{...ri,...e}}catch{return ri}}function ve(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Sf(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let e=ft.type;if(e==="renderer"||e==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class qa{async format(e){let t=await Sf(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Vt.pid,hostname:t(),environment:Vt.env.NODE_ENV||"development",platform:Vt.platform,version:Vt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Vt.env.NODE_ENV||Vt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hi{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={...Fn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new qa,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??De.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ii,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ii};return{...ii,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Fn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await Bc(this.config.logDirectory,ga.F_OK|ga.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await _c(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:bt.from(e);try{if(!gn(this.currentLogFile))await pn(this.currentLogFile,"",{mode:420});if(i=ma(this.currentLogFile,"a",420),Mc(i,o,{flag:"a"}),da(i),i!==void 0)mn(i),i=void 0;if((await _t(this.currentLogFile)).size===0){if(await pn(this.currentLogFile,o,{flag:"w",mode:420}),(await _t(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),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(i!==void 0)try{mn(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Zt(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 Zt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ve())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return dn(16).toString("hex")}generateKey(){return dn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=dn(16),i=Ic("aes-256-gcm",t,r),n=bt.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:bt.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ya(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(bt.from(bt.concat(n)))),i.on("error",r),i.write(e),i.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(ve())return;let e=await _t(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await _r(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await _t(r).catch(()=>null))try{if(await pa(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Zr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await pn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await _t(r).catch(()=>null))await pa(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await _r(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Zr(Zt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=ha(e),i=jc(t),n=ya();await Zc(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),gn(this.currentLogFile))try{let e=ma(this.currentLogFile,"r+");da(e),mn(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(!ve()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await _r(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Zr(Zt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?ue.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=De.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${ue.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!ve()){let f=ao[e],u=this.options.showTags!==!1&&this.name?ue.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:ue.gray(a),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:ue.green(a),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:n,icon:f,tag:u,message:a,level:e}),console.error(l),o){let p=o.split(`
66
66
  `);for(let d of p)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:ue.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!ve()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${a}
67
67
  `;if(o)c+=`${o}
68
68
  `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!ve()){let r=this.options.showTags!==!1&&this.name?ue.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:ue.blue("\u25D0"),tag:r,message:`${ue.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),c=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
69
- `,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!ve()){let f=this.options.showTags!==!1&&this.name?ue.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:ue.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ve())console.error(c.trim());await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new hi(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ve())throw Error("createReadStream is not supported in browser environments");if(!gn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ha(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=bt.isBuffer(e)?e:bt.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),a=i.slice(16,-16),o=Ic("aes-256-gcm",r,n);return o.setAuthTag(s),bt.concat([o.update(a),o.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ve()}isServerMode(){return!ve()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!ve()){let s=e.split(`
69
+ `,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!ve()){let f=this.options.showTags!==!1&&this.name?ue.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:ue.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ve())console.error(c.trim());await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new hi(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ve())throw Error("createReadStream is not supported in browser environments");if(!gn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ha(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=bt.isBuffer(e)?e:bt.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),a=i.slice(16,-16),o=Lc("aes-256-gcm",r,n);return o.setAuthTag(s),bt.concat([o.update(a),o.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ve()}isServerMode(){return!ve()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!ve()){let s=e.split(`
70
70
  `),a=Math.max(...s.map((u)=>u.length))+2,o=`\u250C${"\u2500".repeat(a)}\u2510`,c=`\u2514${"\u2500".repeat(a)}\u2518`,f=s.map((u)=>{let l=" ".repeat(a-u.length-2);return`\u2502 ${u}${l} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:ue.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ue.cyan(o)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:ue.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:ue.cyan(c),showTimestamp:!1}))}else if(!ve())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
71
71
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(ve())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ue.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();De.stdin.removeListener("data",r);try{if(typeof De.stdin.setRawMode==="function")De.stdin.setRawMode(!1)}catch{}De.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof De.stdin.setRawMode==="function")De.stdin.setRawMode(!0)}catch{}De.stdin.resume(),De.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let n=/%([sdijfo%])/g,s=0;if(r=e.replace(n,(a,o)=>{if(o==="%")return"%";if(s>=t.length)return a;let c=t[s++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return a}}),s<t.length)r+=` ${t.slice(s).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!ve()){let n=this.options.showTags!==!1&&this.name?ue.gray(this.formatTag(this.name)):"",s=ue.blue("\u25D0");console.error(`${s} ${n} ${ue.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
72
72
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||ve()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(i,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ve())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),n!==void 0)this.activeProgressBar.message=n;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ve())return;if(this.activeProgressBar.current=this.activeProgressBar.total,i!==void 0)this.activeProgressBar.message=i;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(i,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ve())return;De.stdout.write(`${"\r".padEnd(De.stdout.columns||80)}\r`),this.log(n,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||ve()||!De.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=ue.green("\u2501".repeat(i)),a=ue.gray("\u2501".repeat(n)),o=`[${s}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=t||r===100?ue.green("\u2713"):ue.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ue.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${o} ${c}${f}`,d=De.stdout.columns||80,C=" ".repeat(Math.max(0,d-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${C}`,De.stdout.write(e.lastRenderedLine),t)De.stdout.write(`
73
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ve()||!De.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(ve()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await _r(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Zt(this.config.logDirectory,i);if(e.before)try{if((await _t(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Zr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ti(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&oe(t[0])&&"id"in t[0]&&t[0].id===3&&oe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(oe(t)&&oe(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(oe(e)&&"arr"in e&&Array.isArray(e.arr)&&oe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&oe(t[0])&&oe(e[0])){let i=[...t];for(let n of e)if(oe(n)&&"name"in n){if(!i.find((s)=>oe(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(oe(n)&&"path"in n){if(!i.find((s)=>oe(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>di(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!oe(t)||!oe(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(oe(n)&&oe(r[i]))r[i]=ti(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&oe(n[0])&&oe(r[i][0])){let s=[...n];for(let a of r[i])if(oe(a)&&"name"in a){if(!s.find((o)=>oe(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(oe(a)&&"path"in a){if(!s.find((o)=>oe(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>di(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function Un(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ti(e,t);if(Array.isArray(e))return r==="replace"?t:ti(e,t);if(!oe(t)||!oe(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],a=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(a))if(r==="replace")i[n]=s;else i[n]=ti(a,s);else if(oe(s)&&oe(a))i[n]=Un(a,s,r);else i[n]=s}return i}function di(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!di(e[r],t[r]))return!1;return!0}if(oe(e)&&oe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!di(e[n],t[n]))return!1}return!0}return!1}function oe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Qr(e,t,r="replace"){if(!Ja(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Un(t,n,r)}catch{return null}}catch{return null}}function Sf(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=(b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${l.map(p).join("_")}`,C=`${i}_${l.map((b)=>b.toUpperCase()).join("_")}`;if(r)Le.info(`Checking environment variable ${d} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let b=ur.env[d]||ur.env[C];if(b!==void 0){if(r)Le.info(`Using environment variable ${b?d:C} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(b);else if(typeof u==="boolean")c[f]=b.toLowerCase()==="true";else if(Array.isArray(u))try{let w=JSON.parse(b);if(Array.isArray(w))c[f]=w;else c[f]=b.split(",").map((A)=>A.trim())}catch{c[f]=b.split(",").map((w)=>w.trim())}else c[f]=b}}}return c}return s(n)}async function kf({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:a=!0,arrayStrategy:o="replace"}){let c=a&&typeof n==="object"&&n!==null&&!Array.isArray(n)?Sf(e,n,s):n,f=r||ur.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Le.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),p=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],b=Array.from(new Set([f,Be(f,"config"),Be(f,".config"),i?Be(f,i):void 0].filter(Boolean)));for(let w of b){if(s)Le.info(`Searching for configuration in: ${w}`);let A=[Be(f,"config"),Be(f,".config")].concat(i?[Be(f,i)]:[]).includes(w)?[...l,...p,...d,...C]:[...p,...l,...C,...d];for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from: ${T}`);return v}}}if(e){let w=Be(hn(),".config",e),A=["config",`${e}.config`];if(t)A.push(`${t}.config`);if(s)Le.info(`Checking user config directory: ${w}`);for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory: ${T}`);return v}}}if(e){let w=Be(hn(),".config"),A=[`.${e}.config`];if(t)A.push(`.${t}.config`);if(s)Le.info(`Checking user config directory for dotfile configs: ${w}`);for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory dotfile: ${T}`);return v}}}if(e){let w=hn(),A=[`.${e}.config`,`.${e}`];if(t)A.push(`.${t}.config`),A.push(`.${t}`);if(s)Le.info(`Checking user home directory for dotfile configs: ${w}`);for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from user home directory: ${T}`);return v}}}try{let w=Be(f,"package.json");if(Ja(w)){let A=await import(w),S=A[e];if(!S&&t){if(S=A[t],S&&s)Le.success(`Using alias "${t}" configuration from package.json`)}if(S&&typeof S==="object"&&!Array.isArray(S))try{if(s)Le.success(`Configuration loaded from package.json: ${S===A[e]?e:t}`);return Un(c,S,o)}catch(k){if(s)Le.warn("Failed to merge package.json config:",k)}}}catch(w){if(s)Le.warn("Failed to load package.json:",w)}if(s)Le.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Tf(e,t={}){let r=ai.cwd();while(r.includes("storage"))r=fa(r,"..");let i=fa(r,e||"");if(t?.relative)return Wc(ai.cwd(),i);return i}async function Rf(){try{let e=await kf({name:"clarity",alias:"logging",defaultConfig:ni,cwd:ai.cwd()});return{...ni,...e||{}}}catch{return ni}}function ke(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Nf(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let e=ut.type;if(e==="renderer"||e==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class za{async format(e){let t=await Nf(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Gt.pid,hostname:t(),environment:Gt.env.NODE_ENV||"development",platform:Gt.platform,version:Gt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gt.env.NODE_ENV||Gt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mi{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={...Dn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new za,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??se.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...si,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...si};return{...si,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Dn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ke()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await Gc(this.config.logDirectory,va.F_OK|va.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Uc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ot.from(e);try{if(!Vr(this.currentLogFile))await $n(this.currentLogFile,"",{mode:420});if(i=Ca(this.currentLogFile,"a",420),Jc(i,o,{flag:"a"}),$a(i),i!==void 0)wn(i),i=void 0;if((await Kt(this.currentLogFile)).size===0){if(await $n(this.currentLogFile,o,{flag:"w",mode:420}),(await Kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),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(i!==void 0)try{wn(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Jt(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 Jt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Jt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ke())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return yn(16).toString("hex")}generateKey(){return yn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yn(16),i=Zc("aes-256-gcm",t,r),n=ot.isBuffer(e)?e:ot.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,c=i.getAuthTag(),f=ot.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Aa(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ot.from(ot.concat(n)))),i.on("error",r),i.write(e),i.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(ke())return;if(!this.shouldWriteToFile())return;let e=await Kt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Kr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Kt(r).catch(()=>null))try{if(await ba(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Jr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await $n(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Kt(r).catch(()=>null))await ba(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Kr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Jr(Jt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=wa(e),i=Kc(t),n=Aa();await qc(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}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()})),Vr(this.currentLogFile))try{let e=Ca(this.currentLogFile,"r+");$a(e),wn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ke()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Kr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Jr(Jt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ke())return!1;let e=typeof se.env.NO_COLOR<"u",t=se.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof se.stderr<"u"&&se.stderr.isTTY||typeof se.stdout<"u"&&se.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=se.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${ee.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=ee.underline(ee.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>ee.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>ee.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>ee.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>ee.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>ee.strikethrough(i)),t}supportsHyperlinks(){if(ke())return!1;let e=se.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=se.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Yc(t)||t.startsWith("./")||t.startsWith("../"))t=Hc(t);else return null;return Vr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":oo[e],p=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(d),o){let C=o.split(`
73
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ve()||!De.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(ve()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await _r(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Zt(this.config.logDirectory,i);if(e.before)try{if((await _t(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Zr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ti(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&oe(t[0])&&"id"in t[0]&&t[0].id===3&&oe(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(oe(t)&&oe(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(oe(e)&&"arr"in e&&Array.isArray(e.arr)&&oe(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&oe(t[0])&&oe(e[0])){let i=[...t];for(let n of e)if(oe(n)&&"name"in n){if(!i.find((s)=>oe(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(oe(n)&&"path"in n){if(!i.find((s)=>oe(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>di(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!oe(t)||!oe(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(oe(n)&&oe(r[i]))r[i]=ti(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&oe(n[0])&&oe(r[i][0])){let s=[...n];for(let a of r[i])if(oe(a)&&"name"in a){if(!s.find((o)=>oe(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(oe(a)&&"path"in a){if(!s.find((o)=>oe(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>di(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function Un(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ti(e,t);if(Array.isArray(e))return r==="replace"?t:ti(e,t);if(!oe(t)||!oe(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],a=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(a))if(r==="replace")i[n]=s;else i[n]=ti(a,s);else if(oe(s)&&oe(a))i[n]=Un(a,s,r);else i[n]=s}return i}function di(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!di(e[r],t[r]))return!1;return!0}if(oe(e)&&oe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!di(e[n],t[n]))return!1}return!0}return!1}function oe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Qr(e,t,r="replace"){if(!Ja(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Un(t,n,r)}catch{return null}}catch{return null}}function kf(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=(b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${l.map(p).join("_")}`,C=`${i}_${l.map((b)=>b.toUpperCase()).join("_")}`;if(r)Le.info(`Checking environment variable ${d} for config ${e}.${l.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=s(u,l);else{let b=ur.env[d]||ur.env[C];if(b!==void 0){if(r)Le.info(`Using environment variable ${b?d:C} for config ${e}.${l.join(".")}`);if(typeof u==="number")c[f]=Number(b);else if(typeof u==="boolean")c[f]=b.toLowerCase()==="true";else if(Array.isArray(u))try{let w=JSON.parse(b);if(Array.isArray(w))c[f]=w;else c[f]=b.split(",").map((A)=>A.trim())}catch{c[f]=b.split(",").map((w)=>w.trim())}else c[f]=b}}}return c}return s(n)}async function Tf({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:a=!0,arrayStrategy:o="replace"}){let c=a&&typeof n==="object"&&n!==null&&!Array.isArray(n)?kf(e,n,s):n,f=r||ur.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Le.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${f}`);let l=[e,`.${e}`].filter(Boolean),p=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],b=Array.from(new Set([f,Be(f,"config"),Be(f,".config"),i?Be(f,i):void 0].filter(Boolean)));for(let w of b){if(s)Le.info(`Searching for configuration in: ${w}`);let A=[Be(f,"config"),Be(f,".config")].concat(i?[Be(f,i)]:[]).includes(w)?[...l,...p,...d,...C]:[...p,...l,...C,...d];for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from: ${T}`);return v}}}if(e){let w=Be(hn(),".config",e),A=["config",`${e}.config`];if(t)A.push(`${t}.config`);if(s)Le.info(`Checking user config directory: ${w}`);for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory: ${T}`);return v}}}if(e){let w=Be(hn(),".config"),A=[`.${e}.config`];if(t)A.push(`.${t}.config`);if(s)Le.info(`Checking user config directory for dotfile configs: ${w}`);for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory dotfile: ${T}`);return v}}}if(e){let w=hn(),A=[`.${e}.config`,`.${e}`];if(t)A.push(`.${t}.config`),A.push(`.${t}`);if(s)Le.info(`Checking user home directory for dotfile configs: ${w}`);for(let S of A)for(let k of u){let T=Be(w,`${S}${k}`),v=await Qr(T,c,o);if(v!==null){if(s)Le.success(`Configuration loaded from user home directory: ${T}`);return v}}}try{let w=Be(f,"package.json");if(Ja(w)){let A=await import(w),S=A[e];if(!S&&t){if(S=A[t],S&&s)Le.success(`Using alias "${t}" configuration from package.json`)}if(S&&typeof S==="object"&&!Array.isArray(S))try{if(s)Le.success(`Configuration loaded from package.json: ${S===A[e]?e:t}`);return Un(c,S,o)}catch(k){if(s)Le.warn("Failed to merge package.json config:",k)}}}catch(w){if(s)Le.warn("Failed to load package.json:",w)}if(s)Le.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function Rf(e,t={}){let r=ai.cwd();while(r.includes("storage"))r=fa(r,"..");let i=fa(r,e||"");if(t?.relative)return Pc(ai.cwd(),i);return i}async function Nf(){try{let e=await Tf({name:"clarity",alias:"logging",defaultConfig:ni,cwd:ai.cwd()});return{...ni,...e||{}}}catch{return ni}}function ke(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Wf(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let e=ut.type;if(e==="renderer"||e==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class za{async format(e){let t=await Wf(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Gt.pid,hostname:t(),environment:Gt.env.NODE_ENV||"development",platform:Gt.platform,version:Gt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gt.env.NODE_ENV||Gt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mi{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={...Dn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new za,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??se.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...si,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...si};return{...si,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Dn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ke()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await Uc(this.config.logDirectory,va.F_OK|va.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Yc(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ot.from(e);try{if(!Vr(this.currentLogFile))await $n(this.currentLogFile,"",{mode:420});if(i=Ca(this.currentLogFile,"a",420),Gc(i,o,{flag:"a"}),$a(i),i!==void 0)wn(i),i=void 0;if((await Kt(this.currentLogFile)).size===0){if(await $n(this.currentLogFile,o,{flag:"w",mode:420}),(await Kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),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(i!==void 0)try{wn(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Jt(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 Jt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Jt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ke())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return yn(16).toString("hex")}generateKey(){return yn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yn(16),i=Vc("aes-256-gcm",t,r),n=ot.isBuffer(e)?e:ot.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,c=i.getAuthTag(),f=ot.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Aa(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ot.from(ot.concat(n)))),i.on("error",r),i.write(e),i.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(ke())return;if(!this.shouldWriteToFile())return;let e=await Kt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Kr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Kt(r).catch(()=>null))try{if(await ba(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await Jr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await $n(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Kt(r).catch(()=>null))await ba(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Kr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Jr(Jt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=wa(e),i=Jc(t),n=Aa();await zc(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}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()})),Vr(this.currentLogFile))try{let e=Ca(this.currentLogFile,"r+");$a(e),wn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ke()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Kr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Jr(Jt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ke())return!1;let e=typeof se.env.NO_COLOR<"u",t=se.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof se.stderr<"u"&&se.stderr.isTTY||typeof se.stdout<"u"&&se.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=se.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${ee.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=ee.underline(ee.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>ee.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>ee.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>ee.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>ee.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>ee.strikethrough(i)),t}supportsHyperlinks(){if(ke())return!1;let e=se.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=se.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Hc(t)||t.startsWith("./")||t.startsWith("../"))t=qc(t);else return null;return Vr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":oo[e],p=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:ee.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(d),o){let C=o.split(`
74
74
  `);for(let b of C)if(b.trim()&&!b.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:ee.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!ke()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
75
75
  `;if(o)u+=`${o}
76
76
  `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!ke()&&se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!ke()&&se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!ke()&&se.stdout.isTTY)se.stdout.write(`
77
77
  `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!ke()&&se.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":ee.blue("\u25D0"),tag:r,message:`${ee.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),c=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
78
- `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":ee.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ke())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new mi(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ke())throw Error("createReadStream is not supported in browser environments");if(!Vr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wa(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=ot.isBuffer(e)?e:ot.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=Vc("aes-256-gcm",r,n);o.setAuthTag(s);let c=o.update(a),f=o.final(),u=c.length+f.length,l=ot.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ke()}isServerMode(){return!ke()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
78
+ `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":ee.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ke())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new mi(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ke())throw Error("createReadStream is not supported in browser environments");if(!Vr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wa(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=ot.isBuffer(e)?e:ot.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=Kc("aes-256-gcm",r,n);o.setAuthTag(s);let c=o.update(a),f=o.final(),u=c.length+f.length,l=ot.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ke()}isServerMode(){return!ke()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
79
79
  `),c=Math.max(...o.map((p)=>p.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=o.map((p)=>{return this.formatConsoleMessage({timestamp:r,message:ee.cyan(p),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(f),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(u),showTimestamp:!1}))}else if(!ke())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let a=`${i} ${this.environment}.INFO: [BOX] ${s}
80
80
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(ke())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ee.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();se.stdin.removeListener("data",r);try{if(typeof se.stdin.setRawMode==="function")se.stdin.setRawMode(!1)}catch{}se.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof se.stdin.setRawMode==="function")se.stdin.setRawMode(!0)}catch{}se.stdin.resume(),se.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,o=0;if(r=e.replace(a,(c,f)=>{if(f==="%")return"%";if(o>=t.length)return c;let u=t[o++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),o<t.length)r+=` ${t.slice(o).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${ee.blue("\u25D0")} `;console.error(`${o}${a} ${ee.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
81
81
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!se.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=ee.green("\u2501".repeat(i)),a=ee.gray("\u2501".repeat(n)),o=`[${s}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?ee.green("\u2713"):ee.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${ee.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${o} ${c}${f}`,d=se.stdout.columns||80,C=" ".repeat(Math.max(0,d-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${C}`,se.stdout.write(e.lastRenderedLine),t)se.stdout.write(`
82
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ke()||!se.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(ke()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Kr(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Jt(this.config.logDirectory,i);if(e.before)try{if((await Kt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Jr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Xa(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),o===r||!n(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function Qa(e){return e instanceof Ve}function Wf(e){return e instanceof gi}function Pf(e){if(Qa(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 vi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:a={},verbose:o=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:a,verbose:o,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return mr.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${r}_${o.join("_")}`,f=i.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,i);else{let u=Gr.env[c]||(f?Gr.env[f]:void 0);if(u!==void 0){if(i.verbose){let l=Gr.env[c]?c:f}try{e[n]=this.parseEnvironmentValue(u,typeof s,c,i.customParsers,i.configName)}catch(l){if(l instanceof pi)throw l;throw At.envVar(c,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,a]of Object.entries(i))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw At.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Gr.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],s,a),n){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,i);else i.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
82
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ke()||!se.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(ke()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Kr(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Jt(this.config.logDirectory,i);if(e.before)try{if((await Kt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Jr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Xa(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),o===r||!n(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function Qa(e){return e instanceof Ve}function Pf(e){return e instanceof gi}function Ff(e){if(Qa(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 vi{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:a={},verbose:o=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:a,verbose:o,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return mr.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${r}_${o.join("_")}`,f=i.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,i);else{let u=Gr.env[c]||(f?Gr.env[f]:void 0);if(u!==void 0){if(i.verbose){let l=Gr.env[c]?c:f}try{e[n]=this.parseEnvironmentValue(u,typeof s,c,i.customParsers,i.configName)}catch(l){if(l instanceof pi)throw l;throw At.envVar(c,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,a]of Object.entries(i))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw At.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Gr.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],s,a),n){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,i);else i.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
83
83
 
84
84
  `;for(let i of e)r+=`${i.key}
85
85
  `,r+=` Type: ${i.type}
@@ -91,25 +91,25 @@ ${Fr}/
91
91
  `;r+=`| Variable | Type | Description | Example |
92
92
  `,r+=`|----------|------|-------------|----------|
93
93
  `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
94
- `;return r}}function Ff(e,t){let r=no("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function eo(e,t,r={}){return to(e,t,r,new WeakMap)}function to(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return ro(e,t,n,i);if(!He(t)||!He(e))return t;return jf(e,t,r,i)}function ro(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Df(e,t);case"smart":return If(e,t,i);default:return t}return t}function Df(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Pn(n,i)))r.push(i);return r}function If(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(He(t[0])&&He(e[0]))return Lf(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Lf(e,t,r){let i=[...t];for(let n of e){if(!He(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((c)=>He(c)&&(o in c)&&c[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function jf(e,t,r,i){let n=t;if(He(n)&&i.has(n))return i.get(n);let s={...e};if(He(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(He(o)&&He(c))s[a]=to(c,o,r,i);else if(Array.isArray(o)||Array.isArray(c))s[a]=ro(c,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function Yn(e,t,r="replace"){return eo(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Pn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Pn(e[r],t[r]))return!1;return!0}if(He(e)&&He(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Pn(e[n],t[n]))return!1}return!0}return!1}function He(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let f=qt.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Ur(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,d=Object.keys(u).length>0;if(!p&&!d)throw new hr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new hr(e,Error("Configuration must export a valid object"),"unknown");let C={config:Yn(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)qt.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?At.configLoad(e,f):At.configLoad(e,Error(String(f)))}};if(a)return mr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(Cn(t,`${s}${a}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Xa(async()=>{return Ur(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Ur(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=Cn(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=Cn(e,a);if(await this.checkFileAccess(o))i.push(o)}}catch{return[]}return i}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(!Ur(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Hn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],p);else return this.validateWithJSONSchema(e,t,p)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await mr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!zc(t))throw new dr(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new dr(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,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)i.push({path:r,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)i.push({path:r,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))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(a)})}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:co},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class qn{fileLoader=new bi;envProcessor=new vi;validator=new Hn;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)Xe.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){let c=Date.now()-t;throw Xe.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||St.cwd(),p=[],d=await this.loadLocalConfiguration(i,n,l,a,o,f,u,c,r);if(d)return p.push(...this.getLocalSearchPaths(i,n,l,a)),this.finalizeResult(d,p,c,i,u);let C=await this.loadHomeConfiguration(i,n,o,f,u,c);if(C)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(C,p,c,i,u);let b=await this.loadPackageJsonConfiguration(i,n,l,o,f,u,c);if(b)return p.push(_e(l,"package.json")),this.finalizeResult(b,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,a)),t)throw At.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,o,c,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,c){let f=o?fr(e,n,a):n,u=this.getLocalDirectories(r,i);for(let l of u){if(a)Xe.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)Xe.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?fr(e,r,n):r,o=[_e(Bt(),".config",e),_e(Bt(),".config"),Bt()];for(let c of o){if(n)Xe.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:i,verbose:n});if(u){if(n)Xe.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?fr(e,i,s):i;try{let c=_e(r,"package.json");if(!Nn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Xe.success(`Configuration loaded from package.json: ${l}`);return{config:Yn(o,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)Xe.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!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,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw At.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return qt.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);qt.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,_e(e,"config"),_e(e,".config"),t?_e(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(_e(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[_e(Bt(),".config",e),_e(Bt(),".config"),Bt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Wa(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function Mf(e){return dt.loadConfig({...e,__strictErrorHandling:!0})}async function io(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await dt.loadConfig(e);else i=await dt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Xe.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await dt.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function Bf(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await dt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Wa(r)))return(await dt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await dt.loadConfig({...e,cwd:e.cwd||St.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Wa(t)))return(await dt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function _f(e,t,r="replace"){let i=new bi;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function fr(e,t,r=!1){let i=new vi,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((b)=>b.toUpperCase()).join("")}`,`${n}_${l.map((b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,C;for(let b of p)if(d=St.env[b],d!==void 0){C=b;break}if(d!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Zf(e){let t=_e(St.cwd(),e.configDir),r=_e(St.cwd(),e.generatedDir),i=_e(r,"config-types.ts");if(!Nn(ca(i)))kc(ca(i),{recursive:!0,mode:511});let n=Nn(t)?Tc(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${yu}
94
+ `;return r}}function Df(e,t){let r=no("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function eo(e,t,r={}){return to(e,t,r,new WeakMap)}function to(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return ro(e,t,n,i);if(!He(t)||!He(e))return t;return Mf(e,t,r,i)}function ro(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return If(e,t);case"smart":return Lf(e,t,i);default:return t}return t}function If(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Pn(n,i)))r.push(i);return r}function Lf(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(He(t[0])&&He(e[0]))return jf(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function jf(e,t,r){let i=[...t];for(let n of e){if(!He(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((c)=>He(c)&&(o in c)&&c[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function Mf(e,t,r,i){let n=t;if(He(n)&&i.has(n))return i.get(n);let s={...e};if(He(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(He(o)&&He(c))s[a]=to(c,o,r,i);else if(Array.isArray(o)||Array.isArray(c))s[a]=ro(c,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function Yn(e,t,r="replace"){return eo(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Pn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Pn(e[r],t[r]))return!1;return!0}if(He(e)&&He(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Pn(e[n],t[n]))return!1}return!0}return!1}function He(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bi{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let f=qt.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Ur(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,d=Object.keys(u).length>0;if(!p&&!d)throw new hr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new hr(e,Error("Configuration must export a valid object"),"unknown");let C={config:Yn(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)qt.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?At.configLoad(e,f):At.configLoad(e,Error(String(f)))}};if(a)return mr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(Cn(t,`${s}${a}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Xa(async()=>{return Ur(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Ur(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=Cn(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=Cn(e,a);if(await this.checkFileAccess(o))i.push(o)}}catch{return[]}return i}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(!Ur(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Hn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],p);else return this.validateWithJSONSchema(e,t,p)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await mr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!Xc(t))throw new dr(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new dr(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,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)i.push({path:r,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)i.push({path:r,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))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(a)})}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:co},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class qn{fileLoader=new bi;envProcessor=new vi;validator=new Hn;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)Xe.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){let c=Date.now()-t;throw Xe.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||St.cwd(),p=[],d=await this.loadLocalConfiguration(i,n,l,a,o,f,u,c,r);if(d)return p.push(...this.getLocalSearchPaths(i,n,l,a)),this.finalizeResult(d,p,c,i,u);let C=await this.loadHomeConfiguration(i,n,o,f,u,c);if(C)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(C,p,c,i,u);let b=await this.loadPackageJsonConfiguration(i,n,l,o,f,u,c);if(b)return p.push(_e(l,"package.json")),this.finalizeResult(b,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,a)),t)throw At.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,o,c,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,c){let f=o?fr(e,n,a):n,u=this.getLocalDirectories(r,i);for(let l of u){if(a)Xe.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)Xe.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?fr(e,r,n):r,o=[_e(Bt(),".config",e),_e(Bt(),".config"),Bt()];for(let c of o){if(n)Xe.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:i,verbose:n});if(u){if(n)Xe.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?fr(e,i,s):i;try{let c=_e(r,"package.json");if(!Nn(c))return null;let f=await import(c),u=f[e],l=e;if(!u&&t)u=f[t],l=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Xe.success(`Configuration loaded from package.json: ${l}`);return{config:Yn(o,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)Xe.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!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,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw At.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return qt.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);qt.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,_e(e,"config"),_e(e,".config"),t?_e(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(_e(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[_e(Bt(),".config",e),_e(Bt(),".config"),Bt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Wa(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function Bf(e){return dt.loadConfig({...e,__strictErrorHandling:!0})}async function io(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await dt.loadConfig(e);else i=await dt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Xe.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await dt.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function _f(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await dt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Wa(r)))return(await dt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await dt.loadConfig({...e,cwd:e.cwd||St.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Wa(t)))return(await dt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Zf(e,t,r="replace"){let i=new bi;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function fr(e,t,r=!1){let i=new vi,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((b)=>b.toUpperCase()).join("")}`,`${n}_${l.map((b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,C;for(let b of p)if(d=St.env[b],d!==void 0){C=b;break}if(d!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Vf(e){let t=_e(St.cwd(),e.configDir),r=_e(St.cwd(),e.generatedDir),i=_e(r,"config-types.ts");if(!Nn(ca(i)))Tc(ca(i),{recursive:!0,mode:511});let n=Nn(t)?Rc(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${wu}
95
95
  export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
96
- `;Rc(i,s,{mode:438})}function Vf(e){let t=null,r=null,i=()=>{if(!r)r=io(e).then((s)=>{return t=s,s},(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)Xe.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,a){if(t)return t[a];let o=n[a];return i(),o},has(s,a){return a in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||n,a)},set(s,a,o){if(!t)t={...n};return t[a]=o,!0}})}function Kf(e){let t=xa(ef.cwd(),e?.configDir||"./config");function r(){if(!Xc(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=Qc(t).filter((c)=>n.has(vn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),o=new Map;for(let{base:c,file:f}of a){let u=vn(f).toLowerCase(),l=o.get(c);if(!l){o.set(c,f);continue}let p=vn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(p))o.set(c,f)}return Array.from(o.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function i(){let n=r(),s=n.map((c)=>c.base),a=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",o=n.length?`{
96
+ `;Nc(i,s,{mode:438})}function Kf(e){let t=null,r=null,i=()=>{if(!r)r=io(e).then((s)=>{return t=s,s},(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)Xe.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,a){if(t)return t[a];let o=n[a];return i(),o},has(s,a){return a in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||n,a)},set(s,a,o){if(!t)t={...n};return t[a]=o,!0}})}function Jf(e){let t=xa(tf.cwd(),e?.configDir||"./config");function r(){if(!Qc(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=ef(t).filter((c)=>n.has(vn(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),o=new Map;for(let{base:c,file:f}of a){let u=vn(f).toLowerCase(),l=o.get(c);if(!l){o.set(c,f);continue}let p=vn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(p))o.set(c,f)}return Array.from(o.entries()).map(([c,f])=>({base:c,file:f})).sort((c,f)=>c.base.localeCompare(f.base))}function i(){let n=r(),s=n.map((c)=>c.base),a=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",o=n.length?`{
97
97
  ${n.map((c)=>{let f=xa(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
98
98
  `)}
99
99
  }`:"Record<string, any>";return`export type ConfigNames = ${a}
100
100
  export type ConfigByName = ${o}
101
101
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
102
102
  export type ConfigOf = Config
103
- `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>{return{path:s.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}function $u(e,t={}){let r=ci.cwd();while(r.includes("storage"))r=Ea(r,"..");let i=Ea(r,e||"");if(t?.relative)return rf(ci.cwd(),i);return i}function Re(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vu(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let e=ht.type;if(e==="renderer"||e==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class mo{async format(e){let t=await vu(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Ht.pid,hostname:t(),environment:Ht.env.NODE_ENV||"development",platform:Ht.platform,version:Ht.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ht.env.NODE_ENV||Ht.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ai{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={...yi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mo,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??ae.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rn};return{...Rn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:yi.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Re()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await lf(this.config.logDirectory,Ta.F_OK|Ta.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await cf(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:lt.from(e);try{if(!Yr(this.currentLogFile))await xn(this.currentLogFile,"",{mode:420});if(i=ka(this.currentLogFile,"a",420),of(i,o,{flag:"a"}),Sa(i),i!==void 0)An(i),i=void 0;if((await Ut(this.currentLogFile)).size===0){if(await xn(this.currentLogFile,o,{flag:"w",mode:420}),(await Ut(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),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(i!==void 0)try{An(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Yt(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 Yt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Yt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Re())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return bn(16).toString("hex")}generateKey(){return bn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=bn(16),i=nf("aes-256-gcm",t,r),n=lt.isBuffer(e)?e:lt.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,c=i.getAuthTag(),f=lt.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Na(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(lt.from(lt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Re())return;if(!this.shouldWriteToFile())return;let e=await Ut(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Hr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Ut(r).catch(()=>null))try{if(await Ra(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await qr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await xn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ut(r).catch(()=>null))await Ra(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Hr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await qr(Yt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Oa(e),i=af(t),n=Na();await hf(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Yr(this.currentLogFile))try{let e=ka(this.currentLogFile,"r+");Sa(e),An(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Re()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Hr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await qr(Yt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Re())return!1;let e=typeof ae.env.NO_COLOR<"u",t=ae.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ae.stderr<"u"&&ae.stderr.isTTY||typeof ae.stdout<"u"&&ae.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=ae.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${re.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=re.underline(re.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>re.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>re.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>re.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>re.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>re.strikethrough(i)),t}supportsHyperlinks(){if(Re())return!1;let e=ae.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=ae.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ff(t)||t.startsWith("./")||t.startsWith("../"))t=uf(t);else return null;return Yr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Ou[e],p=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:re.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:re.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(d),o){let C=o.split(`
103
+ `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>{return{path:s.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}function Cu(e,t={}){let r=ci.cwd();while(r.includes("storage"))r=Ea(r,"..");let i=Ea(r,e||"");if(t?.relative)return nf(ci.cwd(),i);return i}function Re(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bu(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let e=ht.type;if(e==="renderer"||e==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class mo{async format(e){let t=await bu(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Ht.pid,hostname:t(),environment:Ht.env.NODE_ENV||"development",platform:Ht.platform,version:Ht.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ht.env.NODE_ENV||Ht.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ai{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={...yi},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mo,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??ae.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rn};return{...Rn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:yi.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Re()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await cf(this.config.logDirectory,Ta.F_OK|Ta.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await ff(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:lt.from(e);try{if(!Yr(this.currentLogFile))await xn(this.currentLogFile,"",{mode:420});if(i=ka(this.currentLogFile,"a",420),lf(i,o,{flag:"a"}),Sa(i),i!==void 0)An(i),i=void 0;if((await Ut(this.currentLogFile)).size===0){if(await xn(this.currentLogFile,o,{flag:"w",mode:420}),(await Ut(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(n<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let l=a*2**n;await new Promise((p)=>setTimeout(p,l)),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(i!==void 0)try{An(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(n===s-1){let f=o,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let c=a*2**(n-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Yt(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 Yt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Yt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Re())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return bn(16).toString("hex")}generateKey(){return bn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=bn(16),i=sf("aes-256-gcm",t,r),n=lt.isBuffer(e)?e:lt.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,c=i.getAuthTag(),f=lt.allocUnsafe(16+o+16);return r.copy(f,0),s.copy(f,16),a.copy(f,16+s.length),c.copy(f,16+o),{encrypted:f,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Na(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(lt.from(lt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Re())return;if(!this.shouldWriteToFile())return;let e=await Ut(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Hr(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Ut(r).catch(()=>null))try{if(await Ra(r,o),t.compress)try{let c=`${o}.gz`;await this.compressLogFile(o,c),await qr(o)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await xn(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ut(r).catch(()=>null))await Ra(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Hr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await qr(Yt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Oa(e),i=of(t),n=Na();await df(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Yr(this.currentLogFile))try{let e=ka(this.currentLogFile,"r+");Sa(e),An(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Re()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Hr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await qr(Yt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Re())return!1;let e=typeof ae.env.NO_COLOR<"u",t=ae.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ae.stderr<"u"&&ae.stderr.isTTY||typeof ae.stdout<"u"&&ae.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=ae.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${n}`;else if(s==="info"||s==="success")f=`${r} ${i} ${n}`;else f=`${r} ${i} ${re.cyan(n)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,p=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(p)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=re.underline(re.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>re.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>re.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>re.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>re.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>re.strikethrough(i)),t}supportsHyperlinks(){if(Re())return!1;let e=ae.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=ae.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(uf(t)||t.startsWith("./")||t.startsWith("../"))t=hf(t);else return null;return Yr(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let l=this.options.showIcons===!1?"":Su[e],p=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:re.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:re.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:l,tag:p,message:c,level:e}),console.error(d),o){let C=o.split(`
104
104
  `);for(let b of C)if(b.trim()&&!b.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:re.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!Re()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${f}
105
105
  `;if(o)u+=`${o}
106
106
  `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!Re()&&ae.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Re()&&ae.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!Re()&&ae.stdout.isTTY)ae.stdout.write(`
107
107
  `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!Re()&&ae.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":re.blue("\u25D0"),tag:r,message:`${re.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),c=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
108
- `,c=c.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:o,icon:this.options.showIcons===!1?"":re.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Re())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ai(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Re())throw Error("createReadStream is not supported in browser environments");if(!Yr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Oa(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=lt.isBuffer(e)?e:lt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=sf("aes-256-gcm",r,n);o.setAuthTag(s);let c=o.update(a),f=o.final(),u=c.length+f.length,l=lt.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Re()}isServerMode(){return!Re()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
108
+ `,c=c.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:o,icon:this.options.showIcons===!1?"":re.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Re())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ai(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Re())throw Error("createReadStream is not supported in browser environments");if(!Yr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Oa(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=lt.isBuffer(e)?e:lt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=af("aes-256-gcm",r,n);o.setAuthTag(s);let c=o.update(a),f=o.final(),u=c.length+f.length,l=lt.allocUnsafe(u);return c.copy(l,0),f.copy(l,c.length),l.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Re()}isServerMode(){return!Re()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
109
109
  `),c=Math.max(...o.map((p)=>p.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,l=o.map((p)=>{return this.formatConsoleMessage({timestamp:r,message:re.cyan(p),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(f),showTimestamp:!1})),l.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(u),showTimestamp:!1}))}else if(!Re())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let a=`${i} ${this.environment}.INFO: [BOX] ${s}
110
110
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(Re())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${re.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();ae.stdin.removeListener("data",r);try{if(typeof ae.stdin.setRawMode==="function")ae.stdin.setRawMode(!1)}catch{}ae.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof ae.stdin.setRawMode==="function")ae.stdin.setRawMode(!0)}catch{}ae.stdin.resume(),ae.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,o=0;if(r=e.replace(a,(c,f)=>{if(f==="%")return"%";if(o>=t.length)return c;let u=t[o++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),o<t.length)r+=` ${t.slice(o).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${re.blue("\u25D0")} `;console.error(`${o}${a} ${re.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
111
111
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ae.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=re.green("\u2501".repeat(i)),a=re.gray("\u2501".repeat(n)),o=`[${s}${a}]`,c=`${r}%`.padStart(4),f=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?re.green("\u2713"):re.blue("\u25B6"),l=this.options.showTags!==!1&&this.name?` ${re.gray(this.formatTag(this.name))}`:"",p=`\r${u}${l} ${o} ${c}${f}`,d=ae.stdout.columns||80,C=" ".repeat(Math.max(0,d-p.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${p}${C}`,ae.stdout.write(e.lastRenderedLine),t)ae.stdout.write(`
112
- `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Re()||!ae.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Re()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Hr(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Yt(this.config.logDirectory,i);if(e.before)try{if((await Ut(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await qr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Su(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),o===r||!n(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class Xn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:a={},verbose:o=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:a,verbose:o,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Vn.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${r}_${o.join("_")}`,f=i.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,i);else{let u=zr.env[c]||(f?zr.env[f]:void 0);if(u!==void 0){if(i.verbose){let l=zr.env[c]?c:f}try{e[n]=this.parseEnvironmentValue(u,typeof s,c,i.customParsers,i.configName)}catch(l){if(l instanceof zn)throw l;throw zt.envVar(c,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,a]of Object.entries(i))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw zt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(zr.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],s,a),n){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,i);else i.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
112
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Re()||!ae.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Re()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Hr(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Yt(this.config.logDirectory,i);if(e.before)try{if((await Ut(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await qr(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function ku(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(c){if(a=c instanceof Error?c:Error(String(c)),o===r||!n(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class Xn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:a={},verbose:o=!1,trackPerformance:c=!0}=r,f=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),l={...t};return this.processObject(l,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:a,verbose:o,configName:e}),{config:l,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Vn.track("applyEnvironmentVariables",f,{configName:e});return f()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${r}_${o.join("_")}`,f=i.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,i);else{let u=zr.env[c]||(f?zr.env[f]:void 0);if(u!==void 0){if(i.verbose){let l=zr.env[c]?c:f}try{e[n]=this.parseEnvironmentValue(u,typeof s,c,i.customParsers,i.configName)}catch(l){if(l instanceof zn)throw l;throw zt.envVar(c,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,a]of Object.entries(i))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw zt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(zr.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],s,a),n){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let a=[...t,n],o=`${r}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,i);else i.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
113
113
 
114
114
  `;for(let i of e)r+=`${i.key}
115
115
  `,r+=` Type: ${i.type}
@@ -121,43 +121,43 @@ export type ConfigOf = Config
121
121
  `;r+=`| Variable | Type | Description | Example |
122
122
  `,r+=`|----------|------|-------------|----------|
123
123
  `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
124
- `;return r}}function ku(e,t,r={}){return bo(e,t,r,new WeakMap)}function bo(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return Ao(e,t,n,i);if(!qe(t)||!qe(e))return t;return Wu(e,t,r,i)}function Ao(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Tu(e,t);case"smart":return Ru(e,t,i);default:return t}return t}function Tu(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Zn(n,i)))r.push(i);return r}function Ru(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(qe(t[0])&&qe(e[0]))return Nu(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Nu(e,t,r){let i=[...t];for(let n of e){if(!qe(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((c)=>qe(c)&&(o in c)&&c[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function Wu(e,t,r,i){let n=t;if(qe(n)&&i.has(n))return i.get(n);let s={...e};if(qe(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(qe(o)&&qe(c))s[a]=bo(c,o,r,i);else if(Array.isArray(o)||Array.isArray(c))s[a]=Ao(c,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function xo(e,t,r="replace"){return ku(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Zn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Zn(e[r],t[r]))return!1;return!0}if(qe(e)&&qe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Zn(e[n],t[n]))return!1}return!0}return!1}function qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Eo{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let f=fi.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Xr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,d=Object.keys(u).length>0;if(!p&&!d)throw new wi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new wi(e,Error("Configuration must export a valid object"),"unknown");let C={config:xo(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)fi.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?zt.configLoad(e,f):zt.configLoad(e,Error(String(f)))}};if(a)return Vn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(En(t,`${s}${a}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return Su(async()=>{return Xr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Xr(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=En(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=En(e,a);if(await this.checkFileAccess(o))i.push(o)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Xr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Oo{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],p);else return this.validateWithJSONSchema(e,t,p)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await Vn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!df(t))throw new $i(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new $i(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,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)i.push({path:r,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)i.push({path:r,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))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(a)})}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:Pu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Fu(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class So{fileLoader=new Eo;envProcessor=new Xn;validator=new Oo;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)ct.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")throw o;let c=Date.now()-t;throw ct.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Ci.cwd(),p=[],d=await this.loadLocalConfiguration(i,n,l,a,o,f,u,c,r);if(d)return p.push(...this.getLocalSearchPaths(i,n,l,a)),this.finalizeResult(d,p,c,i,u);let C=await this.loadHomeConfiguration(i,n,o,f,u,c);if(C)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(C,p,c,i,u);let b=await this.loadPackageJsonConfiguration(i,n,l,o,f,u,c);if(b)return p.push(Ye(l,"package.json")),this.finalizeResult(b,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,a)),t)throw zt.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,o,c,u),warnings:[`No configuration file found for "${i}"${Fu(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,c){let f=o?ei(e,n,a):n,u=this.getLocalDirectories(r,i);for(let l of u){if(a)ct.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)ct.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?ei(e,r,n):r,o=[Ye(Mt(),".config",e),Ye(Mt(),".config"),Mt()];for(let c of o){if(n)ct.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:i,verbose:n});if(u){if(n)ct.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?ei(e,i,s):i;try{let c=Ye(r,"package.json");if(!Oc(c))return null;let f={};try{f=JSON.parse(Sc(c,"utf8"))}catch(p){if(s)ct.warn("Failed to parse package.json:",[p instanceof Error?p:Error(String(p))]);return null}let u=f[e],l=e;if(!u&&t){let p=Array.isArray(t)?t:[t];for(let d of p){if(!d)continue;if(f[d]){u=f[d],l=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ct.success(`Configuration loaded from package.json: ${l}`);return{config:xo(o,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ct.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ei(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw zt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return fi.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);fi.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ye(e,"config"),Ye(e,".config"),t?Ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ye(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(Mt(),".config",e),Ye(Mt(),".config"),Mt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function ei(e,t,r=!1){let i=new Xn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((b)=>b.toUpperCase()).join("")}`,`${n}_${l.map((b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,C;for(let b of p)if(d=Ci.env[b],d!==void 0){C=b;break}if(d!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var fi,Vn,mf,gf=(e)=>e,yf=(e,t)=>{for(var r in t)mf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pf.bind(t,r)})},wf=(e,t)=>()=>(e&&(t=e(e=0)),t),Ha,no,qt,mr,so,Jf,Gf,Pa,ri,Fn,Ie,ue,Uf,Fa,Yf,Da,Hf,qf,On,zf,Ia,La,Sn,Xf,Qf,eu,tu,ii,ao,ru,Le,iu,nu,ja,ni,Dn,Te,ee,su,Ma,au,Ba,ou,lu,kn,cu,_a,Za,fu,Tn,uu,hu,du,mu,gu,si,oo,pu,yu="0.15.6",Ve,gi,hr,In,Ln,pi,jn,Mn,dr,Bn,_n,At,lo,co,Xe,dt,fo,uo,wu,Cu,ho,yi,yg,Fe,re,wg,bu,$g,Au,Cg,vg,Va,bg,xu,Eu,Ag,Ka,xg,Eg,Og,Sg,kg,Rn,Ou,Tg,Qe,go,wi,po,yo,zn,wo,$o,$i,Co,vo,zt,Pu,ct,Rg,Ng,Wg,Du,Qn;var xi=ce(()=>{Br();Cr();fi=new Ua,Vn=new Ya,mf=Object.defineProperty;Ha={};yf(Ha,{withErrorRecovery:()=>Xa,tryLoadConfig:()=>_f,loadConfigWithResult:()=>Mf,loadConfig:()=>io,isRetryableError:()=>Pf,isConfigNotFoundError:()=>Wf,isBunfigError:()=>Qa,globalPerformanceMonitor:()=>mr,globalCache:()=>qt,getEnvOrDefault:()=>Ff,generateConfigTypes:()=>Zf,defaultGeneratedDir:()=>uo,defaultConfigDir:()=>fo,deepMergeWithArrayStrategy:()=>Yn,deepMerge:()=>eo,createLibraryConfig:()=>Vf,config:()=>Bf,bunfigPlugin:()=>Kf,applyEnvVarsToConfig:()=>fr,TypeGenerationError:()=>Mn,SchemaValidationError:()=>dr,PluginError:()=>_n,PerformanceMonitor:()=>Jn,FileSystemError:()=>jn,ErrorFactory:()=>At,EnvVarError:()=>pi,EnvProcessor:()=>vi,ConfigValidator:()=>Hn,ConfigValidationError:()=>In,ConfigNotFoundError:()=>gi,ConfigMergeError:()=>Ln,ConfigLoader:()=>qn,ConfigLoadError:()=>hr,ConfigFileLoader:()=>bi,ConfigCache:()=>Kn,CacheUtils:()=>so,BunfigError:()=>Ve,BrowserConfigError:()=>Bn,ArrayMergeStrategies:()=>lo});wu=wf(async()=>{no=import.meta.require,qt=new Kn,mr=new Jn,so={createKey:$f,isEquivalent:Cf,estimateMemoryUsage:vf},Jf=li(Wn.cwd(),"config"),Gf=li(Wn.cwd(),"src/generated"),Pa=oi.env.CLARITY_LOG_DIR||Pc(xf(),"logs"),ri={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Pa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Fn=await Ef(),Ie={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=Ie,Uf=Ie.red,Fa=Ie.green,Yf=Ie.yellow,Da=Ie.blue,Hf=Ie.magenta,qf=Ie.cyan,On=Ie.white,zf=Ie.gray,Ia=Ie.bgRed,La=Ie.bgYellow,Sn=Ie.bold,Xf=Ie.dim,Qf=Ie.italic,eu=Ie.underline,tu=Ie.reset,ii={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ao={debug:"\uD83D\uDD0D",info:Da("\u2139"),success:Fa("\u2713"),warning:La(On(Sn(" WARN "))),error:Ia(On(Sn(" ERROR ")))},ru=new hi("stacks"),Le=new hi("bunfig",{showTags:!0}),iu=Be(ur.cwd(),"config"),nu=Be(ur.cwd(),"src/generated"),ja=ai.env.CLARITY_LOG_DIR||Nc(Tf(),"logs"),ni={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ja,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Dn=await Rf(),Te={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"},ee=Te,su=Te.red,Ma=Te.green,au=Te.yellow,Ba=Te.blue,ou=Te.magenta,lu=Te.cyan,kn=Te.white,cu=Te.gray,_a=Te.bgRed,Za=Te.bgYellow,fu=Te.bgGray,Tn=Te.bold,uu=Te.dim,hu=Te.italic,du=Te.underline,mu=Te.strikethrough,gu=Te.reset,si={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oo={debug:"\uD83D\uDD0D",info:Ba("\u2139"),success:Ma("\u2713"),warning:Za(kn(Tn(" WARN "))),error:_a(kn(Tn(" ERROR ")))},pu=new mi("stacks"),Ve=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},gi=class extends Ve{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},hr=class extends Ve{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},In=class extends Ve{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ln=class extends Ve{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},pi=class extends Ve{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},jn=class extends Ve{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Mn=class extends Ve{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},dr=class extends Ve{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Bn=class extends Ve{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},_n=class extends Ve{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},At={configNotFound(e,t,r){return new gi(e,t,r)},configLoad(e,t,r){return new hr(e,t,r)},configValidation(e,t,r){return new In(e,t,r)},configMerge(e,t,r,i){return new Ln(e,t,r,i)},envVar(e,t,r,i){return new pi(e,t,r,i)},fileSystem(e,t,r){return new jn(e,t,r)},typeGeneration(e,t,r){return new Mn(e,t,r)},schemaValidation(e,t,r){return new dr(e,t,r)},browserConfig(e,t,r,i){return new Bn(e,t,r,i)},plugin(e,t,r){return new _n(e,t,r)}},lo={replace:"replace",concat:"concat",smart:"smart"},co=/^https?:\/\//,Xe=new mi("bunfig",{showTags:!0}),dt=new qn,fo=_e(St.cwd(),"config"),uo=_e(St.cwd(),"src/generated")});Cu=ci.env.CLARITY_LOG_DIR||tf($u(),"logs"),ho={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},yi={...ho},yg=(async()=>{try{let{loadConfig:e}=await wu().then(()=>Ha),t=await e({name:"clarity",alias:"logging",defaultConfig:ho,cwd:ci.cwd()});if(t)Object.assign(yi,t)}catch{}return yi})();Fe={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=Fe,wg=Fe.red,bu=Fe.green,$g=Fe.yellow,Au=Fe.blue,Cg=Fe.magenta,vg=Fe.cyan,Va=Fe.white,bg=Fe.gray,xu=Fe.bgRed,Eu=Fe.bgYellow,Ag=Fe.bgGray,Ka=Fe.bold,xg=Fe.dim,Eg=Fe.italic,Og=Fe.underline,Sg=Fe.strikethrough,kg=Fe.reset,Rn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ou={debug:"\uD83D\uDD0D",info:Au("\u2139"),success:bu("\u2713"),warning:Eu(Va(Ka(" WARN "))),error:xu(Va(Ka(" ERROR ")))};Tg=new Ai("stacks");Qe=class Qe extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};go=class go extends Qe{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};wi=class wi extends Qe{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};po=class po extends Qe{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};yo=class yo extends Qe{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};zn=class zn extends Qe{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};wo=class wo extends Qe{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};$o=class $o extends Qe{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};$i=class $i extends Qe{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Co=class Co extends Qe{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};vo=class vo extends Qe{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};zt={configNotFound(e,t,r){return new go(e,t,r)},configLoad(e,t,r){return new wi(e,t,r)},configValidation(e,t,r){return new po(e,t,r)},configMerge(e,t,r,i){return new yo(e,t,r,i)},envVar(e,t,r,i){return new zn(e,t,r,i)},fileSystem(e,t,r){return new wo(e,t,r)},typeGeneration(e,t,r){return new $o(e,t,r)},schemaValidation(e,t,r){return new $i(e,t,r)},browserConfig(e,t,r,i){return new Co(e,t,r,i)},plugin(e,t,r){return new vo(e,t,r)}};Pu=/^https?:\/\//;ct=new Ai("bunfig",{showTags:!0});Rg=new So;Ng=Ye(Ci.cwd(),"config"),Wg=Ye(Ci.cwd(),"src/generated"),Du={cwd:Ec.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},Qn=Du});function Xt(e,t){let r=1,i=1;for(let n=0;n<t;n++)if(e.charCodeAt(n)===10)r++,i=1;else i++;return{line:r,column:i}}function ko(e){let t=[],r=[],i=[],n={")":"(","]":"[","}":"{"},s=0,a=0,o=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(o!==-1){if(u===42&&l===47)r.push({start:o,end:f+2}),o=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:a,end:f+1}),s=0;continue}if(u===47&&l===42){o=f,f++;continue}if(u===47&&l===47){let d=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:d,end:f});continue}if(u===39||u===34||u===96){s=u,a=f;continue}let p=e[f];if(p==="("||p==="["||p==="{")i.push({char:p,offset:f});else if(n[p]){let d=i.pop();if(!d||d.char!==n[p])t.push({...Xt(e,f),message:`Unexpected closing delimiter ${p}`,code:"DTSX1004"})}}if(s)t.push({...Xt(e,a),message:"Unterminated string literal",code:"DTSX1002"});if(o!==-1)t.push({...Xt(e,o),message:"Unterminated block comment",code:"DTSX1003"});for(let f of i)t.push({...Xt(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((p)=>l.index>=p.start&&l.index<p.end))continue;t.push({...Xt(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Xt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var es=()=>{};import{statSync as Iu}from"fs";import{readFile as Lu,readdir as zg}from"fs/promises";import{createRequire as ju}from"module";import{dirname as Mu,isAbsolute as To,join as Bu,resolve as Ro}from"path";import _u from"process";async function gr(e,t,r="lf"){let i=t.replace(/\r\n/g,`
124
+ `;return r}}function Tu(e,t,r={}){return bo(e,t,r,new WeakMap)}function bo(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return Ao(e,t,n,i);if(!qe(t)||!qe(e))return t;return Pu(e,t,r,i)}function Ao(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Ru(e,t);case"smart":return Nu(e,t,i);default:return t}return t}function Ru(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Zn(n,i)))r.push(i);return r}function Nu(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(qe(t[0])&&qe(e[0]))return Wu(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function Wu(e,t,r){let i=[...t];for(let n of e){if(!qe(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((c)=>qe(c)&&(o in c)&&c[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function Pu(e,t,r,i){let n=t;if(qe(n)&&i.has(n))return i.get(n);let s={...e};if(qe(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(qe(o)&&qe(c))s[a]=bo(c,o,r,i);else if(Array.isArray(o)||Array.isArray(c))s[a]=Ao(c,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function xo(e,t,r="replace"){return Tu(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Zn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Zn(e[r],t[r]))return!1;return!0}if(qe(e)&&qe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Zn(e[n],t[n]))return!1}return!0}return!1}function qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Eo{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let f=fi.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!Xr(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,p="default"in u,d=Object.keys(u).length>0;if(!p&&!d)throw new wi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new wi(e,Error("Configuration must export a valid object"),"unknown");let C={config:xo(t,l,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)fi.setWithFileCheck("file",C,e,s);return C}catch(f){throw f instanceof Error?zt.configLoad(e,f):zt.configLoad(e,Error(String(f)))}};if(a)return Vn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(En(t,`${s}${a}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return ku(async()=>{return Xr(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Xr(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=En(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=En(e,a);if(await this.checkFileAccess(o))i.push(o)}}catch{return[]}return i}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Xr(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Oo{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],p={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,p);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],p);else return this.validateWithJSONSchema(e,t,p)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await Vn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!mf(t))throw new $i(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new $i(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,c]of Object.entries(t.properties))if(o in a){let f=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],c,f,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(a))if(!o.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,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)i.push({path:r,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)i.push({path:r,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))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(a)})}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:Fu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Du(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class So{fileLoader=new Eo;envProcessor=new Xn;validator=new Oo;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let c=this.checkCache(a.name||"",a);if(c)return c}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(c){let f=a.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(f)throw c;o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let u=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),l=!u&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),p=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(p||u))throw c;if(l&&(!f||!p))o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!f)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)ct.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")throw o;let c=Date.now()-t;throw ct.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Ci.cwd(),p=[],d=await this.loadLocalConfiguration(i,n,l,a,o,f,u,c,r);if(d)return p.push(...this.getLocalSearchPaths(i,n,l,a)),this.finalizeResult(d,p,c,i,u);let C=await this.loadHomeConfiguration(i,n,o,f,u,c);if(C)return p.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(C,p,c,i,u);let b=await this.loadPackageJsonConfiguration(i,n,l,o,f,u,c);if(b)return p.push(Ye(l,"package.json")),this.finalizeResult(b,p,c,i,u);if(p.push(...this.getAllSearchPaths(i,n,l,a)),t)throw zt.configNotFound(i,p,n);return{...await this.applyEnvironmentVariables(i,o,c,u),warnings:[`No configuration file found for "${i}"${Du(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,c){let f=o?ei(e,n,a):n,u=this.getLocalDirectories(r,i);for(let l of u){if(a)ct.info(`Searching for configuration in: ${l}`);let p=this.fileLoader.generateConfigPaths(e,l,t),d=await this.fileLoader.tryLoadFromPaths(p,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(a)ct.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?ei(e,r,n):r,o=[Ye(Mt(),".config",e),Ye(Mt(),".config"),Mt()];for(let c of o){if(n)ct.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:i,verbose:n});if(u){if(n)ct.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?ei(e,i,s):i;try{let c=Ye(r,"package.json");if(!Sc(c))return null;let f={};try{f=JSON.parse(kc(c,"utf8"))}catch(p){if(s)ct.warn("Failed to parse package.json:",[p instanceof Error?p:Error(String(p))]);return null}let u=f[e],l=e;if(!u&&t){let p=Array.isArray(t)?t:[t];for(let d of p){if(!d)continue;if(f[d]){u=f[d],l=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)ct.success(`Configuration loaded from package.json: ${l}`);return{config:xo(o,u,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)ct.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ei(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw zt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return fi.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);fi.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ye(e,"config"),Ye(e,".config"),t?Ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ye(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(Mt(),".config",e),Ye(Mt(),".config"),Mt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function ei(e,t,r=!1){let i=new Xn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let c={...a};for(let[f,u]of Object.entries(a)){let l=[...o,f],p=[`${n}_${l.join("_").toUpperCase()}`,`${n}_${l.map((b)=>b.toUpperCase()).join("")}`,`${n}_${l.map((b)=>b.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,C;for(let b of p)if(d=Ci.env[b],d!==void 0){C=b;break}if(d!==void 0&&C)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let b=Number(d);if(!Number.isNaN(b))c[f]=b}else if(Array.isArray(u))try{c[f]=JSON.parse(d)}catch{c[f]=d.split(",").map((b)=>b.trim())}else c[f]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var fi,Vn,gf,pf=(e)=>e,wf=(e,t)=>{for(var r in t)gf(e,r,{get:t[r],enumerable:!0,configurable:!0,set:yf.bind(t,r)})},$f=(e,t)=>()=>(e&&(t=e(e=0)),t),Ha,no,qt,mr,so,Gf,Uf,Pa,ri,Fn,Ie,ue,Yf,Fa,Hf,Da,qf,zf,On,Xf,Ia,La,Sn,Qf,eu,tu,ru,ii,ao,iu,Le,nu,su,ja,ni,Dn,Te,ee,au,Ma,ou,Ba,lu,cu,kn,fu,_a,Za,uu,Tn,hu,du,mu,gu,pu,si,oo,yu,wu="0.15.6",Ve,gi,hr,In,Ln,pi,jn,Mn,dr,Bn,_n,At,lo,co,Xe,dt,fo,uo,$u,vu,ho,yi,wg,Fe,re,$g,Au,Cg,xu,vg,bg,Va,Ag,Eu,Ou,xg,Ka,Eg,Og,Sg,kg,Tg,Rn,Su,Rg,Qe,go,wi,po,yo,zn,wo,$o,$i,Co,vo,zt,Fu,ct,Ng,Wg,Pg,Iu,Qn;var xi=ce(()=>{Br();Cr();fi=new Ua,Vn=new Ya,gf=Object.defineProperty;Ha={};wf(Ha,{withErrorRecovery:()=>Xa,tryLoadConfig:()=>Zf,loadConfigWithResult:()=>Bf,loadConfig:()=>io,isRetryableError:()=>Ff,isConfigNotFoundError:()=>Pf,isBunfigError:()=>Qa,globalPerformanceMonitor:()=>mr,globalCache:()=>qt,getEnvOrDefault:()=>Df,generateConfigTypes:()=>Vf,defaultGeneratedDir:()=>uo,defaultConfigDir:()=>fo,deepMergeWithArrayStrategy:()=>Yn,deepMerge:()=>eo,createLibraryConfig:()=>Kf,config:()=>_f,bunfigPlugin:()=>Jf,applyEnvVarsToConfig:()=>fr,TypeGenerationError:()=>Mn,SchemaValidationError:()=>dr,PluginError:()=>_n,PerformanceMonitor:()=>Jn,FileSystemError:()=>jn,ErrorFactory:()=>At,EnvVarError:()=>pi,EnvProcessor:()=>vi,ConfigValidator:()=>Hn,ConfigValidationError:()=>In,ConfigNotFoundError:()=>gi,ConfigMergeError:()=>Ln,ConfigLoader:()=>qn,ConfigLoadError:()=>hr,ConfigFileLoader:()=>bi,ConfigCache:()=>Kn,CacheUtils:()=>so,BunfigError:()=>Ve,BrowserConfigError:()=>Bn,ArrayMergeStrategies:()=>lo});$u=$f(async()=>{no=import.meta.require,qt=new Kn,mr=new Jn,so={createKey:Cf,isEquivalent:vf,estimateMemoryUsage:bf},Gf=li(Wn.cwd(),"config"),Uf=li(Wn.cwd(),"src/generated"),Pa=oi.env.CLARITY_LOG_DIR||Fc(Ef(),"logs"),ri={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Pa,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Fn=await Of(),Ie={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=Ie,Yf=Ie.red,Fa=Ie.green,Hf=Ie.yellow,Da=Ie.blue,qf=Ie.magenta,zf=Ie.cyan,On=Ie.white,Xf=Ie.gray,Ia=Ie.bgRed,La=Ie.bgYellow,Sn=Ie.bold,Qf=Ie.dim,eu=Ie.italic,tu=Ie.underline,ru=Ie.reset,ii={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ao={debug:"\uD83D\uDD0D",info:Da("\u2139"),success:Fa("\u2713"),warning:La(On(Sn(" WARN "))),error:Ia(On(Sn(" ERROR ")))},iu=new hi("stacks"),Le=new hi("bunfig",{showTags:!0}),nu=Be(ur.cwd(),"config"),su=Be(ur.cwd(),"src/generated"),ja=ai.env.CLARITY_LOG_DIR||Wc(Rf(),"logs"),ni={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ja,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Dn=await Nf(),Te={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"},ee=Te,au=Te.red,Ma=Te.green,ou=Te.yellow,Ba=Te.blue,lu=Te.magenta,cu=Te.cyan,kn=Te.white,fu=Te.gray,_a=Te.bgRed,Za=Te.bgYellow,uu=Te.bgGray,Tn=Te.bold,hu=Te.dim,du=Te.italic,mu=Te.underline,gu=Te.strikethrough,pu=Te.reset,si={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oo={debug:"\uD83D\uDD0D",info:Ba("\u2139"),success:Ma("\u2713"),warning:Za(kn(Tn(" WARN "))),error:_a(kn(Tn(" ERROR ")))},yu=new mi("stacks"),Ve=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},gi=class extends Ve{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},hr=class extends Ve{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},In=class extends Ve{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ln=class extends Ve{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},pi=class extends Ve{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},jn=class extends Ve{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Mn=class extends Ve{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},dr=class extends Ve{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Bn=class extends Ve{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},_n=class extends Ve{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},At={configNotFound(e,t,r){return new gi(e,t,r)},configLoad(e,t,r){return new hr(e,t,r)},configValidation(e,t,r){return new In(e,t,r)},configMerge(e,t,r,i){return new Ln(e,t,r,i)},envVar(e,t,r,i){return new pi(e,t,r,i)},fileSystem(e,t,r){return new jn(e,t,r)},typeGeneration(e,t,r){return new Mn(e,t,r)},schemaValidation(e,t,r){return new dr(e,t,r)},browserConfig(e,t,r,i){return new Bn(e,t,r,i)},plugin(e,t,r){return new _n(e,t,r)}},lo={replace:"replace",concat:"concat",smart:"smart"},co=/^https?:\/\//,Xe=new mi("bunfig",{showTags:!0}),dt=new qn,fo=_e(St.cwd(),"config"),uo=_e(St.cwd(),"src/generated")});vu=ci.env.CLARITY_LOG_DIR||rf(Cu(),"logs"),ho={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:vu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},yi={...ho},wg=(async()=>{try{let{loadConfig:e}=await $u().then(()=>Ha),t=await e({name:"clarity",alias:"logging",defaultConfig:ho,cwd:ci.cwd()});if(t)Object.assign(yi,t)}catch{}return yi})();Fe={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=Fe,$g=Fe.red,Au=Fe.green,Cg=Fe.yellow,xu=Fe.blue,vg=Fe.magenta,bg=Fe.cyan,Va=Fe.white,Ag=Fe.gray,Eu=Fe.bgRed,Ou=Fe.bgYellow,xg=Fe.bgGray,Ka=Fe.bold,Eg=Fe.dim,Og=Fe.italic,Sg=Fe.underline,kg=Fe.strikethrough,Tg=Fe.reset,Rn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Su={debug:"\uD83D\uDD0D",info:xu("\u2139"),success:Au("\u2713"),warning:Ou(Va(Ka(" WARN "))),error:Eu(Va(Ka(" ERROR ")))};Rg=new Ai("stacks");Qe=class Qe extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};go=class go extends Qe{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};wi=class wi extends Qe{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};po=class po extends Qe{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};yo=class yo extends Qe{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};zn=class zn extends Qe{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};wo=class wo extends Qe{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};$o=class $o extends Qe{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};$i=class $i extends Qe{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Co=class Co extends Qe{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};vo=class vo extends Qe{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};zt={configNotFound(e,t,r){return new go(e,t,r)},configLoad(e,t,r){return new wi(e,t,r)},configValidation(e,t,r){return new po(e,t,r)},configMerge(e,t,r,i){return new yo(e,t,r,i)},envVar(e,t,r,i){return new zn(e,t,r,i)},fileSystem(e,t,r){return new wo(e,t,r)},typeGeneration(e,t,r){return new $o(e,t,r)},schemaValidation(e,t,r){return new $i(e,t,r)},browserConfig(e,t,r,i){return new Co(e,t,r,i)},plugin(e,t,r){return new vo(e,t,r)}};Fu=/^https?:\/\//;ct=new Ai("bunfig",{showTags:!0});Ng=new So;Wg=Ye(Ci.cwd(),"config"),Pg=Ye(Ci.cwd(),"src/generated"),Iu={cwd:Oc.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},Qn=Iu});function Xt(e,t){let r=1,i=1;for(let n=0;n<t;n++)if(e.charCodeAt(n)===10)r++,i=1;else i++;return{line:r,column:i}}function ko(e){let t=[],r=[],i=[],n={")":"(","]":"[","}":"{"},s=0,a=0,o=-1;for(let f=0;f<e.length;f++){let u=e.charCodeAt(f),l=e.charCodeAt(f+1);if(o!==-1){if(u===42&&l===47)r.push({start:o,end:f+2}),o=-1,f++;continue}if(s){if(u===92)f++;else if(u===s)r.push({start:a,end:f+1}),s=0;continue}if(u===47&&l===42){o=f,f++;continue}if(u===47&&l===47){let d=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:d,end:f});continue}if(u===39||u===34||u===96){s=u,a=f;continue}let p=e[f];if(p==="("||p==="["||p==="{")i.push({char:p,offset:f});else if(n[p]){let d=i.pop();if(!d||d.char!==n[p])t.push({...Xt(e,f),message:`Unexpected closing delimiter ${p}`,code:"DTSX1004"})}}if(s)t.push({...Xt(e,a),message:"Unterminated string literal",code:"DTSX1002"});if(o!==-1)t.push({...Xt(e,o),message:"Unterminated block comment",code:"DTSX1003"});for(let f of i)t.push({...Xt(e,f.offset),message:`Unclosed delimiter ${f.char}`,code:"DTSX1001"});let c=[[/\b(?:interface|class|enum)\s*(?=[{=])/g,"Declaration name expected"],[/\bfunction\s*(?=\()/g,"Function name expected"],[/\(\s*:/g,"Parameter name expected"]];for(let[f,u]of c)for(let l of e.matchAll(f)){if(r.some((p)=>l.index>=p.start&&l.index<p.end))continue;t.push({...Xt(e,l.index),message:u,code:"DTSX1005"})}for(let f of e.matchAll(/\btype\s*(?=[{=])/g)){if(r.some((l)=>f.index>=l.start&&f.index<l.end))continue;let u=e.slice(0,f.index).trimEnd();if(u.endsWith("import")||u.endsWith("export"))continue;t.push({...Xt(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var es=()=>{};import{statSync as Lu}from"fs";import{readFile as ju,readdir as Xg}from"fs/promises";import{createRequire as Mu}from"module";import{dirname as Bu,isAbsolute as To,join as _u,resolve as Ro}from"path";import Zu from"process";async function gr(e,t,r="lf"){let i=t.replace(/\r\n/g,`
125
125
  `);if(!i.endsWith(`
126
126
  `))i+=`
127
127
  `;if(r==="crlf")i=i.replace(/\n/g,`\r
128
- `);await Xs(e,i)}function Zu(e){let t="",r=0,i=0;while(r<e.length){let n=e.charCodeAt(r);if(i){if(t+=e[r],n===92&&r+1<e.length){t+=e[r+1],r+=2;continue}if(n===i)i=0;r++;continue}if(n===34){i=n,t+=e[r++];continue}if(n===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10)r++;continue}if(n===47&&e.charCodeAt(r+1)===42){r+=2;while(r+1<e.length&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47)){if(e.charCodeAt(r)===10)t+=`
129
- `;r++}r=Math.min(r+2,e.length);continue}if(n===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let a=e.charCodeAt(s);if(a===93||a===125){r++;continue}}t+=e[r++]}return t}function ts(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(Bu(e,"tsconfig.json"));for(let r of t)try{if(Iu(r).isFile())return r}catch{}return null}function Vu(e,t){if(To(e)||e.startsWith("."))return ts(Ro(Mu(t),e));let r=ju(t);for(let i of[e,`${e}/tsconfig.json`])try{let n=ts(r.resolve(i));if(n)return n}catch{}return null}async function No(e,t){let r=ts(e);if(!r||t.has(r))return;t.add(r);let i=await Lu(r,"utf8"),n=JSON.parse(Zu(i)),s=typeof n.extends==="string"?[n.extends]:n.extends??[],a;for(let o of s){let c=Vu(o,r);if(!c)continue;let f=await No(c,t);if(f!==void 0)a=f}return n.compilerOptions?.isolatedDeclarations??a}async function Wo(e){try{let t=e?.cwd||_u.cwd(),r=e?.tsconfigPath||"tsconfig.json",i=To(r)?r:Ro(t,r);return await No(i,new Set)??!1}catch{return!1}}function Po(e,t){let r={isValid:!0,errors:[]};for(let i of ko(e))r.errors.push({line:i.line,column:i.column,message:i.message,code:i.code});return r.isValid=r.errors.length===0,r}function Fo(e,t,r){if(e===t)return"";let i=e.split(`
128
+ `);await Xs(e,i)}function Vu(e){let t="",r=0,i=0;while(r<e.length){let n=e.charCodeAt(r);if(i){if(t+=e[r],n===92&&r+1<e.length){t+=e[r+1],r+=2;continue}if(n===i)i=0;r++;continue}if(n===34){i=n,t+=e[r++];continue}if(n===47&&e.charCodeAt(r+1)===47){r+=2;while(r<e.length&&e.charCodeAt(r)!==10)r++;continue}if(n===47&&e.charCodeAt(r+1)===42){r+=2;while(r+1<e.length&&!(e.charCodeAt(r)===42&&e.charCodeAt(r+1)===47)){if(e.charCodeAt(r)===10)t+=`
129
+ `;r++}r=Math.min(r+2,e.length);continue}if(n===44){let s=r+1;while(s<e.length){while(s<e.length&&e.charCodeAt(s)<=32)s++;if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===47){s+=2;while(s<e.length&&e.charCodeAt(s)!==10)s++;continue}if(e.charCodeAt(s)===47&&e.charCodeAt(s+1)===42){s+=2;while(s+1<e.length&&!(e.charCodeAt(s)===42&&e.charCodeAt(s+1)===47))s++;s=Math.min(s+2,e.length);continue}break}let a=e.charCodeAt(s);if(a===93||a===125){r++;continue}}t+=e[r++]}return t}function ts(e){let t=[e];if(!e.endsWith(".json"))t.push(`${e}.json`);t.push(_u(e,"tsconfig.json"));for(let r of t)try{if(Lu(r).isFile())return r}catch{}return null}function Ku(e,t){if(To(e)||e.startsWith("."))return ts(Ro(Bu(t),e));let r=Mu(t);for(let i of[e,`${e}/tsconfig.json`])try{let n=ts(r.resolve(i));if(n)return n}catch{}return null}async function No(e,t){let r=ts(e);if(!r||t.has(r))return;t.add(r);let i=await ju(r,"utf8"),n=JSON.parse(Vu(i)),s=typeof n.extends==="string"?[n.extends]:n.extends??[],a;for(let o of s){let c=Ku(o,r);if(!c)continue;let f=await No(c,t);if(f!==void 0)a=f}return n.compilerOptions?.isolatedDeclarations??a}async function Wo(e){try{let t=e?.cwd||Zu.cwd(),r=e?.tsconfigPath||"tsconfig.json",i=To(r)?r:Ro(t,r);return await No(i,new Set)??!1}catch{return!1}}function Po(e,t){let r={isValid:!0,errors:[]};for(let i of ko(e))r.errors.push({line:i.line,column:i.column,message:i.message,code:i.code});return r.isValid=r.errors.length===0,r}function Fo(e,t,r){if(e===t)return"";let i=e.split(`
130
130
  `),n=t.split(`
131
131
  `),s=new Map,a=new Map;for(let u=0;u<i.length;u++)s.set(i[u],(s.get(i[u])??0)+1);for(let u=0;u<n.length;u++)a.set(n[u],(a.get(n[u])??0)+1);let o=[],c=[];for(let[u,l]of s){let p=l-(a.get(u)??0);for(let d=0;d<p;d++)o.push(u)}for(let[u,l]of a){let p=l-(s.get(u)??0);for(let d=0;d<p;d++)c.push(u)}if(o.length===0&&c.length===0)return"";let f=[`--- ${r}`,`+++ ${r}`];for(let u=0;u<o.length;u++)f.push(`- ${o[u]}`);for(let u=0;u<c.length;u++)f.push(`+ ${c[u]}`);return f.join(`
132
132
  `)}function Do(e,t,r,i){let n=e.split(`
133
133
  `),s=[];function a(l){let p="",d=l<0?-l<<1|1:l<<1;do{let C=d&31;if(d>>>=5,d>0)C|=32;p+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[C]}while(d>0);return p}let o=0,c=0,f=0,u=i.split(`
134
134
  `).length;for(let l=0;l<n.length;l++){if(n[l].trim()===""){s.push("");continue}o=0;let p=Math.min(l,u-1),d=[],C=0-o,b=0,w=p-c,A=0-f;d.push(a(C)+a(b)+a(w)+a(A)),o=0,c=p,f=0,s.push(d.join(","))}return{version:3,file:t,sourceRoot:"",sources:[r],sourcesContent:[i],mappings:s.join(";")}}function Io(e,t){return`${e}
135
135
  //# sourceMappingURL=${t}
136
- `}var rs=ce(()=>{xi();es();cr()});function Mo(e,t={}){let{lineEnding:r="lf",trailingNewline:i=!0,maxBlankLines:n=1,trimTrailingWhitespace:s=!0,normalizeIndentation:a=!0,indent:o={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,p=e;if(p=Gu(p,r),f?.enabled!==!1)p=zu(p,f||{});if(c)p=Xu(p,c);if(s)p=Uu(p);if(p=Yu(p,n),a)p=qu(p,o);if(i||l)p=Hu(p);return p}function Gu(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
136
+ `}var rs=ce(()=>{xi();es();cr()});function Mo(e,t={}){let{lineEnding:r="lf",trailingNewline:i=!0,maxBlankLines:n=1,trimTrailingWhitespace:s=!0,normalizeIndentation:a=!0,indent:o={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,p=e;if(p=Uu(p,r),f?.enabled!==!1)p=Xu(p,f||{});if(c)p=Qu(p,c);if(s)p=Yu(p);if(p=Hu(p,n),a)p=zu(p,o);if(i||l)p=qu(p);return p}function Uu(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
137
137
  `)!==-1)r=r.replace(/\r\n/g,`
138
138
  `);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
139
139
  `)}if(t==="crlf")r=r.replace(/\n/g,`\r
140
- `);return r}function Uu(e){return e.split(`
140
+ `);return r}function Yu(e){return e.split(`
141
141
  `).map((t)=>t.replace(/[\t ]+$/,"")).join(`
142
- `)}function Yu(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
143
- `.repeat(t+1))}function Hu(e){return`${e.replace(/\s+$/,"")}
144
- `}function qu(e,t){let{style:r="spaces",size:i=2}=t,n=r==="tabs"?"\t":" ".repeat(i),s=e.split(`
142
+ `)}function Hu(e,t){let r=new RegExp(`\\n{${t+2},}`,"g");return e.replace(r,`
143
+ `.repeat(t+1))}function qu(e){return`${e.replace(/\s+$/,"")}
144
+ `}function zu(e,t){let{style:r="spaces",size:i=2}=t,n=r==="tabs"?"\t":" ".repeat(i),s=e.split(`
145
145
  `),a=[];for(let o of s){let c=o.match(/^([\t ]*)(.*)$/);if(!c){a.push(o);continue}let[,f,u]=c;if(!u){a.push("");continue}let l=f.replace(/\t/g," "),p=Math.floor(l.length/2);a.push(n.repeat(p)+u)}return a.join(`
146
- `)}function zu(e,t){let{groups:r=Ju,separateGroups:i=!0,alphabetize:n=!0}=t,s=e.split(`
146
+ `)}function Xu(e,t){let{groups:r=Gu,separateGroups:i=!0,alphabetize:n=!0}=t,s=e.split(`
147
147
  `),a=[],o=[],c=-1;for(let C=0;C<s.length;C++){let b=s[C],w=Lo(b);if(w)a.push({line:b,source:w.source,group:w.group,isType:w.isType}),c=C;else if(a.length>0&&b.trim()==="")continue;else if(a.length>0||b.trim()!==""){if(a.length===0||C>c+1)o.push(b)}}if(a.length===0)return e;let f=new Map;for(let C of r)f.set(C,[]);for(let C of a)(f.get(C.group)||f.get("external")||[]).push(C);if(n)for(let[,C]of f)C.sort((b,w)=>{if(b.isType!==w.isType)return b.isType?1:-1;return b.source.localeCompare(w.source)});let u=[],l=null;for(let C of r){let b=f.get(C)||[];if(b.length===0)continue;if(i&&l!==null)u.push("");for(let w of b)u.push(w.line);l=C}let p=s.slice(0,s.findIndex((C)=>Lo(C)!==null)),d=o;while(d.length>0&&d[0].trim()==="")d.shift();return[...p,...u,"",...d].join(`
148
- `)}function Lo(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let s=t.match(/^import\s+['"]([^'"]+)['"]/);if(s)return{source:s[1],group:jo(s[1]),isType:!1};return null}let i=!!r[1],n=r[2];return{source:n,group:i?"type":jo(n),isType:i}}function jo(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 Xu(e,t){let{kinds:r=Ku,alphabetize:i=!1,groupExports:n=!0}=t,s=e.split(`
149
- `),a=[],o=[],c=[],f=null,u=0,l=!0,p=!1,d=[];for(let w=0;w<s.length;w++){let A=s[w],S=A.trim(),k=u,T=S.startsWith("///"),v=k===0&&!T&&(S.startsWith("//")||S.startsWith("/*"));if(p||v){if(d.push(A),!p&&S.startsWith("/*")&&!S.includes("*/"))p=!0;else if(p&&S.includes("*/"))p=!1;continue}if(k===0&&d.length>0&&S===""){d.push(A);continue}u+=(A.match(/\{/g)||[]).length,u-=(A.match(/\}/g)||[]).length;let M=Qu(S);if(l&&M&&M.kind!=="import"&&!S.startsWith("//")&&!S.startsWith("/*"))l=!1;if(l){if(d.length>0){if(M?.kind==="import"||!M)o.push(...d),d.length=0}o.push(A);continue}if(M&&u<=1){if(f)a.push(f);f={lines:d.length>0?[...d,A]:[A],kind:M.kind,name:M.name,isExport:M.isExport},d.length=0}else if(f)f.lines.push(A);else{if(S==="")continue;c.push(A)}}if(f)a.push(f);if(d.length>0)c.push(...d);a.sort((w,A)=>{if(n&&w.isExport!==A.isExport)return w.isExport?-1:1;let S=r.indexOf(w.kind),k=r.indexOf(A.kind),T=S>=0?S:r.length,v=k>=0?k:r.length;if(T!==v)return T-v;if(i)return w.name.localeCompare(A.name);return 0});let C=[...o],b=null;for(let w of a){if(b!==null&&w.kind!==b)C.push("");C.push(...w.lines),b=w.kind}if(c.length>0)C.push(""),C.push(...c);return C.join(`
150
- `)}function Qu(e){let t=e.startsWith("export "),r=t?e.slice(7):e;if(e.startsWith("import "))return{kind:"import",name:e.match(/from\s+['"]([^'"]+)['"]/)?.[1]||"",isExport:!1};if(r.startsWith("type ")||r.startsWith("declare type "))return{kind:"type",name:r.match(/type\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("interface ")||r.startsWith("declare interface "))return{kind:"interface",name:r.match(/interface\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("class ")||r.startsWith("abstract class ")||r.startsWith("declare class ")||r.startsWith("declare abstract class "))return{kind:"class",name:r.match(/class\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("enum ")||r.startsWith("const enum ")||r.startsWith("declare enum ")||r.startsWith("declare const enum "))return{kind:"enum",name:r.match(/enum\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("function ")||r.startsWith("async function ")||r.startsWith("declare function ")||r.startsWith("declare async function "))return{kind:"function",name:r.match(/function\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("const ")||r.startsWith("let ")||r.startsWith("var ")||r.startsWith("declare const ")||r.startsWith("declare let ")||r.startsWith("declare var "))return{kind:"variable",name:r.match(/(?:const|let|var)\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("namespace ")||r.startsWith("declare namespace "))return{kind:"namespace",name:r.match(/namespace\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("module ")||r.startsWith("declare module "))return{kind:"module",name:r.match(/module\s+['"]?(\w+)['"]?/)?.[1]||"",isExport:t};if(e.startsWith("export {")||e.startsWith("export *")||e.startsWith("export type {"))return{kind:"export",name:"",isExport:!0};return null}var Ku,Ju;var is=ce(()=>{Ku=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],Ju=["builtin","external","scoped","internal","parent","sibling","index","type"]});class Ei{plugins=[];config=null;register(e){if(this.plugins.some((t)=>t.name===e.name))throw Error(`Plugin "${e.name}" is already registered`);this.plugins.push(e)}unregister(e){let t=this.plugins.findIndex((r)=>r.name===e);if(t>=0)return this.plugins.splice(t,1),!0;return!1}getPlugins(){return this.plugins}createLogger(e){return{debug:(t)=>console.debug(`[${e}] ${t}`),info:(t)=>console.info(`[${e}] ${t}`),warn:(t)=>console.warn(`[${e}] ${t}`),error:(t)=>console.error(`[${e}] ${t}`)}}async runOnStart(e){let t=e;for(let r of this.plugins)if(r.onStart){let i=await r.onStart(t);if(i)t=i}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let i of this.plugins)if(i.onBeforeFile){let n={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(i.name)},s=await i.onBeforeFile(n);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let i=r;for(let n of this.plugins)if(n.onDeclarations){let s={filePath:e,sourceCode:t,declarations:i,config:this.config,log:this.createLogger(n.name)},a=await n.onDeclarations(s);if(a)i=a}return i}async runOnAfterFile(e,t,r){let i=r;for(let n of this.plugins)if(n.onAfterFile){let s={filePath:e,sourceCode:t,content:i,config:this.config,log:this.createLogger(n.name)},a=await n.onAfterFile(s);if(typeof a==="string")i=a}return i}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let i of this.plugins)if(i.onError){let n={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(i.name)};await i.onError(e,n)}}}function eh(e){return e}var ip,np;var ns=ce(()=>{ip=new Ei;np=eh({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>{return e.declarations.filter((t)=>{if(t.leadingComments){if(t.leadingComments.some((r)=>r.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})}})});function mt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let i=e[0];if(i.length>0&&i.charCodeAt(0)>32&&i.charCodeAt(i.length-1)>32)return`${i}
148
+ `)}function Lo(e){let t=e.trim(),r=t.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!r){let s=t.match(/^import\s+['"]([^'"]+)['"]/);if(s)return{source:s[1],group:jo(s[1]),isType:!1};return null}let i=!!r[1],n=r[2];return{source:n,group:i?"type":jo(n),isType:i}}function jo(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 Qu(e,t){let{kinds:r=Ju,alphabetize:i=!1,groupExports:n=!0}=t,s=e.split(`
149
+ `),a=[],o=[],c=[],f=null,u=0,l=!0,p=!1,d=[];for(let w=0;w<s.length;w++){let A=s[w],S=A.trim(),k=u,T=S.startsWith("///"),v=k===0&&!T&&(S.startsWith("//")||S.startsWith("/*"));if(p||v){if(d.push(A),!p&&S.startsWith("/*")&&!S.includes("*/"))p=!0;else if(p&&S.includes("*/"))p=!1;continue}if(k===0&&d.length>0&&S===""){d.push(A);continue}u+=(A.match(/\{/g)||[]).length,u-=(A.match(/\}/g)||[]).length;let M=eh(S);if(l&&M&&M.kind!=="import"&&!S.startsWith("//")&&!S.startsWith("/*"))l=!1;if(l){if(d.length>0){if(M?.kind==="import"||!M)o.push(...d),d.length=0}o.push(A);continue}if(M&&u<=1){if(f)a.push(f);f={lines:d.length>0?[...d,A]:[A],kind:M.kind,name:M.name,isExport:M.isExport},d.length=0}else if(f)f.lines.push(A);else{if(S==="")continue;c.push(A)}}if(f)a.push(f);if(d.length>0)c.push(...d);a.sort((w,A)=>{if(n&&w.isExport!==A.isExport)return w.isExport?-1:1;let S=r.indexOf(w.kind),k=r.indexOf(A.kind),T=S>=0?S:r.length,v=k>=0?k:r.length;if(T!==v)return T-v;if(i)return w.name.localeCompare(A.name);return 0});let C=[...o],b=null;for(let w of a){if(b!==null&&w.kind!==b)C.push("");C.push(...w.lines),b=w.kind}if(c.length>0)C.push(""),C.push(...c);return C.join(`
150
+ `)}function eh(e){let t=e.startsWith("export "),r=t?e.slice(7):e;if(e.startsWith("import "))return{kind:"import",name:e.match(/from\s+['"]([^'"]+)['"]/)?.[1]||"",isExport:!1};if(r.startsWith("type ")||r.startsWith("declare type "))return{kind:"type",name:r.match(/type\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("interface ")||r.startsWith("declare interface "))return{kind:"interface",name:r.match(/interface\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("class ")||r.startsWith("abstract class ")||r.startsWith("declare class ")||r.startsWith("declare abstract class "))return{kind:"class",name:r.match(/class\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("enum ")||r.startsWith("const enum ")||r.startsWith("declare enum ")||r.startsWith("declare const enum "))return{kind:"enum",name:r.match(/enum\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("function ")||r.startsWith("async function ")||r.startsWith("declare function ")||r.startsWith("declare async function "))return{kind:"function",name:r.match(/function\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("const ")||r.startsWith("let ")||r.startsWith("var ")||r.startsWith("declare const ")||r.startsWith("declare let ")||r.startsWith("declare var "))return{kind:"variable",name:r.match(/(?:const|let|var)\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("namespace ")||r.startsWith("declare namespace "))return{kind:"namespace",name:r.match(/namespace\s+(\w+)/)?.[1]||"",isExport:t};if(r.startsWith("module ")||r.startsWith("declare module "))return{kind:"module",name:r.match(/module\s+['"]?(\w+)['"]?/)?.[1]||"",isExport:t};if(e.startsWith("export {")||e.startsWith("export *")||e.startsWith("export type {"))return{kind:"export",name:"",isExport:!0};return null}var Ju,Gu;var is=ce(()=>{Ju=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],Gu=["builtin","external","scoped","internal","parent","sibling","index","type"]});class Ei{plugins=[];config=null;register(e){if(this.plugins.some((t)=>t.name===e.name))throw Error(`Plugin "${e.name}" is already registered`);this.plugins.push(e)}unregister(e){let t=this.plugins.findIndex((r)=>r.name===e);if(t>=0)return this.plugins.splice(t,1),!0;return!1}getPlugins(){return this.plugins}createLogger(e){return{debug:(t)=>console.debug(`[${e}] ${t}`),info:(t)=>console.info(`[${e}] ${t}`),warn:(t)=>console.warn(`[${e}] ${t}`),error:(t)=>console.error(`[${e}] ${t}`)}}async runOnStart(e){let t=e;for(let r of this.plugins)if(r.onStart){let i=await r.onStart(t);if(i)t=i}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let i of this.plugins)if(i.onBeforeFile){let n={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(i.name)},s=await i.onBeforeFile(n);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let i=r;for(let n of this.plugins)if(n.onDeclarations){let s={filePath:e,sourceCode:t,declarations:i,config:this.config,log:this.createLogger(n.name)},a=await n.onDeclarations(s);if(a)i=a}return i}async runOnAfterFile(e,t,r){let i=r;for(let n of this.plugins)if(n.onAfterFile){let s={filePath:e,sourceCode:t,content:i,config:this.config,log:this.createLogger(n.name)},a=await n.onAfterFile(s);if(typeof a==="string")i=a}return i}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let i of this.plugins)if(i.onError){let n={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(i.name)};await i.onError(e,n)}}}function th(e){return e}var np,sp;var ns=ce(()=>{np=new Ei;sp=th({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(e)=>{return e.declarations.filter((t)=>{if(t.leadingComments){if(t.leadingComments.some((r)=>r.includes("@internal")))return e.log.debug(`Stripping internal declaration: ${t.name}`),!1}return!0})}})});function mt(e,t=!0){if(!t||!e||e.length===0)return"";if(e.length===1){let i=e[0];if(i.length>0&&i.charCodeAt(0)>32&&i.charCodeAt(i.length-1)>32)return`${i}
151
151
  `;return`${i.trim()}
152
152
  `}let r="";for(let i=0;i<e.length;i++){if(i>0)r+=`
153
153
  `;r+=e[i].trim()}return`${r}
154
- `}var ss=()=>{};function nh(e){let t=[],r=0;for(let i=0;i<=e.length;i++)if(i===e.length||e[i]===`
155
- `){let n=r,s=i;while(n<s&&(e[n]===" "||e[n]==="\t"||e[n]==="\r"))n++;while(s>n&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let a=e.slice(n,s);if(r=i+1,a.startsWith("///")){if(a.indexOf("<")===-1)continue;if(th.test(a)||rh.test(a)||ih.test(a))t.push(a)}else if(a===""||a.startsWith("//"))continue;else break}return t}function sh(e){if(e.includes(`
154
+ `}var ss=()=>{};function sh(e){let t=[],r=0;for(let i=0;i<=e.length;i++)if(i===e.length||e[i]===`
155
+ `){let n=r,s=i;while(n<s&&(e[n]===" "||e[n]==="\t"||e[n]==="\r"))n++;while(s>n&&(e[s-1]===" "||e[s-1]==="\t"||e[s-1]==="\r"))s--;let a=e.slice(n,s);if(r=i+1,a.startsWith("///")){if(a.indexOf("<")===-1)continue;if(rh.test(a)||ih.test(a)||nh.test(a))t.push(a)}else if(a===""||a.startsWith("//"))continue;else break}return t}function ah(e){if(e.includes(`
156
156
  `))return`/**
157
157
  * ${e}
158
158
  */
159
159
  `;return`/** ${e} */
160
- `}function ah(e){let t=e.indexOf("{");if(t===-1)return-1;let r=e.indexOf("<");if(r===-1||r>t)return t;let i=0,n=!1,s="";for(let a=0;a<e.length;a++){let o=e[a],c=a>0?e[a-1]:"";if(!n&&(o==='"'||o==="'"||o==="`"))n=!0,s=o;else if(n&&o===s&&c!=="\\")n=!1;if(!n){if(o==="<")i++;else if(o===">")i--;else if(o==="{"&&i===0)return a}}return-1}function oh(e,t=!0){return mt(e.leadingComments,t)+e.text}function lh(e,t=!0){let r=mt(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return r+e.text;let i="";if(e.isExported)i+="export ";i+="declare ";let n=e.modifiers?.[0]||"const";i+=`${n} `,i+=e.name;let{typeAnnotation:s,value:a}=e;if(a&&a.includes(" satisfies ")){let c=Is(a);if(c)s=c}else if(!s&&a&&a.trim().endsWith("as const"))s=Ae(a,!0);else if(!s&&a&&n==="const"){let c=a.trim(),f=c.startsWith("{")||c.startsWith("[");if(f)Gi();s=Ae(a,!f)}else if(!s&&a)s=Ae(a,n==="const");if(!s)s="unknown";let o="";if(t&&a&&!e.typeAnnotation&&!a.trim().endsWith("as const")){let c=a.trim();if(n!=="const"){if((s==="string"||s==="number"||s==="boolean")&&c.length>0)o=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let f=Ui();if(f)if(f.includes(`
160
+ `}function oh(e){let t=e.indexOf("{");if(t===-1)return-1;let r=e.indexOf("<");if(r===-1||r>t)return t;let i=0,n=!1,s="";for(let a=0;a<e.length;a++){let o=e[a],c=a>0?e[a-1]:"";if(!n&&(o==='"'||o==="'"||o==="`"))n=!0,s=o;else if(n&&o===s&&c!=="\\")n=!1;if(!n){if(o==="<")i++;else if(o===">")i--;else if(o==="{"&&i===0)return a}}return-1}function lh(e,t=!0){return mt(e.leadingComments,t)+e.text}function ch(e,t=!0){let r=mt(e.leadingComments,t);if(e.typeAnnotation&&!e.value)return r+e.text;let i="";if(e.isExported)i+="export ";i+="declare ";let n=e.modifiers?.[0]||"const";i+=`${n} `,i+=e.name;let{typeAnnotation:s,value:a}=e;if(a&&a.includes(" satisfies ")){let c=Is(a);if(c)s=c}else if(!s&&a&&a.trim().endsWith("as const"))s=Ae(a,!0);else if(!s&&a&&n==="const"){let c=a.trim(),f=c.startsWith("{")||c.startsWith("[");if(f)Gi();s=Ae(a,!f)}else if(!s&&a)s=Ae(a,n==="const");if(!s)s="unknown";let o="";if(t&&a&&!e.typeAnnotation&&!a.trim().endsWith("as const")){let c=a.trim();if(n!=="const"){if((s==="string"||s==="number"||s==="boolean")&&c.length>0)o=`@defaultValue ${c}`}else if(c.startsWith("{")||c.startsWith("[")){let f=Ui();if(f)if(f.includes(`
161
161
  `))o=`@defaultValue
162
162
  * \`\`\`ts
163
163
  ${f.split(`
@@ -178,19 +178,19 @@ ${u.split(`
178
178
  * ${c.replace(/^\/\/\s*/,"")}
179
179
  * ${o}
180
180
  */
181
- ${i}`}if(o)return`${sh(o)}${i}`;return r+i}function ch(e,t=!0){let r=mt(e.leadingComments,t),i=e.text;if(i.startsWith("export declare interface")||i.startsWith("declare interface"))return r+i;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 s=ah(e.text);if(s!==-1)n+=` ${e.text.slice(s)}`;else n+=" {}";return r+n}function fh(e,t=!0){let r=mt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let i="";if(e.isExported)i+="export ";if(!e.isExported&&!e.text.includes(" from "))i+="declare ";let n=e.text.indexOf("type ");if(n!==-1){let a=e.text.slice(n),o=a.length;while(o>0&&(a.charCodeAt(o-1)===59||a.charCodeAt(o-1)===32||a.charCodeAt(o-1)===10||a.charCodeAt(o-1)===13))o--;if(o<a.length)a=a.slice(0,o);i+=a}else{if(i+=`type ${e.name}`,e.generics)i+=e.generics;i+=" = any"}let s=i.trimEnd();if(!s.endsWith(";")&&!s.endsWith("}"))i+=";";return r+i}function uh(e,t=!0){return mt(e.leadingComments,t)+e.text}function hh(e,t=!0){let r=mt(e.leadingComments,t),i="";if(e.isExported)i+="export ";if(i+="declare ",e.modifiers?.includes("const"))i+="const ";i+="enum ",i+=e.name;let n=e.text.indexOf("{");if(n!==-1)i+=` ${e.text.slice(n)}`;else i+=" {}";return r+i}function dh(e,t=!0){let r=mt(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let s="declare module ";s+=e.name;let a=e.text.indexOf("{");if(a!==-1)s+=` ${e.text.slice(a)}`;else s+=" {}";return r+s}let i="";if(e.isExported)i+="export ";if(!e.modifiers?.includes("declare"))i+="declare ";i+="namespace ",i+=e.name;let n=e.text.indexOf("{");if(n!==-1)i+=` ${e.text.slice(n)}`;else i+=" {}";return r+i}function mh(e){let t=kt.get(e);if(t)return kt.delete(e),kt.set(e,t),t;return null}function Bo(e,t){if(kt.set(e,t),kt.size>200){let r=0;for(let i of kt.keys()){if(r++>=20)break;kt.delete(i)}}}function gh(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),i=r[0];if(i!=='"'&&i!=="'")return null;let n=r.indexOf(i,1);if(n===-1)return null;let s=r.slice(1,n),a=e.slice(0,t).trim(),o=a.startsWith("import type ");if(a.startsWith("import "))a=a.slice(7).trim();if(a.startsWith("type "))a=a.slice(5).trim();let c=null,f=[],u=!1,l=a.indexOf("{"),p=a.lastIndexOf("}");if(l!==-1&&p!==-1){let d=a.slice(0,l).trim();if(d.endsWith(","))c=d.slice(0,-1).trim()||null;let C=a.slice(l+1,p),b=0;for(let w=0;w<=C.length;w++)if(w===C.length||C.charCodeAt(w)===44){let A=b,S=w;while(A<S&&(C.charCodeAt(A)===32||C.charCodeAt(A)===9||C.charCodeAt(A)===10))A++;while(S>A&&(C.charCodeAt(S-1)===32||C.charCodeAt(S-1)===9||C.charCodeAt(S-1)===10))S--;if(A<S)f.push(C.slice(A,S));b=w+1}}else{let d=a.trim();if(d.startsWith("* as "))c=d.slice(5).trim()||null,u=!0;else c=d||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:o,isNamespace:u}}function ph(e){let t=mh(e);if(t)return t;let r=[],i=e.indexOf(" from ");if(i===-1)return Bo(e,r),r;let n=e.slice(0,i).trim();if(n.startsWith("import "))n=n.slice(7).trim();if(n.startsWith("type "))n=n.slice(5).trim();let s=n.indexOf("{"),a=n.lastIndexOf("}");if(s!==-1&&a!==-1){let o=n.slice(0,s).trim();if(o.endsWith(",")){let f=o.slice(0,-1).trim();if(f)r.push(f)}else if(o&&!o.includes(","))r.push(o);let c=n.slice(s+1,a).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let l=u.indexOf(" as ");if(l!==-1)u=u.slice(l+4).trim();if(u)r.push(u)}}else{let o=n.trim();if(o.startsWith("* as ")){let c=o.slice(5).trim();if(c)r.push(c)}else if(o)r.push(o)}return Bo(e,r),r}function _o(e,t){throw Error(t||`Unexpected value: ${e}`)}function yh(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Zo(e){let t=new Set,r=0,i=e.length;while(r<i){let n=e.charCodeAt(r);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let s=r;r++;while(r<i&&yh(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function as(e,t,r=!0,i=["bun"]){let n="",s=t.sourceCode;if(s){let F=0;while(F<s.length&&(s.charCodeAt(F)===32||s.charCodeAt(F)===9||s.charCodeAt(F)===10||s.charCodeAt(F)===13))F++;if(F<s.length-2&&s.charCodeAt(F)===47&&s.charCodeAt(F+1)===47&&s.charCodeAt(F+2)===47){let K=nh(s);if(K.length>0)for(let q=0;q<K.length;q++){if(n)n+=`
182
- `;n+=K[q]}}}let a=[],o=[],c=[],f=[],u=[],l=[],p=[],d=[],C=[];for(let F of e){let K=F.kind;switch(K){case"import":a.push(F);break;case"function":o.push(F);break;case"variable":c.push(F);break;case"interface":f.push(F);break;case"type":u.push(F);break;case"class":l.push(F);break;case"enum":p.push(F);break;case"module":d.push(F);break;case"export":C.push(F);break;case"namespace":d.push(F);break;case"unknown":break;default:_o(K,`Unhandled declaration kind: ${K}`)}}let b=new Set,w=[],A=[],S=[],k=new Set;for(let F of C){let K=mt(F.leadingComments,r);if(F.text.startsWith("export default")){let q=F.text.endsWith(";")?F.text:`${F.text};`;S.push(K+q)}else{let q=F.text.trim();if(!q.endsWith(";"))q+=";";let ne=q.match(wh);if(ne){let H=ne[1],G=0;for(let J=0;J<=H.length;J++)if(J===H.length||H.charCodeAt(J)===44){let ye=G,X=J;while(ye<X&&H.charCodeAt(ye)<=32)ye++;while(X>ye&&H.charCodeAt(X-1)<=32)X--;if(ye<X)b.add(H.slice(ye,X));G=J+1}}let V=K+q;if(!k.has(V))if(k.add(V),V.includes("export type"))w.push(V);else A.push(V)}}let T=new Map;if(a.length>0)for(let F of a){let K=ph(F.text);for(let q of K)T.set(q,F)}let v=new Set;if(f.length>0){let F=[];for(let K of o)if(K.isExported)F.push(K.text);for(let K of l)F.push(K.text);for(let K of u)F.push(K.text);if(F.length>0){let K=Zo(F.join(`
181
+ ${i}`}if(o)return`${ah(o)}${i}`;return r+i}function fh(e,t=!0){let r=mt(e.leadingComments,t),i=e.text;if(i.startsWith("export declare interface")||i.startsWith("declare interface"))return r+i;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 s=oh(e.text);if(s!==-1)n+=` ${e.text.slice(s)}`;else n+=" {}";return r+n}function uh(e,t=!0){let r=mt(e.leadingComments,t);if(e.text.includes("{")&&e.text.includes("}")&&e.text.includes("from"))return r+e.text;let i="";if(e.isExported)i+="export ";if(!e.isExported&&!e.text.includes(" from "))i+="declare ";let n=e.text.indexOf("type ");if(n!==-1){let a=e.text.slice(n),o=a.length;while(o>0&&(a.charCodeAt(o-1)===59||a.charCodeAt(o-1)===32||a.charCodeAt(o-1)===10||a.charCodeAt(o-1)===13))o--;if(o<a.length)a=a.slice(0,o);i+=a}else{if(i+=`type ${e.name}`,e.generics)i+=e.generics;i+=" = any"}let s=i.trimEnd();if(!s.endsWith(";")&&!s.endsWith("}"))i+=";";return r+i}function hh(e,t=!0){return mt(e.leadingComments,t)+e.text}function dh(e,t=!0){let r=mt(e.leadingComments,t),i="";if(e.isExported)i+="export ";if(i+="declare ",e.modifiers?.includes("const"))i+="const ";i+="enum ",i+=e.name;let n=e.text.indexOf("{");if(n!==-1)i+=` ${e.text.slice(n)}`;else i+=" {}";return r+i}function mh(e,t=!0){let r=mt(e.leadingComments,t);if(e.text.startsWith("declare global"))return r+e.text;if(e.source||(e.name.startsWith('"')||e.name.startsWith("'")||e.name.startsWith("`"))){let s="declare module ";s+=e.name;let a=e.text.indexOf("{");if(a!==-1)s+=` ${e.text.slice(a)}`;else s+=" {}";return r+s}let i="";if(e.isExported)i+="export ";if(!e.modifiers?.includes("declare"))i+="declare ";i+="namespace ",i+=e.name;let n=e.text.indexOf("{");if(n!==-1)i+=` ${e.text.slice(n)}`;else i+=" {}";return r+i}function gh(e){let t=kt.get(e);if(t)return kt.delete(e),kt.set(e,t),t;return null}function Bo(e,t){if(kt.set(e,t),kt.size>200){let r=0;for(let i of kt.keys()){if(r++>=20)break;kt.delete(i)}}}function ph(e){let t=e.indexOf(" from ");if(t===-1)return null;let r=e.slice(t+6).trim(),i=r[0];if(i!=='"'&&i!=="'")return null;let n=r.indexOf(i,1);if(n===-1)return null;let s=r.slice(1,n),a=e.slice(0,t).trim(),o=a.startsWith("import type ");if(a.startsWith("import "))a=a.slice(7).trim();if(a.startsWith("type "))a=a.slice(5).trim();let c=null,f=[],u=!1,l=a.indexOf("{"),p=a.lastIndexOf("}");if(l!==-1&&p!==-1){let d=a.slice(0,l).trim();if(d.endsWith(","))c=d.slice(0,-1).trim()||null;let C=a.slice(l+1,p),b=0;for(let w=0;w<=C.length;w++)if(w===C.length||C.charCodeAt(w)===44){let A=b,S=w;while(A<S&&(C.charCodeAt(A)===32||C.charCodeAt(A)===9||C.charCodeAt(A)===10))A++;while(S>A&&(C.charCodeAt(S-1)===32||C.charCodeAt(S-1)===9||C.charCodeAt(S-1)===10))S--;if(A<S)f.push(C.slice(A,S));b=w+1}}else{let d=a.trim();if(d.startsWith("* as "))c=d.slice(5).trim()||null,u=!0;else c=d||null}return{defaultName:c,namedItems:f,source:s,isTypeOnly:o,isNamespace:u}}function yh(e){let t=gh(e);if(t)return t;let r=[],i=e.indexOf(" from ");if(i===-1)return Bo(e,r),r;let n=e.slice(0,i).trim();if(n.startsWith("import "))n=n.slice(7).trim();if(n.startsWith("type "))n=n.slice(5).trim();let s=n.indexOf("{"),a=n.lastIndexOf("}");if(s!==-1&&a!==-1){let o=n.slice(0,s).trim();if(o.endsWith(",")){let f=o.slice(0,-1).trim();if(f)r.push(f)}else if(o&&!o.includes(","))r.push(o);let c=n.slice(s+1,a).split(",");for(let f=0;f<c.length;f++){let u=c[f].trim();if(!u)continue;if(u.startsWith("type "))u=u.slice(5).trim();let l=u.indexOf(" as ");if(l!==-1)u=u.slice(l+4).trim();if(u)r.push(u)}}else{let o=n.trim();if(o.startsWith("* as ")){let c=o.slice(5).trim();if(c)r.push(c)}else if(o)r.push(o)}return Bo(e,r),r}function _o(e,t){throw Error(t||`Unexpected value: ${e}`)}function wh(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===36||e>127}function Zo(e){let t=new Set,r=0,i=e.length;while(r<i){let n=e.charCodeAt(r);if(n>=65&&n<=90||n>=97&&n<=122||n===95||n===36||n>127){let s=r;r++;while(r<i&&wh(e.charCodeAt(r)))r++;t.add(e.substring(s,r))}else r++}return t}function as(e,t,r=!0,i=["bun"]){let n="",s=t.sourceCode;if(s){let F=0;while(F<s.length&&(s.charCodeAt(F)===32||s.charCodeAt(F)===9||s.charCodeAt(F)===10||s.charCodeAt(F)===13))F++;if(F<s.length-2&&s.charCodeAt(F)===47&&s.charCodeAt(F+1)===47&&s.charCodeAt(F+2)===47){let K=sh(s);if(K.length>0)for(let q=0;q<K.length;q++){if(n)n+=`
182
+ `;n+=K[q]}}}let a=[],o=[],c=[],f=[],u=[],l=[],p=[],d=[],C=[];for(let F of e){let K=F.kind;switch(K){case"import":a.push(F);break;case"function":o.push(F);break;case"variable":c.push(F);break;case"interface":f.push(F);break;case"type":u.push(F);break;case"class":l.push(F);break;case"enum":p.push(F);break;case"module":d.push(F);break;case"export":C.push(F);break;case"namespace":d.push(F);break;case"unknown":break;default:_o(K,`Unhandled declaration kind: ${K}`)}}let b=new Set,w=[],A=[],S=[],k=new Set;for(let F of C){let K=mt(F.leadingComments,r);if(F.text.startsWith("export default")){let q=F.text.endsWith(";")?F.text:`${F.text};`;S.push(K+q)}else{let q=F.text.trim();if(!q.endsWith(";"))q+=";";let ne=q.match($h);if(ne){let H=ne[1],G=0;for(let J=0;J<=H.length;J++)if(J===H.length||H.charCodeAt(J)===44){let ye=G,X=J;while(ye<X&&H.charCodeAt(ye)<=32)ye++;while(X>ye&&H.charCodeAt(X-1)<=32)X--;if(ye<X)b.add(H.slice(ye,X));G=J+1}}let V=K+q;if(!k.has(V))if(k.add(V),V.includes("export type"))w.push(V);else A.push(V)}}let T=new Map;if(a.length>0)for(let F of a){let K=yh(F.text);for(let q of K)T.set(q,F)}let v=new Set;if(f.length>0){let F=[];for(let K of o)if(K.isExported)F.push(K.text);for(let K of l)F.push(K.text);for(let K of u)F.push(K.text);if(F.length>0){let K=Zo(F.join(`
183
183
  `));for(let q of f)if(K.has(q.name))v.add(q.name)}}let M=[];if(a.length>0){let F=new Set,K=[];for(let V of o)if(V.isExported)K.push(V.text);for(let V of c)if(K.push(V.text),V.typeAnnotation)K.push(V.typeAnnotation);for(let V of f)if(V.isExported||v.has(V.name))K.push(V.text);for(let V of u)K.push(V.text);for(let V of l)K.push(V.text);for(let V of p)K.push(V.text);for(let V of d)K.push(V.text);for(let V of C)K.push(V.text);let q=K.join(`
184
- `);if(q&&T.size>0){let V=Zo(q);for(let H of T.keys())if(V.has(H))F.add(H)}for(let V of b)if(T.has(V))F.add(V);for(let V of a){if(V.isSideEffect){let le=V.text.trim(),nt=le.endsWith(";")?le:`${le};`;M.push(nt);continue}let H=gh(V.text);if(!H)continue;let{defaultName:G,namedItems:J,source:ye,isTypeOnly:X,isNamespace:ie}=H,er=G?F.has(G):!1,xt="",et=0;for(let le=0;le<J.length;le++){let nt=J[le],gt=nt.charCodeAt(0)===116&&nt.startsWith("type ")?nt.slice(5).trim():nt.trim(),tr=gt.indexOf(" as ");if(tr!==-1)gt=gt.slice(tr+4).trim();if(F.has(gt)){if(et>0)xt+=", ";xt+=nt,et++}}if(er||et>0){let le=X?"import type ":"import ";if(er&&G)if(ie)le+=`* as ${G}`;else le+=et>0?`${G}, { ${xt} }`:G;else if(et>0)le+=`{ ${xt} }`;le+=` from '${ye}';`,M.push(le)}}let ne=i.length;if(M.length>1){if(Vo!==i)Vo=i,Ko=i.map((J)=>`from '${J}`),Jo=i.map((J)=>`from "${J}`);let V=Ko,H=Jo,G=new Map;for(let J of M){let ye=ne;for(let X=0;X<i.length;X++)if(J.includes(V[X])||J.includes(H[X])){ye=X;break}G.set(J,ye)}M.sort((J,ye)=>{let X=G.get(J),ie=G.get(ye);return X!==ie?X-ie:J.localeCompare(ye)})}}for(let F=0;F<M.length;F++){if(n)n+=`
184
+ `);if(q&&T.size>0){let V=Zo(q);for(let H of T.keys())if(V.has(H))F.add(H)}for(let V of b)if(T.has(V))F.add(V);for(let V of a){if(V.isSideEffect){let le=V.text.trim(),nt=le.endsWith(";")?le:`${le};`;M.push(nt);continue}let H=ph(V.text);if(!H)continue;let{defaultName:G,namedItems:J,source:ye,isTypeOnly:X,isNamespace:ie}=H,er=G?F.has(G):!1,xt="",tt=0;for(let le=0;le<J.length;le++){let nt=J[le],gt=nt.charCodeAt(0)===116&&nt.startsWith("type ")?nt.slice(5).trim():nt.trim(),tr=gt.indexOf(" as ");if(tr!==-1)gt=gt.slice(tr+4).trim();if(F.has(gt)){if(tt>0)xt+=", ";xt+=nt,tt++}}if(er||tt>0){let le=X?"import type ":"import ";if(er&&G)if(ie)le+=`* as ${G}`;else le+=tt>0?`${G}, { ${xt} }`:G;else if(tt>0)le+=`{ ${xt} }`;le+=` from '${ye}';`,M.push(le)}}let ne=i.length;if(M.length>1){if(Vo!==i)Vo=i,Ko=i.map((J)=>`from '${J}`),Jo=i.map((J)=>`from "${J}`);let V=Ko,H=Jo,G=new Map;for(let J of M){let ye=ne;for(let X=0;X<i.length;X++)if(J.includes(V[X])||J.includes(H[X])){ye=X;break}G.set(J,ye)}M.sort((J,ye)=>{let X=G.get(J),ie=G.get(ye);return X!==ie?X-ie:J.localeCompare(ye)})}}for(let F=0;F<M.length;F++){if(n)n+=`
185
185
  `;n+=M[F]}for(let F=0;F<w.length;F++){if(n)n+=`
186
- `;n+=w[F]}let te=[o,c,f,u,l,p,d];for(let F=0;F<te.length;F++){let K=te[F];for(let q=0;q<K.length;q++){let ne=K[q],V="",H=ne.kind;switch(H){case"function":V=oh(ne,r);break;case"variable":V=lh(ne,r);break;case"interface":V=ch(ne,r);break;case"type":V=fh(ne,r);break;case"class":V=uh(ne,r);break;case"enum":V=hh(ne,r);break;case"module":case"namespace":V=dh(ne,r);break;case"import":case"export":case"unknown":break;default:_o(H,`Unhandled declaration kind in processor: ${H}`)}if(V){if(n)n+=`
186
+ `;n+=w[F]}let te=[o,c,f,u,l,p,d];for(let F=0;F<te.length;F++){let K=te[F];for(let q=0;q<K.length;q++){let ne=K[q],V="",H=ne.kind;switch(H){case"function":V=lh(ne,r);break;case"variable":V=ch(ne,r);break;case"interface":V=fh(ne,r);break;case"type":V=uh(ne,r);break;case"class":V=hh(ne,r);break;case"enum":V=dh(ne,r);break;case"module":case"namespace":V=mh(ne,r);break;case"import":case"export":case"unknown":break;default:_o(H,`Unhandled declaration kind in processor: ${H}`)}if(V){if(n)n+=`
187
187
  `;n+=V}}}for(let F=0;F<A.length;F++){if(n)n+=`
188
188
  `;n+=A[F]}for(let F=0;F<S.length;F++){if(n)n+=`
189
- `;n+=S[F]}if(!n&&(a.length>0||C.length>0))return"export {};";return n}var th,rh,ih,kt,wh,Vo=null,Ko,Jo;var Oi=ce(()=>{ss();Er();th=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,rh=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,ih=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;kt=new Map;wh=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Ko=[],Jo=[]});import{mkdir as os,readdir as $h,realpath as Ch,rm as vh}from"fs/promises";import{availableParallelism as bh}from"os";import{basename as Ho,dirname as yr,extname as Ah,isAbsolute as fs,parse as xh,relative as Ne,resolve as ze}from"path";async function Go(e,t,r,i,n){let s=Ho(e)||"output.d.ts",a=Ne(yr(e),t),o=`${s}.map`,c=r.lastIndexOf(`
190
- //# sourceMappingURL=`),f=c===-1?r:r.slice(0,c),u=Do(f,s,a,i),l=`${e}.map`;return await gr(l,JSON.stringify(u)),Z.debug(` Generated source map: ${Ne(n,l)}`),o}async function ki(e){let t=Date.now(),r={...Qn,...e};if(r.logLevel)un(r.logLevel);else if(r.verbose)un("debug");let i=new Ei;if(r.plugins&&r.plugins.length>0){for(let w of r.plugins)i.register(w),Z.debug(`Registered plugin: ${w.name}`);r=await i.runOnStart(r)}if(await Oh(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await Wo(r);let n=r.typeMappings?Dr(r.typeMappings):void 0,s=null;if(r.incremental){if(s=new nn(r),r.clearCache){if(Z.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let w=s.getStats();Z.debug(`Loaded build cache with ${w.entries} entries`)}else Z.debug("No existing build cache found, starting fresh");if(!r.dryRun)Ys(r.cwd)}let a={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},o=0;if(Z.debug("Starting DTS generation..."),Z.debug(`Using ${a.generationMode} declaration generation path`),Z.debug("Config:",r),r.clean&&!r.dryRun)await kh(r);let c=await Th(r),f=c.slice(),u=null;if(r.autoIncludeReExports!==!1&&f.length>0){u=await cn(f,{includeImports:!0});let w=ze(r.cwd,r.root),A=r.exclude||[],S=[];for(let k of u.reachable){if(f.includes(k))continue;if(!cs(k))continue;if(k.endsWith(".d.ts"))continue;if(k.includes("node_modules"))continue;if(!Si(k,w)){Z.warn(`Skipping auto-included source outside root: ${Ne(r.cwd,k)}`);continue}if(ls(k,A,w))continue;S.push(k)}if(S.length>0)f=[...f,...S],Z.debug(`Auto-included ${S.length} file(s) reached via relative re-exports`)}if(Rh(f,r),s&&!r.dryRun){let w=s.prune(new Set(f),r.cwd);if(w>0)Z.debug(`Pruned ${w} deleted files from cache`)}if(Z.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let w=r.parallel?"parallel":"sequential";Z.info(`Processing ${f.length} files (${w})...`)}let l=async(w,A)=>{let S;try{let k=wr(w,r),T=async(H)=>{if(!r.diff)return;try{let G=await at(k),J=Fo(G,H,Ne(r.cwd,k));if(J)Z.info(`
189
+ `;n+=S[F]}if(!n&&(a.length>0||C.length>0))return"export {};";return n}var rh,ih,nh,kt,$h,Vo=null,Ko,Jo;var Oi=ce(()=>{ss();Er();rh=/^\/\/\/\s*<reference\s+(?:path|types|lib|no-default-lib)\s*=\s*["'][^"']+["']\s*\/>/,ih=/^\/\/\/\s*<amd-module\s+name\s*=\s*["'][^"']+["']\s*\/>/,nh=/^\/\/\/\s*<amd-dependency\s+path\s*=\s*["'][^"']+["']/;kt=new Map;$h=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/,Ko=[],Jo=[]});import{mkdir as os,readdir as Ch,realpath as vh,rm as bh}from"fs/promises";import{availableParallelism as Ah}from"os";import{basename as Ho,dirname as yr,extname as xh,isAbsolute as fs,parse as Eh,relative as Ne,resolve as ze}from"path";async function Go(e,t,r,i,n){let s=Ho(e)||"output.d.ts",a=Ne(yr(e),t),o=`${s}.map`,c=r.lastIndexOf(`
190
+ //# sourceMappingURL=`),f=c===-1?r:r.slice(0,c),u=Do(f,s,a,i),l=`${e}.map`;return await gr(l,JSON.stringify(u)),Z.debug(` Generated source map: ${Ne(n,l)}`),o}async function ki(e){let t=Date.now(),r={...Qn,...e};if(r.logLevel)un(r.logLevel);else if(r.verbose)un("debug");let i=new Ei;if(r.plugins&&r.plugins.length>0){for(let w of r.plugins)i.register(w),Z.debug(`Registered plugin: ${w.name}`);r=await i.runOnStart(r)}if(await Sh(r),r.isolatedDeclarations===void 0)r.isolatedDeclarations=await Wo(r);let n=r.typeMappings?Dr(r.typeMappings):void 0,s=null;if(r.incremental){if(s=new nn(r),r.clearCache){if(Z.debug("Clearing build cache..."),!r.dryRun)s.clear()}else if(s.load()){let w=s.getStats();Z.debug(`Loaded build cache with ${w.entries} entries`)}else Z.debug("No existing build cache found, starting fresh");if(!r.dryRun)Ys(r.cwd)}let a={generationMode:r.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},o=0;if(Z.debug("Starting DTS generation..."),Z.debug(`Using ${a.generationMode} declaration generation path`),Z.debug("Config:",r),r.clean&&!r.dryRun)await Th(r);let c=await Rh(r),f=c.slice(),u=null;if(r.autoIncludeReExports!==!1&&f.length>0){u=await cn(f,{includeImports:!0});let w=ze(r.cwd,r.root),A=r.exclude||[],S=[];for(let k of u.reachable){if(f.includes(k))continue;if(!cs(k))continue;if(k.endsWith(".d.ts"))continue;if(k.includes("node_modules"))continue;if(!Si(k,w)){Z.warn(`Skipping auto-included source outside root: ${Ne(r.cwd,k)}`);continue}if(ls(k,A,w))continue;S.push(k)}if(S.length>0)f=[...f,...S],Z.debug(`Auto-included ${S.length} file(s) reached via relative re-exports`)}if(Nh(f,r),s&&!r.dryRun){let w=s.prune(new Set(f),r.cwd);if(w>0)Z.debug(`Pruned ${w} deleted files from cache`)}if(Z.debug(`Found ${f.length} TypeScript files`),r.progress&&f.length>0){let w=r.parallel?"parallel":"sequential";Z.info(`Processing ${f.length} files (${w})...`)}let l=async(w,A)=>{let S;try{let k=wr(w,r),T=async(H)=>{if(!r.diff)return;try{let G=await at(k),J=Fo(G,H,Ne(r.cwd,k));if(J)Z.info(`
191
191
  ${J}`);else Z.debug(`[no changes] ${k}`)}catch{Z.info(`[new file] ${Ne(r.cwd,k)}`)}},v=(H)=>{if(!r.validate)return 0;let G=Po(H,k);if(G.isValid)return Z.debug(`[validation] ${k} - OK`),0;Z.warn(`[validation] ${Ne(r.cwd,k)} has ${G.errors.length} error(s):`);for(let J of G.errors){let ye=` Line ${J.line}:${J.column}`;if(J.code)ye+=` [${J.code}]`;if(ye+=` - ${J.message}`,Z.warn(ye),J.suggestion)Z.warn(` Suggestion: ${J.suggestion}`)}return G.errors.length},M=(H)=>{Z.info(`[dry-run] Would generate: ${k}`),Z.debug("--- Content preview ---"),Z.debug(H.slice(0,500)+(H.length>500?`
192
- ...`:"")),Z.debug("--- End preview ---")};if(s){let H=s.getCachedIfValid(w,r.cwd);if(H){await T(H);let G=v(H);if(r.dryRun)M(H);else{if(await os(yr(k),{recursive:!0}),r.declarationMap)S=A??await at(w),await Go(k,w,H,S,r.cwd);await gr(k,H,r.lineEnding)}return Z.debug(`[cached] ${Ne(r.cwd,k)}`),{success:!0,file:w,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:G}}}S=A??await at(w);let{content:te,declarationCount:F,importCount:K,exportCount:q}=await Ph(w,S,r,i,n),ne=te;if(r.prettier||r.indentStyle||r.indentSize){let H=await Es(ne,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},k);ne=H.content;for(let G of H.warnings??[])Z.warn(`[format] ${G}`)}if(r.declarationMap){let H=`${Ho(k)||"output.d.ts"}.map`;ne=Io(ne,H)}await T(ne);let V=v(ne);if(r.dryRun)M(ne);else{if(await os(yr(k),{recursive:!0}),r.declarationMap&&S)await Go(k,w,ne,S,r.cwd);if(await gr(k,ne,r.lineEnding),s&&S)s.update(w,S,ne,r.cwd);Z.debug(`Generated: ${k}`)}return{success:!0,file:w,declarationCount:F,importCount:K,exportCount:q,validationErrorCount:V}}catch(k){let T=As(k,w,S);if(r.plugins&&r.plugins.length>0)await i.runOnError(k instanceof Error?k:Error(String(k)),w,S||"");return{success:!1,file:w,declarationCount:0,importCount:0,exportCount:0,dtsError:T,validationErrorCount:0}}},p=r.parallel||r.parallel!==!1&&f.length>=10,d=Rr(r.concurrency,bh?.()??8),C=new Map;if(p&&f.length>1){let w=f.map(async(A)=>{try{let S=await at(A);return{file:A,source:S}}catch{return{file:A,source:null}}});for(let A of await Promise.all(w))if(A.source!==null)C.set(A.file,A.source)}let b=(w)=>{if(a.filesProcessed++,w.success){if(w.cached)o++;else a.filesGenerated++,a.declarationsFound+=w.declarationCount,a.importsProcessed+=w.importCount,a.exportsProcessed+=w.exportCount;if(r.validate){if(a.filesValidated++,w.validationErrorCount)a.validationErrors+=w.validationErrorCount}}else if(a.filesFailed++,w.dtsError){a.errors.push(w.dtsError);let A=xs(w.dtsError);if(r.continueOnError)Z.warn(A);else throw Z.error(A),Error(w.dtsError.message)}};if(p)for(let w=0;w<f.length;w+=d){let A=f.slice(w,w+d),S=await Promise.all(A.map((k)=>l(k,C.get(k))));for(let k of S)b(k);if(r.progress){let k=Math.round(a.filesProcessed/f.length*100);Z.info(`[${a.filesProcessed}/${f.length}] ${k}%`)}}else for(let w of f){let A=await l(w);if(b(A),r.progress){let S=Math.round(a.filesProcessed/f.length*100),k=A.cached?"[cached]":"";Z.info(`[${a.filesProcessed}/${f.length}] ${S}% - ${Ne(r.cwd,w)} ${k}`)}}if(s&&!r.dryRun)s.save(),Z.debug("Saved build cache");if(!r.bundle){let w=[];if(u)for(let A of u.unresolved)w.push({from:A.from,specifier:A.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let A=new Set(f);for(let S of f){let k;try{k=await at(S)}catch{continue}for(let T of ln(k)){if(!T.specifier.startsWith("."))continue;let v=jr(T.specifier,S);if(!v.resolved)w.push({from:S,specifier:T.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(v.resolved)&&!A.has(v.resolved))w.push({from:S,specifier:T.specifier,reason:"not-emitted"})}}}if(w.length>0){let A=[];A.push(`Found ${w.length} re-export(s) pointing at siblings that won't be in the output:`);for(let k of w){let T=Ne(r.cwd,k.from);if(k.reason==="missing")A.push(` ${T} \u2192 '${k.specifier}' (path not found on disk)`);else A.push(` ${T} \u2192 '${k.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let S=A.join(`
192
+ ...`:"")),Z.debug("--- End preview ---")};if(s){let H=s.getCachedIfValid(w,r.cwd);if(H){await T(H);let G=v(H);if(r.dryRun)M(H);else{if(await os(yr(k),{recursive:!0}),r.declarationMap)S=A??await at(w),await Go(k,w,H,S,r.cwd);await gr(k,H,r.lineEnding)}return Z.debug(`[cached] ${Ne(r.cwd,k)}`),{success:!0,file:w,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:G}}}S=A??await at(w);let{content:te,declarationCount:F,importCount:K,exportCount:q}=await Fh(w,S,r,i,n),ne=te;if(r.prettier||r.indentStyle||r.indentSize){let H=await Es(ne,{usePrettier:r.prettier,builtIn:{indentSize:r.indentSize||2,useTabs:r.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},k);ne=H.content;for(let G of H.warnings??[])Z.warn(`[format] ${G}`)}if(r.declarationMap){let H=`${Ho(k)||"output.d.ts"}.map`;ne=Io(ne,H)}await T(ne);let V=v(ne);if(r.dryRun)M(ne);else{if(await os(yr(k),{recursive:!0}),r.declarationMap&&S)await Go(k,w,ne,S,r.cwd);if(await gr(k,ne,r.lineEnding),s&&S)s.update(w,S,ne,r.cwd);Z.debug(`Generated: ${k}`)}return{success:!0,file:w,declarationCount:F,importCount:K,exportCount:q,validationErrorCount:V}}catch(k){let T=As(k,w,S);if(r.plugins&&r.plugins.length>0)await i.runOnError(k instanceof Error?k:Error(String(k)),w,S||"");return{success:!1,file:w,declarationCount:0,importCount:0,exportCount:0,dtsError:T,validationErrorCount:0}}},p=r.parallel||r.parallel!==!1&&f.length>=10,d=Rr(r.concurrency,Ah?.()??8),C=new Map;if(p&&f.length>1){let w=f.map(async(A)=>{try{let S=await at(A);return{file:A,source:S}}catch{return{file:A,source:null}}});for(let A of await Promise.all(w))if(A.source!==null)C.set(A.file,A.source)}let b=(w)=>{if(a.filesProcessed++,w.success){if(w.cached)o++;else a.filesGenerated++,a.declarationsFound+=w.declarationCount,a.importsProcessed+=w.importCount,a.exportsProcessed+=w.exportCount;if(r.validate){if(a.filesValidated++,w.validationErrorCount)a.validationErrors+=w.validationErrorCount}}else if(a.filesFailed++,w.dtsError){a.errors.push(w.dtsError);let A=xs(w.dtsError);if(r.continueOnError)Z.warn(A);else throw Z.error(A),Error(w.dtsError.message)}};if(p)for(let w=0;w<f.length;w+=d){let A=f.slice(w,w+d),S=await Promise.all(A.map((k)=>l(k,C.get(k))));for(let k of S)b(k);if(r.progress){let k=Math.round(a.filesProcessed/f.length*100);Z.info(`[${a.filesProcessed}/${f.length}] ${k}%`)}}else for(let w of f){let A=await l(w);if(b(A),r.progress){let S=Math.round(a.filesProcessed/f.length*100),k=A.cached?"[cached]":"";Z.info(`[${a.filesProcessed}/${f.length}] ${S}% - ${Ne(r.cwd,w)} ${k}`)}}if(s&&!r.dryRun)s.save(),Z.debug("Saved build cache");if(!r.bundle){let w=[];if(u)for(let A of u.unresolved)w.push({from:A.from,specifier:A.specifier,reason:"missing"});if(r.autoIncludeReExports===!1&&f.length>0){let A=new Set(f);for(let S of f){let k;try{k=await at(S)}catch{continue}for(let T of ln(k)){if(!T.specifier.startsWith("."))continue;let v=jr(T.specifier,S);if(!v.resolved)w.push({from:S,specifier:T.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(v.resolved)&&!A.has(v.resolved))w.push({from:S,specifier:T.specifier,reason:"not-emitted"})}}}if(w.length>0){let A=[];A.push(`Found ${w.length} re-export(s) pointing at siblings that won't be in the output:`);for(let k of w){let T=Ne(r.cwd,k.from);if(k.reason==="missing")A.push(` ${T} \u2192 '${k.specifier}' (path not found on disk)`);else A.push(` ${T} \u2192 '${k.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let S=A.join(`
193
193
  `);if(r.failOnUnresolvedReExport)throw Error(S);Z.warn(S),Z.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(r.bundle&&(a.filesGenerated>0||o>0)&&c.length>0)try{Z.debug("Bundling declarations...");let w=new Map,A=async(k)=>{let T=w.get(k);if(T!==void 0)return T;return T=await at(k),w.set(k,T),T};for(let k of f)await A(k);let S=c.length===1&&!!r.bundleOutput;for(let k of c){let T=await cn([k],{includeImports:!0}),v=new Set;for(let q of T.reachable){if(q.endsWith(".d.ts"))continue;if(q.includes("node_modules"))continue;v.add(q)}let M=f.filter((q)=>v.has(q));if(!M.includes(k))M.push(k);let te=new Map;for(let q of M){let ne=w.get(q)??await A(q);te.set(q,ne)}let F=await Zs(M,te,r),K=S?ze(r.cwd,r.outdir,r.bundleOutput):wr(k,r);if(r.dryRun)Z.info(`[dry-run] Would bundle ${F.files.length} files to: ${Ne(r.cwd,K)}`);else await os(yr(K),{recursive:!0}),await gr(K,F.content,r.lineEnding),Z.info(`Bundled ${F.files.length} files to: ${Ne(r.cwd,K)}`);if(S)break}}catch(w){let A=w instanceof Error?w.message:String(w);Z.error(`Bundle failed: ${A}`)}if(a.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(a,null,2));else{if(Z.info(`
194
194
  --- Generation Statistics ---`),Z.info(`Files processed: ${a.filesProcessed}`),Z.info(`Files generated: ${a.filesGenerated}`),o>0)Z.info(`Files cached: ${o}`);if(a.filesFailed>0)Z.info(`Files failed: ${a.filesFailed}`);if(Z.info(`Declarations found: ${a.declarationsFound}`),Z.info(`Imports processed: ${a.importsProcessed}`),Z.info(`Exports processed: ${a.exportsProcessed}`),a.filesValidated>0){if(Z.info(`Files validated: ${a.filesValidated}`),a.validationErrors>0)Z.info(`Validation errors: ${a.validationErrors}`)}if(Z.info(`Duration: ${a.durationMs}ms`),a.errors.length>0){Z.info(`
195
195
  Errors:`);for(let w of a.errors){let A=` - ${w.file}`;if(w.location)A+=`:${w.location.line}:${w.location.column}`;if(w.code)A+=` [${w.code}]`;if(A+=`: ${w.message}`,Z.info(A),w.suggestion)Z.info(` Suggestion: ${w.suggestion}`)}}Z.info(`-----------------------------
196
- `)}if(r.plugins&&r.plugins.length>0)await i.runOnEnd(a);return Z.debug("DTS generation complete!"),a}async function Uo(e){try{return await Ch(e)}catch{return ze(e)}}async function Oh(e){let t=ze(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(fs(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let n=ze(t,e.bundleOutput);if(!Si(n,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===xh(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,i]=await Promise.all([Uo(t),Uo(ze(e.cwd,e.root))]);if(Si(i,r))throw Error("Refusing to clean an outdir that contains the source root")}function Sh(e){let t=pr.get(e);if(!t){if(t=new Yo(e),pr.set(e,t),pr.size>Eh){let r=pr.keys().next().value;if(r!==void 0)pr.delete(r)}}return t}async function kh(e){let t=ze(e.cwd,e.outdir);async function r(i){let n;try{n=await $h(i,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async(s)=>{let a=ze(i,s.name);if(s.isDirectory()){await r(a);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await vh(a,{force:!0})}))}await r(t)}function ls(e,t,r){if(!t||t.length===0)return!1;let i=Ne(r,e);for(let n of t){let s=Sh(n);if(s.match(i)||s.match(e))return!0}return!1}async function Th(e){let t=[],r=ze(e.cwd,e.root),i=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let s of n)if(fs(s)&&cs(s)){if(!s.includes("node_modules")){if(!Si(s,r)&&e.outputStructure!=="flat")Z.warn(`Skipping entrypoint outside root: ${Ne(e.cwd,s)}`);else if(!ls(s,i,r))t.push(s)}}else{let a=new Yo(s);for await(let o of a.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(cs(o)&&!o.includes("node_modules")){if(!ls(o,i,r))t.push(o)}}return[...new Set(t)].sort()}function Si(e,t){let r=Ne(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!fs(r)}function Rh(e,t){let r=new Map;for(let i of e){let n=wr(i,t),s=r.get(n);if(s&&s!==i)throw Error(`Output path collision: ${Ne(t.cwd,s)} and ${Ne(t.cwd,i)} both emit ${Ne(t.cwd,n)}`);r.set(n,i)}}function cs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function wr(e,t){let r=ze(t.cwd,t.root),i=Ne(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs)$/,(n)=>{if(n===".mts"||n===".mjs")return".d.mts";if(n===".cts"||n===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return ze(t.cwd,t.outdir,i);else{let n=i.split("/").pop();return ze(t.cwd,t.outdir,n)}}function Nh(e,t,r=""){let i=Ne(yr(e),t).replace(/\\/g,"/");if(i=i.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)i+=r;if(!i.startsWith("."))i=`./${i}`;return i}function Wh(e,t,r){let i=wr(t,r),n=(s)=>{let a=jr(s,t);if(!a.isRelative||!a.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(a.resolved))return s;let o=s.match(/[?#].*$/)?.[0]??"",c=o?s.slice(0,-o.length):s,f=Ah(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return Nh(i,wr(a.resolved,r),u)+o};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`})}async function Ph(e,t,r,i,n){let s=t;if(i)s=await i.runOnBeforeFile(e,t);let a=Nr(s,e,r.keepComments,r.isolatedDeclarations??!1);if(i)a=await i.runOnDeclarations(e,s,a);let o=0,c=0;for(let u=0;u<a.length;u++){let l=a[u];if(l.kind==="import")o++;if(l.kind==="export"||l.isExported)c++}let f=as(a,{filePath:e,sourceCode:s,declarations:a},r.keepComments,r.importOrder);if(f=Wh(f,e,r),n)f=zs(f,n,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Mo(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(i)f=await i.runOnAfterFile(e,s,f);return{content:f,declarationCount:a.length,importCount:o,exportCount:c}}var Yo,Eh=50,pr;var qo=ce(()=>{Mi();Bi();en();sn();an();fn();rs();xi();cr();is();ns();Br();Oi();Wr();or();({Glob:Yo}=globalThis.Bun);pr=new Map});var zo=ce(()=>{Oi();Tr();kr();Dt()});var Xo=ce(()=>{qo();Mi();Bi();en();sn();an();fn();rs();xi();es();cr();is();ns();Br();zo();Oi();ss();Wr();Tr();kr();Er();Qi();or();Dt();Cr()});var il={};dl(il,{dtsWatch:()=>Gh,dtsCheck:()=>Uh,dts:()=>hs,default:()=>Hh,clearCache:()=>Yh,PluginErrorCodes:()=>Vh,DtsxPluginError:()=>Qt});import{createHash as Ih}from"crypto";import{existsSync as Lh,readFileSync as jh,writeFileSync as Mh}from"fs";import{dirname as Bh,join as _h,relative as Qo,resolve as $r,sep as Ti}from"path";import Zh from"process";class el{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},i=this.listeners.get(e)||[];for(let n of i)await n(r)}}class us{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=_h(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(Lh(this.manifestPath)){let t=JSON.parse(jh(this.manifestPath,"utf-8"));if(t.configHash===e&&t.version==="1.0")return t}}catch{}return{version:"1.0",configHash:e,entries:{}}}save(){try{let{mkdirSync:e}=Dh("fs");e(this.cacheDir,{recursive:!0}),Mh(this.manifestPath,JSON.stringify(this.manifest,null,2))}catch{}}getEntry(e){return this.manifest.entries[e]}setEntry(e,t){this.manifest.entries[e]=t}isValid(e,t){return this.getEntry(e)?.hash===t}clear(){this.manifest.entries={},this.save()}}function Kh(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Ih("md5").update(JSON.stringify(t)).digest("hex")}function hs(e={}){let{onSuccess:t,onError:r,failOnError:i=!0,incremental:n=!1,cacheDir:s=".dtsx-cache",on:a,timeout:o=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new el;if(a){for(let[p,d]of Object.entries(a))if(d)l.on(p,d)}return{name:"bun-plugin-dtsx",async setup(p){let d=Date.now(),C=null,b=0;try{let w=rl(u,p),A=Kh(w);if(n)C=new us($r(s),A);if(await l.emit("start",{type:"start",files:w.entrypoints||[],config:w}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),n)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let k=await(async()=>{return new Promise((v,M)=>{let te=setTimeout(()=>{M(new Qt(`Generation timed out after ${o}ms`,"TIMEOUT_ERROR",{timeout:o}))},o);ki(w).then((F)=>{clearTimeout(te),v(F)}).catch((F)=>{clearTimeout(te),M(F)})})})(),T=Date.now()-d;if(C)C.save();if(await l.emit("complete",{type:"complete",stats:k,duration:T,fromCache:b}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${T}ms`),b>0)console.log(`[bun-plugin-dtsx] ${b} files served from cache`)}if(t)await t(k)}catch(w){let A=tl(w);if(await l.emit("error",{type:"error",error:A}),r)await r(A);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${A.code}`),console.error(` Message: ${A.message}`),A.context)console.error(` Context: ${JSON.stringify(A.context)}`);if(f&&A.stack)console.error(` Stack: ${A.stack}`)}if(i&&!c)throw A}}}}function tl(e){if(e instanceof Qt)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 Qt(e.message,t,{originalError:e.name},e)}return new Qt(String(e),"GENERATION_ERROR")}function Jh(e){let t=e.map((i)=>Bh(i).split(Ti)),r=t[0];for(let i of t.slice(1)){let n=0;while(n<r.length&&n<i.length&&r[n]===i[n])n++;r=r.slice(0,n)}return r.join(Ti)||Ti}function rl(e,t){let r=e.cwd||Zh.cwd(),i=t?.config?.entrypoints,n=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&i?.length){let o=Jh(i.map((c)=>$r(r,c)));s=Qo(r,o)||"."}s=s||"./src";let a=e.entrypoints;if(!a)if(i?.length){let o=$r(r,s),c=[];for(let f of i){let u=$r(r,f);if(u===o||u.startsWith(o+Ti))c.push(Qo(o,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}a=c.length?c:["index.ts"]}else a=["index.ts"];return{...e,cwd:r,root:s,entrypoints:a,outdir:n,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function Gh(e={}){return hs({...e,incremental:!0,verbose:e.verbose??!0})}function Uh(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=rl({...e,outdir:""},t);try{await ki({...r,clean:!1})}catch(i){let n=tl(i);if(e.onError)await e.onError(n);if(e.failOnError!==!1)throw n}}}}function Yh(e=".dtsx-cache"){new us($r(e),"").clear()}var Dh,Vh,Qt,Hh;var nl=ce(()=>{Xo();Dh=import.meta.require,Vh={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};Qt=class Qt extends Error{code;context;cause;constructor(e,t,r,i){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Hh=hs});import{mkdir as qh,stat as zh}from"fs/promises";import{bold as ds,dim as ms,green as Xh,italic as sl,log as Qh}from"@stacksjs/cli";import{path as it}from"@stacksjs/path";import{glob as ed}from"@stacksjs/storage";async function xy(e){let r=Date.now()-e.startTime,i=e.pkgName??`@stacksjs/${it.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let s=e.result.logs?.[0]||"Unknown build error";throw console.log(s),Error(`Build failed: ${s}`)}let n=await ed([it.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of n){let a=await zh(s),o;if(a.size<1048576)o=`${(a.size/1024).toFixed(2)}kb`;else o=`${(a.size/1024/1024).toFixed(2)}mb`;let c=it.relative(e.dir,s).replace("dist/","");console.log(`${ds(ms(`[${o}]`))} ${ms("dist/")}${c}`)}console.log(`${ds(ms(`[${r}ms]`))} Built ${sl(ds(Xh(i)))}`)}async function Ey(e){let t=e.pkgName??`@stacksjs/${it.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Qh.info(`Building ${sl(t)}...`);return{startTime:Date.now()}}async function Oy(e){let{dts:t}=await Promise.resolve().then(() => (nl(),il)),r=it.resolve(e.dir,"src"),i=it.resolve(e.dir,"dist"),n=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((a)=>!a.endsWith(".d.ts"));await Bun.build({entrypoints:n.map((a)=>it.resolve(r,a)),outdir:i,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??td(),plugins:[t({root:r,outdir:i})]});let s=new Bun.Transpiler({loader:"ts",target:"bun"});for(let a of n){let o=s.transformSync(await Bun.file(it.resolve(r,a)).text());o=o.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=it.resolve(i,a.replace(/\.ts$/,".js"));await qh(it.dirname(c),{recursive:!0}),await Bun.write(c,o)}}function td(e=[]){let t=[];try{let r=Ke("fs"),i=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(i.dependencies??{}),...Object.keys(i.peerDependencies??{}),...Object.keys(i.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Oy as transpilePackage,xy as outro,Ey as intro,td as frameworkExternal};
196
+ `)}if(r.plugins&&r.plugins.length>0)await i.runOnEnd(a);return Z.debug("DTS generation complete!"),a}async function Uo(e){try{return await vh(e)}catch{return ze(e)}}async function Sh(e){let t=ze(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(fs(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let n=ze(t,e.bundleOutput);if(!Si(n,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===Eh(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,i]=await Promise.all([Uo(t),Uo(ze(e.cwd,e.root))]);if(Si(i,r))throw Error("Refusing to clean an outdir that contains the source root")}function kh(e){let t=pr.get(e);if(!t){if(t=new Yo(e),pr.set(e,t),pr.size>Oh){let r=pr.keys().next().value;if(r!==void 0)pr.delete(r)}}return t}async function Th(e){let t=ze(e.cwd,e.outdir);async function r(i){let n;try{n=await Ch(i,{withFileTypes:!0})}catch{return}await Promise.all(n.map(async(s)=>{let a=ze(i,s.name);if(s.isDirectory()){await r(a);return}if(s.name.endsWith(".d.ts")||s.name.endsWith(".d.mts")||s.name.endsWith(".d.cts")||s.name.endsWith(".d.ts.map")||s.name.endsWith(".d.mts.map")||s.name.endsWith(".d.cts.map"))await bh(a,{force:!0})}))}await r(t)}function ls(e,t,r){if(!t||t.length===0)return!1;let i=Ne(r,e);for(let n of t){let s=kh(n);if(s.match(i)||s.match(e))return!0}return!1}async function Rh(e){let t=[],r=ze(e.cwd,e.root),i=e.exclude||[],n=[...e.entrypoints,...e.include??[]];for(let s of n)if(fs(s)&&cs(s)){if(!s.includes("node_modules")){if(!Si(s,r)&&e.outputStructure!=="flat")Z.warn(`Skipping entrypoint outside root: ${Ne(e.cwd,s)}`);else if(!ls(s,i,r))t.push(s)}}else{let a=new Yo(s);for await(let o of a.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(cs(o)&&!o.includes("node_modules")){if(!ls(o,i,r))t.push(o)}}return[...new Set(t)].sort()}function Si(e,t){let r=Ne(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!fs(r)}function Nh(e,t){let r=new Map;for(let i of e){let n=wr(i,t),s=r.get(n);if(s&&s!==i)throw Error(`Output path collision: ${Ne(t.cwd,s)} and ${Ne(t.cwd,i)} both emit ${Ne(t.cwd,n)}`);r.set(n,i)}}function cs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function wr(e,t){let r=ze(t.cwd,t.root),i=Ne(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs)$/,(n)=>{if(n===".mts"||n===".mjs")return".d.mts";if(n===".cts"||n===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return ze(t.cwd,t.outdir,i);else{let n=i.split("/").pop();return ze(t.cwd,t.outdir,n)}}function Wh(e,t,r=""){let i=Ne(yr(e),t).replace(/\\/g,"/");if(i=i.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)i+=r;if(!i.startsWith("."))i=`./${i}`;return i}function Ph(e,t,r){let i=wr(t,r),n=(s)=>{let a=jr(s,t);if(!a.isRelative||!a.resolved)return s;if(/\.d\.(?:ts|mts|cts)$/.test(a.resolved))return s;let o=s.match(/[?#].*$/)?.[0]??"",c=o?s.slice(0,-o.length):s,f=xh(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return Wh(i,wr(a.resolved,r),u)+o};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${n(c)}${o}`})}async function Fh(e,t,r,i,n){let s=t;if(i)s=await i.runOnBeforeFile(e,t);let a=Nr(s,e,r.keepComments,r.isolatedDeclarations??!1);if(i)a=await i.runOnDeclarations(e,s,a);let o=0,c=0;for(let u=0;u<a.length;u++){let l=a[u];if(l.kind==="import")o++;if(l.kind==="export"||l.isExported)c++}let f=as(a,{filePath:e,sourceCode:s,declarations:a},r.keepComments,r.importOrder);if(f=Ph(f,e,r),n)f=zs(f,n,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Mo(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(i)f=await i.runOnAfterFile(e,s,f);return{content:f,declarationCount:a.length,importCount:o,exportCount:c}}var Yo,Oh=50,pr;var qo=ce(()=>{Mi();Bi();en();sn();an();fn();rs();xi();cr();is();ns();Br();Oi();Wr();or();({Glob:Yo}=globalThis.Bun);pr=new Map});var zo=ce(()=>{Oi();Tr();kr();Dt()});var Xo=ce(()=>{qo();Mi();Bi();en();sn();an();fn();rs();xi();es();cr();is();ns();Br();zo();Oi();ss();Wr();Tr();kr();Er();Qi();or();Dt();Cr()});var il={};ml(il,{dtsWatch:()=>Uh,dtsCheck:()=>Yh,dts:()=>hs,default:()=>qh,clearCache:()=>Hh,PluginErrorCodes:()=>Kh,DtsxPluginError:()=>Qt});import{createHash as Lh}from"crypto";import{existsSync as jh,readFileSync as Mh,writeFileSync as Bh}from"fs";import{dirname as _h,join as Zh,relative as Qo,resolve as $r,sep as Ti}from"path";import Vh from"process";class el{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},i=this.listeners.get(e)||[];for(let n of i)await n(r)}}class us{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=Zh(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(jh(this.manifestPath)){let t=JSON.parse(Mh(this.manifestPath,"utf-8"));if(t.configHash===e&&t.version==="1.0")return t}}catch{}return{version:"1.0",configHash:e,entries:{}}}save(){try{let{mkdirSync:e}=Ih("fs");e(this.cacheDir,{recursive:!0}),Bh(this.manifestPath,JSON.stringify(this.manifest,null,2))}catch{}}getEntry(e){return this.manifest.entries[e]}setEntry(e,t){this.manifest.entries[e]=t}isValid(e,t){return this.getEntry(e)?.hash===t}clear(){this.manifest.entries={},this.save()}}function Jh(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return Lh("md5").update(JSON.stringify(t)).digest("hex")}function hs(e={}){let{onSuccess:t,onError:r,failOnError:i=!0,incremental:n=!1,cacheDir:s=".dtsx-cache",on:a,timeout:o=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new el;if(a){for(let[p,d]of Object.entries(a))if(d)l.on(p,d)}return{name:"bun-plugin-dtsx",async setup(p){let d=Date.now(),C=null,b=0;try{let w=rl(u,p),A=Jh(w);if(n)C=new us($r(s),A);if(await l.emit("start",{type:"start",files:w.entrypoints||[],config:w}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),n)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let k=await(async()=>{return new Promise((v,M)=>{let te=setTimeout(()=>{M(new Qt(`Generation timed out after ${o}ms`,"TIMEOUT_ERROR",{timeout:o}))},o);ki(w).then((F)=>{clearTimeout(te),v(F)}).catch((F)=>{clearTimeout(te),M(F)})})})(),T=Date.now()-d;if(C)C.save();if(await l.emit("complete",{type:"complete",stats:k,duration:T,fromCache:b}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${T}ms`),b>0)console.log(`[bun-plugin-dtsx] ${b} files served from cache`)}if(t)await t(k)}catch(w){let A=tl(w);if(await l.emit("error",{type:"error",error:A}),r)await r(A);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${A.code}`),console.error(` Message: ${A.message}`),A.context)console.error(` Context: ${JSON.stringify(A.context)}`);if(f&&A.stack)console.error(` Stack: ${A.stack}`)}if(i&&!c)throw A}}}}function tl(e){if(e instanceof Qt)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 Qt(e.message,t,{originalError:e.name},e)}return new Qt(String(e),"GENERATION_ERROR")}function Gh(e){let t=e.map((i)=>_h(i).split(Ti)),r=t[0];for(let i of t.slice(1)){let n=0;while(n<r.length&&n<i.length&&r[n]===i[n])n++;r=r.slice(0,n)}return r.join(Ti)||Ti}function rl(e,t){let r=e.cwd||Vh.cwd(),i=t?.config?.entrypoints,n=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&i?.length){let o=Gh(i.map((c)=>$r(r,c)));s=Qo(r,o)||"."}s=s||"./src";let a=e.entrypoints;if(!a)if(i?.length){let o=$r(r,s),c=[];for(let f of i){let u=$r(r,f);if(u===o||u.startsWith(o+Ti))c.push(Qo(o,u));else console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${s}": ${f}`)}a=c.length?c:["index.ts"]}else a=["index.ts"];return{...e,cwd:r,root:s,entrypoints:a,outdir:n,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function Uh(e={}){return hs({...e,incremental:!0,verbose:e.verbose??!0})}function Yh(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=rl({...e,outdir:""},t);try{await ki({...r,clean:!1})}catch(i){let n=tl(i);if(e.onError)await e.onError(n);if(e.failOnError!==!1)throw n}}}}function Hh(e=".dtsx-cache"){new us($r(e),"").clear()}var Ih,Kh,Qt,qh;var nl=ce(()=>{Xo();Ih=import.meta.require,Kh={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};Qt=class Qt extends Error{code;context;cause;constructor(e,t,r,i){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};qh=hs});import{mkdir as zh,stat as Xh}from"fs/promises";import{bold as ds,dim as ms,green as Qh,italic as sl,log as ed}from"@stacksjs/cli";import{path as et}from"@stacksjs/path";import{glob as al}from"@stacksjs/storage";async function td(e){let t=await al([et.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let i of t){let n=await Bun.file(i).text(),s=n.replace(/^(\s*)([$A-Z_a-z][$\w]*)(<[^:\n]+>):\s+\(/gm,"$1$2: $3(").replace(/\b(interface|class)\s+([$A-Z_a-z][$\w]*)extends\b/g,"$1 $2 extends");if(s!==n)await Bun.write(i,s);try{r.transformSync(s)}catch(a){throw Error(`Invalid declaration generated at ${i}: ${a instanceof Error?a.message:String(a)}`)}}}async function Ey(e){let r=Date.now()-e.startTime,i=e.pkgName??`@stacksjs/${et.basename(e.dir)}`;if(e.result.errors&&e.result.errors.length>0)throw console.error("Build errors:",e.result.errors),Error(`Build failed with errors: ${JSON.stringify(e.result.errors)}`);else if(e.result.success!==void 0&&!e.result.success){let s=e.result.logs?.[0]||"Unknown build error";throw console.log(s),Error(`Build failed: ${s}`)}await td(e.dir);let n=await al([et.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of n){let a=await Xh(s),o;if(a.size<1048576)o=`${(a.size/1024).toFixed(2)}kb`;else o=`${(a.size/1024/1024).toFixed(2)}mb`;let c=et.relative(e.dir,s).replace("dist/","");console.log(`${ds(ms(`[${o}]`))} ${ms("dist/")}${c}`)}console.log(`${ds(ms(`[${r}ms]`))} Built ${sl(ds(Qh(i)))}`)}async function Oy(e){let t=e.pkgName??`@stacksjs/${et.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else ed.info(`Building ${sl(t)}...`);return{startTime:Date.now()}}async function Sy(e){let{dts:t}=await Promise.resolve().then(() => (nl(),il)),r=et.resolve(e.dir,"src"),i=et.resolve(e.dir,"dist"),n=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((a)=>!a.endsWith(".d.ts"));await Bun.build({entrypoints:n.map((a)=>et.resolve(r,a)),outdir:i,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??rd(),plugins:[t({root:r,outdir:i})]});let s=new Bun.Transpiler({loader:"ts",target:"bun"});for(let a of n){let o=s.transformSync(await Bun.file(et.resolve(r,a)).text());o=o.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=et.resolve(i,a.replace(/\.ts$/,".js"));await zh(et.dirname(c),{recursive:!0}),await Bun.write(c,o)}}function rd(e=[]){let t=[];try{let r=Ke("fs"),i=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(i.dependencies??{}),...Object.keys(i.peerDependencies??{}),...Object.keys(i.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Sy as transpilePackage,Ey as outro,td as normalizeDeclarations,Oy as intro,rd as frameworkExternal};