@stacksjs/build 0.71.1 → 0.71.10

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.d.ts CHANGED
@@ -6,6 +6,22 @@
6
6
  * `.d.ts` does not parse.
7
7
  */
8
8
  export declare function validateDeclarations(dir: string): Promise<void>;
9
+ /**
10
+ * Link the built entry before a package can report a successful build.
11
+ *
12
+ * A minified bundle can emit `export { S as requireSite }` whose local `S`
13
+ * was renamed away, which parses fine and only fails when something imports
14
+ * the package: `Exported binding 'S' needs to refer to a top-level declared
15
+ * variable`. That shipped three times (ts-collect, bun-router, and again in
16
+ * sites/cms/analytics), each time discovered by a downstream app rather than
17
+ * by us, so the check belongs here — at the moment the dist is produced.
18
+ *
19
+ * Loading happens in a subprocess because it EXECUTES module top-level code;
20
+ * a package that needs env or a database at import must not fail its build
21
+ * for that reason. Only the link-error family is fatal, and anything else is
22
+ * left alone deliberately.
23
+ */
24
+ export declare function validateRuntimeExports(dir: string): Promise<void>;
9
25
  export declare function outro(options: {
10
26
  dir: string
11
27
  startTime: number
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var cc=Object.defineProperty;var fc=(e)=>e;function uc(e,t){this[e]=fc.bind(null,t)}var hc=(e,t)=>{for(var r in t)cc(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uc.bind(t,r)})};var ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ye=import.meta.require;class Or{plugins=[];config=null;register(e){if(this.plugins.some((t)=>t.name===e.name))throw Error(`Plugin "${e.name}" is already registered`);this.plugins.push(e)}unregister(e){let t=this.plugins.findIndex((r)=>r.name===e);if(t>=0)return this.plugins.splice(t,1),!0;return!1}getPlugins(){return this.plugins}createLogger(e){return{debug:(t)=>console.debug(`[${e}] ${t}`),info:(t)=>console.info(`[${e}] ${t}`),warn:(t)=>console.warn(`[${e}] ${t}`),error:(t)=>console.error(`[${e}] ${t}`)}}async runOnStart(e){let t=e;for(let r of this.plugins)if(r.onStart){let n=await r.onStart(t);if(n)t=n}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let n of this.plugins)if(n.onBeforeFile){let i={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(n.name)},s=await n.onBeforeFile(i);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let s={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},a=await i.onDeclarations(s);if(a)n=a}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let s={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},a=await i.onAfterFile(s);if(typeof a==="string")n=a}return n}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let n of this.plugins)if(n.onError){let i={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(n.name)};await n.onError(e,i)}}}function dc(e){return e}var Mm,Im;var Rs=ae(()=>{Mm=new Or;Im=dc({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})}})});import{readFile as mc,stat as Nm,writeFile as pc}from"fs/promises";async function Os(e,t){if(Pr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await pc(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function ct(e){if(Pr)return globalThis.Bun.file(e).text();return mc(e,"utf-8")}var Pr,Lm;var kr=ae(()=>{Pr=typeof globalThis.Bun<"u",Lm=!Pr&&typeof process<"u"&&!!process.versions?.node});import{existsSync as gc,statSync as yc}from"fs";import{dirname as Cc,extname as wc,isAbsolute as Ji,resolve as $c}from"path";function Mr(e){try{return yc(e).isFile()}catch{return!1}}function Ir(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!Ji(r))return{resolved:null,isRelative:!1};let n=Cc(t),i=Ji(r)?r:$c(n,r);if(Mr(i))return{resolved:i,isRelative:!0};let s=wc(i),a=Ec[s];if(a){let o=i.slice(0,-s.length);for(let c of a){let f=o+c;if(Mr(f))return{resolved:f,isRelative:!0}}}for(let o of Ps){let c=i+o;if(Mr(c))return{resolved:c,isRelative:!0}}if(gc(i))for(let o of Ps){let c=`${i}/index${o}`;if(Mr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function vc(e){let t=e.length,r="",n=0;while(n<t){let i=e.charCodeAt(n);if(i===34||i===39||i===96){let s=i;r+=e[n++];while(n<t){let a=e.charCodeAt(n),o=e[n++];if(r+=s===96&&a!==s?a===10||a===13?o:" ":o,a===92&&n<t){let c=e[n++];r+=s===96?c===`
2
+ var cc=Object.defineProperty;var fc=(e)=>e;function uc(e,t){this[e]=fc.bind(null,t)}var hc=(e,t)=>{for(var r in t)cc(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uc.bind(t,r)})};var ae=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ye=import.meta.require;class Or{plugins=[];config=null;register(e){if(this.plugins.some((t)=>t.name===e.name))throw Error(`Plugin "${e.name}" is already registered`);this.plugins.push(e)}unregister(e){let t=this.plugins.findIndex((r)=>r.name===e);if(t>=0)return this.plugins.splice(t,1),!0;return!1}getPlugins(){return this.plugins}createLogger(e){return{debug:(t)=>console.debug(`[${e}] ${t}`),info:(t)=>console.info(`[${e}] ${t}`),warn:(t)=>console.warn(`[${e}] ${t}`),error:(t)=>console.error(`[${e}] ${t}`)}}async runOnStart(e){let t=e;for(let r of this.plugins)if(r.onStart){let n=await r.onStart(t);if(n)t=n}return this.config=t,t}async runOnBeforeFile(e,t){let r=t;for(let n of this.plugins)if(n.onBeforeFile){let i={filePath:e,sourceCode:t,content:r,config:this.config,log:this.createLogger(n.name)},s=await n.onBeforeFile(i);if(typeof s==="string")r=s}return r}async runOnDeclarations(e,t,r){let n=r;for(let i of this.plugins)if(i.onDeclarations){let s={filePath:e,sourceCode:t,declarations:n,config:this.config,log:this.createLogger(i.name)},a=await i.onDeclarations(s);if(a)n=a}return n}async runOnAfterFile(e,t,r){let n=r;for(let i of this.plugins)if(i.onAfterFile){let s={filePath:e,sourceCode:t,content:n,config:this.config,log:this.createLogger(i.name)},a=await i.onAfterFile(s);if(typeof a==="string")n=a}return n}async runOnEnd(e){for(let t of this.plugins)if(t.onEnd)await t.onEnd(e)}async runOnError(e,t,r){for(let n of this.plugins)if(n.onError){let i={filePath:t,sourceCode:r,config:this.config,log:this.createLogger(n.name)};await n.onError(e,i)}}}function dc(e){return e}var Im,Dm;var Rs=ae(()=>{Im=new Or;Dm=dc({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})}})});import{readFile as mc,stat as Lm,writeFile as pc}from"fs/promises";async function Os(e,t){if(Pr)return globalThis.Bun.write(e,t);let r=typeof t==="string"?t:t instanceof ArrayBuffer?Buffer.from(t):t;return await pc(e,r),typeof t==="string"?Buffer.byteLength(t):t.byteLength}async function ct(e){if(Pr)return globalThis.Bun.file(e).text();return mc(e,"utf-8")}var Pr,Wm;var kr=ae(()=>{Pr=typeof globalThis.Bun<"u",Wm=!Pr&&typeof process<"u"&&!!process.versions?.node});import{existsSync as gc,statSync as yc}from"fs";import{dirname as Cc,extname as wc,isAbsolute as Ji,resolve as $c}from"path";function Mr(e){try{return yc(e).isFile()}catch{return!1}}function Ir(e,t){let r=e.replace(/[?#].*$/,"");if(!(r.startsWith("./")||r.startsWith("../")||r==="."||r==="..")&&!Ji(r))return{resolved:null,isRelative:!1};let n=Cc(t),i=Ji(r)?r:$c(n,r);if(Mr(i))return{resolved:i,isRelative:!0};let s=wc(i),a=Ec[s];if(a){let o=i.slice(0,-s.length);for(let c of a){let f=o+c;if(Mr(f))return{resolved:f,isRelative:!0}}}for(let o of Ps){let c=i+o;if(Mr(c))return{resolved:c,isRelative:!0}}if(gc(i))for(let o of Ps){let c=`${i}/index${o}`;if(Mr(c))return{resolved:c,isRelative:!0}}return{resolved:null,isRelative:!0}}function vc(e){let t=e.length,r="",n=0;while(n<t){let i=e.charCodeAt(n);if(i===34||i===39||i===96){let s=i;r+=e[n++];while(n<t){let a=e.charCodeAt(n),o=e[n++];if(r+=s===96&&a!==s?a===10||a===13?o:" ":o,a===92&&n<t){let c=e[n++];r+=s===96?c===`
3
3
  `||c==="\r"?c:" ":c;continue}if(a===s)break}continue}if(i===47&&n+1<t){let s=e.charCodeAt(n+1);if(s===47){n+=2;while(n<t&&e.charCodeAt(n)!==10)n++;continue}if(s===42){n+=2;while(n+1<t&&!(e.charCodeAt(n)===42&&e.charCodeAt(n+1)===47))n++;n+=2;continue}}r+=e[n++]}return r}function Ui(e,t={}){let r=[],n=vc(e);ks.lastIndex=0;let i;while((i=ks.exec(n))!==null){let s=!!i[1],a=i[3],o=i[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){Ms.lastIndex=0;while((i=Ms.exec(n))!==null)r.push({specifier:i[3],kind:"import",isTypeOnly:!!i[1]})}return r}async function Yi(e,t={}){let r=new Set,n=new Map,i=[],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 ct(a)}catch{continue}let c=Ui(o,t);n.set(a,c);for(let f of c){if(!(f.specifier.startsWith(".")||Ji(f.specifier)))continue;let u=Ir(f.specifier,a);if(u.resolved){if(!r.has(u.resolved))r.add(u.resolved),s.push(u.resolved)}else i.push({from:a,specifier:f.specifier,isTypeOnly:f.isTypeOnly})}}return{reachable:r,reExports:n,unresolved:i}}var Ps,Ec,ks,Ms;var Is=ae(()=>{kr();Ps=[".ts",".tsx",".mts",".cts",".vue",".stx",".js",".jsx",".mjs",".cjs",".d.ts",".d.mts",".d.cts"],Ec={".js":[".ts",".tsx",".d.ts"],".jsx":[".tsx",".ts",".d.ts"],".mjs":[".mts",".d.mts"],".cjs":[".cts",".d.cts"]};ks=/(?:^|[\n;{}])\s*export\s+(type\s+)?(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+(['"])([^'"]+)\2/g,Ms=/(?:^|[\n;{}])\s*import\s+(type\s+)?(?:[^'";\n]+\s+from\s+)?(['"])([^'"]+)\2/g});function Ns(e,t={}){let{lineEnding:r="lf",trailingNewline:n=!0,maxBlankLines:i=1,trimTrailingWhitespace:s=!0,normalizeIndentation:a=!0,indent:o={style:"spaces",size:2},declarationOrder:c,importGrouping:f,preserveComments:u=!0,insertFinalNewline:l=!0}=t,g=e;if(g=Ac(g,r),f?.enabled!==!1)g=Pc(g,f||{});if(c)g=kc(g,c);if(s)g=xc(g);if(g=Tc(g,i),a)g=Oc(g,o);if(n||l)g=Rc(g);return g}function Ac(e,t){let r=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
4
4
  `)!==-1)r=r.replace(/\r\n/g,`
5
5
  `);if(r.indexOf("\r")!==-1)r=r.replace(/\r/g,`
@@ -79,13 +79,13 @@ ${t.scriptSetup.content}`:t.script.content;if(r=C.script,C.options){let x=Vr(C.o
79
79
  defineProps<${r}>()`,null)}function Df(e){return cn(e)}function ua(e){let t=on(e).trimStart();if(t==="")return!0;return/^(?:import\b|export\b|declare\b|interface\b|type\b|(?:export\s+)?namespace\b|(?:export\s+)?module\b|(?:abstract\s+)?class\b|const\b|let\b|var\b|(?:async\s+)?function\b)/.test(t)}function Ff(e){let t=[],r=0,n=0,i=0;while(i<e.length){let a=e[i],o=an(e,i);if(o>i){i=o;continue}if(a==="{"||a==="["||a==="(")n++;else if(a==="}"||a==="]"||a===")")n=Math.max(0,n-1);if((a===";"||a===`
80
80
  `)&&n===0){let c=i+1;if(!ua(e.slice(r,c)))t.push([r,c]);r=c}i++}if(r<e.length&&!ua(e.slice(r)))t.push([r,e.length]);let s=e;for(let a=t.length-1;a>=0;a--)s=s.slice(0,t[a][0])+s.slice(t[a][1]);return s}function da(e){let t=xf(e).filter(Tf).map((v)=>v.content).join(`
81
81
  `),r=null,n=fn(t);if(n.passthrough)return t;if(t=n.script,n.options){let v=Vr(n.options,"props");if(v)r=jr(v)}let i=t,s=Df(t),a=If(i),o=a?.type??r??"{}",c=hn(i,null),f=dn(i,null),u=mr(i,"defineSlots")?.generic??null,l=a?.inlinedLocal;if(l)s=Hr(s,l.name,l.declText);let g=`DefineComponent<${o}>`,h=[];if(c)h.push(`readonly __stxEmits?: ${c}`);if(u)h.push(`readonly __stxSlots?: ${u}`);if(f)h.push(`readonly __stxExposed?: ${f}`);if(h.length>0)g+=` & { ${h.join(", ")} }`;g=un(g),s=Ff(_r(s,g));let w=["import type { DefineComponent } from '@stacksjs/stx'",`type __DtsxStxComponentType = ${g}`,"const __dtsx_component__: __DtsxStxComponentType = null as unknown as __DtsxStxComponentType","export default __dtsx_component__"];if(s.trim()!=="")w.push(s);return w.join(`
82
- `)}var ma=ae(()=>{mn()});function pr(e){if(Nf)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t}return t}var Nf;var pn=ae(()=>{Nf=typeof globalThis.Bun?.hash==="function"});function ga(e,t,r=!0,n=!1){if(oa(t))e=fa(e);else if(ha(t))e=da(e);let i=pr(e),s=`${t}:${r?1:0}:${n?1:0}`,a=Vt.get(s);if(a&&a.contentHash===i)return a.lastAccess=++pa,a.declarations;let o=n?ra(e,t,r):ia(e,t,r);if(Vt.set(s,{declarations:o,contentHash:i,lastAccess:++pa}),Vt.size>Lf){let c=Math.max(1,Math.ceil(Vt.size*0.1)),f=[];for(let[u,l]of Vt)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)Vt.delete(f[u][0])}return o}var Lf=100,pa=0,Vt;var ya=ae(()=>{sa();ma();pn();mn();Vt=new Map});function Ca(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 wa=()=>{};function Jr(e,t,r=!0,n=!1){return ga(e,t,r,n)}var gn=ae(()=>{ya()});import{dirname as lp,relative as Wf,resolve as cp}from"path";async function $a(e,t,r){let n=new Map,i=[],s=new Set,a=0,o=0,c=0,f=[];for(let O of e){let R=t.get(O);if(!R)continue;f.push({file:O,decls:Jr(R,O,r.keepComments)})}for(let{file:O,decls:R}of f){a+=R.length;for(let k of R)if(k.kind==="import"){o++;let E=k.source||"";if(E.startsWith("."))continue;if(!n.has(E))n.set(E,{source:E,specifiers:new Map,isTypeOnly:k.isTypeOnly||!1,isSideEffect:k.isSideEffect||!1});let G=n.get(E);if(k.specifiers)for(let re of k.specifiers){let I=re.alias||re.name;if(!G.specifiers.has(I))G.specifiers.set(I,{name:re.name,alias:re.alias,isType:re.isType||!1})}if(!k.isTypeOnly)G.isTypeOnly=!1}else if(k.isExported||k.kind==="export"){if(c++,k.kind==="export"&&k.source&&(k.source.startsWith(".")||k.source.startsWith("/")))continue;if(k.name&&s.has(k.name))continue;if(k.name)s.add(k.name);i.push({declaration:k,file:O})}}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"],g=Array.from(n.values()),h=Array(g.length);for(let O=0;O<g.length;O++){let R=g[O].source,k=l.length;for(let E=0;E<l.length;E++)if(R.startsWith(l[E])){k=E;break}h[O]=k}let w=g.map((O,R)=>R);w.sort((O,R)=>{let k=h[O],E=h[R];if(k!==E)return k-E;return g[O].source.localeCompare(g[R].source)});let v=w.map((O)=>g[O]);for(let O of v)if(O.isSideEffect)u.push(`import '${O.source}';`);else if(O.specifiers.size>0){let R=Array.from(O.specifiers.values()).map((E)=>{let G=E.isType?"type ":"";return E.alias?`${G}${E.name} as ${E.alias}`:`${G}${E.name}`}),k=O.isTypeOnly?"type ":"";u.push(`import ${k}{ ${R.join(", ")} } from '${O.source}';`)}if(v.length>0)u.push("");let C=new Map;for(let{declaration:O,file:R}of i){if(!C.has(R))C.set(R,[]);C.get(R).push(O)}for(let[O,R]of C){let k=Wf(r.cwd,O);u.push(`// From: ${k}`);for(let E of R){if(r.keepComments&&E.leadingComments)for(let G of E.leadingComments)u.push(G);u.push(Ea(E))}u.push("")}let x=u.join(`
82
+ `)}var ma=ae(()=>{mn()});function pr(e){if(Nf)return Bun.hash(e);let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)-t+n,t=t&t}return t}var Nf;var pn=ae(()=>{Nf=typeof globalThis.Bun?.hash==="function"});function ga(e,t,r=!0,n=!1){if(oa(t))e=fa(e);else if(ha(t))e=da(e);let i=pr(e),s=`${t}:${r?1:0}:${n?1:0}`,a=Vt.get(s);if(a&&a.contentHash===i)return a.lastAccess=++pa,a.declarations;let o=n?ra(e,t,r):ia(e,t,r);if(Vt.set(s,{declarations:o,contentHash:i,lastAccess:++pa}),Vt.size>Lf){let c=Math.max(1,Math.ceil(Vt.size*0.1)),f=[];for(let[u,l]of Vt)f.push([u,l.lastAccess]);f.sort((u,l)=>u[1]-l[1]);for(let u=0;u<c&&u<f.length;u++)Vt.delete(f[u][0])}return o}var Lf=100,pa=0,Vt;var ya=ae(()=>{sa();ma();pn();mn();Vt=new Map});function Ca(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 wa=()=>{};function Jr(e,t,r=!0,n=!1){return ga(e,t,r,n)}var gn=ae(()=>{ya()});import{dirname as cp,relative as Wf,resolve as fp}from"path";async function $a(e,t,r){let n=new Map,i=[],s=new Set,a=0,o=0,c=0,f=[];for(let O of e){let R=t.get(O);if(!R)continue;f.push({file:O,decls:Jr(R,O,r.keepComments)})}for(let{file:O,decls:R}of f){a+=R.length;for(let k of R)if(k.kind==="import"){o++;let E=k.source||"";if(E.startsWith("."))continue;if(!n.has(E))n.set(E,{source:E,specifiers:new Map,isTypeOnly:k.isTypeOnly||!1,isSideEffect:k.isSideEffect||!1});let G=n.get(E);if(k.specifiers)for(let re of k.specifiers){let I=re.alias||re.name;if(!G.specifiers.has(I))G.specifiers.set(I,{name:re.name,alias:re.alias,isType:re.isType||!1})}if(!k.isTypeOnly)G.isTypeOnly=!1}else if(k.isExported||k.kind==="export"){if(c++,k.kind==="export"&&k.source&&(k.source.startsWith(".")||k.source.startsWith("/")))continue;if(k.name&&s.has(k.name))continue;if(k.name)s.add(k.name);i.push({declaration:k,file:O})}}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"],g=Array.from(n.values()),h=Array(g.length);for(let O=0;O<g.length;O++){let R=g[O].source,k=l.length;for(let E=0;E<l.length;E++)if(R.startsWith(l[E])){k=E;break}h[O]=k}let w=g.map((O,R)=>R);w.sort((O,R)=>{let k=h[O],E=h[R];if(k!==E)return k-E;return g[O].source.localeCompare(g[R].source)});let v=w.map((O)=>g[O]);for(let O of v)if(O.isSideEffect)u.push(`import '${O.source}';`);else if(O.specifiers.size>0){let R=Array.from(O.specifiers.values()).map((E)=>{let G=E.isType?"type ":"";return E.alias?`${G}${E.name} as ${E.alias}`:`${G}${E.name}`}),k=O.isTypeOnly?"type ":"";u.push(`import ${k}{ ${R.join(", ")} } from '${O.source}';`)}if(v.length>0)u.push("");let C=new Map;for(let{declaration:O,file:R}of i){if(!C.has(R))C.set(R,[]);C.get(R).push(O)}for(let[O,R]of C){let k=Wf(r.cwd,O);u.push(`// From: ${k}`);for(let E of R){if(r.keepComments&&E.leadingComments)for(let G of E.leadingComments)u.push(G);u.push(Ea(E))}u.push("")}let x=u.join(`
83
83
  `);return{content:x,files:e,declarationCount:a,importCount:o,exportCount:c,size:Buffer.byteLength(x,"utf8"),warnings:[]}}function Ea(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(`(${Gf(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(` ${Ea(r)}`);t.push("}");break;case"enum":if(t.push("declare enum"),t.push(e.name),t.push("{"),e.members){let r=e.members.map((n)=>n.value!==void 0?`${n.name} = ${n.value}`:n.name);t.push(` ${r.join(`,
84
84
  `)}`)}t.push("}");break;default:return e.text||""}return t.join(" ")}function Gf(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 va=ae(()=>{gn()});import{existsSync as gr,mkdirSync as Bf,readFileSync as Cn,renameSync as Vf,rmSync as ba,statSync as Sa,writeFileSync as Aa}from"fs";import{join as xa,relative as Ur,resolve as _f}from"path";class wn{cacheDir;manifestPath;manifest=null;configHash;constructor(e){this.cacheDir=_f(e.cwd,Yr),this.manifestPath=xa(this.cacheDir,Hf),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(pr(JSON.stringify(t)))}hashString(e){return String(pr(e))}load(){try{if(!gr(this.manifestPath))return!1;let e=Cn(this.manifestPath,"utf-8"),t=JSON.parse(e);if(t.version!==yn)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:yn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!gr(this.cacheDir))Bf(this.cacheDir,{recursive:!0});let e=`${this.manifestPath}.${process.pid}.tmp`;try{Aa(e,JSON.stringify(this.manifest,null,2)),Vf(e,this.manifestPath)}finally{if(gr(e))ba(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=Ur(t,e),n=this.manifest.entries[r];if(!n)return null;if(typeof n.dtsContent!=="string"||typeof n.dtsHash!=="string"||n.configHash!==this.configHash||this.hashString(n.dtsContent)!==n.dtsHash)return null;try{let i=Sa(e),s=i.mtimeMs,a=i.ctimeMs;if(i.size!==n.sourceSize)return null;if(s!==n.sourceMtime||a!==n.sourceCtime){let o=Cn(e,"utf-8");if(this.hashString(o)!==n.sourceHash)return null;n.sourceMtime=s,n.sourceCtime=a}return n.dtsContent}catch{return null}}update(e,t,r,n){if(!this.manifest)this.manifest={version:yn,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let i=Ur(n,e),s,a,o;try{let c=Sa(e);s=c.mtimeMs,a=c.ctimeMs,o=c.size}catch{s=Date.now(),a=s,o=Buffer.byteLength(t)}this.manifest.entries[i]={sourcePath:i,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=Ur(t,e);delete this.manifest.entries[r]}clear(){this.manifest=null;try{if(gr(this.manifestPath))ba(this.cacheDir,{recursive:!0,force:!0})}catch{}}getStats(){if(!this.manifest)return{entries:0,size:0};let e=Object.keys(this.manifest.entries).length,t=0;for(let r of Object.values(this.manifest.entries))t+=r.dtsContent.length;return{entries:e,size:t}}prune(e,t){if(!this.manifest)return 0;let r=0,n=new Set(Array.from(e).map((i)=>Ur(t,i)));for(let i of Object.keys(this.manifest.entries))if(!n.has(i))delete this.manifest.entries[i],r++;return r}}function Ta(e){let t=xa(e,".gitignore");try{let r="";if(gr(t))r=Cn(t,"utf-8");if(!r.split(/\r?\n/).some((n)=>n.trim()===Yr||n.trim()===`${Yr}/`)){let n=r.trimEnd(),i=`${n}${n?`
85
85
 
86
86
  `:""}# dtsx cache
87
87
  ${Yr}/
88
- `;Aa(t,i)}}catch{}}var yn=3,Yr=".dtsx-cache",Hf="manifest.json";var Ra=ae(()=>{pn()});function Yf(e){switch(e){case"strict":return Kf;case"readonly":return Jf;case"simplified":return Uf;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 Pa{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...jf);if(e.presets)for(let t of e.presets)this.rules.push(...Yf(t));this.rules.push(...e.rules),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let r=this.rules[t],n=typeof r.pattern==="string"?new RegExp(r.pattern.replace(Zf,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:n}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,n=this.cache.get(r);if(n!==void 0)return n;let i=e,s=null;for(let 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(i)){if(c.lastIndex=0,i=i.replace(c,o.replacement),c.lastIndex=0,!o.global)break}}if(this.cache.size>=Oa){let a=Math.ceil(Oa*0.1),o=0;for(let c of this.cache.keys()){if(o++>=a)break;this.cache.delete(c)}}return this.cache.set(r,i),i}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let n=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?n!==e:!e.test(n)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Zr(e={rules:[]}){return new Pa(e)}function ka(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>{return`: ${t.map(i.trim(),r)}`})}var jf,Kf,Jf,Uf,Zf,Oa=2048,pp,gp;var Ma=ae(()=>{jf=[{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}],Kf=[{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}],Jf=[{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}],Uf=[{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}];Zf=/[.*+?^${}()|[\]\\]/g;pp=Zr({rules:[]}),gp=Zr({rules:[],presets:["strict"]})});async function qf(){if(qr!==null)return qr;try{return St=await import("prettier"),qr=!0,!0}catch{return qr=!1,!1}}async function Xf(e,t){if(!St)return null;try{if(t&&St.resolveConfig){let r=await St.resolveConfig(t);if(r)return r}if(e&&St.resolveConfig){let r=await St.resolveConfig(e);if(r)return r}return null}catch{return null}}async function zf(e,t){if(!St)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return St.format(e,r)}function Qf(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:a=!0,sortImports:o=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
88
+ `;Aa(t,i)}}catch{}}var yn=3,Yr=".dtsx-cache",Hf="manifest.json";var Ra=ae(()=>{pn()});function Yf(e){switch(e){case"strict":return Kf;case"readonly":return Jf;case"simplified":return Uf;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 Pa{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...jf);if(e.presets)for(let t of e.presets)this.rules.push(...Yf(t));this.rules.push(...e.rules),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let t=0;t<this.rules.length;t++){let r=this.rules[t],n=typeof r.pattern==="string"?new RegExp(r.pattern.replace(Zf,"\\$&"),r.global?"g":""):r.pattern;e[t]={rule:r,regex:n}}this.compiled=e}map(e,t={}){let r=!t.declarationName&&!t.declarationKind&&!t.filePath&&!t.isReturnType&&!t.isParameterType&&!t.isPropertyType?e:`${e}\x00${t.declarationName??""}\x00${t.declarationKind??""}\x00${t.filePath??""}\x00${t.isReturnType?"r":""}${t.isParameterType?"p":""}${t.isPropertyType?"P":""}`,n=this.cache.get(r);if(n!==void 0)return n;let i=e,s=null;for(let 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(i)){if(c.lastIndex=0,i=i.replace(c,o.replacement),c.lastIndex=0,!o.global)break}}if(this.cache.size>=Oa){let a=Math.ceil(Oa*0.1),o=0;for(let c of this.cache.keys()){if(o++>=a)break;this.cache.delete(c)}}return this.cache.set(r,i),i}mapAll(e,t={}){return e.map((r)=>this.map(r,{...t,type:r}))}addRule(e){this.rules.push(e),this.rules.sort((t,r)=>(r.priority||0)-(t.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let t=this.rules.length;return this.rules=this.rules.filter((r)=>{let n=typeof r.pattern==="string"?r.pattern:r.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?n!==e:!e.test(n)}),this.recompile(),this.cache.clear(),t-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function Zr(e={rules:[]}){return new Pa(e)}function ka(e,t,r={}){return e.replace(/:\s*([^;,)\]}]+)/g,(n,i)=>{return`: ${t.map(i.trim(),r)}`})}var jf,Kf,Jf,Uf,Zf,Oa=2048,gp,yp;var Ma=ae(()=>{jf=[{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}],Kf=[{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}],Jf=[{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}],Uf=[{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}];Zf=/[.*+?^${}()|[\]\\]/g;gp=Zr({rules:[]}),yp=Zr({rules:[],presets:["strict"]})});async function qf(){if(qr!==null)return qr;try{return St=await import("prettier"),qr=!0,!0}catch{return qr=!1,!1}}async function Xf(e,t){if(!St)return null;try{if(t&&St.resolveConfig){let r=await St.resolveConfig(t);if(r)return r}if(e&&St.resolveConfig){let r=await St.resolveConfig(e);if(r)return r}return null}catch{return null}}async function zf(e,t){if(!St)throw Error("Prettier is not available");let r={...t,parser:t.parser||"typescript"};return St.format(e,r)}function Qf(e,t={}){let{indentSize:r=2,useTabs:n=!1,maxLineWidth:i=100,trailingNewline:s=!0,normalizeWhitespace:a=!0,sortImports:o=!0,groupImports:c=!0}=t,f=e,u=n?"\t":" ".repeat(r);if(f.indexOf(`\r
89
89
  `)!==-1)f=f.replace(/\r\n/g,`
90
90
  `);if(a){if(/[ \t]\n/.test(f)||/[ \t]$/.test(f))f=f.replace(/[ \t]+$/gm,"");if(f.indexOf(`
91
91
 
@@ -146,7 +146,7 @@ ${n}`}if(o)return`${fu(o)}${n}`;return r+n}function du(e,t=!0){let r=ut(e.leadin
146
146
  `?`
147
147
  `:" ";n=o;continue}let s=e[n];if(t.strings&&(s==='"'||s==="'"||s==="`")){let a=s;r+=" ",n++;while(n<e.length){if(e[n]==="\\"){r+=" ",n+=2;continue}if(e[n]===a){r+=" ",n++;break}r+=e[n]===`
148
148
  `?`
149
- `:" ",n++}continue}r+=s,n++}return r}function Su(e){let t=new Set,r=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of r)for(let i of e.matchAll(n))t.add(i[1]);return t}function Au(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let s=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let o of s.split(",")){let c=o.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let a=/\{([\s\S]*?)\}/.exec(n);if(a)for(let o of a[1].split(",")){let c=o.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function xu(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let a=s.trim().split(/\s+|=/)[0]?.trim();if(a&&/^[A-Za-z_$][\w$]*$/.test(a))t.add(a)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function Tu(e){let t=new Map,r=(i)=>{let s=1;for(let a=0;a<i&&a<e.length;a++)if(e.charCodeAt(a)===10)s++;return s},n=(i,s,a)=>{for(let o of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=o[1];if(t.has(c))continue;let f=i.slice(o.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(s),context:a.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function Xa(e){let t=qa(e),r=qa(e,{strings:!1}),n=new Set([...Su(t),...Au(r),...xu(t),...Ya,...bu]),i=[];for(let[s,a]of Tu(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:a.line,context:a.context})}return i.sort((s,a)=>s.line-a.line||s.name.localeCompare(a.name))}var bu;var za=ae(()=>{Za();bu=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function _t(e){return Qa[e]>=Qa[Xr]}function Pu(){if(!Ou)return"";return`[${new Date().toISOString().slice(11,23)}] `}function ku(e,t){let r=Pu();if(e||r)return[`${r}${e}`,...t];return t}function Ht(e,t,r){let n=ku(t,r);if(eo){eo(e,...n);return}switch(e){case"debug":console.debug(...n);break;case"info":console.log(...n);break;case"warn":console.warn(...n);break;case"error":console.error(...n);break}}function to(e){return{debug:(...t)=>{if(_t("debug"))Ht("debug",e,t)},info:(...t)=>{if(_t("info"))Ht("info",e,t)},warn:(...t)=>{if(_t("warn"))Ht("warn",e,t)},error:(...t)=>{if(_t("error"))Ht("error",e,t)},setLevel:(t)=>{Xr=t},getLevel:()=>Xr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return to(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(_t("debug"))Ht("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(_t("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Ht("info",e,[t])}}}function $n(e){Xr=e}var Qa,Xr="info",Ru="[dtsx]",Ou=!1,eo=null,H;var ro=ae(()=>{Qa={debug:0,info:1,warn:2,error:3,silent:4};H=to(Ru)});import Mu from"process";import{existsSync as io,statSync as no}from"fs";import{existsSync as Iu,mkdirSync as kp,readdirSync as Mp,readFileSync as Du,writeFileSync as Ip}from"fs";import{homedir as jt}from"os";import{dirname as Np,resolve as Qe}from"path";import ki from"process";import{existsSync as so,statSync as ao}from"fs";import{existsSync as Bn,mkdirSync as Fu,readdirSync as Nu,writeFileSync as Lu}from"fs";import{homedir as Kt}from"os";import{dirname as oo,resolve as je}from"path";import Mt from"process";import{join as Wu,relative as Gu,resolve as lo}from"path";import yi from"process";import{existsSync as jo,mkdirSync as Jp,readdirSync as Up,writeFileSync as Yp}from"fs";import{homedir as En}from"os";import{dirname as Xp,resolve as He}from"path";import wr from"process";import{join as Bu,relative as Vu,resolve as co}from"path";import Ci from"process";import{existsSync as Ko,mkdirSync as rg,readdirSync as ig,writeFileSync as ng}from"fs";import{dirname as ag,resolve as wi}from"path";import Vn from"process";import{Buffer as At}from"buffer";import{createCipheriv as _u,createDecipheriv as Hu,randomBytes as vn}from"crypto";import{closeSync as bn,createReadStream as fo,createWriteStream as ju,existsSync as Sn,fsyncSync as uo,openSync as ho,writeFileSync as Ku}from"fs";import{access as Ju,constants as mo,mkdir as Uu,readdir as zr,rename as po,stat as Jt,unlink as Qr,writeFile as An}from"fs/promises";import{join as Ut}from"path";import We from"process";import{pipeline as Yu}from"stream/promises";import{createGzip as go}from"zlib";import Yt from"process";import pt from"process";import{Buffer as ht}from"buffer";import{createCipheriv as Zu,createDecipheriv as qu,randomBytes as xn}from"crypto";import{closeSync as Tn,createReadStream as yo,createWriteStream as Xu,existsSync as ei,fsyncSync as Co,openSync as wo,writeFileSync as zu}from"fs";import{access as Qu,constants as $o,mkdir as eh,readdir as ti,rename as Eo,stat as Zt,unlink as ri,writeFile as Rn}from"fs/promises";import{isAbsolute as th,join as qt,resolve as rh}from"path";import ce from"process";import{pipeline as ih}from"stream/promises";import{createGzip as vo}from"zlib";import Xt from"process";import gt from"process";import ii from"process";import{existsSync as ni}from"fs";import{resolve as On}from"path";import{existsSync as nh}from"fs";import{existsSync as sh,readdirSync as ah}from"fs";import{extname as Pn,resolve as bo}from"path";import oh from"process";import{join as lh,relative as ch,resolve as So}from"path";import $i from"process";import{Buffer as dt}from"buffer";import{createCipheriv as fh,createDecipheriv as uh,randomBytes as kn}from"crypto";import{closeSync as Mn,createReadStream as Ao,createWriteStream as hh,existsSync as si,fsyncSync as xo,openSync as To,writeFileSync as dh}from"fs";import{access as mh,constants as Ro,mkdir as ph,readdir as ai,rename as Oo,stat as zt,unlink as oi,writeFile as In}from"fs/promises";import{isAbsolute as gh,join as Qt,resolve as yh}from"path";import fe from"process";import{pipeline as Ch}from"stream/promises";import{createGzip as Po}from"zlib";import er from"process";import yt from"process";import li from"process";import{existsSync as ci}from"fs";import{resolve as Dn}from"path";import{existsSync as wh}from"fs";class Jo{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,a=this.estimateSize(t);this.cache.set(i,{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),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!io(e))return!0;return no(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=io(r)?no(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Uo{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),s}catch(s){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function vh(e,t){this[e]=Eh.bind(null,t)}class Qn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,a=this.estimateSize(t);this.cache.set(i,{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),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!so(e))return!0;return ao(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=so(r)?ao(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class es{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),s}catch(s){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ah(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function xh(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Th(e){return e.getStats().size*2}function ts(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ye(t[0])&&"id"in t[0]&&t[0].id===3&&ye(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ye(t)&&ye(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(ye(e)&&"arr"in e&&Array.isArray(e.arr)&&ye(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ye(t[0])&&ye(e[0])){let n=[...t];for(let i of e)if(ye(i)&&"name"in i){if(!n.find((s)=>ye(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(ye(i)&&"path"in i){if(!n.find((s)=>ye(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>vi(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!ye(t)||!ye(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(ye(i)&&ye(r[n]))r[n]=ts(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ye(i[0])&&ye(r[n][0])){let s=[...i];for(let a of r[n])if(ye(a)&&"name"in a){if(!s.find((o)=>ye(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ye(a)&&"path"in a){if(!s.find((o)=>ye(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>vi(o,a)))s.push(a);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let a of r[n])if(!s.includes(a))s.push(a);r[n]=s}else r[n]=i;else r[n]=i}return r}function vi(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(!vi(e[r],t[r]))return!1;return!0}if(ye(e)&&ye(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!vi(e[i],t[i]))return!1}return!0}return!1}function ye(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Rh(e,t){if(!Ko(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return ts(t,n)}catch{return null}}catch{return null}}async function Oh({name:e="",cwd:t,defaultConfig:r}){let n=t||Vn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of s)for(let o of i){let c=wi(n,`${a}${o}`),f=await Rh(c,r);if(f!==null)return f}try{let a=wi(n,"package.json");if(Ko(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return ts(r,o)}catch{}}}catch{}return r}function Ph(e,t={}){let r=Ci.cwd();while(r.includes("storage"))r=co(r,"..");let n=co(r,e||"");if(t?.relative)return Vu(Ci.cwd(),n);return n}async function kh(){try{let e=await Oh({name:"clarity",defaultConfig:di,cwd:Ci.cwd(),endpoint:"",headers:{}});return{...di,...e}}catch{return di}}function ve(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mh(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let e=pt.type;if(e==="renderer"||e==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class Zo{async format(e){let t=await Mh(),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:Yt.pid,hostname:t(),environment:Yt.env.NODE_ENV||"development",platform:Yt.platform,version:Yt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yt.env.NODE_ENV||Yt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bi{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Hn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Zo,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??We.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...mi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...mi};return{...mi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Hn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,a=1000;while(i<s)try{try{try{await Ju(this.config.logDirectory,mo.F_OK|mo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Uu(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:At.from(e);try{if(!Sn(this.currentLogFile))await An(this.currentLogFile,"",{mode:420});if(n=ho(this.currentLogFile,"a",420),Ku(n,o,{flag:"a"}),uo(n),n!==void 0)bn(n),n=void 0;if((await Jt(this.currentLogFile)).size===0){if(await An(this.currentLogFile,o,{flag:"w",mode:420}),(await Jt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=a*2**i;await new Promise((g)=>setTimeout(g,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{bn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(i===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}i++;let c=a*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ut(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 Ut(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ut(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((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[a]of n.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return vn(16).toString("hex")}generateKey(){return vn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=vn(16),n=_u("aes-256-gcm",t,r),i=At.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:At.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=go(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(At.from(At.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ve())return;let e=await Jt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await zr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Jt(r).catch(()=>null))try{if(await po(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&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await An(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Jt(r).catch(()=>null))await po(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await zr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await Qr(Ut(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=fo(e),n=ju(t),i=go();await Yu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Sn(this.currentLogFile))try{let e=ho(this.currentLogFile,"r+");uo(e),bn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ve()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Qr(Ut(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?me.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:a=!0}=e,o=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let c=We.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${me.cyan(i)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${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,n=0,i=e.replace(r,(s,a)=>{if(a==="%")return"%";if(n>=t.length)return s;let o=t[n++];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(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!ve()){let f=sl[e],u=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:me.gray(a),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:me.green(a),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(l),o){let g=o.split(`
149
+ `:" ",n++}continue}r+=s,n++}return r}function Su(e){let t=new Set,r=[/\b(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?:type|interface|class|enum|namespace|module)\s+([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g,/\b(?:export\s+)?declare\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g];for(let n of r)for(let i of e.matchAll(n))t.add(i[1]);return t}function Au(e){let t=new Set;for(let r of e.matchAll(/\bimport\s+(?:type\s+)?([\s\S]*?)\s+from\s*['"`]/g)){let n=r[1],i=/\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(n);if(i)t.add(i[1]);let s=n.split("{")[0].replace(/\*\s*as\s+[A-Za-z_$][\w$]*/,"");for(let o of s.split(",")){let c=o.trim();if(/^[A-Za-z_$][\w$]*$/.test(c))t.add(c)}let a=/\{([\s\S]*?)\}/.exec(n);if(a)for(let o of a[1].split(",")){let c=o.trim().replace(/^type\s+/,"");if(!c)continue;let f=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(c);t.add(f?f[1]:c.split(/\s+/)[0])}}for(let r of e.matchAll(/\bimport\s*\(\s*['"`][^'"`]*['"`]\s*\)\s*\.\s*([A-Za-z_$][\w$]*)/g))t.add(r[1]);return t}function xu(e){let t=new Set,r=(i)=>{for(let s of i.split(",")){let a=s.trim().split(/\s+|=/)[0]?.trim();if(a&&/^[A-Za-z_$][\w$]*$/.test(a))t.add(a)}},n=/\b(?:type|interface|class|function)\s+[A-Za-z_$][\w$]*\s*<([^<>]*(?:<[^<>]*>[^<>]*)*)>/g;for(let i of e.matchAll(n))r(i[1]);for(let i of e.matchAll(/(?:\b[A-Za-z_$][\w$]*)?\s*<([^<>()]*)>\s*\(/g))r(i[1]);for(let i of e.matchAll(/\binfer\s+([A-Za-z_$][\w$]*)/g))t.add(i[1]);for(let i of e.matchAll(/\[\s*([A-Za-z_$][\w$]*)\s+in\b/g))t.add(i[1]);return t}function Tu(e){let t=new Map,r=(i)=>{let s=1;for(let a=0;a<i&&a<e.length;a++)if(e.charCodeAt(a)===10)s++;return s},n=(i,s,a)=>{for(let o of i.matchAll(/\b([A-Z][\w$]*)\b/g)){let c=o[1];if(t.has(c))continue;let f=i.slice(o.index+c.length);if(/^\s*\??:/.test(f))continue;t.set(c,{line:r(s),context:a.trim().slice(0,120)})}};for(let i of e.matchAll(/\btype\s+[A-Za-z_$][\w$]*\s*(?:<[^=]*?>)?\s*=([^;]*)/g))n(i[1],i.index+i[0].indexOf("="),i[0]);for(let i of e.matchAll(/\b(?:extends|implements)\s+([^{;]*)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/:\s*([^;,){}\n=]+)/g))n(i[1],i.index,i[0]);for(let i of e.matchAll(/<([^<>()]*)>/g))n(i[1],i.index,i[0]);return t}function Xa(e){let t=qa(e),r=qa(e,{strings:!1}),n=new Set([...Su(t),...Au(r),...xu(t),...Ya,...bu]),i=[];for(let[s,a]of Tu(t)){if(n.has(s))continue;if(new RegExp(`[\\w$]\\s*\\.\\s*${s}\\b`).test(t))continue;i.push({name:s,line:a.line,context:a.context})}return i.sort((s,a)=>s.line-a.line||s.name.localeCompare(a.name))}var bu;var za=ae(()=>{Za();bu=new Set(["This","True","False","Null","Undefined","Void","Never","Any","Unknown","Object","Infinity","NaN"])});function _t(e){return Qa[e]>=Qa[Xr]}function Pu(){if(!Ou)return"";return`[${new Date().toISOString().slice(11,23)}] `}function ku(e,t){let r=Pu();if(e||r)return[`${r}${e}`,...t];return t}function Ht(e,t,r){let n=ku(t,r);if(eo){eo(e,...n);return}switch(e){case"debug":console.debug(...n);break;case"info":console.log(...n);break;case"warn":console.warn(...n);break;case"error":console.error(...n);break}}function to(e){return{debug:(...t)=>{if(_t("debug"))Ht("debug",e,t)},info:(...t)=>{if(_t("info"))Ht("info",e,t)},warn:(...t)=>{if(_t("warn"))Ht("warn",e,t)},error:(...t)=>{if(_t("error"))Ht("error",e,t)},setLevel:(t)=>{Xr=t},getLevel:()=>Xr,child:(t)=>{let r=e?`${e}:${t}`:`[${t}]`;return to(r)},time:(t)=>{let r=performance.now();return()=>{let n=performance.now()-r;if(_t("debug"))Ht("debug",e,[`${t}: ${n.toFixed(2)}ms`])}},progress:(t)=>{if(_t("info"))if(typeof process<"u"&&process.stdout?.isTTY)process.stdout.write(`\r${e} ${t}`);else Ht("info",e,[t])}}}function $n(e){Xr=e}var Qa,Xr="info",Ru="[dtsx]",Ou=!1,eo=null,H;var ro=ae(()=>{Qa={debug:0,info:1,warn:2,error:3,silent:4};H=to(Ru)});import Mu from"process";import{existsSync as io,statSync as no}from"fs";import{existsSync as Iu,mkdirSync as Mp,readdirSync as Ip,readFileSync as Du,writeFileSync as Dp}from"fs";import{homedir as jt}from"os";import{dirname as Lp,resolve as Qe}from"path";import ki from"process";import{existsSync as so,statSync as ao}from"fs";import{existsSync as Bn,mkdirSync as Fu,readdirSync as Nu,writeFileSync as Lu}from"fs";import{homedir as Kt}from"os";import{dirname as oo,resolve as je}from"path";import Mt from"process";import{join as Wu,relative as Gu,resolve as lo}from"path";import yi from"process";import{existsSync as jo,mkdirSync as Up,readdirSync as Yp,writeFileSync as Zp}from"fs";import{homedir as En}from"os";import{dirname as zp,resolve as He}from"path";import wr from"process";import{join as Bu,relative as Vu,resolve as co}from"path";import Ci from"process";import{existsSync as Ko,mkdirSync as ig,readdirSync as ng,writeFileSync as sg}from"fs";import{dirname as og,resolve as wi}from"path";import Vn from"process";import{Buffer as At}from"buffer";import{createCipheriv as _u,createDecipheriv as Hu,randomBytes as vn}from"crypto";import{closeSync as bn,createReadStream as fo,createWriteStream as ju,existsSync as Sn,fsyncSync as uo,openSync as ho,writeFileSync as Ku}from"fs";import{access as Ju,constants as mo,mkdir as Uu,readdir as zr,rename as po,stat as Jt,unlink as Qr,writeFile as An}from"fs/promises";import{join as Ut}from"path";import We from"process";import{pipeline as Yu}from"stream/promises";import{createGzip as go}from"zlib";import Yt from"process";import pt from"process";import{Buffer as ht}from"buffer";import{createCipheriv as Zu,createDecipheriv as qu,randomBytes as xn}from"crypto";import{closeSync as Tn,createReadStream as yo,createWriteStream as Xu,existsSync as ei,fsyncSync as Co,openSync as wo,writeFileSync as zu}from"fs";import{access as Qu,constants as $o,mkdir as eh,readdir as ti,rename as Eo,stat as Zt,unlink as ri,writeFile as Rn}from"fs/promises";import{isAbsolute as th,join as qt,resolve as rh}from"path";import ce from"process";import{pipeline as ih}from"stream/promises";import{createGzip as vo}from"zlib";import Xt from"process";import gt from"process";import ii from"process";import{existsSync as ni}from"fs";import{resolve as On}from"path";import{existsSync as nh}from"fs";import{existsSync as sh,readdirSync as ah}from"fs";import{extname as Pn,resolve as bo}from"path";import oh from"process";import{join as lh,relative as ch,resolve as So}from"path";import $i from"process";import{Buffer as dt}from"buffer";import{createCipheriv as fh,createDecipheriv as uh,randomBytes as kn}from"crypto";import{closeSync as Mn,createReadStream as Ao,createWriteStream as hh,existsSync as si,fsyncSync as xo,openSync as To,writeFileSync as dh}from"fs";import{access as mh,constants as Ro,mkdir as ph,readdir as ai,rename as Oo,stat as zt,unlink as oi,writeFile as In}from"fs/promises";import{isAbsolute as gh,join as Qt,resolve as yh}from"path";import fe from"process";import{pipeline as Ch}from"stream/promises";import{createGzip as Po}from"zlib";import er from"process";import yt from"process";import li from"process";import{existsSync as ci}from"fs";import{resolve as Dn}from"path";import{existsSync as wh}from"fs";class Jo{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,a=this.estimateSize(t);this.cache.set(i,{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),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!io(e))return!0;return no(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=io(r)?no(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Uo{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),s}catch(s){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function vh(e,t){this[e]=Eh.bind(null,t)}class Qn{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,a=this.estimateSize(t);this.cache.set(i,{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),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!so(e))return!0;return ao(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=so(r)?ao(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class es{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),a=performance.now()-n;return this.recordMetric({operation:e,duration:a,timestamp:i,...r}),s}catch(s){let a=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ah(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function xh(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Th(e){return e.getStats().size*2}function ts(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ye(t[0])&&"id"in t[0]&&t[0].id===3&&ye(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ye(t)&&ye(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(ye(e)&&"arr"in e&&Array.isArray(e.arr)&&ye(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ye(t[0])&&ye(e[0])){let n=[...t];for(let i of e)if(ye(i)&&"name"in i){if(!n.find((s)=>ye(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(ye(i)&&"path"in i){if(!n.find((s)=>ye(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>vi(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!ye(t)||!ye(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(ye(i)&&ye(r[n]))r[n]=ts(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ye(i[0])&&ye(r[n][0])){let s=[...i];for(let a of r[n])if(ye(a)&&"name"in a){if(!s.find((o)=>ye(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ye(a)&&"path"in a){if(!s.find((o)=>ye(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>vi(o,a)))s.push(a);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let a of r[n])if(!s.includes(a))s.push(a);r[n]=s}else r[n]=i;else r[n]=i}return r}function vi(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(!vi(e[r],t[r]))return!1;return!0}if(ye(e)&&ye(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!vi(e[i],t[i]))return!1}return!0}return!1}function ye(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Rh(e,t){if(!Ko(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return ts(t,n)}catch{return null}}catch{return null}}async function Oh({name:e="",cwd:t,defaultConfig:r}){let n=t||Vn.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of s)for(let o of i){let c=wi(n,`${a}${o}`),f=await Rh(c,r);if(f!==null)return f}try{let a=wi(n,"package.json");if(Ko(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return ts(r,o)}catch{}}}catch{}return r}function Ph(e,t={}){let r=Ci.cwd();while(r.includes("storage"))r=co(r,"..");let n=co(r,e||"");if(t?.relative)return Vu(Ci.cwd(),n);return n}async function kh(){try{let e=await Oh({name:"clarity",defaultConfig:di,cwd:Ci.cwd(),endpoint:"",headers:{}});return{...di,...e}}catch{return di}}function ve(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mh(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let e=pt.type;if(e==="renderer"||e==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class Zo{async format(e){let t=await Mh(),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:Yt.pid,hostname:t(),environment:Yt.env.NODE_ENV||"development",platform:Yt.platform,version:Yt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yt.env.NODE_ENV||Yt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bi{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Hn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Zo,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??We.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...mi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...mi};return{...mi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Hn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,a=1000;while(i<s)try{try{try{await Ju(this.config.logDirectory,mo.F_OK|mo.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Uu(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:At.from(e);try{if(!Sn(this.currentLogFile))await An(this.currentLogFile,"",{mode:420});if(n=ho(this.currentLogFile,"a",420),Ku(n,o,{flag:"a"}),uo(n),n!==void 0)bn(n),n=void 0;if((await Jt(this.currentLogFile)).size===0){if(await An(this.currentLogFile,o,{flag:"w",mode:420}),(await Jt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let f=c;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(i<s-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let l=a*2**i;await new Promise((g)=>setTimeout(g,l)),i++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{bn(n)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(o){if(i===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}i++;let c=a*2**(i-1);await new Promise((f)=>setTimeout(f,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ut(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 Ut(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ut(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((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[a]of n.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return vn(16).toString("hex")}generateKey(){return vn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=vn(16),n=_u("aes-256-gcm",t,r),i=At.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:At.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=go(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(At.from(At.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ve())return;let e=await Jt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await zr(this.config.logDirectory),s=i.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Jt(r).catch(()=>null))try{if(await po(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&&!i.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await An(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Jt(r).catch(()=>null))await po(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await zr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of i.slice(t.maxFiles))await Qr(Ut(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=fo(e),n=ju(t),i=go();await Yu(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Sn(this.currentLogFile))try{let e=ho(this.currentLogFile,"r+");uo(e),bn(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ve()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Qr(Ut(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?me.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:a=!0}=e,o=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(t);if(s==="warning")h.push("WARN");else if(s==="error")h.push("ERROR");else if(r)h.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)h.push(n.replace(/[[\]]/g,""));return h.push(i),h.join(" ")}let c=We.stdout.columns||120,f="";if(s==="warning"||s==="error")f=`${r} ${i}`;else if(s==="info"||s==="success")f=`${r} ${n} ${i}`;else f=`${r} ${n} ${me.cyan(i)}`;if(!a)return f.trim();let u=o(f).trim().length,l=o(t).length,g=Math.max(1,c-2-u-l);return`${f.trim()}${" ".repeat(g)}${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,n=0,i=e.replace(r,(s,a)=>{if(a==="%")return"%";if(n>=t.length)return s;let o=t[n++];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(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!ve()){let f=sl[e],u=this.options.showTags!==!1&&this.name?me.gray(this.formatTag(this.name)):"",l;switch(e){case"debug":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:me.gray(a),level:e}),console.error(l);break;case"info":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(l);break;case"success":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:me.green(a),level:e}),console.error(l);break;case"warning":l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.warn(l);break;case"error":if(l=this.formatConsoleMessage({timestamp:i,icon:f,tag:u,message:a,level:e}),console.error(l),o){let g=o.split(`
150
150
  `);for(let h of g)if(h.trim()&&!h.includes(a))console.error(this.formatConsoleMessage({timestamp:i,message:me.gray(` ${h}`),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}
151
151
  `;if(o)c+=`${o}
152
152
  `;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?me.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:me.blue("\u25D0"),tag:r,message:`${me.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,a=new Date,o=this.formatConsoleTimestamp(a),c=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
@@ -175,9 +175,9 @@ ${n}`}if(o)return`${fu(o)}${n}`;return r+n}function du(e,t=!0){let r=ut(e.leadin
175
175
  `;r+=`| Variable | Type | Description | Example |
176
176
  `,r+=`|----------|------|-------------|----------|
177
177
  `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
178
- `;return r}}function Bh(e,t){let r=il("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Qo(e,t,r={}){return el(e,t,r,new WeakMap)}function el(e,t,r,n){let{arrayMergeMode:i="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 tl(e,t,i,n);if(!et(t)||!et(e))return t;return jh(e,t,r,n)}function tl(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Vh(e,t);case"smart":return _h(e,t,n);default:return t}return t}function Vh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>_n(i,n)))r.push(n);return r}function _h(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(et(t[0])&&et(e[0]))return Hh(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Hh(e,t,r){let n=[...t];for(let i of e){if(!et(i)){n.push(i);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in i){if(n.find((c)=>et(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function jh(e,t,r,n){let i=t;if(et(i)&&n.has(i))return n.get(i);let s={...e};if(et(i))n.set(i,s);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let o=i[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(et(o)&&et(c))s[a]=el(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=tl(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function is(e,t,r="replace"){return Qo(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function _n(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(!_n(e[r],t[r]))return!1;return!0}if(et(e)&&et(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!_n(e[i],t[i]))return!1}return!0}return!1}function et(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ii{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(i){let f=tr.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ni(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,h=Object.keys(u).length>0;if(!g&&!h)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let w={config:is(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)tr.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?xt.configLoad(e,f):xt.configLoad(e,Error(String(f)))}};if(a)return vr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let a of this.extensions)i.push(On(t,`${s}${a}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Xo(async()=>{return ni(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ni(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let a of this.extensions){let o=On(e,`${s}${a}`);if(await this.checkFileAccess(o))n.push(o)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=On(e,a);if(await this.checkFileAccess(o))n.push(o)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ni(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class ns{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await vr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!nh(t))throw new Er(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Er(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(n.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(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,n,i,s),s.stopOnFirstError&&n.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(n.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,n,i,s),s.stopOnFirstError&&n.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))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(n.push(...o),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,a]=n;t.push({path:i,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:ll},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ss{fileLoader=new Ii;envProcessor=new Mi;validator=new ns;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,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")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))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(i||s)await this.validateConfiguration(o.config,i,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)it.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){let c=Date.now()-t;throw it.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Mt.cwd(),g=[],h=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(h)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(h,g,c,n,u);let w=await this.loadHomeConfiguration(n,i,o,f,u,c);if(w)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(je(l,"package.json")),this.finalizeResult(v,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,a)),t)throw xt.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,o,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,a,o,c){let f=o?Cr(e,i,a):i,u=this.getLocalDirectories(r,n);for(let l of u){if(a)it.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)it.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?Cr(e,r,i):r,o=[je(Kt(),".config",e),je(Kt(),".config"),Kt()];for(let c of o){if(i)it.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)it.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,a){let o=a?Cr(e,n,s):n;try{let c=je(r,"package.json");if(!Bn(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)it.success(`Configuration loaded from package.json: ${l}`);return{config:is(o,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)it.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cr(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw xt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return tr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);tr.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,je(e,"config"),je(e,".config"),t?je(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(je(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let a of i)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[je(Kt(),".config",e),je(Kt(),".config"),Kt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ko(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 Kh(e){return Ct.loadConfig({...e,__strictErrorHandling:!0})}async function rl(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Ct.loadConfig(e);else n=await Ct.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)it.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);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 Ct.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function Jh(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Ct.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"&&ko(r)))return(await Ct.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Ct.loadConfig({...e,cwd:e.cwd||Mt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ko(t)))return(await Ct.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Uh(e,t,r="replace"){let n=new Ii;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Cr(e,t,r=!1){let n=new Mi,i=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],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((v)=>v.toUpperCase()).join("")}`,`${i}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let v of g)if(h=Mt.env[v],h!==void 0){w=v;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let v=Number(h);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((v)=>v.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Yh(e){let t=je(Mt.cwd(),e.configDir),r=je(Mt.cwd(),e.generatedDir),n=je(r,"config-types.ts");if(!Bn(oo(n)))Fu(oo(n),{recursive:!0,mode:511});let i=Bn(t)?Nu(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${bd}
178
+ `;return r}}function Bh(e,t){let r=il("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Qo(e,t,r={}){return el(e,t,r,new WeakMap)}function el(e,t,r,n){let{arrayMergeMode:i="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 tl(e,t,i,n);if(!et(t)||!et(e))return t;return jh(e,t,r,n)}function tl(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Vh(e,t);case"smart":return _h(e,t,n);default:return t}return t}function Vh(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>_n(i,n)))r.push(n);return r}function _h(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(et(t[0])&&et(e[0]))return Hh(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Hh(e,t,r){let n=[...t];for(let i of e){if(!et(i)){n.push(i);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in i){if(n.find((c)=>et(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function jh(e,t,r,n){let i=t;if(et(i)&&n.has(i))return n.get(i);let s={...e};if(et(i))n.set(i,s);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let o=i[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(et(o)&&et(c))s[a]=el(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=tl(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function is(e,t,r="replace"){return Qo(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function _n(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(!_n(e[r],t[r]))return!1;return!0}if(et(e)&&et(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!_n(e[i],t[i]))return!1}return!0}return!1}function et(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ii{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(i){let f=tr.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ni(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,h=Object.keys(u).length>0;if(!g&&!h)throw new $r(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new $r(e,Error("Configuration must export a valid object"),"unknown");let w={config:is(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)tr.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?xt.configLoad(e,f):xt.configLoad(e,Error(String(f)))}};if(a)return vr.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let a of this.extensions)i.push(On(t,`${s}${a}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Xo(async()=>{return ni(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ni(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let a of this.extensions){let o=On(e,`${s}${a}`);if(await this.checkFileAccess(o))n.push(o)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=On(e,a);if(await this.checkFileAccess(o))n.push(o)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ni(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class ns{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await vr.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!nh(t))throw new Er(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Er(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(n.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(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,n,i,s),s.stopOnFirstError&&n.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(n.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,n,i,s),s.stopOnFirstError&&n.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))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(n.push(...o),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,a]=n;t.push({path:i,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:ll},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ss{fileLoader=new Ii;envProcessor=new Mi;validator=new ns;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,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")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))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(i||s)await this.validateConfiguration(o.config,i,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)nt.warn(`Slow configuration loading detected: ${c.duration}ms for ${a.name}`);o.metrics=c}return o}catch(o){let c=Date.now()-t;throw nt.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||Mt.cwd(),g=[],h=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(h)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(h,g,c,n,u);let w=await this.loadHomeConfiguration(n,i,o,f,u,c);if(w)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(je(l,"package.json")),this.finalizeResult(v,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,a)),t)throw xt.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,o,c,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,a,o,c){let f=o?Cr(e,i,a):i,u=this.getLocalDirectories(r,n);for(let l of u){if(a)nt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)nt.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?Cr(e,r,i):r,o=[je(Kt(),".config",e),je(Kt(),".config"),Kt()];for(let c of o){if(i)nt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)nt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,a){let o=a?Cr(e,n,s):n;try{let c=je(r,"package.json");if(!Bn(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)nt.success(`Configuration loaded from package.json: ${l}`);return{config:is(o,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)nt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cr(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw xt.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return tr.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);tr.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,je(e,"config"),je(e,".config"),t?je(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(je(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let a of i)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[je(Kt(),".config",e),je(Kt(),".config"),Kt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ko(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 Kh(e){return Ct.loadConfig({...e,__strictErrorHandling:!0})}async function rl(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Ct.loadConfig(e);else n=await Ct.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)nt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);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 Ct.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function Jh(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Ct.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"&&ko(r)))return(await Ct.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Ct.loadConfig({...e,cwd:e.cwd||Mt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ko(t)))return(await Ct.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Uh(e,t,r="replace"){let n=new Ii;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Cr(e,t,r=!1){let n=new Mi,i=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],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((v)=>v.toUpperCase()).join("")}`,`${i}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let v of g)if(h=Mt.env[v],h!==void 0){w=v;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let v=Number(h);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((v)=>v.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}function Yh(e){let t=je(Mt.cwd(),e.configDir),r=je(Mt.cwd(),e.generatedDir),n=je(r,"config-types.ts");if(!Bn(oo(n)))Fu(oo(n),{recursive:!0,mode:511});let i=Bn(t)?Nu(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${bd}
179
179
  export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
180
- `;Lu(n,s,{mode:438})}function Zh(e){let t=null,r=null,n=()=>{if(!r)r=rl(e).then((s)=>{return t=s,s},(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)it.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,a){if(t)return t[a];let o=i[a];return n(),o},has(s,a){return a in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||i,a)},set(s,a,o){if(!t)t={...i};return t[a]=o,!0}})}function qh(e){let t=bo(oh.cwd(),e?.configDir||"./config");function r(){if(!sh(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=ah(t).filter((c)=>i.has(Pn(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=Pn(f).toLowerCase(),l=o.get(c);if(!l){o.set(c,f);continue}let g=Pn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(g))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 n(){let i=r(),s=i.map((c)=>c.base),a=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",o=i.length?`{
180
+ `;Lu(n,s,{mode:438})}function Zh(e){let t=null,r=null,n=()=>{if(!r)r=rl(e).then((s)=>{return t=s,s},(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)nt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,a){if(t)return t[a];let o=i[a];return n(),o},has(s,a){return a in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||i,a)},set(s,a,o){if(!t)t={...i};return t[a]=o,!0}})}function qh(e){let t=bo(oh.cwd(),e?.configDir||"./config");function r(){if(!sh(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=ah(t).filter((c)=>i.has(Pn(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=Pn(f).toLowerCase(),l=o.get(c);if(!l){o.set(c,f);continue}let g=Pn(l).toLowerCase();if(s.indexOf(u)<s.indexOf(g))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 n(){let i=r(),s=i.map((c)=>c.base),a=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",o=i.length?`{
181
181
  ${i.map((c)=>{let f=bo(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${f}').default`}).join(`,
182
182
  `)}
183
183
  }`:"Record<string, any>";return`export type ConfigNames = ${a}
@@ -205,7 +205,7 @@ export type ConfigOf = Config
205
205
  `;r+=`| Variable | Type | Description | Example |
206
206
  `,r+=`|----------|------|-------------|----------|
207
207
  `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
208
- `;return r}}function Dd(e,t,r={}){return $l(e,t,r,new WeakMap)}function $l(e,t,r,n){let{arrayMergeMode:i="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 El(e,t,i,n);if(!tt(t)||!tt(e))return t;return Wd(e,t,r,n)}function El(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Fd(e,t);case"smart":return Nd(e,t,n);default:return t}return t}function Fd(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Xn(i,n)))r.push(n);return r}function Nd(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(tt(t[0])&&tt(e[0]))return Ld(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Ld(e,t,r){let n=[...t];for(let i of e){if(!tt(i)){n.push(i);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in i){if(n.find((c)=>tt(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function Wd(e,t,r,n){let i=t;if(tt(i)&&n.has(i))return n.get(i);let s={...e};if(tt(i))n.set(i,s);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let o=i[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(tt(o)&&tt(c))s[a]=$l(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=El(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function vl(e,t,r="replace"){return Dd(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Xn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Xn(e[r],t[r]))return!1;return!0}if(tt(e)&&tt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Xn(e[i],t[i]))return!1}return!0}return!1}function tt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(i){let f=Ei.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ci(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,h=Object.keys(u).length>0;if(!g&&!h)throw new Oi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Oi(e,Error("Configuration must export a valid object"),"unknown");let w={config:vl(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Ei.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?rr.configLoad(e,f):rr.configLoad(e,Error(String(f)))}};if(a)return zn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let a of this.extensions)i.push(Dn(t,`${s}${a}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return Id(async()=>{return ci(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ci(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let a of this.extensions){let o=Dn(e,`${s}${a}`);if(await this.checkFileAccess(o))n.push(o)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=Dn(e,a);if(await this.checkFileAccess(o))n.push(o)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ci(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Sl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await zn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!wh(t))throw new Pi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Pi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(n.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(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,n,i,s),s.stopOnFirstError&&n.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(n.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,n,i,s),s.stopOnFirstError&&n.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))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(n.push(...o),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,a]=n;t.push({path:i,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:Gd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Bd(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 Al{fileLoader=new bl;envProcessor=new os;validator=new Sl;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,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")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))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(i||s)await this.validateConfiguration(o.config,i,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)mt.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 mt.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||ki.cwd(),g=[],h=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(h)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(h,g,c,n,u);let w=await this.loadHomeConfiguration(n,i,o,f,u,c);if(w)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(Qe(l,"package.json")),this.finalizeResult(v,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,a)),t)throw rr.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,o,c,u),warnings:[`No configuration file found for "${n}"${Bd(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,a,o,c){let f=o?ui(e,i,a):i,u=this.getLocalDirectories(r,n);for(let l of u){if(a)mt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)mt.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?ui(e,r,i):r,o=[Qe(jt(),".config",e),Qe(jt(),".config"),jt()];for(let c of o){if(i)mt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)mt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,a){let o=a?ui(e,n,s):n;try{let c=Qe(r,"package.json");if(!Iu(c))return null;let f={};try{f=JSON.parse(Du(c,"utf8"))}catch(g){if(s)mt.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let u=f[e],l=e;if(!u&&t){let g=Array.isArray(t)?t:[t];for(let h of g){if(!h)continue;if(f[h]){u=f[h],l=h;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)mt.success(`Configuration loaded from package.json: ${l}`);return{config:vl(o,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)mt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ui(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw rr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ei.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Ei.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Qe(e,"config"),Qe(e,".config"),t?Qe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Qe(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let a of i)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Qe(jt(),".config",e),Qe(jt(),".config"),jt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ui(e,t,r=!1){let n=new os,i=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],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((v)=>v.toUpperCase()).join("")}`,`${i}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let v of g)if(h=ki.env[v],h!==void 0){w=v;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let v=Number(h);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((v)=>v.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var Ei,zn,$h,Eh=(e)=>e,bh=(e,t)=>{for(var r in t)$h(e,r,{get:t[r],enumerable:!0,configurable:!0,set:vh.bind(t,r)})},Sh=(e,t)=>()=>(e&&(t=e(e=0)),t),Yo,il,tr,vr,nl,Xh,zh,Mo,di,Hn,Ge,me,Qh,Io,ed,Do,td,rd,Fn,id,Fo,No,Nn,nd,sd,ad,od,mi,sl,ld,Be,cd,fd,Lo,pi,jn,Me,ee,ud,Wo,hd,Go,dd,md,Ln,pd,Bo,Vo,gd,Wn,yd,Cd,wd,$d,Ed,gi,al,vd,bd="0.15.6",Ue,xi,$r,Kn,Jn,Ti,Un,Yn,Er,Zn,qn,xt,ol,ll,it,Ct,cl,fl,Sd,xd,ul,Ri,Xg,Le,te,zg,Rd,Qg,Od,ey,ty,_o,ry,Pd,kd,iy,Ho,ny,sy,ay,oy,ly,Gn,Md,cy,nt,dl,Oi,ml,pl,as,gl,yl,Pi,Cl,wl,rr,Gd,mt,fy,uy,hy,Vd,xl;var Tl=ae(()=>{Ei=new Jo,zn=new Uo,$h=Object.defineProperty;Yo={};bh(Yo,{withErrorRecovery:()=>Xo,tryLoadConfig:()=>Uh,loadConfigWithResult:()=>Kh,loadConfig:()=>rl,isRetryableError:()=>Gh,isConfigNotFoundError:()=>Wh,isBunfigError:()=>zo,globalPerformanceMonitor:()=>vr,globalCache:()=>tr,getEnvOrDefault:()=>Bh,generateConfigTypes:()=>Yh,defaultGeneratedDir:()=>fl,defaultConfigDir:()=>cl,deepMergeWithArrayStrategy:()=>is,deepMerge:()=>Qo,createLibraryConfig:()=>Zh,config:()=>Jh,bunfigPlugin:()=>qh,applyEnvVarsToConfig:()=>Cr,TypeGenerationError:()=>Yn,SchemaValidationError:()=>Er,PluginError:()=>qn,PerformanceMonitor:()=>es,FileSystemError:()=>Un,ErrorFactory:()=>xt,EnvVarError:()=>Ti,EnvProcessor:()=>Mi,ConfigValidator:()=>ns,ConfigValidationError:()=>Kn,ConfigNotFoundError:()=>xi,ConfigMergeError:()=>Jn,ConfigLoader:()=>ss,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Ii,ConfigCache:()=>Qn,CacheUtils:()=>nl,BunfigError:()=>Ue,BrowserConfigError:()=>Zn,ArrayMergeStrategies:()=>ol});Sd=Sh(async()=>{il=import.meta.require,tr=new Qn,vr=new es,nl={createKey:Ah,isEquivalent:xh,estimateMemoryUsage:Th},Xh=wi(Vn.cwd(),"config"),zh=wi(Vn.cwd(),"src/generated"),Mo=Ci.env.CLARITY_LOG_DIR||Bu(Ph(),"logs"),di={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hn=await kh(),Ge={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"},me=Ge,Qh=Ge.red,Io=Ge.green,ed=Ge.yellow,Do=Ge.blue,td=Ge.magenta,rd=Ge.cyan,Fn=Ge.white,id=Ge.gray,Fo=Ge.bgRed,No=Ge.bgYellow,Nn=Ge.bold,nd=Ge.dim,sd=Ge.italic,ad=Ge.underline,od=Ge.reset,mi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sl={debug:"\uD83D\uDD0D",info:Do("\u2139"),success:Io("\u2713"),warning:No(Fn(Nn(" WARN "))),error:Fo(Fn(Nn(" ERROR ")))},ld=new bi("stacks"),Be=new bi("bunfig",{showTags:!0}),cd=He(wr.cwd(),"config"),fd=He(wr.cwd(),"src/generated"),Lo=yi.env.CLARITY_LOG_DIR||Wu(Fh(),"logs"),pi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn=await Nh(),Me={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=Me,ud=Me.red,Wo=Me.green,hd=Me.yellow,Go=Me.blue,dd=Me.magenta,md=Me.cyan,Ln=Me.white,pd=Me.gray,Bo=Me.bgRed,Vo=Me.bgYellow,gd=Me.bgGray,Wn=Me.bold,yd=Me.dim,Cd=Me.italic,wd=Me.underline,$d=Me.strikethrough,Ed=Me.reset,gi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},al={debug:"\uD83D\uDD0D",info:Go("\u2139"),success:Wo("\u2713"),warning:Vo(Ln(Wn(" WARN "))),error:Bo(Ln(Wn(" ERROR ")))},vd=new Ai("stacks"),Ue=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}`}},xi=class extends Ue{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},$r=class extends Ue{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Kn=class extends Ue{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Jn=class extends Ue{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Ti=class extends Ue{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Un=class extends Ue{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}},Yn=class extends Ue{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Er=class extends Ue{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Zn=class extends Ue{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},qn=class extends Ue{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}},xt={configNotFound(e,t,r){return new xi(e,t,r)},configLoad(e,t,r){return new $r(e,t,r)},configValidation(e,t,r){return new Kn(e,t,r)},configMerge(e,t,r,n){return new Jn(e,t,r,n)},envVar(e,t,r,n){return new Ti(e,t,r,n)},fileSystem(e,t,r){return new Un(e,t,r)},typeGeneration(e,t,r){return new Yn(e,t,r)},schemaValidation(e,t,r){return new Er(e,t,r)},browserConfig(e,t,r,n){return new Zn(e,t,r,n)},plugin(e,t,r){return new qn(e,t,r)}},ol={replace:"replace",concat:"concat",smart:"smart"},ll=/^https?:\/\//,it=new Ai("bunfig",{showTags:!0}),Ct=new ss,cl=je(Mt.cwd(),"config"),fl=je(Mt.cwd(),"src/generated")});xd=$i.env.CLARITY_LOG_DIR||lh(Ad(),"logs"),ul={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xd,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ri={...ul},Xg=(async()=>{try{let{loadConfig:e}=await Sd().then(()=>Yo),t=await e({name:"clarity",alias:"logging",defaultConfig:ul,cwd:$i.cwd()});if(t)Object.assign(Ri,t)}catch{}return Ri})();Le={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"},te=Le,zg=Le.red,Rd=Le.green,Qg=Le.yellow,Od=Le.blue,ey=Le.magenta,ty=Le.cyan,_o=Le.white,ry=Le.gray,Pd=Le.bgRed,kd=Le.bgYellow,iy=Le.bgGray,Ho=Le.bold,ny=Le.dim,sy=Le.italic,ay=Le.underline,oy=Le.strikethrough,ly=Le.reset,Gn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Md={debug:"\uD83D\uDD0D",info:Od("\u2139"),success:Rd("\u2713"),warning:kd(_o(Ho(" WARN "))),error:Pd(_o(Ho(" ERROR ")))};cy=new Di("stacks");nt=class nt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};dl=class dl extends nt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Oi=class Oi extends nt{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}};ml=class ml extends nt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};pl=class pl extends nt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};as=class as extends nt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};gl=class gl extends nt{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}};yl=class yl extends nt{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}};Pi=class Pi extends nt{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})}};Cl=class Cl extends nt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};wl=class wl extends nt{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}};rr={configNotFound(e,t,r){return new dl(e,t,r)},configLoad(e,t,r){return new Oi(e,t,r)},configValidation(e,t,r){return new ml(e,t,r)},configMerge(e,t,r,n){return new pl(e,t,r,n)},envVar(e,t,r,n){return new as(e,t,r,n)},fileSystem(e,t,r){return new gl(e,t,r)},typeGeneration(e,t,r){return new yl(e,t,r)},schemaValidation(e,t,r){return new Pi(e,t,r)},browserConfig(e,t,r,n){return new Cl(e,t,r,n)},plugin(e,t,r){return new wl(e,t,r)}};Gd=/^https?:\/\//;mt=new Di("bunfig",{showTags:!0});fy=new Al;uy=Qe(ki.cwd(),"config"),hy=Qe(ki.cwd(),"src/generated"),Vd={cwd:Mu.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},xl=Vd});function ir(e,t){let r=1,n=1;for(let i=0;i<t;i++)if(e.charCodeAt(i)===10)r++,n=1;else n++;return{line:r,column:n}}function Rl(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},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 h=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:h,end:f});continue}if(u===39||u===34||u===96){s=u,a=f;continue}let g=e[f];if(g==="("||g==="["||g==="{")n.push({char:g,offset:f});else if(i[g]){let h=n.pop();if(!h||h.char!==i[g])t.push({...ir(e,f),message:`Unexpected closing delimiter ${g}`,code:"DTSX1004"})}}if(s)t.push({...ir(e,a),message:"Unterminated string literal",code:"DTSX1002"});if(o!==-1)t.push({...ir(e,o),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...ir(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((g)=>l.index>=g.start&&l.index<g.end))continue;t.push({...ir(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({...ir(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var Ol=()=>{};import{statSync as _d}from"fs";import{readFile as Hd,readdir as ky}from"fs/promises";import{createRequire as jd}from"module";import{dirname as Kd,isAbsolute as Pl,join as Jd,resolve as kl}from"path";import Ud from"process";function cs(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function br(e,t,r="lf"){let n=t.replace(/\r\n/g,`
208
+ `;return r}}function Dd(e,t,r={}){return $l(e,t,r,new WeakMap)}function $l(e,t,r,n){let{arrayMergeMode:i="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 El(e,t,i,n);if(!tt(t)||!tt(e))return t;return Wd(e,t,r,n)}function El(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Fd(e,t);case"smart":return Nd(e,t,n);default:return t}return t}function Fd(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Xn(i,n)))r.push(n);return r}function Nd(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(tt(t[0])&&tt(e[0]))return Ld(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Ld(e,t,r){let n=[...t];for(let i of e){if(!tt(i)){n.push(i);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in i){if(n.find((c)=>tt(c)&&(o in c)&&c[o]===i[o])){a=!0;break}}if(!a)n.push(i)}return n}function Wd(e,t,r,n){let i=t;if(tt(i)&&n.has(i))return n.get(i);let s={...e};if(tt(i))n.set(i,s);for(let a in i){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let o=i[a],c=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(tt(o)&&tt(c))s[a]=$l(c,o,r,n);else if(Array.isArray(o)||Array.isArray(c))s[a]=El(c,o,r.arrayMergeMode||"smart",n);else s[a]=o}return s}function vl(e,t,r="replace"){return Dd(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Xn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Xn(e[r],t[r]))return!1;return!0}if(tt(e)&&tt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Xn(e[i],t[i]))return!1}return!0}return!1}function tt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(i){let f=Ei.getWithFileCheck("file",e);if(f){if(o)console.log(`Configuration loaded from cache: ${e}`);return f}}let c=async()=>{if(!ci(e))return null;try{let f=`?t=${Date.now()}`,u=await import(e+f),l=u.default||u,g="default"in u,h=Object.keys(u).length>0;if(!g&&!h)throw new Oi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof l!=="object"||l===null||Array.isArray(l))throw new Oi(e,Error("Configuration must export a valid object"),"unknown");let w={config:vl(t,l,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Ei.setWithFileCheck("file",w,e,s);return w}catch(f){throw f instanceof Error?rr.configLoad(e,f):rr.configLoad(e,Error(String(f)))}};if(a)return zn.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let a of this.extensions)i.push(Dn(t,`${s}${a}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return Id(async()=>{return ci(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ci(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let a of this.extensions){let o=Dn(e,`${s}${a}`);if(await this.checkFileAccess(o))n.push(o)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=Dn(e,a);if(await this.checkFileAccess(o))n.push(o)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ci(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Sl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:c=!1}=r,f=async()=>{let u=[],l=[],g={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:a,trackPerformance:o,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:l}}};if(o)return await zn.track("validateConfiguration",f);return f()}async validateWithSchemaFile(e,t,r){try{if(!wh(t))throw new Pi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Pi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(n.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(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let a=0;a<e.length;a++){let o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,n,i,s),s.stopOnFirstError&&n.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(n.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,n,i,s),s.stopOnFirstError&&n.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))i.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(n.push(...o),r.stopOnFirstError&&n.length>0)break}catch(a){n.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,a]=n;t.push({path:i,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:Gd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Bd(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 Al{fileLoader=new bl;envProcessor=new os;validator=new Sl;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,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")),g=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(f&&(g||u))throw c;if(l&&(!f||!g))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(i||s)await this.validateConfiguration(o.config,i,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(n?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(c);if(n.slowThreshold&&c.duration>n.slowThreshold)mt.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 mt.error(`Configuration loading failed after ${c}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:a,defaultConfig:o,checkEnv:c=!0,arrayStrategy:f="replace",verbose:u=!1}=e,l=s||ki.cwd(),g=[],h=await this.loadLocalConfiguration(n,i,l,a,o,f,u,c,r);if(h)return g.push(...this.getLocalSearchPaths(n,i,l,a)),this.finalizeResult(h,g,c,n,u);let w=await this.loadHomeConfiguration(n,i,o,f,u,c);if(w)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,g,c,n,u);let v=await this.loadPackageJsonConfiguration(n,i,l,o,f,u,c);if(v)return g.push(Qe(l,"package.json")),this.finalizeResult(v,g,c,n,u);if(g.push(...this.getAllSearchPaths(n,i,l,a)),t)throw rr.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,o,c,u),warnings:[`No configuration file found for "${n}"${Bd(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,a,o,c){let f=o?ui(e,i,a):i,u=this.getLocalDirectories(r,n);for(let l of u){if(a)mt.info(`Searching for configuration in: ${l}`);let g=this.fileLoader.generateConfigPaths(e,l,t),h=await this.fileLoader.tryLoadFromPaths(g,f,{arrayStrategy:s,verbose:a,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(h){if(a)mt.success(`Configuration loaded from: ${h.source.path}`);return h}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let a=s?ui(e,r,i):r,o=[Qe(jt(),".config",e),Qe(jt(),".config"),jt()];for(let c of o){if(i)mt.info(`Checking home directory: ${c}`);let f=this.fileLoader.generateConfigPaths(e,c,t),u=await this.fileLoader.tryLoadFromPaths(f,a,{arrayStrategy:n,verbose:i});if(u){if(i)mt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,a){let o=a?ui(e,n,s):n;try{let c=Qe(r,"package.json");if(!Iu(c))return null;let f={};try{f=JSON.parse(Du(c,"utf8"))}catch(g){if(s)mt.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let u=f[e],l=e;if(!u&&t){let g=Array.isArray(t)?t:[t];for(let h of g){if(!h)continue;if(f[h]){u=f[h],l=h;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)mt.success(`Configuration loaded from package.json: ${l}`);return{config:vl(o,u,i),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)mt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ui(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(i.length>0)throw rr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ei.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Ei.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Qe(e,"config"),Qe(e,".config"),t?Qe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Qe(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let a of i)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Qe(jt(),".config",e),Qe(jt(),".config"),jt()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function ui(e,t,r=!1){let n=new os,i=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],g=[`${i}_${l.join("_").toUpperCase()}`,`${i}_${l.map((v)=>v.toUpperCase()).join("")}`,`${i}_${l.map((v)=>v.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,w;for(let v of g)if(h=ki.env[v],h!==void 0){w=v;break}if(h!==void 0&&w)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let v=Number(h);if(!Number.isNaN(v))c[f]=v}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((v)=>v.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=s(u,l)}return c}return s(t)}var Ei,zn,$h,Eh=(e)=>e,bh=(e,t)=>{for(var r in t)$h(e,r,{get:t[r],enumerable:!0,configurable:!0,set:vh.bind(t,r)})},Sh=(e,t)=>()=>(e&&(t=e(e=0)),t),Yo,il,tr,vr,nl,Xh,zh,Mo,di,Hn,Ge,me,Qh,Io,ed,Do,td,rd,Fn,id,Fo,No,Nn,nd,sd,ad,od,mi,sl,ld,Be,cd,fd,Lo,pi,jn,Me,ee,ud,Wo,hd,Go,dd,md,Ln,pd,Bo,Vo,gd,Wn,yd,Cd,wd,$d,Ed,gi,al,vd,bd="0.15.6",Ue,xi,$r,Kn,Jn,Ti,Un,Yn,Er,Zn,qn,xt,ol,ll,nt,Ct,cl,fl,Sd,xd,ul,Ri,zg,Le,te,Qg,Rd,ey,Od,ty,ry,_o,iy,Pd,kd,ny,Ho,sy,ay,oy,ly,cy,Gn,Md,fy,st,dl,Oi,ml,pl,as,gl,yl,Pi,Cl,wl,rr,Gd,mt,uy,hy,dy,Vd,xl;var Tl=ae(()=>{Ei=new Jo,zn=new Uo,$h=Object.defineProperty;Yo={};bh(Yo,{withErrorRecovery:()=>Xo,tryLoadConfig:()=>Uh,loadConfigWithResult:()=>Kh,loadConfig:()=>rl,isRetryableError:()=>Gh,isConfigNotFoundError:()=>Wh,isBunfigError:()=>zo,globalPerformanceMonitor:()=>vr,globalCache:()=>tr,getEnvOrDefault:()=>Bh,generateConfigTypes:()=>Yh,defaultGeneratedDir:()=>fl,defaultConfigDir:()=>cl,deepMergeWithArrayStrategy:()=>is,deepMerge:()=>Qo,createLibraryConfig:()=>Zh,config:()=>Jh,bunfigPlugin:()=>qh,applyEnvVarsToConfig:()=>Cr,TypeGenerationError:()=>Yn,SchemaValidationError:()=>Er,PluginError:()=>qn,PerformanceMonitor:()=>es,FileSystemError:()=>Un,ErrorFactory:()=>xt,EnvVarError:()=>Ti,EnvProcessor:()=>Mi,ConfigValidator:()=>ns,ConfigValidationError:()=>Kn,ConfigNotFoundError:()=>xi,ConfigMergeError:()=>Jn,ConfigLoader:()=>ss,ConfigLoadError:()=>$r,ConfigFileLoader:()=>Ii,ConfigCache:()=>Qn,CacheUtils:()=>nl,BunfigError:()=>Ue,BrowserConfigError:()=>Zn,ArrayMergeStrategies:()=>ol});Sd=Sh(async()=>{il=import.meta.require,tr=new Qn,vr=new es,nl={createKey:Ah,isEquivalent:xh,estimateMemoryUsage:Th},Xh=wi(Vn.cwd(),"config"),zh=wi(Vn.cwd(),"src/generated"),Mo=Ci.env.CLARITY_LOG_DIR||Bu(Ph(),"logs"),di={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hn=await kh(),Ge={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"},me=Ge,Qh=Ge.red,Io=Ge.green,ed=Ge.yellow,Do=Ge.blue,td=Ge.magenta,rd=Ge.cyan,Fn=Ge.white,id=Ge.gray,Fo=Ge.bgRed,No=Ge.bgYellow,Nn=Ge.bold,nd=Ge.dim,sd=Ge.italic,ad=Ge.underline,od=Ge.reset,mi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sl={debug:"\uD83D\uDD0D",info:Do("\u2139"),success:Io("\u2713"),warning:No(Fn(Nn(" WARN "))),error:Fo(Fn(Nn(" ERROR ")))},ld=new bi("stacks"),Be=new bi("bunfig",{showTags:!0}),cd=He(wr.cwd(),"config"),fd=He(wr.cwd(),"src/generated"),Lo=yi.env.CLARITY_LOG_DIR||Wu(Fh(),"logs"),pi={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn=await Nh(),Me={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=Me,ud=Me.red,Wo=Me.green,hd=Me.yellow,Go=Me.blue,dd=Me.magenta,md=Me.cyan,Ln=Me.white,pd=Me.gray,Bo=Me.bgRed,Vo=Me.bgYellow,gd=Me.bgGray,Wn=Me.bold,yd=Me.dim,Cd=Me.italic,wd=Me.underline,$d=Me.strikethrough,Ed=Me.reset,gi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},al={debug:"\uD83D\uDD0D",info:Go("\u2139"),success:Wo("\u2713"),warning:Vo(Ln(Wn(" WARN "))),error:Bo(Ln(Wn(" ERROR ")))},vd=new Ai("stacks"),Ue=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}`}},xi=class extends Ue{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},$r=class extends Ue{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Kn=class extends Ue{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Jn=class extends Ue{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Ti=class extends Ue{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Un=class extends Ue{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}},Yn=class extends Ue{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Er=class extends Ue{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Zn=class extends Ue{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},qn=class extends Ue{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}},xt={configNotFound(e,t,r){return new xi(e,t,r)},configLoad(e,t,r){return new $r(e,t,r)},configValidation(e,t,r){return new Kn(e,t,r)},configMerge(e,t,r,n){return new Jn(e,t,r,n)},envVar(e,t,r,n){return new Ti(e,t,r,n)},fileSystem(e,t,r){return new Un(e,t,r)},typeGeneration(e,t,r){return new Yn(e,t,r)},schemaValidation(e,t,r){return new Er(e,t,r)},browserConfig(e,t,r,n){return new Zn(e,t,r,n)},plugin(e,t,r){return new qn(e,t,r)}},ol={replace:"replace",concat:"concat",smart:"smart"},ll=/^https?:\/\//,nt=new Ai("bunfig",{showTags:!0}),Ct=new ss,cl=je(Mt.cwd(),"config"),fl=je(Mt.cwd(),"src/generated")});xd=$i.env.CLARITY_LOG_DIR||lh(Ad(),"logs"),ul={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xd,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ri={...ul},zg=(async()=>{try{let{loadConfig:e}=await Sd().then(()=>Yo),t=await e({name:"clarity",alias:"logging",defaultConfig:ul,cwd:$i.cwd()});if(t)Object.assign(Ri,t)}catch{}return Ri})();Le={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"},te=Le,Qg=Le.red,Rd=Le.green,ey=Le.yellow,Od=Le.blue,ty=Le.magenta,ry=Le.cyan,_o=Le.white,iy=Le.gray,Pd=Le.bgRed,kd=Le.bgYellow,ny=Le.bgGray,Ho=Le.bold,sy=Le.dim,ay=Le.italic,oy=Le.underline,ly=Le.strikethrough,cy=Le.reset,Gn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Md={debug:"\uD83D\uDD0D",info:Od("\u2139"),success:Rd("\u2713"),warning:kd(_o(Ho(" WARN "))),error:Pd(_o(Ho(" ERROR ")))};fy=new Di("stacks");st=class st 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}`}};dl=class dl extends st{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};Oi=class Oi extends st{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}};ml=class ml extends st{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};pl=class pl extends st{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};as=class as extends st{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};gl=class gl extends st{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}};yl=class yl extends st{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}};Pi=class Pi extends st{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})}};Cl=class Cl extends st{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};wl=class wl extends st{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}};rr={configNotFound(e,t,r){return new dl(e,t,r)},configLoad(e,t,r){return new Oi(e,t,r)},configValidation(e,t,r){return new ml(e,t,r)},configMerge(e,t,r,n){return new pl(e,t,r,n)},envVar(e,t,r,n){return new as(e,t,r,n)},fileSystem(e,t,r){return new gl(e,t,r)},typeGeneration(e,t,r){return new yl(e,t,r)},schemaValidation(e,t,r){return new Pi(e,t,r)},browserConfig(e,t,r,n){return new Cl(e,t,r,n)},plugin(e,t,r){return new wl(e,t,r)}};Gd=/^https?:\/\//;mt=new Di("bunfig",{showTags:!0});uy=new Al;hy=Qe(ki.cwd(),"config"),dy=Qe(ki.cwd(),"src/generated"),Vd={cwd:Mu.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},xl=Vd});function ir(e,t){let r=1,n=1;for(let i=0;i<t;i++)if(e.charCodeAt(i)===10)r++,n=1;else n++;return{line:r,column:n}}function Rl(e){let t=[],r=[],n=[],i={")":"(","]":"[","}":"{"},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 h=f;while(f<e.length&&e.charCodeAt(f)!==10)f++;r.push({start:h,end:f});continue}if(u===39||u===34||u===96){s=u,a=f;continue}let g=e[f];if(g==="("||g==="["||g==="{")n.push({char:g,offset:f});else if(i[g]){let h=n.pop();if(!h||h.char!==i[g])t.push({...ir(e,f),message:`Unexpected closing delimiter ${g}`,code:"DTSX1004"})}}if(s)t.push({...ir(e,a),message:"Unterminated string literal",code:"DTSX1002"});if(o!==-1)t.push({...ir(e,o),message:"Unterminated block comment",code:"DTSX1003"});for(let f of n)t.push({...ir(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((g)=>l.index>=g.start&&l.index<g.end))continue;t.push({...ir(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({...ir(e,f.index),message:"Declaration name expected",code:"DTSX1005"})}return t.sort((f,u)=>f.line-u.line||f.column-u.column)}var Ol=()=>{};import{statSync as _d}from"fs";import{readFile as Hd,readdir as My}from"fs/promises";import{createRequire as jd}from"module";import{dirname as Kd,isAbsolute as Pl,join as Jd,resolve as kl}from"path";import Ud from"process";function cs(){return`${String.fromCharCode(47,47,35)} sourceMappingURL=`}async function br(e,t,r="lf"){let n=t.replace(/\r\n/g,`
209
209
  `);if(!n.endsWith(`
210
210
  `))n+=`
211
211
  `;if(r==="crlf")n=n.replace(/\n/g,`\r
@@ -224,4 +224,6 @@ ${K}`);else H.debug(`[no changes] ${R}`)}catch{H.info(`[new file] ${De(r.cwd,R)}
224
224
  `);if(r.failOnUnresolvedReExport)throw Error(O);H.warn(O),H.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{H.debug("Bundling declarations...");let C=new Map,x=async(R)=>{let k=C.get(R);if(k!==void 0)return k;return k=await ct(R),C.set(R,k),k};for(let R of f)await x(R);let O=c.length===1&&!!r.bundleOutput;for(let R of c){let k=await Yi([R],{includeImports:!0}),E=new Set;for(let X of k.reachable){if(X.endsWith(".d.ts"))continue;if(X.includes("node_modules"))continue;E.add(X)}let G=f.filter((X)=>E.has(X));if(!G.includes(R))G.push(R);let re=new Map;for(let X of G){let se=C.get(X)??await x(X);re.set(X,se)}let I=await $a(G,re,r),_=O?rt(r.cwd,r.outdir,r.bundleOutput):xr(R,r);if(r.dryRun)H.info(`[dry-run] Would bundle ${I.files.length} files to: ${De(r.cwd,_)}`);else await fs(Ar(_),{recursive:!0}),await br(_,I.content,r.lineEnding),H.info(`Bundled ${I.files.length} files to: ${De(r.cwd,_)}`);if(O)break}}catch(C){let x=C instanceof Error?C.message:String(C);H.error(`Bundle failed: ${x}`)}if(a.durationMs=Date.now()-t,r.stats)if(r.outputFormat==="json")console.log(JSON.stringify(a,null,2));else{if(H.info(`
225
225
  --- Generation Statistics ---`),H.info(`Files processed: ${a.filesProcessed}`),H.info(`Files generated: ${a.filesGenerated}`),o>0)H.info(`Files cached: ${o}`);if(a.filesFailed>0)H.info(`Files failed: ${a.filesFailed}`);if(H.info(`Declarations found: ${a.declarationsFound}`),H.info(`Imports processed: ${a.importsProcessed}`),H.info(`Exports processed: ${a.exportsProcessed}`),a.filesValidated>0){if(H.info(`Files validated: ${a.filesValidated}`),a.validationErrors>0)H.info(`Validation errors: ${a.validationErrors}`)}if(H.info(`Duration: ${a.durationMs}ms`),a.errors.length>0){H.info(`
226
226
  Errors:`);for(let C of a.errors){let x=` - ${C.file}`;if(C.location)x+=`:${C.location.line}:${C.location.column}`;if(C.code)x+=` [${C.code}]`;if(x+=`: ${C.message}`,H.info(x),C.suggestion)H.info(` Suggestion: ${C.suggestion}`)}}H.info(`-----------------------------
227
- `)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(a);return H.debug("DTS generation complete!"),a}async function Bl(e){try{return await Xd(e)}catch{return rt(e)}}async function im(e){let t=rt(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(ds(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=rt(t,e.bundleOutput);if(!Fi(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===tm(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Bl(t),Bl(rt(e.cwd,e.root))]);if(Fi(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function nm(e){let t=Sr.get(e);if(!t){if(t=new Vl(e),Sr.set(e,t),Sr.size>rm){let r=Sr.keys().next().value;if(r!==void 0)Sr.delete(r)}}return t}async function sm(e){let t=rt(e.cwd,e.outdir);async function r(n){let i;try{i=await qd(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let a=rt(n,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 zd(a,{force:!0})}))}await r(t)}function us(e,t,r){if(!t||t.length===0)return!1;let n=De(r,e);for(let i of t){let s=nm(i);if(s.match(n)||s.match(e))return!0}return!1}async function am(e){let t=[],r=rt(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(ds(s)&&hs(s)){if(!s.includes("node_modules")){if(!Fi(s,r)&&e.outputStructure!=="flat")H.warn(`Skipping entrypoint outside root: ${De(e.cwd,s)}`);else if(!us(s,n,r))t.push(s)}}else{let a=new Vl(s);for await(let o of a.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(hs(o)&&!o.includes("node_modules")){if(!us(o,n,r))t.push(o)}}return[...new Set(t)].sort()}function Fi(e,t){let r=De(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!ds(r)}function om(e,t){let r=new Map;for(let n of e){let i=xr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${De(t.cwd,s)} and ${De(t.cwd,n)} both emit ${De(t.cwd,i)}`);r.set(i,n)}}function hs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function xr(e,t){let r=rt(t.cwd,t.root),n=De(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return rt(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return rt(t.cwd,t.outdir,i)}}function lm(e,t,r=""){let n=De(Ar(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}function cm(e,t,r){let n=xr(t,r),i=(s)=>{let a=Ir(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=em(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return lm(n,xr(a.resolved,r),u)+o};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`})}async function fm(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let a=Jr(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)a=await n.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=Ja(a,{filePath:e,sourceCode:s,declarations:a},r.keepComments,r.importOrder);if(f=cm(f,e,r),i)f=ka(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Ns(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:a.length,importCount:o,exportCount:c}}var Vl,rm=50,Sr;var Hl=ae(()=>{Rs();Is();Ls();va();Ra();Ma();Da();La();Ua();gn();wa();Wl();Tl();kr();ro();({Glob:Vl}=globalThis.Bun);Sr=new Map});var jl=ae(()=>{Hl()});var Xl={};hc(Xl,{dtsWatch:()=>Em,dtsCheck:()=>vm,dts:()=>ps,default:()=>Sm,clearCache:()=>bm,PluginErrorCodes:()=>Cm,DtsxPluginError:()=>sr});import{createHash as hm}from"crypto";import{existsSync as dm,readFileSync as mm,writeFileSync as pm}from"fs";import{dirname as gm,join as ym,relative as Kl,resolve as nr,sep as Li}from"path";import Ul from"process";class Yl{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},n=this.listeners.get(e)||[];for(let i of n)await i(r)}}class ms{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=ym(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(dm(this.manifestPath)){let t=JSON.parse(mm(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}=um("fs");e(this.cacheDir,{recursive:!0}),pm(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 wm(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return hm("md5").update(JSON.stringify(t)).digest("hex")}function ps(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:a,timeout:o=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new Yl;if(a){for(let[g,h]of Object.entries(a))if(h)l.on(g,h)}return{name:"bun-plugin-dtsx",async setup(g){let h=Date.now(),w=null,v=0;try{let C=ql(u,g),x=wm(C);if(C.clean){let E=nr(C.cwd??Ul.cwd(),C.outdir??"./dist");if(Jl.has(E))C.clean=!1;else Jl.add(E)}if(i)w=new ms(nr(s),x);if(await l.emit("start",{type:"start",files:C.entrypoints||[],config:C}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let R=await(async()=>{return new Promise((E,G)=>{let re=setTimeout(()=>{G(new sr(`Generation timed out after ${o}ms`,"TIMEOUT_ERROR",{timeout:o}))},o);Ni(C).then((I)=>{clearTimeout(re),E(I)}).catch((I)=>{clearTimeout(re),G(I)})})})(),k=Date.now()-h;if(w)w.save();if(await l.emit("complete",{type:"complete",stats:R,duration:k,fromCache:v}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${k}ms`),v>0)console.log(`[bun-plugin-dtsx] ${v} files served from cache`)}if(t)await t(R)}catch(C){let x=Zl(C);if(await l.emit("error",{type:"error",error:x}),r)await r(x);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${x.code}`),console.error(` Message: ${x.message}`),x.context)console.error(` Context: ${JSON.stringify(x.context)}`);if(f&&x.stack)console.error(` Stack: ${x.stack}`)}if(n&&!c)throw x}}}}function Zl(e){if(e instanceof sr)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 sr(e.message,t,{originalError:e.name},e)}return new sr(String(e),"GENERATION_ERROR")}function $m(e){let t=e.map((n)=>gm(n).split(Li)),r=t[0];for(let n of t.slice(1)){let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;r=r.slice(0,i)}return r.join(Li)||Li}function ql(e,t){let r=e.cwd||Ul.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&n?.length){let o=$m(n.map((c)=>nr(r,c)));s=Kl(r,o)||"."}s=s||"./src";let a=e.entrypoints;if(!a)if(n?.length){let o=nr(r,s),c=[];for(let f of n){let u=nr(r,f);if(u===o||u.startsWith(o+Li))c.push(Kl(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:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function Em(e={}){return ps({...e,incremental:!0,verbose:e.verbose??!0})}function vm(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=ql({...e,outdir:""},t);try{await Ni({...r,clean:!1})}catch(n){let i=Zl(n);if(e.onError)await e.onError(i);if(e.failOnError!==!1)throw i}}}}function bm(e=".dtsx-cache"){new ms(nr(e),"").clear()}var um,Cm,sr,Jl,Sm;var zl=ae(()=>{jl();um=import.meta.require,Cm={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};sr=class sr extends Error{code;context;cause;constructor(e,t,r,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Jl=new Set;Sm=ps});import{mkdir as Am,stat as xm}from"fs/promises";import{bold as gs,dim as ys,green as Tm,italic as Ql,log as Rm}from"@stacksjs/cli";import{path as st}from"@stacksjs/path";import{glob as ec}from"@stacksjs/storage";async function Om(e){let t=await ec([st.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(s){throw Error(`Invalid declaration generated at ${n}: ${s instanceof Error?s.message:String(s)}`)}}}async function E0(e){let r=Date.now()-e.startTime,n=e.pkgName??`@stacksjs/${st.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 Om(e.dir);let i=await ec([st.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let a=await xm(s),o;if(a.size<1048576)o=`${(a.size/1024).toFixed(2)}kb`;else o=`${(a.size/1024/1024).toFixed(2)}mb`;let c=st.relative(e.dir,s).replace("dist/","");console.log(`${gs(ys(`[${o}]`))} ${ys("dist/")}${c}`)}console.log(`${gs(ys(`[${r}ms]`))} Built ${Ql(gs(Tm(n)))}`)}async function v0(e){let t=e.pkgName??`@stacksjs/${st.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Rm.info(`Building ${Ql(t)}...`);return{startTime:Date.now()}}async function b0(e){let{dts:t}=await Promise.resolve().then(() => (zl(),Xl)),r=st.resolve(e.dir,"src"),n=st.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((a)=>!a.endsWith(".d.ts")).filter((a)=>!a.endsWith(".test.ts")&&!a.endsWith(".spec.ts"));await Bun.build({entrypoints:i.map((a)=>st.resolve(r,a)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??Pm(),plugins:[t({root:r,outdir:n})]});let s=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0});for(let a of i){let o=s.transformSync(await Bun.file(st.resolve(r,a)).text());o=o.replace(/(['"])(\.\.?\/[^'"]+?)\.tsx?\1/g,"$1$2.js$1");let c=st.resolve(n,a.replace(/\.ts$/,".js"));await Am(st.dirname(c),{recursive:!0}),await Bun.write(c,o)}}function Pm(e=[]){let t=[];try{let r=Ye("fs"),n=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((r)=>`${r}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Om as validateDeclarations,b0 as transpilePackage,E0 as outro,v0 as intro,Pm as frameworkExternal};
227
+ `)}if(r.plugins&&r.plugins.length>0)await n.runOnEnd(a);return H.debug("DTS generation complete!"),a}async function Bl(e){try{return await Xd(e)}catch{return rt(e)}}async function im(e){let t=rt(e.cwd,e.outdir);if(e.bundle&&e.bundleOutput){if(ds(e.bundleOutput))throw Error("bundleOutput must be relative to outdir");let i=rt(t,e.bundleOutput);if(!Fi(i,t))throw Error("bundleOutput must stay within outdir")}if(!e.clean||e.dryRun)return;if(t===tm(t).root)throw Error("Refusing to clean declarations from the filesystem root");let[r,n]=await Promise.all([Bl(t),Bl(rt(e.cwd,e.root))]);if(Fi(n,r))throw Error("Refusing to clean an outdir that contains the source root")}function nm(e){let t=Sr.get(e);if(!t){if(t=new Vl(e),Sr.set(e,t),Sr.size>rm){let r=Sr.keys().next().value;if(r!==void 0)Sr.delete(r)}}return t}async function sm(e){let t=rt(e.cwd,e.outdir);async function r(n){let i;try{i=await qd(n,{withFileTypes:!0})}catch{return}await Promise.all(i.map(async(s)=>{let a=rt(n,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 zd(a,{force:!0})}))}await r(t)}function us(e,t,r){if(!t||t.length===0)return!1;let n=De(r,e);for(let i of t){let s=nm(i);if(s.match(n)||s.match(e))return!0}return!1}async function am(e){let t=[],r=rt(e.cwd,e.root),n=e.exclude||[],i=[...e.entrypoints,...e.include??[]];for(let s of i)if(ds(s)&&hs(s)){if(!s.includes("node_modules")){if(!Fi(s,r)&&e.outputStructure!=="flat")H.warn(`Skipping entrypoint outside root: ${De(e.cwd,s)}`);else if(!us(s,n,r))t.push(s)}}else{let a=new Vl(s);for await(let o of a.scan({cwd:r,absolute:!0,onlyFiles:!0}))if(hs(o)&&!o.includes("node_modules")){if(!us(o,n,r))t.push(o)}}return[...new Set(t)].sort()}function Fi(e,t){let r=De(t,e);return r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!ds(r)}function om(e,t){let r=new Map;for(let n of e){let i=xr(n,t),s=r.get(i);if(s&&s!==n)throw Error(`Output path collision: ${De(t.cwd,s)} and ${De(t.cwd,n)} both emit ${De(t.cwd,i)}`);r.set(i,n)}}function hs(e){return/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/.test(e)&&!/\.d\.(?:ts|mts|cts)$/.test(e)}function xr(e,t){let r=rt(t.cwd,t.root),n=De(r,e).replace(/\.(m?tsx?|cts|jsx?|mjs|cjs|vue|stx)$/,(i)=>{if(i===".mts"||i===".mjs")return".d.mts";if(i===".cts"||i===".cjs")return".d.cts";return".d.ts"});if(t.outputStructure==="mirror")return rt(t.cwd,t.outdir,n);else{let i=n.split("/").pop();return rt(t.cwd,t.outdir,i)}}function lm(e,t,r=""){let n=De(Ar(e),t).replace(/\\/g,"/");if(n=n.replace(/\.d\.mts$/,"").replace(/\.d\.cts$/,"").replace(/\.d\.ts$/,""),r)n+=r;if(!n.startsWith("."))n=`./${n}`;return n}function cm(e,t,r){let n=xr(t,r),i=(s)=>{let a=Ir(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=em(c),u=/^(?:\.js|\.jsx|\.mjs|\.cjs)$/.test(f)?f:"";return lm(n,xr(a.resolved,r),u)+o};return e.replace(/\b(from\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`}).replace(/\b(import\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`}).replace(/\b(import\s*\(\s*)(['"])(\.{1,2}\/[^'"]+)\2/g,(s,a,o,c)=>{return`${a}${o}${i(c)}${o}`})}async function fm(e,t,r,n,i){let s=t;if(n)s=await n.runOnBeforeFile(e,t);let a=Jr(s,e,r.keepComments,r.isolatedDeclarations??!1);if(n)a=await n.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=Ja(a,{filePath:e,sourceCode:s,declarations:a},r.keepComments,r.importOrder);if(f=cm(f,e,r),i)f=ka(f,i,{filePath:e});if(r.normalizeOutput===!0||r.declarationOrder)f=Ns(f,{lineEnding:"lf",declarationOrder:r.declarationOrder,indent:{style:r.indentStyle??"spaces",size:r.indentSize??2}});if(n)f=await n.runOnAfterFile(e,s,f);return{content:f,declarationCount:a.length,importCount:o,exportCount:c}}var Vl,rm=50,Sr;var Hl=ae(()=>{Rs();Is();Ls();va();Ra();Ma();Da();La();Ua();gn();wa();Wl();Tl();kr();ro();({Glob:Vl}=globalThis.Bun);Sr=new Map});var jl=ae(()=>{Hl()});var Xl={};hc(Xl,{dtsWatch:()=>Em,dtsCheck:()=>vm,dts:()=>ps,default:()=>Sm,clearCache:()=>bm,PluginErrorCodes:()=>Cm,DtsxPluginError:()=>sr});import{createHash as hm}from"crypto";import{existsSync as dm,readFileSync as mm,writeFileSync as pm}from"fs";import{dirname as gm,join as ym,relative as Kl,resolve as nr,sep as Li}from"path";import Ul from"process";class Yl{listeners=new Map;on(e,t){let r=this.listeners.get(e)||[];r.push(t),this.listeners.set(e,r)}async emit(e,t){let r={type:e,timestamp:Date.now(),data:t},n=this.listeners.get(e)||[];for(let i of n)await i(r)}}class ms{manifest;cacheDir;manifestPath;constructor(e,t){this.cacheDir=e,this.manifestPath=ym(e,"manifest.json"),this.manifest=this.loadManifest(t)}loadManifest(e){try{if(dm(this.manifestPath)){let t=JSON.parse(mm(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}=um("fs");e(this.cacheDir,{recursive:!0}),pm(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 wm(e){let t={root:e.root,outdir:e.outdir,entrypoints:e.entrypoints,clean:e.clean,tsconfigPath:e.tsconfigPath};return hm("md5").update(JSON.stringify(t)).digest("hex")}function ps(e={}){let{onSuccess:t,onError:r,failOnError:n=!0,incremental:i=!1,cacheDir:s=".dtsx-cache",on:a,timeout:o=60000,continueOnError:c=!1,verbose:f=!1,...u}=e,l=new Yl;if(a){for(let[g,h]of Object.entries(a))if(h)l.on(g,h)}return{name:"bun-plugin-dtsx",async setup(g){let h=Date.now(),w=null,v=0;try{let C=ql(u,g),x=wm(C);if(C.clean){let E=nr(C.cwd??Ul.cwd(),C.outdir??"./dist");if(Jl.has(E))C.clean=!1;else Jl.add(E)}if(i)w=new ms(nr(s),x);if(await l.emit("start",{type:"start",files:C.entrypoints||[],config:C}),f){if(console.log("[bun-plugin-dtsx] Starting declaration generation..."),i)console.log("[bun-plugin-dtsx] Incremental mode enabled")}let R=await(async()=>{return new Promise((E,G)=>{let re=setTimeout(()=>{G(new sr(`Generation timed out after ${o}ms`,"TIMEOUT_ERROR",{timeout:o}))},o);Ni(C).then((I)=>{clearTimeout(re),E(I)}).catch((I)=>{clearTimeout(re),G(I)})})})(),k=Date.now()-h;if(w)w.save();if(await l.emit("complete",{type:"complete",stats:R,duration:k,fromCache:v}),f){if(console.log(`[bun-plugin-dtsx] Generation complete in ${k}ms`),v>0)console.log(`[bun-plugin-dtsx] ${v} files served from cache`)}if(t)await t(R)}catch(C){let x=Zl(C);if(await l.emit("error",{type:"error",error:x}),r)await r(x);else{if(console.error("[bun-plugin-dtsx] Error generating declarations:"),console.error(` Code: ${x.code}`),console.error(` Message: ${x.message}`),x.context)console.error(` Context: ${JSON.stringify(x.context)}`);if(f&&x.stack)console.error(` Stack: ${x.stack}`)}if(n&&!c)throw x}}}}function Zl(e){if(e instanceof sr)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 sr(e.message,t,{originalError:e.name},e)}return new sr(String(e),"GENERATION_ERROR")}function $m(e){let t=e.map((n)=>gm(n).split(Li)),r=t[0];for(let n of t.slice(1)){let i=0;while(i<r.length&&i<n.length&&r[i]===n[i])i++;r=r.slice(0,i)}return r.join(Li)||Li}function ql(e,t){let r=e.cwd||Ul.cwd(),n=t?.config?.entrypoints,i=e.outdir||e.build?.config.outdir||t?.config.outdir||"./dist",s=e.root||e.build?.config.root||t?.config.root;if(!s&&n?.length){let o=$m(n.map((c)=>nr(r,c)));s=Kl(r,o)||"."}s=s||"./src";let a=e.entrypoints;if(!a)if(n?.length){let o=nr(r,s),c=[];for(let f of n){let u=nr(r,f);if(u===o||u.startsWith(o+Li))c.push(Kl(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:i,clean:e.clean??!0,tsconfigPath:e.tsconfigPath}}function Em(e={}){return ps({...e,incremental:!0,verbose:e.verbose??!0})}function vm(e){return{name:"bun-plugin-dtsx-check",async setup(t){let r=ql({...e,outdir:""},t);try{await Ni({...r,clean:!1})}catch(n){let i=Zl(n);if(e.onError)await e.onError(i);if(e.failOnError!==!1)throw i}}}}function bm(e=".dtsx-cache"){new ms(nr(e),"").clear()}var um,Cm,sr,Jl,Sm;var zl=ae(()=>{jl();um=import.meta.require,Cm={CONFIG_ERROR:"CONFIG_ERROR",GENERATION_ERROR:"GENERATION_ERROR",FILE_ERROR:"FILE_ERROR",CACHE_ERROR:"CACHE_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR"};sr=class sr extends Error{code;context;cause;constructor(e,t,r,n){super(e);if(this.name="DtsxPluginError",this.code=t,this.context=r,this.cause=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}};Jl=new Set;Sm=ps});import{mkdir as Am,stat as xm}from"fs/promises";import{bold as gs,dim as ys,green as Tm,italic as Ql,log as Rm}from"@stacksjs/cli";import{path as it}from"@stacksjs/path";import{glob as ec}from"@stacksjs/storage";async function Om(e){let t=await ec([it.resolve(e,"dist","**/*.d.ts")],{absolute:!0}),r=new Bun.Transpiler({loader:"ts",target:"bun"});for(let n of t){let i=await Bun.file(n).text();try{r.transformSync(i)}catch(s){throw Error(`Invalid declaration generated at ${n}: ${s instanceof Error?s.message:String(s)}`)}}}async function Pm(e){let t=it.resolve(e,"dist","index.js");if(!await Bun.file(t).exists())return;let r=Bun.spawnSync({cmd:[process.execPath,"-e",`await import(${JSON.stringify(t)})`],stdout:"ignore",stderr:"pipe",env:{...process.env,NODE_ENV:"test"}});if(r.exitCode===0)return;let n=new TextDecoder().decode(r.stderr??new Uint8Array);if(/needs to refer to a top-level declared variable|does not provide an export named|Export named .* not found/i.test(n))throw Error(`Built package at ${t} cannot be imported: ${n.trim().split(`
228
+ `)[0]}
229
+ This is the minified-barrel failure. Build with \`transpilePackage\` instead of a minifying \`Bun.build\`.`)}async function v0(e){let r=Date.now()-e.startTime,n=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}`)}await Om(e.dir),await Pm(e.dir);let i=await ec([it.resolve(e.dir,"dist","**/*")],{absolute:!0});for(let s of i){let a=await xm(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(`${gs(ys(`[${o}]`))} ${ys("dist/")}${c}`)}console.log(`${gs(ys(`[${r}ms]`))} Built ${Ql(gs(Tm(n)))}`)}async function b0(e){let t=e.pkgName??`@stacksjs/${it.basename(e.dir)}`;if(e.styled===!1)console.log(`Building ${t}...`);else Rm.info(`Building ${Ql(t)}...`);return{startTime:Date.now()}}async function S0(e){let{dts:t}=await Promise.resolve().then(() => (zl(),Xl)),r=it.resolve(e.dir,"src"),n=it.resolve(e.dir,"dist"),i=(await Array.fromAsync(new Bun.Glob("**/*.ts").scan({cwd:r}))).filter((a)=>!a.endsWith(".d.ts")).filter((a)=>!a.endsWith(".test.ts")&&!a.endsWith(".spec.ts"));await Bun.build({entrypoints:i.map((a)=>it.resolve(r,a)),outdir:n,root:r,target:"bun",format:"esm",splitting:!1,external:e.external??km(),plugins:[t({root:r,outdir:n})]});let s=new Bun.Transpiler({loader:"ts",target:"bun",minifyWhitespace:!0});for(let a of i){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(n,a.replace(/\.ts$/,".js"));await Am(it.dirname(c),{recursive:!0}),await Bun.write(c,o)}}function km(e=[]){let t=[];try{let r=Ye("fs"),n=JSON.parse(r.readFileSync(`${process.cwd()}/package.json`,"utf8"));t=[...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})]}catch{}return["@stacksjs/*",...t,...t.map((r)=>`${r}/*`),"bun-queue","ioredis","localtunnels","localtunnels/*","@craft-native/ts","ts-md","meilisearch","algoliasearch","@opensearch-project/opensearch","*.yaml","*.yml",...e]}export{Pm as validateRuntimeExports,Om as validateDeclarations,S0 as transpilePackage,v0 as outro,b0 as intro,km as frameworkExternal};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/build",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.71.1",
5
+ "version": "0.71.10",
6
6
  "description": "The Stacks framework build tools and configurations.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -59,9 +59,9 @@
59
59
  },
60
60
  "dependencies": {},
61
61
  "devDependencies": {
62
- "@stacksjs/cli": "0.71.1",
62
+ "@stacksjs/cli": "0.71.10",
63
63
  "better-dx": "^0.2.23",
64
- "@stacksjs/path": "0.71.1",
65
- "@stacksjs/storage": "0.71.1"
64
+ "@stacksjs/path": "0.71.10",
65
+ "@stacksjs/storage": "0.71.10"
66
66
  }
67
67
  }