@stacksjs/dtsx 0.9.9 → 0.9.11

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.
Files changed (113) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +243 -15
  3. package/dist/bin/cli.js +10 -22
  4. package/dist/branded-types.d.ts +150 -0
  5. package/dist/bundler.d.ts +55 -0
  6. package/dist/cache.d.ts +43 -0
  7. package/dist/checker.d.ts +107 -0
  8. package/dist/chunk-1bav913n.js +6 -0
  9. package/dist/chunk-2wbhe1k8.js +2 -0
  10. package/dist/chunk-3d18fhrg.js +3 -0
  11. package/dist/chunk-3g2v2ns2.js +2 -0
  12. package/dist/chunk-3j7r0fxz.js +2 -0
  13. package/dist/chunk-4qpg9xnt.js +3 -0
  14. package/dist/chunk-57agx6g8.js +3 -0
  15. package/dist/chunk-5vqtjws2.js +2 -0
  16. package/dist/chunk-6mwq397e.js +2 -0
  17. package/dist/chunk-6qv7p9sg.js +170 -0
  18. package/dist/chunk-6s7n1gt0.js +2 -0
  19. package/dist/chunk-74j5mydx.js +3 -0
  20. package/dist/chunk-7cpp6v8f.js +2 -0
  21. package/dist/chunk-9a6yn7sv.js +75 -0
  22. package/dist/chunk-axb2kjeq.js +2 -0
  23. package/dist/chunk-begk3j01.js +33 -0
  24. package/dist/chunk-cmenkst5.js +3 -0
  25. package/dist/chunk-d0p3jzwb.js +34 -0
  26. package/dist/chunk-f18nyrrb.js +32 -0
  27. package/dist/chunk-fb4c98h2.js +2 -0
  28. package/dist/chunk-ggmn4a8c.js +4 -0
  29. package/dist/chunk-hrmnrn4p.js +3 -0
  30. package/dist/chunk-j0y71ank.js +2 -0
  31. package/dist/chunk-j6aqdbc4.js +2 -0
  32. package/dist/chunk-jm5ywn4e.js +13 -0
  33. package/dist/chunk-knkfbqze.js +2 -0
  34. package/dist/chunk-n28rjf9h.js +3 -0
  35. package/dist/chunk-p1d09y82.js +449 -0
  36. package/dist/chunk-r1m3q3dj.js +2 -0
  37. package/dist/chunk-r1ywapeb.js +6 -0
  38. package/dist/chunk-rnt0wkrk.js +23 -0
  39. package/dist/chunk-rw6j20e2.js +3 -0
  40. package/dist/chunk-v96rjx7x.js +134 -0
  41. package/dist/chunk-w9abhtgg.js +22 -0
  42. package/dist/chunk-wfevdmvd.js +19 -0
  43. package/dist/chunk-ws2dmfvj.js +2 -0
  44. package/dist/chunk-xnq1xw73.js +15 -0
  45. package/dist/chunk-xyctgc6x.js +102 -0
  46. package/dist/chunk-y3q50bn2.js +2 -0
  47. package/dist/chunk-ywd4k4hn.js +3 -0
  48. package/dist/circular.d.ts +82 -0
  49. package/dist/compat.d.ts +108 -0
  50. package/dist/config.d.ts +33 -3
  51. package/dist/diff.d.ts +82 -0
  52. package/dist/docs.d.ts +97 -0
  53. package/dist/errors.d.ts +113 -0
  54. package/dist/extractor/builders.d.ts +38 -0
  55. package/dist/extractor/cache.d.ts +47 -0
  56. package/dist/extractor/declarations.d.ts +50 -0
  57. package/dist/extractor/directives.d.ts +9 -0
  58. package/dist/extractor/extract.d.ts +10 -0
  59. package/dist/extractor/hash.d.ts +1 -0
  60. package/dist/extractor/helpers.d.ts +39 -0
  61. package/dist/extractor/index.d.ts +70 -0
  62. package/dist/extractor/scanner.d.ts +6 -0
  63. package/dist/extractor.d.ts +3 -4
  64. package/dist/formats.d.ts +50 -0
  65. package/dist/formatter.d.ts +61 -0
  66. package/dist/generator.d.ts +12 -3
  67. package/dist/import-sorter.d.ts +99 -0
  68. package/dist/incremental.d.ts +84 -0
  69. package/dist/index.d.ts +54 -1
  70. package/dist/logger.d.ts +57 -0
  71. package/dist/lsp.d.ts +317 -0
  72. package/dist/memory.d.ts +110 -0
  73. package/dist/merger.d.ts +38 -0
  74. package/dist/optimizer.d.ts +52 -0
  75. package/dist/output-normalizer.d.ts +123 -0
  76. package/dist/parallel-processor.d.ts +63 -0
  77. package/dist/parser.d.ts +24 -15
  78. package/dist/plugins/bun.d.ts +58 -0
  79. package/dist/plugins/esbuild.d.ts +63 -0
  80. package/dist/plugins/index.d.ts +14 -0
  81. package/dist/plugins/tsup.d.ts +53 -0
  82. package/dist/plugins/vite.d.ts +49 -0
  83. package/dist/plugins/webpack.d.ts +66 -0
  84. package/dist/plugins.d.ts +83 -0
  85. package/dist/process-source.d.ts +11 -0
  86. package/dist/processor/cache.d.ts +16 -0
  87. package/dist/processor/comments.d.ts +7 -0
  88. package/dist/processor/declarations.d.ts +37 -0
  89. package/dist/processor/imports.d.ts +65 -0
  90. package/dist/processor/index.d.ts +34 -0
  91. package/dist/processor/type-inference.d.ts +106 -0
  92. package/dist/processor.d.ts +3 -43
  93. package/dist/profiling.d.ts +101 -0
  94. package/dist/security.d.ts +100 -0
  95. package/dist/sourcemap.d.ts +125 -0
  96. package/dist/src/index.js +55 -2
  97. package/dist/src/plugins/bun.js +2 -0
  98. package/dist/src/plugins/esbuild.js +2 -0
  99. package/dist/src/plugins/index.js +2 -0
  100. package/dist/src/plugins/tsup.js +2 -0
  101. package/dist/src/plugins/vite.js +2 -0
  102. package/dist/src/plugins/webpack.js +2 -0
  103. package/dist/tracking.d.ts +89 -0
  104. package/dist/transformers.d.ts +173 -0
  105. package/dist/tree-shaker.d.ts +69 -0
  106. package/dist/type-mappings.d.ts +124 -0
  107. package/dist/types.d.ts +137 -7
  108. package/dist/utils.d.ts +53 -1
  109. package/dist/watcher.d.ts +64 -0
  110. package/dist/worker.d.ts +84 -0
  111. package/dist/workspace.d.ts +62 -0
  112. package/package.json +49 -11
  113. package/dist/chunk-qsyn1k3w.js +0 -504
@@ -0,0 +1,75 @@
1
+ // @bun
2
+ import{ec as u}from"./chunk-wfevdmvd.js";import{hc as TY}from"./chunk-p1d09y82.js";import{kc as XJ}from"./chunk-74j5mydx.js";import{Bc as gJ}from"./chunk-begk3j01.js";import{Tc as m}from"./chunk-f18nyrrb.js";import{Vc as W,Xc as n}from"./chunk-57agx6g8.js";import{ad as kY,cd as BJ}from"./chunk-rw6j20e2.js";var{Glob:pJ}=globalThis.Bun;import{mkdir as i}from"fs/promises";import{availableParallelism as FY}from"os";import{dirname as g,relative as S,resolve as y}from"path";import{existsSync as YJ,mkdirSync as sJ,readFileSync as aJ,writeFileSync as iJ}from"fs";import{dirname as nJ,relative as oJ,resolve as rJ}from"path";async function KJ(J,Y,$){let X=new Map,Z=[],Q=new Set,U=0,z=0,H=0;for(let q of J){let G=Y.get(q);if(!G)continue;let O=u(G,q,$.keepComments);U+=O.length;for(let V of O)if(V.kind==="import"){z++;let K=V.source||"";if(K.startsWith("."))continue;if(!X.has(K))X.set(K,{source:K,specifiers:new Map,isTypeOnly:V.isTypeOnly||!1,isSideEffect:V.isSideEffect||!1});let B=X.get(K);if(V.specifiers)for(let k of V.specifiers){let T=k.alias||k.name;if(!B.specifiers.has(T))B.specifiers.set(T,{name:k.name,alias:k.alias,isType:k.isType||!1})}if(!V.isTypeOnly)B.isTypeOnly=!1}else if(V.isExported||V.kind==="export"){if(H++,V.name&&Q.has(V.name))continue;if(V.name)Q.add(V.name);Z.push({declaration:V,file:q})}}let j=[];j.push("/**"),j.push(" * Bundled TypeScript declarations"),j.push(` * Generated from ${J.length} source files`),j.push(" */"),j.push("");let _=Array.from(X.values()).sort((q,G)=>{let O=$.importOrder||["bun"],V=O.findIndex((B)=>q.source.startsWith(B)),K=O.findIndex((B)=>G.source.startsWith(B));if(V!==-1&&K!==-1)return V-K;if(V!==-1)return-1;if(K!==-1)return 1;return q.source.localeCompare(G.source)});for(let q of _)if(q.isSideEffect)j.push(`import '${q.source}';`);else if(q.specifiers.size>0){let O=Array.from(q.specifiers.values()).map((K)=>{let B=K.isType?"type ":"";return K.alias?`${B}${K.name} as ${K.alias}`:`${B}${K.name}`}),V=q.isTypeOnly?"type ":"";j.push(`import ${V}{ ${O.join(", ")} } from '${q.source}';`)}if(_.length>0)j.push("");let A=new Map;for(let{declaration:q,file:G}of Z){if(!A.has(G))A.set(G,[]);A.get(G).push(q)}for(let[q,G]of A){let O=oJ($.cwd,q);j.push(`// From: ${O}`);for(let V of G){if($.keepComments&&V.leadingComments)for(let K of V.leadingComments)j.push(K);j.push(OJ(V))}j.push("")}let R=j.join(`
3
+ `);return{content:R,files:J,declarationCount:U,importCount:z,exportCount:H,size:Buffer.byteLength(R,"utf8"),warnings:[]}}function OJ(J){if(J.text){let $=J.text.trim();if(J.isExported&&!$.startsWith("export"))$=`export ${$}`;if(!$.endsWith(";")&&!$.endsWith("}"))$+=";";return $}let Y=[];if(J.isExported)Y.push("export");if(J.isDefault)Y.push("default");switch(J.kind){case"function":if(Y.push("declare function"),Y.push(J.name),J.generics)Y.push(J.generics);if(Y.push(`(${tJ(J.parameters)})`),J.returnType)Y.push(`: ${J.returnType}`);break;case"variable":if(Y.push("declare const"),Y.push(J.name),J.typeAnnotation)Y.push(`: ${J.typeAnnotation}`);break;case"interface":if(Y.push("interface"),Y.push(J.name),J.generics)Y.push(J.generics);if(J.extends)Y.push(`extends ${J.extends}`);if(Y.push("{"),J.members)for(let $ of J.members)Y.push(` ${$.name}${$.typeAnnotation?`: ${$.typeAnnotation}`:""};`);Y.push("}");break;case"type":if(Y.push("type"),Y.push(J.name),J.generics)Y.push(J.generics);Y.push("="),Y.push(J.typeAnnotation||"unknown");break;case"class":if(Y.push("declare class"),Y.push(J.name),J.generics)Y.push(J.generics);if(J.extends)Y.push(`extends ${J.extends}`);if(J.implements&&J.implements.length>0)Y.push(`implements ${J.implements.join(", ")}`);if(Y.push("{"),J.members)for(let $ of J.members)Y.push(` ${OJ($)}`);Y.push("}");break;case"enum":if(Y.push("declare enum"),Y.push(J.name),Y.push("{"),J.members){let $=J.members.map((X)=>X.value!==void 0?`${X.name} = ${X.value}`:X.name);Y.push(` ${$.join(`,
4
+ `)}`)}Y.push("}");break;default:return J.text||""}return Y.join(" ")}function tJ(J){if(!J||J.length===0)return"";return J.map((Y)=>{let $="";if(Y.rest)$+="...";if($+=Y.name,Y.optional)$+="?";if(Y.type)$+=`: ${Y.type}`;if(Y.defaultValue)$+=` = ${Y.defaultValue}`;return $}).join(", ")}async function AJ(J,Y={}){let $=[],X=new Map,Z=[],Q=[],U=new Set,z=0,H=0,j=0;for(let q of J){if(!YJ(q)){$.push(`File not found: ${q}`);continue}let G=aJ(q,"utf-8");Q.push(q);let O=G.split(`
5
+ `),V=[],K=0,B=!1;for(let k of O){let T=k.trim();if(!T&&!B)continue;if(T.startsWith("import ")){H++;let M=T.match(/import\s+(type\s+)?(?:\{([^}]+)\}|(\w+)|\*\s+as\s+(\w+))\s+from\s+['"]([^'"]+)['"]/);if(M){let[,N,L,D,GJ,F]=M;if(Y.externals?.some((o)=>F.startsWith(o))){Z.push(T);continue}if(F.startsWith("."))continue;if(!X.has(F))X.set(F,{source:F,specifiers:new Map,isTypeOnly:!!N,isSideEffect:!1});let HJ=X.get(F);if(L){let o=L.split(",").map((r)=>r.trim());for(let r of o){let[t,e]=r.split(/\s+as\s+/).map((lJ)=>lJ.trim()),WJ=t.startsWith("type "),JJ=WJ?t.replace("type ",""):t;HJ.specifiers.set(e||JJ,{name:JJ,alias:e!==JJ?e:void 0,isType:WJ})}}if(!N)HJ.isTypeOnly=!1}continue}if(/^(export\s+)?(declare\s+)?(interface|type|class|function|const|let|var|enum|namespace|module)\s/.test(T)){if(B=!0,V=[k],K=(k.match(/\{/g)||[]).length-(k.match(/\}/g)||[]).length,K===0&&(T.endsWith(";")||!T.includes("{"))){let M=p(T);if(!U.has(M)||!Y.mergeDuplicates){if(U.add(M),Z.push(k),z++,T.startsWith("export"))j++}B=!1,V=[]}}else if(B){if(V.push(k),K+=(k.match(/\{/g)||[]).length-(k.match(/\}/g)||[]).length,K<=0){let M=V.join(`
6
+ `),N=p(V[0]);if(!U.has(N)||!Y.mergeDuplicates){if(U.add(N),Z.push(M),z++,V[0].trim().startsWith("export"))j++}B=!1,V=[]}}else if(T.startsWith("export ")&&!T.includes("declare"))Z.push(k),j++}}let _=[];if(Y.banner)_.push(Y.banner),_.push("");if(Y.includeReferences&&Y.references){for(let q of Y.references)_.push(`/// <reference types="${q}" />`);_.push("")}let A=Array.from(X.values()).sort((q,G)=>q.source.localeCompare(G.source));for(let q of A)if(q.specifiers.size>0){let O=Array.from(q.specifiers.values()).map((K)=>{let B=K.isType?"type ":"";return K.alias?`${B}${K.name} as ${K.alias}`:`${B}${K.name}`}),V=q.isTypeOnly?"type ":"";_.push(`import ${V}{ ${O.join(", ")} } from '${q.source}';`)}if(A.length>0)_.push("");if(Y.ambient&&Y.moduleName){_.push(`declare module '${Y.moduleName}' {`);for(let q of Z){let G=q.split(`
7
+ `).map((O)=>` ${O.replace(/^(\s*)(export\s+)?declare\s+/,"$1$2")}`).join(`
8
+ `);_.push(G)}_.push("}")}else{if(Y.sortDeclarations)Z.sort((q,G)=>{let O=p(q),V=p(G);return O.localeCompare(V)});for(let q of Z)_.push(q)}if(Y.footer)_.push(""),_.push(Y.footer);let R=_.join(`
9
+ `);return{content:R,files:Q,declarationCount:z,importCount:H,exportCount:j,size:Buffer.byteLength(R,"utf-8"),warnings:$}}function p(J){let Y=J.match(/(interface|type|class|function|const|let|var|enum|namespace|module)\s+(\w+)/);return Y?`${Y[1]}:${Y[2]}`:J.trim()}async function eJ(J,Y,$={}){let X=await AJ(J,$),Z=nJ(Y);if(!YJ(Z))sJ(Z,{recursive:!0});return iJ(Y,X.content),X}function CY(J={}){return{bundle:(Y)=>AJ(Y,J),bundleAndWrite:(Y,$)=>eJ(Y,$,{...J,output:$})}}async function PY(J,Y=process.cwd()){let $=Array.isArray(J)?J:[J],X=[];for(let Z of $){if(Z.includes("*"))continue;let Q=rJ(Y,Z);if(YJ(Q))X.push(Q)}return X}import{existsSync as c,mkdirSync as JY,readFileSync as ZJ,statSync as RJ,writeFileSync as kJ}from"fs";import{join as TJ,relative as d,resolve as YY}from"path";var $J=1,qJ=".dtsx-cache",$Y="manifest.json";class QJ{cacheDir;manifestPath;manifest=null;configHash;constructor(J){this.cacheDir=YY(J.cwd,qJ),this.manifestPath=TJ(this.cacheDir,$Y),this.configHash=this.hashConfig(J)}hashConfig(J){let Y={keepComments:J.keepComments,importOrder:J.importOrder,outputStructure:J.outputStructure};return String(XJ(JSON.stringify(Y)))}hashString(J){return String(XJ(J))}load(){try{if(!c(this.manifestPath))return!1;let J=ZJ(this.manifestPath,"utf-8"),Y=JSON.parse(J);if(Y.version!==$J)return!1;if(Y.configHash!==this.configHash)return!1;return this.manifest=Y,!0}catch{return!1}}save(){if(!this.manifest)this.manifest={version:$J,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};if(this.manifest.updatedAt=Date.now(),!c(this.cacheDir))JY(this.cacheDir,{recursive:!0});kJ(this.manifestPath,JSON.stringify(this.manifest,null,2))}needsRegeneration(J,Y){return this.getCachedIfValid(J,Y)===null}getCached(J,Y){return this.getCachedIfValid(J,Y)}getCachedIfValid(J,Y){if(!this.manifest)return null;let $=d(Y,J),X=this.manifest.entries[$];if(!X)return null;try{let Q=RJ(J).mtimeMs;if(Q>X.sourceMtime){let U=ZJ(J,"utf-8");if(this.hashString(U)!==X.sourceHash)return null;X.sourceMtime=Q}return X.dtsContent}catch{return null}}update(J,Y,$,X){if(!this.manifest)this.manifest={version:$J,configHash:this.configHash,entries:{},createdAt:Date.now(),updatedAt:Date.now()};let Z=d(X,J),Q;try{Q=RJ(J).mtimeMs}catch{Q=Date.now()}this.manifest.entries[Z]={sourcePath:Z,sourceHash:this.hashString(Y),sourceMtime:Q,dtsContent:$,dtsHash:this.hashString($),generatedAt:Date.now(),configHash:this.configHash}}remove(J,Y){if(!this.manifest)return;let $=d(Y,J);delete this.manifest.entries[$]}clear(){this.manifest=null;try{if(c(this.manifestPath))BJ("fs").rmSync(this.cacheDir,{recursive:!0,force:!0})}catch{}}getStats(){if(!this.manifest)return{entries:0,size:0};let J=Object.keys(this.manifest.entries).length,Y=0;for(let $ of Object.values(this.manifest.entries))Y+=$.dtsContent.length;return{entries:J,size:Y}}prune(J,Y){if(!this.manifest)return 0;let $=0,X=new Set(Array.from(J).map((Z)=>d(Y,Z)));for(let Z of Object.keys(this.manifest.entries))if(!X.has(Z))delete this.manifest.entries[Z],$++;return $}}function NJ(J){let Y=TJ(J,".gitignore");try{let $="";if(c(Y))$=ZJ(Y,"utf-8");if(!$.includes(qJ)){let X=`${$.trimEnd()}
10
+
11
+ # dtsx cache
12
+ ${qJ}/
13
+ `;kJ(Y,X)}}catch{}}import{spawn as XY}from"child_process";import{readFile as LJ,stat as ZY,writeFile as qY}from"fs/promises";var v=typeof globalThis.Bun<"u",cY=!v&&typeof process<"u"&&!!process.versions?.node,lY=v?"bun":"node";class MJ{name;_size=-1;constructor(J){this.name=J}async exists(){try{return await ZY(this.name),!0}catch{return!1}}async text(){return LJ(this.name,"utf-8")}async arrayBuffer(){let J=await LJ(this.name);return J.buffer.slice(J.byteOffset,J.byteOffset+J.byteLength)}get size(){if(this._size===-1)return-1;return this._size}}class SJ{pid;stdout;stderr;stdin;exited;process;constructor(J){this.process=J,this.pid=J.pid??0,this.stdout=J.stdout,this.stderr=J.stderr,this.stdin=J.stdin,this.exited=new Promise((Y)=>{J.on("exit",($)=>{Y($??0)}),J.on("error",()=>{Y(1)})})}kill(J){this.process.kill(J)}ref(){this.process.ref()}unref(){this.process.unref()}}function l(J){if(v)return globalThis.Bun.file(J);return new MJ(J)}async function UJ(J,Y){if(v)return globalThis.Bun.write(J,Y);let $=typeof Y==="string"?Y:Y instanceof ArrayBuffer?Buffer.from(Y):Y;return await qY(J,$),typeof Y==="string"?Buffer.byteLength(Y):Y.byteLength}function wJ(J,Y={}){if(v)return globalThis.Bun.spawn(J,Y);let $=Array.isArray(J)?J:[J],[X,...Z]=$,Q={cwd:Y.cwd,env:Y.env,stdio:[Y.stdin??"pipe",Y.stdout??"pipe",Y.stderr??"pipe"]},U=XY(X,Z,Q);return new SJ(U)}async function I(J){return l(J).text()}async function sY(J){return l(J).exists()}async function aY(J,Y){await UJ(J,Y)}function iY(){if(v)return{name:"bun",version:globalThis.Bun.version,isBun:!0,isNode:!1};return{name:"node",version:process.versions.node,isBun:!1,isNode:!0}}var P={PARSE_ERROR:"PARSE_ERROR",SYNTAX_ERROR:"SYNTAX_ERROR",FILE_NOT_FOUND:"FILE_NOT_FOUND",FILE_READ_ERROR:"FILE_READ_ERROR",FILE_WRITE_ERROR:"FILE_WRITE_ERROR",TYPE_INFERENCE_ERROR:"TYPE_INFERENCE_ERROR",UNRESOLVED_TYPE:"UNRESOLVED_TYPE",EXTRACTION_ERROR:"EXTRACTION_ERROR",PROCESSING_ERROR:"PROCESSING_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",INVALID_DECLARATION:"INVALID_DECLARATION",CONFIG_ERROR:"CONFIG_ERROR",INVALID_ENTRYPOINT:"INVALID_ENTRYPOINT",CIRCULAR_DEPENDENCY:"CIRCULAR_DEPENDENCY",TIMEOUT_ERROR:"TIMEOUT_ERROR",NOT_SUPPORTED:"NOT_SUPPORTED",UNKNOWN_ERROR:"UNKNOWN_ERROR"};class w extends Error{code;context;constructor(J,Y="UNKNOWN_ERROR",$){super(J);if(this.name="DtsxError",this.code=Y,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toString(){let J=`${this.name} [${this.code}]: ${this.message}`;if(this.context)J+=`
14
+ Context: ${JSON.stringify(this.context,null,2)}`;return J}toJSON(){return{name:this.name,code:this.code,message:this.message,context:this.context,stack:this.stack}}}class FJ extends w{filePath;line;column;constructor(J,Y,$){super(J,"PARSE_ERROR",{filePath:Y,line:$?.line,column:$?.column});if(this.name="ParseError",this.filePath=Y,this.line=$?.line,this.column=$?.column,$?.cause)this.cause=$.cause}get locationString(){if(this.line!==void 0&&this.column!==void 0)return`${this.filePath}:${this.line}:${this.column}`;return this.line!==void 0?`${this.filePath}:${this.line}`:this.filePath}}class QY extends w{filePath;declarationKind;constructor(J,Y,$,X){super(J,"EXTRACTION_ERROR",{filePath:Y,declarationKind:$});if(this.name="ExtractionError",this.filePath=Y,this.declarationKind=$,X)this.cause=X}}class UY extends w{declarationName;constructor(J,Y,$){super(J,"PROCESSING_ERROR",{declarationName:Y});if(this.name="ProcessingError",this.declarationName=Y,$)this.cause=$}}class vJ extends w{filePath;operation;constructor(J,Y,$,X){super(J,$==="read"?"FILE_READ_ERROR":"FILE_WRITE_ERROR",{filePath:Y,operation:$});if(this.name="FileError",this.filePath=Y,this.operation=$,X)this.cause=X}}class EJ extends w{configPath;invalidKey;constructor(J,Y){super(J,"CONFIG_ERROR",{configPath:Y?.configPath,invalidKey:Y?.invalidKey});if(this.name="ConfigError",this.configPath=Y?.configPath,this.invalidKey=Y?.invalidKey,Y?.cause)this.cause=Y.cause}}class jY extends w{cycle;constructor(J){super(`Circular dependency detected: ${J.join(" -> ")}`,"CIRCULAR_DEPENDENCY",{cycle:J});this.name="CircularDependencyError",this.cycle=J}}function oY(J){return J instanceof w}function rY(J){return J instanceof FJ}function tY(J){return J instanceof vJ}function eY(J){return J instanceof EJ}function J0(J,Y="UNKNOWN_ERROR",$){if(J instanceof w)return J;let X=$||(J instanceof Error?J.message:String(J)),Z=new w(X,Y);if(J instanceof Error)Z.cause=J;return Z}function Y0(J,Y){let $=1,X=1,Z=0;for(let Q of J){if(Z>=Y)break;if(Q===`
15
+ `)$++,X=1;else X++;Z++}return{line:$,column:X,offset:Y}}function $0(J,Y,$,X){let Z=J.split(`
16
+ `),Q=Y.line-1,U=[];if(X)U.push(`${X}:${Y.line}:${Y.column}`);else U.push(`Line ${Y.line}, Column ${Y.column}`);U.push(`Error: ${$}`),U.push("");let z=Math.max(0,Q-1),H=Math.min(Z.length-1,Q+1);for(let j=z;j<=H;j++){let _=(j+1).toString().padStart(4," "),A=j===Q?">":" ";if(U.push(`${A} ${_} | ${Z[j]}`),j===Q){let R=" ".repeat(8+Y.column-1);U.push(`${R}^`)}}return U.join(`
17
+ `)}function jJ(J,Y,$){let X={file:Y,message:"Unknown error",code:P.UNKNOWN_ERROR};if(J instanceof Error){X.message=J.message,X.stack=J.stack;let Z=J.message.match(/\((\d+),(\d+)\)/);if(Z)X.location={line:Number.parseInt(Z[1],10),column:Number.parseInt(Z[2],10)};if(J.message.includes("Cannot find")||J.message.includes("not found"))X.code=P.FILE_NOT_FOUND,X.suggestion="Check that the file path is correct and the file exists.";else if(J.message.includes("syntax")||J.message.includes("Unexpected token"))X.code=P.SYNTAX_ERROR,X.suggestion="Check for syntax errors in your TypeScript code.";else if(J.message.includes("type")&&J.message.includes("cannot"))X.code=P.TYPE_INFERENCE_ERROR,X.suggestion="Add explicit type annotations to help with type inference.";else if(J.message.includes("parse")||J.message.includes("Parse"))X.code=P.PARSE_ERROR,X.suggestion="The file contains invalid TypeScript syntax."}else if(typeof J==="string")X.message=J;return X}function yJ(J,Y){let $=[],X=J.file;if(J.location)X+=`:${J.location.line}:${J.location.column}`;if(J.code)X+=` [${J.code}]`;if($.push(X),$.push(` Error: ${J.message}`),Y&&J.location){$.push("");let Z=Y.split(`
18
+ `),Q=J.location.line-1;if(Q>=0&&Q<Z.length){let U=Math.max(0,Q-1),z=Math.min(Z.length-1,Q+1);for(let H=U;H<=z;H++){let j=(H+1).toString().padStart(4," "),_=H===Q?">":" ";if($.push(` ${_} ${j} | ${Z[H]}`),H===Q&&J.location.column>0){let A=" ".repeat(10+J.location.column-1);$.push(` ${A}^`)}}}}if(J.suggestion)$.push(""),$.push(` Suggestion: ${J.suggestion}`);return $.join(`
19
+ `)}function X0(J){if(J.length===0)return"No errors";let Y=new Map;for(let X of J){let Z=X.code||"UNKNOWN";Y.set(Z,(Y.get(Z)||0)+1)}let $=[`${J.length} error(s) found:`];for(let[X,Z]of Y.entries())$.push(` - ${X}: ${Z}`);return $.join(`
20
+ `)}var s=null,E=null;async function VY(){if(s!==null)return s;try{return E=await import("prettier"),s=!0,!0}catch{return s=!1,!1}}async function zY(J,Y){if(!E)return null;try{if(Y&&E.resolveConfig){let $=await E.resolveConfig(Y);if($)return $}if(J&&E.resolveConfig){let $=await E.resolveConfig(J);if($)return $}return null}catch{return null}}async function _Y(J,Y){if(!E)throw Error("Prettier is not available");let $={...Y,parser:Y.parser||"typescript"};return E.format(J,$)}function GY(J,Y={}){let{indentSize:$=2,useTabs:X=!1,maxLineWidth:Z=100,trailingNewline:Q=!0,normalizeWhitespace:U=!0,sortImports:z=!0,groupImports:H=!0}=Y,j=J,_=X?"\t":" ".repeat($);if(j=j.replace(/\r\n/g,`
21
+ `),U)j=j.replace(/[ \t]+$/gm,""),j=j.replace(/\n{3,}/g,`
22
+
23
+ `),j=HY(j,_);if(z||H)j=WY(j,{sort:z,group:H});if(Z>0)j=OY(j,Z,_);if(Q&&!j.endsWith(`
24
+ `))j+=`
25
+ `;return j}function HY(J,Y){let $=J.split(`
26
+ `),X=[];for(let Z of $){let Q=Z.match(/^(\s*)(.*)$/);if(!Q){X.push(Z);continue}let[,U,z]=Q;if(!z){X.push("");continue}let H=U.replace(/\t/g," ").length,j=Math.floor(H/2);X.push(Y.repeat(j)+z)}return X.join(`
27
+ `)}function WY(J,Y){let $=J.split(`
28
+ `),X=[],Z=[],Q=!1,U=0;for(let H=0;H<$.length;H++){let j=$[H],_=j.match(/^(import\s+(?:type\s+)?.*from\s+['"])([^'"]+)(['"].*)$/);if(_)Q=!0,U=H,X.push({line:j,source:_[2],isType:j.includes("import type")});else if(Q&&j.trim()==="")continue;else{if(Q)Q=!1;Z.push(j)}}if(X.length===0)return J;if(Y.sort)X.sort((H,j)=>{if(H.isType!==j.isType)return H.isType?1:-1;return KY(H.source,j.source)});let z;if(Y.group){let H=X.filter((q)=>q.source.startsWith("node:")),j=X.filter((q)=>!q.source.startsWith(".")&&!q.source.startsWith("node:")&&!q.source.includes("/")),_=X.filter((q)=>!q.source.startsWith(".")&&!q.source.startsWith("node:")&&q.source.includes("/")&&!q.source.startsWith("@")),A=X.filter((q)=>q.source.startsWith("@")),R=X.filter((q)=>q.source.startsWith("."));z=[...H.map((q)=>q.line),...H.length>0&&j.length>0?[""]:[],...j.map((q)=>q.line),...(H.length>0||j.length>0)&&_.length>0?[""]:[],..._.map((q)=>q.line),...A.length>0&&(H.length>0||j.length>0||_.length>0)?[""]:[],...A.map((q)=>q.line),...R.length>0?[""]:[],...R.map((q)=>q.line)]}else z=X.map((H)=>H.line);return[...z,"",...Z].join(`
29
+ `)}function KY(J,Y){let $=J.startsWith("node:"),X=Y.startsWith("node:");if($!==X)return $?-1:1;let Z=J.startsWith("."),Q=Y.startsWith(".");if(Z!==Q)return Z?1:-1;return J.localeCompare(Y)}function OY(J,Y,$){let X=J.split(`
30
+ `),Z=[];for(let Q of X){if(Q.length<=Y){Z.push(Q);continue}if(Q.trimStart().startsWith("import ")){Z.push(Q);continue}let U=Q.match(/^(\s*)/)?.[1]||"",z=U+$;if(Q.includes("{")&&Q.includes("}")){let H=AY(Q,Y,U,z);Z.push(...H);continue}if(Q.includes(" | ")){let H=RY(Q,Y,U,z);Z.push(...H);continue}Z.push(Q)}return Z.join(`
31
+ `)}function AY(J,Y,$,X){let Z=J.match(/^(\s*)(.*?)(\{)(.+)(\}.*)$/);if(!Z)return[J];let[,,Q,U,z,H]=Z,j=z.split(/;\s*|,\s*/).filter((A)=>A.trim());if(j.length<=1)return[J];return[`${$}${Q}${U}`,...j.map((A)=>`${X}${A.trim()};`),`${$}${H.trim()}`]}function RY(J,Y,$,X){let Z=J.match(/^(\s*)(.*?=\s*)(.+)$/);if(!Z)return[J];let[,,Q,U]=Z,z=U.split(/\s*\|\s*/).filter((j)=>j.trim());if(z.length<=2)return[J];return[`${$}${Q}`,...z.map((j,_)=>`${X}${_>0?"| ":" "}${j.trim()}`)]}async function h(J,Y={},$){let X=[];if(Y.usePrettier!==!1){if(await VY())try{let z={...await zY(Y.prettierConfigPath,$),...Y.prettierOptions,parser:"typescript"};return{content:await _Y(J,z),usedPrettier:!0}}catch(U){X.push(`Prettier formatting failed: ${U}. Using built-in formatter.`)}else if(Y.usePrettier===!0)X.push("Prettier requested but not available. Using built-in formatter.")}return{content:GY(J,Y.builtIn),usedPrettier:!1,warnings:X.length>0?X:void 0}}async function BY(J,Y={}){let $=new Map;for(let[X,Z]of J){let Q=await h(Z,Y,X);$.set(X,Q)}return $}function q0(J={}){return{format:(Y,$)=>h(Y,J,$),formatMany:(Y)=>BY(Y,J)}}async function Q0(J){return(await h(J,{usePrettier:!0,builtIn:{indentSize:2,normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}})).content}class a{plugins=[];config=null;register(J){if(this.plugins.some((Y)=>Y.name===J.name))throw Error(`Plugin "${J.name}" is already registered`);this.plugins.push(J)}unregister(J){let Y=this.plugins.findIndex(($)=>$.name===J);if(Y>=0)return this.plugins.splice(Y,1),!0;return!1}getPlugins(){return this.plugins}createLogger(J){return{debug:(Y)=>console.debug(`[${J}] ${Y}`),info:(Y)=>console.info(`[${J}] ${Y}`),warn:(Y)=>console.warn(`[${J}] ${Y}`),error:(Y)=>console.error(`[${J}] ${Y}`)}}async runOnStart(J){let Y=J;for(let $ of this.plugins)if($.onStart){let X=await $.onStart(Y);if(X)Y=X}return this.config=Y,Y}async runOnBeforeFile(J,Y){let $=Y;for(let X of this.plugins)if(X.onBeforeFile){let Z={filePath:J,sourceCode:Y,content:$,config:this.config,log:this.createLogger(X.name)},Q=await X.onBeforeFile(Z);if(typeof Q==="string")$=Q}return $}async runOnDeclarations(J,Y,$){let X=$;for(let Z of this.plugins)if(Z.onDeclarations){let Q={filePath:J,sourceCode:Y,declarations:X,config:this.config,log:this.createLogger(Z.name)},U=await Z.onDeclarations(Q);if(U)X=U}return X}async runOnAfterFile(J,Y,$){let X=$;for(let Z of this.plugins)if(Z.onAfterFile){let Q={filePath:J,sourceCode:Y,content:X,config:this.config,log:this.createLogger(Z.name)},U=await Z.onAfterFile(Q);if(typeof U==="string")X=U}return X}async runOnEnd(J){for(let Y of this.plugins)if(Y.onEnd)await Y.onEnd(J)}async runOnError(J,Y,$){for(let X of this.plugins)if(X.onError){let Z={filePath:Y,sourceCode:$,config:this.config,log:this.createLogger(X.name)};await X.onError(J,Z)}}}var j0=new a;function VJ(J){return J}var V0=VJ({name:"strip-internal",version:"1.0.0",description:"Removes declarations marked with @internal",onDeclarations:(J)=>{return J.declarations.filter((Y)=>{if(Y.leadingComments){if(Y.leadingComments.some((X)=>X.includes("@internal")))return J.log.debug(`Stripping internal declaration: ${Y.name}`),!1}return!0})}});function z0(J){return VJ({name:"banner",version:"1.0.0",description:"Adds a banner comment to generated files",onAfterFile:(Y)=>{return`/**
32
+ * ${J.split(`
33
+ `).join(`
34
+ * `)}
35
+ */
36
+
37
+ `+Y.content}})}function _0(J){return VJ({name:"filter",version:"1.0.0",description:"Filters declarations by name",onDeclarations:(Y)=>{return Y.declarations.filter(($)=>{if($.kind==="import")return!0;return J($.name)})}})}var b=kY(TY(),1);import{readdir as NY}from"fs/promises";import{dirname as LY,extname as MY,isAbsolute as SY,join as bJ,resolve as DJ}from"path";import xJ from"process";import{pathToFileURL as zJ}from"url";function B0(J,Y){throw Error(Y||`Unexpected value: ${J}`)}async function x(J,Y){let $=Y.replace(/\r\n/g,`
38
+ `);if(!$.endsWith(`
39
+ `))$+=`
40
+ `;await UJ(J,$)}async function wY(J){let Y=J??m.root,$=await NY(Y,{withFileTypes:!0}),X=await Promise.all($.map((Z)=>{let Q=bJ(Y,Z.name);return Z.isDirectory()?wY(Q):Q}));return Array.prototype.concat(...X).filter((Z)=>MY(Z)===".ts")}async function CJ(J){try{let Y=J?.cwd||xJ.cwd(),$=J?.tsconfigPath||bJ(Y,"tsconfig.json"),Z=await import(zJ($).href);if(Z.compilerOptions?.isolatedDeclarations===!0)return!0;if(Z.extends){let Q=IJ($,Z.extends),U=Q.endsWith(".json")?Q:`${Q}.json`,H=await import(zJ(U).href);if(H.compilerOptions?.isolatedDeclarations===!0)return!0;if(H.extends){let j=IJ(U,H.extends),_=j.endsWith(".json")?j:`${j}.json`;if((await import(zJ(_).href)).compilerOptions?.isolatedDeclarations===!0)return!0}}return!1}catch{return!1}}function PJ(J,Y){let $={isValid:!0,errors:[]},X=b.default.createSourceFile(Y,J,b.default.ScriptTarget.Latest,!0,b.default.ScriptKind.TS),Z={getSourceFile:(z)=>{if(z===Y)return X;return},getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:(z)=>z,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
41
+ `,fileExists:(z)=>z===Y,readFile:()=>{return}},U=[...b.default.createProgram({rootNames:[Y],options:{noEmit:!0,declaration:!0,skipLibCheck:!0,noLib:!0},host:Z}).getSyntacticDiagnostics(X)];for(let z of U){let H=b.default.flattenDiagnosticMessageText(z.messageText,`
42
+ `),j=`TS${z.code}`,_;switch(z.code){case 1005:_="Add a semicolon at the end of the statement.";break;case 1109:_="Check for missing or malformed expressions.";break;case 1128:_="Ensure proper declaration syntax is used.";break;case 2304:_="Import or declare the missing type/value.";break;case 2307:_="Check that the module exists and is installed.";break;case 2322:_="Check type compatibility between the values.";break;case 2339:_="Add the missing property to the type definition.";break;case 2345:_="Check the argument types match the expected parameters.";break}if(z.file&&z.start!==void 0){let{line:A,character:R}=z.file.getLineAndCharacterOfPosition(z.start);$.errors.push({line:A+1,column:R+1,message:H,code:j,suggestion:_})}else $.errors.push({line:0,column:0,message:H,code:j,suggestion:_})}return $.isValid=$.errors.length===0,$}function hJ(J,Y,$){let X=J.split(`
43
+ `),Z=Y.split(`
44
+ `),Q=new Set(X),U=new Set(Z),z=X.filter((_)=>!U.has(_)),H=Z.filter((_)=>!Q.has(_));if(z.length===0&&H.length===0)return"";let j=[];j.push(`--- ${$}`),j.push(`+++ ${$}`);for(let _ of z)j.push(`- ${_}`);for(let _ of H)j.push(`+ ${_}`);return j.join(`
45
+ `)}function IJ(J,Y){if(SY(Y))return Y;if(Y.startsWith("."))return DJ(LY(J),Y);return DJ(xJ.cwd(),"node_modules",Y)}function mJ(J,Y,$,X){let Z=J.split(`
46
+ `),Q=[];function U(_){let R="",q=_<0?-_<<1|1:_<<1;do{let G=q&31;if(q>>>=5,q>0)G|=32;R+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[G]}while(q>0);return R}let z=0,H=0,j=0;for(let _=0;_<Z.length;_++){if(Z[_].trim()===""){Q.push("");continue}z=0;let R=Math.min(_,X.split(`
47
+ `).length-1),q=[],G=0-z,O=0,V=R-H,K=0-j;q.push(U(G)+U(O)+U(V)+U(K)),z=0,H=R,j=0,Q.push(q.join(","))}return{version:3,file:Y,sourceRoot:"",sources:[$],sourcesContent:[X],mappings:Q.join(";")}}function fJ(J,Y){return`${J}
48
+ //# sourceMappingURL=${Y}
49
+ `}async function vY(J){let Y=Date.now(),$={...m,...J};if($.logLevel)n($.logLevel);else if($.verbose)n("debug");let X=new a;if($.plugins&&$.plugins.length>0){for(let q of $.plugins)X.register(q),W.debug(`Registered plugin: ${q.name}`);$=await X.runOnStart($)}if($.isolatedDeclarations===void 0)$.isolatedDeclarations=await CJ($);let Z=null;if($.incremental){if(Z=new QJ($),$.clearCache)W.debug("Clearing build cache..."),Z.clear();else if(Z.load()){let G=Z.getStats();W.debug(`Loaded build cache with ${G.entries} entries`)}else W.debug("No existing build cache found, starting fresh");NJ($.cwd)}let Q={filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},U=0;W.debug("Starting DTS generation..."),W.debug("Config:",$);let z=await DY($);if(Z){let q=Z.prune(new Set(z),$.cwd);if(q>0)W.debug(`Pruned ${q} deleted files from cache`)}if(W.debug(`Found ${z.length} TypeScript files`),$.progress&&z.length>0){let q=$.parallel?"parallel":"sequential";W.info(`Processing ${z.length} files (${q})...`)}let H=async(q,G)=>{let O;try{let V=uJ(q,$);if(Z){let M=Z.getCachedIfValid(q,$.cwd);if(M)return await i(g(V),{recursive:!0}),await x(V,M),W.debug(`[cached] ${S($.cwd,V)}`),{success:!0,file:q,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:0}}O=G??await I(q);let{content:K,declarationCount:B,importCount:k,exportCount:T}=await cJ(q,O,$,X),C=0;if($.dryRun)W.info(`[dry-run] Would generate: ${V}`),W.debug("--- Content preview ---"),W.debug(K.slice(0,500)+(K.length>500?`
50
+ ...`:"")),W.debug("--- End preview ---");else{if($.diff)try{let N=await I(V),L=hJ(N,K,S($.cwd,V));if(L)W.info(`
51
+ ${L}`);else W.debug(`[no changes] ${V}`)}catch{W.info(`[new file] ${S($.cwd,V)}`)}await i(g(V),{recursive:!0});let M=K;if($.declarationMap&&O){let N=V.split("/").pop()||"output.d.ts",L=S(g(V),q),D=`${N}.map`,GJ=mJ(K,N,L,O),F=`${V}.map`;await x(F,JSON.stringify(GJ)),M=fJ(K,D),W.debug(` Generated source map: ${S($.cwd,F)}`)}if($.prettier||$.indentStyle||$.indentSize){let N=await h(M,{usePrettier:$.prettier,builtIn:{indentSize:$.indentSize||2,useTabs:$.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},V);if(M=N.content,N.warnings?.length)for(let L of N.warnings)W.warn(`[format] ${L}`)}if(await x(V,M),Z&&O)Z.update(q,O,M,$.cwd);if($.validate){let N=PJ(K,V);if(!N.isValid){C=N.errors.length,W.warn(`[validation] ${S($.cwd,V)} has ${N.errors.length} error(s):`);for(let L of N.errors){let D=` Line ${L.line}:${L.column}`;if(L.code)D+=` [${L.code}]`;if(D+=` - ${L.message}`,W.warn(D),L.suggestion)W.warn(` Suggestion: ${L.suggestion}`)}}else W.debug(`[validation] ${V} - OK`)}W.debug(`Generated: ${V}`)}return{success:!0,file:q,declarationCount:B,importCount:k,exportCount:T,validationErrorCount:C}}catch(V){let K=jJ(V,q,O);if($.plugins&&$.plugins.length>0)await X.runOnError(V instanceof Error?V:Error(String(V)),q,O||"");return{success:!1,file:q,declarationCount:0,importCount:0,exportCount:0,dtsError:K,validationErrorCount:0}}},j=$.parallel||$.parallel!==!1&&z.length>=10,_=$.concurrency||(FY?.()??8),A=new Map;if(j&&z.length>1){let q=z.map(async(G)=>{try{let O=await I(G);return{file:G,source:O}}catch{return{file:G,source:null}}});for(let G of await Promise.all(q))if(G.source!==null)A.set(G.file,G.source)}let R=(q)=>{if(Q.filesProcessed++,q.success){if(q.cached)U++;else Q.filesGenerated++,Q.declarationsFound+=q.declarationCount,Q.importsProcessed+=q.importCount,Q.exportsProcessed+=q.exportCount;if($.validate){if(Q.filesValidated++,q.validationErrorCount)Q.validationErrors+=q.validationErrorCount}}else if(Q.filesFailed++,q.dtsError){Q.errors.push(q.dtsError);let G=yJ(q.dtsError);if($.continueOnError)W.warn(G);else throw W.error(G),Error(q.dtsError.message)}};if(j)for(let q=0;q<z.length;q+=_){let G=z.slice(q,q+_),O=await Promise.all(G.map((V)=>H(V,A.get(V))));for(let V of O)R(V);if($.progress){let V=Math.round(Q.filesProcessed/z.length*100);W.info(`[${Q.filesProcessed}/${z.length}] ${V}%`)}}else for(let q of z){let G=await H(q);if(R(G),$.progress){let O=Math.round(Q.filesProcessed/z.length*100),V=G.cached?"[cached]":"";W.info(`[${Q.filesProcessed}/${z.length}] ${O}% - ${S($.cwd,q)} ${V}`)}}if(Z)Z.save(),W.debug("Saved build cache");if($.bundle&&(Q.filesGenerated>0||U>0))try{W.debug("Bundling declarations...");let q=new Map;for(let K of z){let B=await I(K);q.set(K,B)}let G=await KJ(z,q,$),O=$.bundleOutput||"index.d.ts",V=y($.cwd,$.outdir,O);await i(g(V),{recursive:!0}),await x(V,G.content),W.info(`Bundled ${G.files.length} files to: ${S($.cwd,V)}`)}catch(q){let G=q instanceof Error?q.message:String(q);W.error(`Bundle failed: ${G}`)}if(Q.durationMs=Date.now()-Y,$.stats)if($.outputFormat==="json")console.log(JSON.stringify(Q,null,2));else{if(W.info(`
52
+ --- Generation Statistics ---`),W.info(`Files processed: ${Q.filesProcessed}`),W.info(`Files generated: ${Q.filesGenerated}`),U>0)W.info(`Files cached: ${U}`);if(Q.filesFailed>0)W.info(`Files failed: ${Q.filesFailed}`);if(W.info(`Declarations found: ${Q.declarationsFound}`),W.info(`Imports processed: ${Q.importsProcessed}`),W.info(`Exports processed: ${Q.exportsProcessed}`),Q.filesValidated>0){if(W.info(`Files validated: ${Q.filesValidated}`),Q.validationErrors>0)W.info(`Validation errors: ${Q.validationErrors}`)}if(W.info(`Duration: ${Q.durationMs}ms`),Q.errors.length>0){W.info(`
53
+ Errors:`);for(let q of Q.errors){let G=` - ${q.file}`;if(q.location)G+=`:${q.location.line}:${q.location.column}`;if(q.code)G+=` [${q.code}]`;if(G+=`: ${q.message}`,W.info(G),q.suggestion)W.info(` Suggestion: ${q.suggestion}`)}}W.info(`-----------------------------
54
+ `)}if($.plugins&&$.plugins.length>0)await X.runOnEnd(Q);return W.debug("DTS generation complete!"),Q}var EY=50,f=new Map;function yY(J){let Y=f.get(J);if(!Y){if(Y=new pJ(J),f.set(J,Y),f.size>EY){let $=f.keys().next().value;if($!==void 0)f.delete($)}}return Y}function _J(J,Y,$){if(!Y||Y.length===0)return!1;let X=S($,J);for(let Z of Y){let Q=yY(Z);if(Q.match(X)||Q.match(J))return!0}return!1}async function DY(J){let Y=[],$=y(J.cwd,J.root),X=J.exclude||[];for(let Z of J.entrypoints)if(Z.startsWith("/")&&Z.endsWith(".ts")){if(!Z.endsWith(".d.ts")&&!Z.includes("node_modules")){if(!_J(Z,X,$))Y.push(Z)}}else{let Q=new pJ(Z);for await(let U of Q.scan({cwd:$,absolute:!0,onlyFiles:!0}))if(!U.endsWith(".d.ts")&&!U.includes("node_modules")){if(!_J(U,X,$))Y.push(U)}}return[...new Set(Y)]}function uJ(J,Y){let $=y(Y.cwd,Y.root),Z=S($,J).replace(/\.(m?tsx?|cts)$/,(Q)=>{if(Q===".mts")return".d.mts";if(Q===".cts")return".d.cts";return".d.ts"});if(Y.outputStructure==="mirror")return y(Y.cwd,Y.outdir,Z);else{let Q=Z.split("/").pop();return y(Y.cwd,Y.outdir,Q)}}async function h0(J,Y){return(await dJ(J,Y)).content}async function dJ(J,Y,$){let X=await I(J);return cJ(J,X,Y,$)}async function cJ(J,Y,$,X){let Z=Y;if(X)Z=await X.runOnBeforeFile(J,Y);let Q=u(Z,J,$.keepComments,$.isolatedDeclarations??!1);if(X)Q=await X.runOnDeclarations(J,Z,Q);let U=0,z=0;for(let _=0;_<Q.length;_++){let A=Q[_];if(A.kind==="import")U++;if(A.kind==="export"||A.isExported)z++}let j=gJ(Q,{filePath:J,sourceCode:Z,declarations:Q},$.keepComments,$.importOrder);if(X)j=await X.runOnAfterFile(J,Z,j);return{content:j,declarationCount:Q.length,importCount:U,exportCount:z}}async function m0(J){let Y={...m,...J};if(Y.logLevel)n(Y.logLevel);let $=y(Y.cwd,Y.root),X=150,Z=5,Q=1e4,U={pendingChanges:new Set,debounceTimer:null,isProcessing:!1,errorCount:0,lastErrorTime:0};W.info(`Watching for changes in ${$}...`),W.info(`Press Ctrl+C to stop
55
+ `);try{await vY(Y),W.info(`[watch] Initial generation complete
56
+ `)}catch(A){let R=A instanceof Error?A.message:String(A);W.error(`[watch] Initial generation failed: ${R}`),W.info(`[watch] Continuing to watch for changes...
57
+ `)}async function z(){if(U.isProcessing||U.pendingChanges.size===0)return;let A=Date.now();if(U.errorCount>=Z){if(A-U.lastErrorTime<Q){W.warn(`[watch] Too many errors, pausing for ${Math.ceil((Q-(A-U.lastErrorTime))/1000)}s...`);return}U.errorCount=0}U.isProcessing=!0;let R=Array.from(U.pendingChanges);U.pendingChanges.clear();let q=new Date().toLocaleTimeString();if(R.length===1)W.info(`
58
+ [${q}] File changed: ${R[0]}`);else W.info(`
59
+ [${q}] ${R.length} files changed`);let G=0,O=0;for(let V of R){let K=y($,V);try{let B=Y.exclude||[];if(_J(K,B,$)){W.debug(` Skipping excluded file: ${V}`);continue}if(!await l(K).exists()){W.debug(` Skipping deleted file: ${V}`);continue}let T=uJ(K,Y),{content:C}=await dJ(K,Y);await i(g(T),{recursive:!0}),await x(T,C),W.info(` \u2713 ${S(Y.cwd,T)}`),G++}catch(B){O++,U.errorCount++,U.lastErrorTime=Date.now();let k=jJ(B,K);if(W.error(` \u2717 ${V}: ${k.message}`),k.suggestion)W.error(` Suggestion: ${k.suggestion}`)}}if(R.length>1)W.info(` Done: ${G} generated, ${O} failed`);if(O===0)U.errorCount=0;if(U.isProcessing=!1,U.pendingChanges.size>0)U.debounceTimer=setTimeout(z,X)}function H(A){if(U.pendingChanges.add(A),U.debounceTimer)clearTimeout(U.debounceTimer);U.debounceTimer=setTimeout(z,X)}let _=wJ([v?"bun":"node","-e",`
60
+ const fs = require('fs');
61
+
62
+ const rootPath = '${$}';
63
+
64
+ fs.watch(rootPath, { recursive: true }, (eventType, filename) => {
65
+ if (filename && filename.endsWith('.ts') && !filename.endsWith('.d.ts')) {
66
+ console.log('CHANGED:' + filename);
67
+ }
68
+ });
69
+
70
+ // Keep process alive
71
+ setInterval(() => {}, 1000);
72
+ `],{stdout:"pipe",stderr:"inherit"});if(v){let A=_.stdout.getReader(),R=new TextDecoder,q="";while(!0){let{done:G,value:O}=await A.read();if(G)break;q+=R.decode(O,{stream:!0});let V=q.split(`
73
+ `);q=V.pop()||"";for(let K of V)if(K.startsWith("CHANGED:")){let B=K.slice(8);H(B)}}}else{let A=_.stdout,R="";A.on("data",(q)=>{R+=q.toString();let G=R.split(`
74
+ `);R=G.pop()||"";for(let O of G)if(O.startsWith("CHANGED:")){let V=O.slice(8);H(V)}}),await _.exited}}
75
+ export{KJ as ua,AJ as va,eJ as wa,CY as xa,PY as ya,QJ as za,NJ as Aa,v as Ba,cY as Ca,lY as Da,l as Ea,UJ as Fa,wJ as Ga,I as Ha,sY as Ia,aY as Ja,iY as Ka,P as La,w as Ma,FJ as Na,QY as Oa,UY as Pa,vJ as Qa,EJ as Ra,jY as Sa,oY as Ta,rY as Ua,tY as Va,eY as Wa,J0 as Xa,Y0 as Ya,$0 as Za,jJ as _a,yJ as $a,X0 as ab,h as bb,BY as cb,q0 as db,Q0 as eb,a as fb,j0 as gb,VJ as hb,V0 as ib,z0 as jb,_0 as kb,B0 as lb,x as mb,wY as nb,CJ as ob,PJ as pb,hJ as qb,mJ as rb,fJ as sb,vY as tb,h0 as ub,m0 as vb};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{nc as a}from"./chunk-rnt0wkrk.js";import"./chunk-rw6j20e2.js";export{a as scanDeclarations};
@@ -0,0 +1,33 @@
1
+ // @bun
2
+ import{Cc as Kz,Dc as Uz,Ec as P,Lc as u,Mc as p,Nc as jz}from"./chunk-xnq1xw73.js";function _(z,X=!0){if(!X||!z||z.length===0)return"";if(z.length===1)return z[0].trim()+`
3
+ `;let K="";for(let Z=0;Z<z.length;Z++){if(Z>0)K+=`
4
+ `;K+=z[Z].trim()}return`${K}
5
+ `}function Jz(z){if(z.includes(`
6
+ `))return`/**
7
+ * ${z}
8
+ */
9
+ `;return`/** ${z} */
10
+ `}function Xz(z){let X=z.indexOf("{");if(X===-1)return-1;let K=z.indexOf("<");if(K===-1||K>X)return X;let Z=0,H=!1,j="";for(let Y=0;Y<z.length;Y++){let J=z[Y],G=Y>0?z[Y-1]:"";if(!H&&(J==='"'||J==="'"||J==="`"))H=!0,j=J;else if(H&&J===j&&G!=="\\")H=!1;if(!H){if(J==="<")Z++;else if(J===">")Z--;else if(J==="{"&&Z===0)return Y}}return-1}function n(z,X=!0){return _(z.leadingComments,X)+z.text}function c(z,X=!0){let K=_(z.leadingComments,X);if(z.typeAnnotation&&!z.value)return K+z.text;let Z="";if(z.isExported)Z+="export ";Z+="declare ";let H=z.modifiers?.[0]||"const";Z+=`${H} `,Z+=z.name;let{typeAnnotation:j,value:Y}=z;if(Y&&Y.includes(" satisfies ")){let G=p(Y);if(G)j=G}else if(Y&&Y.trim().endsWith("as const"))j=P(Y,!0);else if(!j&&Y&&H==="const"){let G=Y.trim(),W=G.startsWith("{")||G.startsWith("[");if(W)Kz();j=P(Y,!W)}else if(j&&Y&&H==="const"&&u(j)){let G=P(Y,!0);if(G!=="unknown")j=G}else if(!j&&Y)j=P(Y,H==="const");if(!j)j="unknown";let J="";if(Y&&!z.typeAnnotation&&!Y.trim().endsWith("as const")){let G=Y.trim();if(H!=="const"){if((j==="string"||j==="number"||j==="boolean")&&G.length>0)J=`@defaultValue ${G}`}else if(G.startsWith("{")||G.startsWith("[")){let W=Uz();if(W)if(W.includes(`
11
+ `))J=`@defaultValue
12
+ * \`\`\`ts
13
+ ${W.split(`
14
+ `).map((R)=>` * ${R}`).join(`
15
+ `)}
16
+ * \`\`\``;else J=`@defaultValue \`${W}\``}}if(Z+=`: ${j};`,J&&K&&K.includes("@defaultValue"))J="";if(J&&K){let G=K.trimEnd(),W=G.lastIndexOf("*/");if(W!==-1){let R=G.slice(0,W).trimEnd();if(R.startsWith("/** ")&&!R.includes(`
17
+ `))R=`/**
18
+ * ${R.slice(4)}`;return`${R}
19
+ * ${J}
20
+ */
21
+ `+Z}return`/**
22
+ * ${G.replace(/^\/\/\s*/,"")}
23
+ * ${J}
24
+ */
25
+ ${Z}`}if(J)return`${Jz(J)}${Z}`;return K+Z}function d(z,X=!0){let K=_(z.leadingComments,X),Z=z.text;if(Z.startsWith("export declare interface")||Z.startsWith("declare interface"))return K+Z;let H="";if(z.isExported)H+="export ";if(H+="declare interface ",H+=z.name,z.generics)H+=z.generics;if(z.extends)H+=` extends ${z.extends}`;let j=Xz(z.text);if(j!==-1)H+=` ${z.text.slice(j)}`;else H+=" {}";return K+H}function l(z,X=!0){let K=_(z.leadingComments,X);if(z.text.includes("{")&&z.text.includes("}")&&z.text.includes("from"))return K+z.text;let Z="";if(z.isExported)Z+="export ";if(!z.isExported&&!z.text.includes(" from "))Z+="declare ";let H=z.text.indexOf("type ");if(H!==-1){let Y=z.text.slice(H),J=Y.length;while(J>0&&(Y.charCodeAt(J-1)===59||Y.charCodeAt(J-1)===32||Y.charCodeAt(J-1)===10||Y.charCodeAt(J-1)===13))J--;if(J<Y.length)Y=Y.slice(0,J);Z+=Y}else{if(Z+=`type ${z.name}`,z.generics)Z+=z.generics;Z+=" = any"}let j=Z.trimEnd();if(!j.endsWith(";")&&!j.endsWith("}"))Z+=";";return K+Z}function i(z,X=!0){return _(z.leadingComments,X)+z.text}function o(z,X=!0){let K=_(z.leadingComments,X),Z="";if(z.isExported)Z+="export ";if(Z+="declare ",z.modifiers?.includes("const"))Z+="const ";Z+="enum ",Z+=z.name;let H=z.text.indexOf("{");if(H!==-1)Z+=` ${z.text.slice(H)}`;else Z+=" {}";return K+Z}function Lz(z){let X=z.text.trim(),K=X.length;while(K>0&&X.charCodeAt(K-1)===59)K--;if(K<X.length)X=X.slice(0,K);return X+=";",X}function Gz(z,X=!0){return _(z.leadingComments,X)+z.text.trim()}function s(z,X=!0){let K=_(z.leadingComments,X);if(z.text.startsWith("declare global"))return K+z.text;if(z.source||(z.name.startsWith('"')||z.name.startsWith("'")||z.name.startsWith("`"))){let Y="declare module ";Y+=z.name;let J=z.text.indexOf("{");if(J!==-1)Y+=` ${z.text.slice(J)}`;else Y+=" {}";return K+Y}let H="";if(z.isExported)H+="export ";if(!z.modifiers?.includes("declare"))H+="declare ";H+="namespace ",H+=z.name;let j=z.text.indexOf("{");if(j!==-1)H+=` ${z.text.slice(j)}`;else H+=" {}";return K+H}var Rz=new Map,T=new Map;function Yz(z){return T.get(z)??null}function m(z,X){if(T.set(z,X),T.size>200){let K=0;for(let Z of T.keys()){if(K++>=20)break;T.delete(Z)}}}function Wz(){Rz.clear(),T.clear()}function a(z){let X=z.indexOf(" from ");if(X===-1)return null;let K=z.slice(X+6).trim(),Z=K[0];if(Z!=='"'&&Z!=="'")return null;let H=K.indexOf(Z,1);if(H===-1)return null;let j=K.slice(1,H),Y=z.slice(0,X).trim(),J=Y.startsWith("import type ");if(Y.startsWith("import "))Y=Y.slice(7).trim();if(Y.startsWith("type "))Y=Y.slice(5).trim();let G=null,W=[],Q=Y.indexOf("{"),R=Y.lastIndexOf("}");if(Q!==-1&&R!==-1){let D=Y.slice(0,Q).trim();if(D.endsWith(","))G=D.slice(0,-1).trim()||null;let w=Y.slice(Q+1,R),b=0;for(let S=0;S<=w.length;S++)if(S===w.length||w.charCodeAt(S)===44){let F=b,O=S;while(F<O&&(w.charCodeAt(F)===32||w.charCodeAt(F)===9||w.charCodeAt(F)===10))F++;while(O>F&&(w.charCodeAt(O-1)===32||w.charCodeAt(O-1)===9||w.charCodeAt(O-1)===10))O--;if(F<O)W.push(w.slice(F,O));b=S+1}}else G=Y.trim()||null;return{defaultName:G,namedItems:W,source:j,isTypeOnly:J}}function r(z){let X=Yz(z);if(X)return X;let K=[],Z=z.indexOf(" from ");if(Z===-1)return m(z,K),K;let H=z.slice(0,Z).trim();if(H.startsWith("import "))H=H.slice(7).trim();if(H.startsWith("type "))H=H.slice(5).trim();let j=H.indexOf("{"),Y=H.lastIndexOf("}");if(j!==-1&&Y!==-1){let J=H.slice(0,j).trim();if(J.endsWith(",")){let Q=J.slice(0,-1).trim();if(Q)K.push(Q)}else if(J&&!J.includes(","))K.push(J);let W=H.slice(j+1,Y).split(",");for(let Q=0;Q<W.length;Q++){let R=W[Q].trim();if(!R)continue;if(R.startsWith("type "))R=R.slice(5).trim();let D=R.indexOf(" as ");if(D!==-1)R=R.slice(D+4).trim();if(R)K.push(R)}}else{let J=H.trim();if(J)K.push(J)}return m(z,K),K}function Zz(z,X){throw Error(X||`Unexpected value: ${z}`)}function Vz(z){return z>=65&&z<=90||z>=97&&z<=122||z>=48&&z<=57||z===95||z===36||z>127}function $z(z){let X=new Set,K=0,Z=z.length;while(K<Z){let H=z.charCodeAt(K);if(H>=65&&H<=90||H>=97&&H<=122||H===95||H===36||H>127){let j=K;K++;while(K<Z&&Vz(z.charCodeAt(K)))K++;X.add(z.substring(j,K))}else K++}return X}var Qz=/export\s+(?:type\s+)?\{\s*([^}]+)\s*\}/;function Tz(z,X,K=!0,Z=["bun"]){let H="",j=X.sourceCode;if(j){let U=0;while(U<j.length&&(j.charCodeAt(U)===32||j.charCodeAt(U)===9||j.charCodeAt(U)===10||j.charCodeAt(U)===13))U++;if(U<j.length-2&&j.charCodeAt(U)===47&&j.charCodeAt(U+1)===47&&j.charCodeAt(U+2)===47){let L=jz(j);if(L.length>0)for(let V=0;V<L.length;V++){if(H)H+=`
26
+ `;H+=L[V]}}}let Y=[],J=[],G=[],W=[],Q=[],R=[],D=[],w=[],b=[];for(let U of z){let L=U.kind;switch(L){case"import":Y.push(U);break;case"function":J.push(U);break;case"variable":G.push(U);break;case"interface":W.push(U);break;case"type":Q.push(U);break;case"class":R.push(U);break;case"enum":D.push(U);break;case"module":w.push(U);break;case"export":b.push(U);break;case"namespace":w.push(U);break;case"unknown":break;default:Zz(L,`Unhandled declaration kind: ${L}`)}}let S=new Set,F=[],O=[],x=[],t=new Set;for(let U of b){let L=_(U.leadingComments,K);if(U.text.startsWith("export default")){let V=U.text.endsWith(";")?U.text:`${U.text};`;x.push(L+V)}else{let V=U.text.trim();if(!V.endsWith(";"))V+=";";let M=V.match(Qz);if(M){let q=M[1].split(",").map((B)=>B.trim());for(let B of q)S.add(B)}let $=L+V;if(!t.has($))if(t.add($),$.includes("export type"))F.push($);else O.push($)}}let y=new Map;if(Y.length>0)for(let U of Y){let L=r(U.text);for(let V of L)y.set(V,U)}let e=new Set;if(W.length>0){let U=[];for(let L of J)if(L.isExported)U.push(L.text);for(let L of R)U.push(L.text);for(let L of Q)U.push(L.text);if(U.length>0){let L=$z(U.join(`
27
+ `));for(let V of W)if(L.has(V.name))e.add(V.name)}}let N=[];if(Y.length>0){let U=new Set,L=[];for(let $ of J)if($.isExported)L.push($.text);for(let $ of G)if($.isExported){if(L.push($.text),$.typeAnnotation)L.push($.typeAnnotation)}for(let $ of W)if($.isExported||e.has($.name))L.push($.text);for(let $ of Q)L.push($.text);for(let $ of R)L.push($.text);for(let $ of D)L.push($.text);for(let $ of w)L.push($.text);for(let $ of b)L.push($.text);let V=L.join(`
28
+ `);if(V&&y.size>0){let $=$z(V);for(let q of y.keys())if($.has(q))U.add(q)}for(let $ of S)if(y.has($))U.add($);for(let $ of Y){if($.isSideEffect){let E=$.text.trim(),g=E.endsWith(";")?E:`${E};`;N.push(g);continue}let q=a($.text);if(!q)continue;let{defaultName:B,namedItems:A,source:v,isTypeOnly:k}=q,h=B?U.has(B):!1,I="",C=0;for(let E=0;E<A.length;E++){let g=A[E],f=g.charCodeAt(0)===116&&g.startsWith("type ")?g.slice(5).trim():g.trim(),Hz=f.indexOf(" as ");if(Hz!==-1)f=f.slice(Hz+4).trim();if(U.has(f)){if(C>0)I+=", ";I+=g,C++}}if(h||C>0){let E=k?"import type ":"import ";if(h&&B)E+=C>0?`${B}, { ${I} }`:B;else if(C>0)E+=`{ ${I} }`;E+=` from '${v}';`,N.push(E)}}let M=Z.length;if(N.length>1){let $=Z.map((A)=>`from '${A}`),q=Z.map((A)=>`from "${A}`),B=new Map;for(let A of N){let v=M;for(let k=0;k<Z.length;k++)if(A.includes($[k])||A.includes(q[k])){v=k;break}B.set(A,v)}N.sort((A,v)=>{let k=B.get(A),h=B.get(v);return k!==h?k-h:A.localeCompare(v)})}}for(let U=0;U<N.length;U++){if(H)H+=`
29
+ `;H+=N[U]}for(let U=0;U<F.length;U++){if(H)H+=`
30
+ `;H+=F[U]}let zz=[J,G,W,Q,R,D,w];for(let U=0;U<zz.length;U++){let L=zz[U];for(let V=0;V<L.length;V++){let M=L[V],$="",q=M.kind;switch(q){case"function":$=n(M,K);break;case"variable":$=c(M,K);break;case"interface":$=d(M,K);break;case"type":$=l(M,K);break;case"class":$=i(M,K);break;case"enum":$=o(M,K);break;case"module":case"namespace":$=s(M,K);break;case"import":case"export":case"unknown":break;default:Zz(q,`Unhandled declaration kind in processor: ${q}`)}if($){if(H)H+=`
31
+ `;H+=$}}}for(let U=0;U<O.length;U++){if(H)H+=`
32
+ `;H+=O[U]}for(let U=0;U<x.length;U++){if(H)H+=`
33
+ `;H+=x[U]}return H}export{_ as oc,n as pc,c as qc,d as rc,l as sc,i as tc,o as uc,Lz as vc,Gz as wc,s as xc,Wz as yc,a as zc,r as Ac,Tz as Bc};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{tb as K}from"./chunk-9a6yn7sv.js";function L(N={}){let{buildStart:P=!0,buildEnd:Q=!1,writeBundle:T=!1,modes:y,onGenerated:U,onError:H,...W}=N,I="production",z=async()=>{try{let q=await K(W);U?.(q)}catch(q){let J=q instanceof Error?q:Error(String(q));if(H?.(J),!H)console.error("[dtsx] Generation failed:",J.message)}},F=()=>{if(!y||y.length===0)return!0;return y.includes(I)};return{name:"dtsx",apply(q){return I=q.mode,!0},async buildStart(){if(P&&F())await z()},async buildEnd(){if(Q&&F())await z()},async writeBundle(){if(T&&F())await z()}}}var Y=L,_=L;
3
+ export{L as ca,Y as da,_ as ea};
@@ -0,0 +1,34 @@
1
+ // @bun
2
+ function W(B,g){let w=B.trim();if(w==="string")return{type:"string"};if(w==="number")return{type:"number"};if(w==="boolean")return{type:"boolean"};if(w==="null")return{type:"null"};if(w==="undefined")return{type:"null"};if(w==="any"||w==="unknown")return{};if(w==="never")return{not:{}};if(w==="void")return{type:"null"};if(w==="bigint")return{type:"integer"};if(w==="symbol")return{type:"string",description:"Symbol type"};if(w==="object")return{type:"object"};if(w.startsWith("'")||w.startsWith('"'))return{const:w.slice(1,-1)};if(/^-?\d+(\.\d+)?$/.test(w))return{const:Number.parseFloat(w)};if(w==="true")return{const:!0};if(w==="false")return{const:!1};let j=w.match(/^(.+)\[\]$/)||w.match(/^Array<(.+)>$/i);if(j)return{type:"array",items:W(j[1],g)};let E=w.match(/^\[(.+)\]$/);if(E){let Q=X(E[1],",").map((G)=>W(G.trim(),g));return{type:"array",items:Q,minItems:Q.length,maxItems:Q.length}}if(w.includes("|")){let Q=X(w,"|");if(Q.length>1){let G=Q.filter((K)=>K.trim()!=="null"&&K.trim()!=="undefined");if(Q.some((K)=>K.trim()==="null"||K.trim()==="undefined")&&G.length===1){let K=W(G[0],g);if(K.type&&typeof K.type==="string")return{...K,type:[K.type,"null"]};return{oneOf:[K,{type:"null"}]}}return{oneOf:Q.map((K)=>W(K.trim(),g))}}}if(w.includes("&")){let Q=X(w,"&");if(Q.length>1)return{allOf:Q.map((G)=>W(G.trim(),g))}}let H=w.match(/^Record<(.+),\s*(.+)>$/i);if(H)return{type:"object",additionalProperties:W(H[2],g)};let F=w.match(/^Promise<(.+)>$/i);if(F)return W(F[1],g);let L=w.match(/^Partial<(.+)>$/i);if(L)return{...W(L[1],g),required:[]};let _=w.match(/^Required<(.+)>$/i);if(_)return W(_[1],g);let P=w.match(/^Readonly<(.+)>$/i);if(P)return W(P[1],g);let $=w.match(/^Pick<(.+),\s*(.+)>$/i);if($)return W($[1],g);let D=w.match(/^Omit<(.+),\s*(.+)>$/i);if(D)return W(D[1],g);if(w==="Date")return{type:"string",format:"date-time"};if(/^[A-Z]\w*$/.test(w))return{$ref:`#/$defs/${w}`};return{type:"object"}}function Y(B,g={}){let w=g.indent??2,j=g.jsonSchemaDraft??"2020-12",E={"2020-12":"https://json-schema.org/draft/2020-12/schema","2019-09":"https://json-schema.org/draft/2019-09/schema","draft-07":"http://json-schema.org/draft-07/schema#"}[j],H=new Map,F={$schema:g.includeSchema!==!1?E:void 0,$defs:{}};for(let L of B)if(L.kind==="interface"||L.kind==="type"){let _=q(L,H,g);if(F.$defs)F.$defs[L.name]=_}if(F.$defs&&Object.keys(F.$defs).length===1){let[L,_]=Object.entries(F.$defs)[0];return JSON.stringify({$schema:F.$schema,title:L,..._},null,w)}return JSON.stringify(F,null,w)}function q(B,g,w){let j={type:"object"};if(w.includeDescriptions&&B.leadingComments?.length){let E=C(B.leadingComments);if(E)j.description=E}if(B.members&&B.members.length>0){j.properties={},j.required=[];for(let E of B.members)if(E.name&&E.typeAnnotation){let H=W(E.typeAnnotation,g);if(w.includeDescriptions&&E.leadingComments?.length){let L=C(E.leadingComments);if(L)H.description=L}if(j.properties[E.name]=H,!(E.modifiers?.includes("?")||E.text?.includes("?:")||w.allOptional))j.required.push(E.name)}if(j.required.length===0)delete j.required}else if(B.typeAnnotation)return W(B.typeAnnotation,g);return j}function k(B,g={}){let w=["import { z } from 'zod'",""];for(let j of B)if(j.kind==="interface"||j.kind==="type"){let E=g.exportName||`${j.name}Schema`,H=I(j,g);if(w.push(`export const ${E} = ${H}`),w.push(""),g.useInfer!==!1)w.push(`export type ${j.name} = z.infer<typeof ${E}>`),w.push("")}return w.join(`
3
+ `)}function I(B,g){if(B.members&&B.members.length>0)return`z.object({
4
+ ${B.members.filter((j)=>j.name&&j.typeAnnotation).map((j)=>{let E=R(j.typeAnnotation);if(j.modifiers?.includes("?")||j.text?.includes("?:")||g.allOptional)E=`${E}.optional()`;if(g.includeDescriptions&&j.leadingComments?.length){let F=C(j.leadingComments);if(F)E=`${E}.describe(${JSON.stringify(F)})`}return` ${j.name}: ${E}`}).join(`,
5
+ `)}
6
+ })`;if(B.typeAnnotation)return R(B.typeAnnotation);return"z.unknown()"}function R(B){let g=B.trim();if(g==="string")return"z.string()";if(g==="number")return"z.number()";if(g==="boolean")return"z.boolean()";if(g==="null")return"z.null()";if(g==="undefined")return"z.undefined()";if(g==="any")return"z.any()";if(g==="unknown")return"z.unknown()";if(g==="never")return"z.never()";if(g==="void")return"z.void()";if(g==="bigint")return"z.bigint()";if(g==="symbol")return"z.symbol()";if(g==="Date")return"z.date()";if(g.startsWith("'")||g.startsWith('"'))return`z.literal(${g})`;if(/^-?\d+(\.\d+)?$/.test(g))return`z.literal(${g})`;if(g==="true"||g==="false")return`z.literal(${g})`;let w=g.match(/^(.+)\[\]$/)||g.match(/^Array<(.+)>$/i);if(w)return`z.array(${R(w[1])})`;let j=g.match(/^\[(.+)\]$/);if(j)return`z.tuple([${X(j[1],",").map((D)=>R(D.trim())).join(", ")}])`;if(g.includes("|")){let $=X(g,"|");if($.length>1){let D=$.filter((K)=>K.trim()!=="null"&&K.trim()!=="undefined"),Q=$.some((K)=>K.trim()==="null"),G=$.some((K)=>K.trim()==="undefined");if((Q||G)&&D.length===1){let K=R(D[0]);if(Q)K=`${K}.nullable()`;if(G)K=`${K}.optional()`;return K}return`z.union([${$.map((K)=>R(K.trim())).join(", ")}])`}}if(g.includes("&")){let $=X(g,"&");if($.length>1)return $.map((Q)=>R(Q.trim())).reduce((Q,G)=>`${Q}.and(${G})`)}let E=g.match(/^Record<(.+),\s*(.+)>$/i);if(E)return`z.record(${R(E[1])}, ${R(E[2])})`;let H=g.match(/^Promise<(.+)>$/i);if(H)return`z.promise(${R(H[1])})`;let F=g.match(/^Map<(.+),\s*(.+)>$/i);if(F)return`z.map(${R(F[1])}, ${R(F[2])})`;let L=g.match(/^Set<(.+)>$/i);if(L)return`z.set(${R(L[1])})`;let _=g.match(/^Partial<(.+)>$/i);if(_)return`${R(_[1])}.partial()`;let P=g.match(/^Required<(.+)>$/i);if(P)return`${R(P[1])}.required()`;if(/^[A-Z]\w*$/.test(g))return`${g}Schema`;return"z.unknown()"}function V(B,g={}){let w=["import * as v from 'valibot'",""];for(let j of B)if(j.kind==="interface"||j.kind==="type"){let E=g.exportName||`${j.name}Schema`,H=J(j,g);if(w.push(`export const ${E} = ${H}`),w.push(""),g.useInfer!==!1)w.push(`export type ${j.name} = v.InferOutput<typeof ${E}>`),w.push("")}return w.join(`
7
+ `)}function J(B,g){if(B.members&&B.members.length>0)return`v.object({
8
+ ${B.members.filter((j)=>j.name&&j.typeAnnotation).map((j)=>{let E=O(j.typeAnnotation);if(j.modifiers?.includes("?")||j.text?.includes("?:")||g.allOptional)E=`v.optional(${E})`;return` ${j.name}: ${E}`}).join(`,
9
+ `)}
10
+ })`;if(B.typeAnnotation)return O(B.typeAnnotation);return"v.unknown()"}function O(B){let g=B.trim();if(g==="string")return"v.string()";if(g==="number")return"v.number()";if(g==="boolean")return"v.boolean()";if(g==="null")return"v.null_()";if(g==="undefined")return"v.undefined_()";if(g==="any")return"v.any()";if(g==="unknown")return"v.unknown()";if(g==="never")return"v.never()";if(g==="void")return"v.void_()";if(g==="bigint")return"v.bigint()";if(g==="symbol")return"v.symbol()";if(g==="Date")return"v.date()";if(g.startsWith("'")||g.startsWith('"'))return`v.literal(${g})`;if(/^-?\d+(\.\d+)?$/.test(g))return`v.literal(${g})`;if(g==="true"||g==="false")return`v.literal(${g})`;let w=g.match(/^(.+)\[\]$/)||g.match(/^Array<(.+)>$/i);if(w)return`v.array(${O(w[1])})`;let j=g.match(/^\[(.+)\]$/);if(j)return`v.tuple([${X(j[1],",").map((F)=>O(F.trim())).join(", ")}])`;if(g.includes("|")){let H=X(g,"|");if(H.length>1){let F=H.filter((P)=>P.trim()!=="null"&&P.trim()!=="undefined"),L=H.some((P)=>P.trim()==="null"),_=H.some((P)=>P.trim()==="undefined");if((L||_)&&F.length===1){let P=O(F[0]);if(L)P=`v.nullable(${P})`;if(_)P=`v.optional(${P})`;return P}return`v.union([${H.map((P)=>O(P.trim())).join(", ")}])`}}if(g.includes("&")){let H=X(g,"&");if(H.length>1)return`v.intersect([${H.map((F)=>O(F.trim())).join(", ")}])`}let E=g.match(/^Record<(.+),\s*(.+)>$/i);if(E)return`v.record(${O(E[1])}, ${O(E[2])})`;if(/^[A-Z]\w*$/.test(g))return`${g}Schema`;return"v.unknown()"}function Z(B,g={}){let w=["import * as t from 'io-ts'",""];for(let j of B)if(j.kind==="interface"||j.kind==="type"){let E=g.exportName||`${j.name}Codec`,H=U(j,g);if(w.push(`export const ${E} = ${H}`),w.push(""),g.useInfer!==!1)w.push(`export type ${j.name} = t.TypeOf<typeof ${E}>`),w.push("")}return w.join(`
11
+ `)}function U(B,g){if(B.members&&B.members.length>0){let w=[],j=[];for(let E of B.members){if(!E.name||!E.typeAnnotation)continue;let H=v(E.typeAnnotation),F=E.modifiers?.includes("?")||E.text?.includes("?:")||g.allOptional,L=` ${E.name}: ${H}`;if(F)j.push(L);else w.push(L)}if(j.length>0)return`t.intersection([
12
+ t.type({
13
+ ${w.join(`,
14
+ `)}
15
+ }),
16
+ t.partial({
17
+ ${j.join(`,
18
+ `)}
19
+ })
20
+ ])`;return`t.type({
21
+ ${w.join(`,
22
+ `)}
23
+ })`}if(B.typeAnnotation)return v(B.typeAnnotation);return"t.unknown"}function v(B){let g=B.trim();if(g==="string")return"t.string";if(g==="number")return"t.number";if(g==="boolean")return"t.boolean";if(g==="null")return"t.null";if(g==="undefined")return"t.undefined";if(g==="any")return"t.unknown";if(g==="unknown")return"t.unknown";if(g==="never")return"t.never";if(g==="void")return"t.void";if(g.startsWith("'")||g.startsWith('"'))return`t.literal(${g})`;if(/^-?\d+(\.\d+)?$/.test(g))return`t.literal(${g})`;if(g==="true"||g==="false")return`t.literal(${g})`;let w=g.match(/^(.+)\[\]$/)||g.match(/^Array<(.+)>$/i);if(w)return`t.array(${v(w[1])})`;let j=g.match(/^\[(.+)\]$/);if(j)return`t.tuple([${X(j[1],",").map((F)=>v(F.trim())).join(", ")}])`;if(g.includes("|")){let H=X(g,"|");if(H.length>1)return`t.union([${H.map((F)=>v(F.trim())).join(", ")}])`}if(g.includes("&")){let H=X(g,"&");if(H.length>1)return`t.intersection([${H.map((F)=>v(F.trim())).join(", ")}])`}let E=g.match(/^Record<(.+),\s*(.+)>$/i);if(E)return`t.record(${v(E[1])}, ${v(E[2])})`;if(/^[A-Z]\w*$/.test(g))return`${g}Codec`;return"t.unknown"}function N(B,g={}){let w=["import * as yup from 'yup'",""];for(let j of B)if(j.kind==="interface"||j.kind==="type"){let E=g.exportName||`${j.name}Schema`,H=S(j,g);if(w.push(`export const ${E} = ${H}`),w.push(""),g.useInfer!==!1)w.push(`export type ${j.name} = yup.InferType<typeof ${E}>`),w.push("")}return w.join(`
24
+ `)}function S(B,g){if(B.members&&B.members.length>0)return`yup.object({
25
+ ${B.members.filter((j)=>j.name&&j.typeAnnotation).map((j)=>{let E=x(j.typeAnnotation);if(!(j.modifiers?.includes("?")||j.text?.includes("?:")||g.allOptional))E=`${E}.required()`;return` ${j.name}: ${E}`}).join(`,
26
+ `)}
27
+ })`;if(B.typeAnnotation)return x(B.typeAnnotation);return"yup.mixed()"}function x(B){let g=B.trim();if(g==="string")return"yup.string()";if(g==="number")return"yup.number()";if(g==="boolean")return"yup.boolean()";if(g==="Date")return"yup.date()";if(g==="any"||g==="unknown")return"yup.mixed()";let w=g.match(/^(.+)\[\]$/)||g.match(/^Array<(.+)>$/i);if(w)return`yup.array().of(${x(w[1])})`;if(g.includes("|")){let j=X(g,"|");if(j.length>1){let E=j.filter((F)=>F.trim()!=="null"&&F.trim()!=="undefined");if(j.some((F)=>F.trim()==="null"||F.trim()==="undefined")&&E.length===1)return`${x(E[0])}.nullable()`}}if(/^[A-Z]\w*$/.test(g))return`${g}Schema`;return"yup.mixed()"}function f(B,g={}){let w=["import { type } from 'arktype'",""];for(let j of B)if(j.kind==="interface"||j.kind==="type"){let E=g.exportName||j.name,H=u(j,g);if(w.push(`export const ${E} = ${H}`),w.push(""),g.useInfer!==!1)w.push(`export type ${j.name}Type = typeof ${E}.infer`),w.push("")}return w.join(`
28
+ `)}function u(B,g){if(B.members&&B.members.length>0)return`type({
29
+ ${B.members.filter((j)=>j.name&&j.typeAnnotation).map((j)=>{let E=A(j.typeAnnotation);return` ${j.modifiers?.includes("?")||j.text?.includes("?:")||g.allOptional?`'${j.name}?'`:`${j.name}`}: ${E}`}).join(`,
30
+ `)}
31
+ })`;if(B.typeAnnotation)return`type(${A(B.typeAnnotation)})`;return"type('unknown')"}function A(B){let g=B.trim();if(g==="string")return"'string'";if(g==="number")return"'number'";if(g==="boolean")return"'boolean'";if(g==="null")return"'null'";if(g==="undefined")return"'undefined'";if(g==="bigint")return"'bigint'";if(g==="symbol")return"'symbol'";if(g==="Date")return"'Date'";if(g==="any"||g==="unknown")return"'unknown'";let w=g.match(/^(.+)\[\]$/)||g.match(/^Array<(.+)>$/i);if(w)return`${A(w[1])}.array()`;if(g.includes("|")){let j=X(g,"|");if(j.length>1)return`'${j.map((E)=>E.trim()).join(" | ")}'`}if(g.startsWith("'")||g.startsWith('"'))return`'${g}'`;return`'${g}'`}function X(B,g){let w=[],j="",E=0;for(let H=0;H<B.length;H++){let F=B[H];if(F==="<"||F==="("||F==="["||F==="{")E++,j+=F;else if(F===">"||F===")"||F==="]"||F==="}")E--,j+=F;else if(E===0&&B.slice(H,H+g.length)===g)w.push(j.trim()),j="",H+=g.length-1;else j+=F}if(j.trim())w.push(j.trim());return w}function C(B){for(let g of B){let w=g.replace(/^\/\*\*|\*\/$/g,"").replace(/^\s*\*\s?/gm,"").replace(/@\w.*/g,"").trim();if(w)return w}return null}function M(B,g){switch(g.format){case"json-schema":return Y(B,g);case"zod":return k(B,g);case"valibot":return V(B,g);case"io-ts":return Z(B,g);case"yup":return N(B,g);case"arktype":return f(B,g);case"dts":default:return B.map((w)=>w.text).join(`
32
+
33
+ `)}}function b(B){switch(B){case"json-schema":return".schema.json";case"zod":case"valibot":case"io-ts":case"yup":case"arktype":return".schema.ts";case"dts":default:return".d.ts"}}
34
+ export{Y as I,k as J,V as K,Z as L,N as M,f as N,M as O,b as P};
@@ -0,0 +1,32 @@
1
+ // @bun
2
+ import{Vc as xX}from"./chunk-57agx6g8.js";import{cd as r}from"./chunk-rw6j20e2.js";import{existsSync as CY}from"fs";import{resolve as xY}from"path";import kX from"process";import{pathToFileURL as kY}from"url";import{existsSync as gQ,statSync as cQ}from"fs";import{existsSync as PX,mkdirSync as hY,readdirSync as dY,writeFileSync as fY}from"fs";import{homedir as u}from"os";import{dirname as uY,resolve as x}from"path";import KQ from"process";import{join as bX,relative as yX,resolve as lQ}from"path";import AQ from"process";import{existsSync as WX,mkdirSync as iY,readdirSync as sY,writeFileSync as oY}from"fs";import{homedir as IQ}from"os";import{dirname as aY,resolve as C}from"path";import t from"process";import{join as vX,relative as hX,resolve as nQ}from"path";import zQ from"process";import{existsSync as BX,mkdirSync as ZZ,readdirSync as $Z,writeFileSync as UZ}from"fs";import{dirname as JZ,resolve as WQ}from"path";import hQ from"process";import{Buffer as m}from"buffer";import{createCipheriv as dX,createDecipheriv as fX,randomBytes as MQ}from"crypto";import{closeSync as DQ,createReadStream as iQ,createWriteStream as pX,existsSync as TQ,fsyncSync as sQ,openSync as oQ,writeFileSync as mX}from"fs";import{access as uX,constants as rQ,mkdir as gX,readdir as QQ,rename as tQ,stat as g,unlink as XQ,writeFile as VQ}from"fs/promises";import{join as c}from"path";import V from"process";import{pipeline as cX}from"stream/promises";import{createGzip as aQ}from"zlib";import l from"process";import f from"process";import{Buffer as h}from"buffer";import{createCipheriv as lX,createDecipheriv as nX,randomBytes as NQ}from"crypto";import{closeSync as SQ,createReadStream as eQ,createWriteStream as iX,existsSync as YQ,fsyncSync as QX,openSync as XX,writeFileSync as sX}from"fs";import{access as oX,constants as YX,mkdir as rX,readdir as ZQ,rename as ZX,stat as n,unlink as $Q,writeFile as OQ}from"fs/promises";import{isAbsolute as tX,join as i,resolve as aX}from"path";import R from"process";import{pipeline as eX}from"stream/promises";import{createGzip as $X}from"zlib";import s from"process";import p from"process";import HQ from"process";import{existsSync as JQ}from"fs";import{resolve as PQ}from"path";import{existsSync as OY}from"fs";class AX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),U=Z??this.options.ttl,H=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:U,hits:0,size:H}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!gQ(Q))return!0;return cQ(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=gQ(Y)?cQ(Y):null,U=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:U},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class zX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let U=await X(),H=performance.now()-Z;return this.recordMetric({operation:Q,duration:H,timestamp:$,...Y}),U}catch(U){let H=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:H,timestamp:$,...Y}),U}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,U)=>$+U,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var _Q=new AX,vQ=new zX;function dQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let $ of Q)if(F($)&&"name"in $){if(!Z.find((H)=>F(H)&&("name"in H)&&H.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((H)=>F(H)&&("path"in H)&&H.path===$.path))Z.push($)}else if(!Z.some((U)=>BQ(U,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!F(X)||!F(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(F($)&&F(Y[Z]))Y[Z]=dQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&F($[0])&&F(Y[Z][0])){let U=[...$];for(let H of Y[Z])if(F(H)&&"name"in H){if(!U.find((J)=>F(J)&&("name"in J)&&J.name===H.name))U.push(H)}else if(F(H)&&"path"in H){if(!U.find((J)=>F(J)&&("path"in J)&&J.path===H.path))U.push(H)}else if(!U.some((q)=>BQ(q,H)))U.push(H);Y[Z]=U}else if($.every((U)=>typeof U==="string")&&Y[Z].every((U)=>typeof U==="string")){let U=[...$];for(let H of Y[Z])if(!U.includes(H))U.push(H);Y[Z]=U}else Y[Z]=$;else Y[Z]=$}return Y}function BQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!BQ(Q[Y],X[Y]))return!1;return!0}if(F(Q)&&F(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!BQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function QY(Q,X){if(!BX(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return dQ(X,Z)}catch{return null}}catch{return null}}async function XY({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||hQ.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],U=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let H of U)for(let q of $){let J=WQ(Z,`${H}${q}`),G=await QY(J,Y);if(G!==null)return G}try{let H=WQ(Z,"package.json");if(BX(H)){let J=(await import(H))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return dQ(Y,J)}catch{}}}catch{}return Y}var EZ=WQ(hQ.cwd(),"config"),CZ=WQ(hQ.cwd(),"src/generated");function YY(Q,X={}){let Y=zQ.cwd();while(Y.includes("storage"))Y=nQ(Y,"..");let Z=nQ(Y,Q||"");if(X?.relative)return hX(zQ.cwd(),Z);return Z}var ZY=zQ.env.CLARITY_LOG_DIR||vX(YY(),"logs"),EQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ZY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1};async function $Y(){try{let Q=await XY({name:"clarity",defaultConfig:EQ,cwd:zQ.cwd(),endpoint:"",headers:{}});return{...EQ,...Q}}catch{return EQ}}var UX=await $Y();function I(){if(f.env.NODE_ENV==="test"||f.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UY(){if(f.env.NODE_ENV==="test"||f.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof f<"u"){let Q=f.type;if(Q==="renderer"||Q==="worker")return!1;return!!(f.versions&&(f.versions.node||f.versions.bun))}return!1}class RX{async format(Q){let X=await UY(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:l.pid,hostname:X(),environment:l.env.NODE_ENV||"development",platform:l.platform,version:l.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:l.env.NODE_ENV||l.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},j=E,xZ=E.red,HY=E.green,kZ=E.yellow,JY=E.blue,PZ=E.magenta,bZ=E.cyan,HX=E.white,yZ=E.gray,qY=E.bgRed,GY=E.bgYellow,JX=E.bold,vZ=E.dim,hZ=E.italic,dZ=E.underline,fZ=E.reset,CQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_Y={debug:"\uD83D\uDD0D",info:JY("\u2139"),success:HY("\u2713"),warning:GY(HX(JX(" WARN "))),error:qY(HX(JX(" ERROR ")))};class jQ{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(Q,X={}){this.name=Q,this.config={...UX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new RX,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),U=this.generateKey();this.currentKeyId=$,this.keys.set($,U),this.encryptionKeys.set($,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...CQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...CQ};return{...CQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:UX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,U=0,H=3,q=1000;while(U<H)try{try{try{await uX(this.config.logDirectory,rQ.F_OK|rQ.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await gX(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:m.from(Q);try{if(!TQ(this.currentLogFile))await VQ(this.currentLogFile,"",{mode:420});if($=oQ(this.currentLogFile,"a",420),mX($,J,{flag:"a"}),sQ($),$!==void 0)DQ($),$=void 0;if((await g(this.currentLogFile)).size===0){if(await VQ(this.currentLogFile,J,{flag:"w",mode:420}),(await g(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let _=G;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(U<H-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${H}:`,A);let W=q*2**U;await new Promise((z)=>setTimeout(z,W)),U++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{DQ($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}catch(J){if(U===H-1){let _=J,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}U++;let G=q*2**(U-1);await new Promise((_)=>setTimeout(_,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 c(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 c(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return c(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(I())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,q],[,J])=>J.createdAt.getTime()-q.createdAt.getTime()),U=typeof X.maxKeys==="number"?X.maxKeys:1,H=Math.max(1,U);if($.length>H)for(let[q]of $.slice(H))this.encryptionKeys.delete(q),this.keys.delete(q)}generateKeyId(){return MQ(16).toString("hex")}generateKey(){return MQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=MQ(16),Z=dX("aes-256-gcm",X,Y),$=m.concat([Z.update(Q,"utf8"),Z.final()]),U=Z.getAuthTag();return{encrypted:m.concat([Y,$,U]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=aQ(),$=[];Z.on("data",(U)=>$.push(U)),Z.on("end",()=>X(m.from(m.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(I())return;let Q=await g(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await QQ(this.config.logDirectory),U=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let _=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),H=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,q=`${Y}.${H}`;if(await g(Y).catch(()=>null))try{if(await tQ(Y,q),X.compress)try{let J=`${q}.gz`;await this.compressLogFile(q,J),await XQ(q)}catch(J){console.error("Error compressing rotated file:",J)}if(U.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await VQ(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),U=Y.replace(/\.log$/,`-${$}.log`);if(await g(Y).catch(()=>null))await tQ(Y,U)}if(this.currentLogFile=Z,X.maxFiles){let U=(await QQ(this.config.logDirectory)).filter((H)=>H.startsWith(this.name)).sort((H,q)=>q.localeCompare(H));for(let H of U.slice(X.maxFiles))await XQ(c(this.config.logDirectory,H))}}}async compressLogFile(Q,X){let Y=iQ(Q),Z=pX(X),$=aQ();await cX(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),TQ(this.currentLogFile))try{let Q=oQ(this.currentLogFile,"r+");sQ(Q),DQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!I()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await QQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await XQ(c(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?j.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:U,showTimestamp:H=!0}=Q,q=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(H)z.push(X);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(Y)z.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)z.push(Z.replace(/[[\]]/g,""));return z.push($),z.join(" ")}let J=V.stdout.columns||120,G="";if(U==="warning"||U==="error")G=`${Y} ${$}`;else if(U==="info"||U==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${j.cyan($)}`;if(!H)return G.trim();let _=q(G).trim().length,A=q(X).length,W=Math.max(1,J-2-_-A);return`${G.trim()}${" ".repeat(W)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(U,H)=>{let q=Number.parseInt(H,10);return q<X[0].length?String(X[0][q]):U});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(U,H)=>{if(H==="%")return"%";if(Z>=X.length)return U;let q=X[Z++];switch(H){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return U}});if(Z<X.length)$+=` ${X.slice(Z).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),U=this.formatFileTimestamp(Z),H,q;if(X instanceof Error)H=X.message,q=X.stack;else H=this.formatMessage(X,Y);if(this.fancy&&!I()){let G=_Y[Q],_=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:j.gray(H),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:H,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:j.green(H),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:H,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:G,tag:_,message:H,level:Q}),console.error(A),q){let W=q.split(`
3
+ `);for(let z of W)if(z.trim()&&!z.includes(H))console.error(this.formatConsoleMessage({timestamp:$,message:j.gray(` ${z}`),level:Q,showTimestamp:!1}))}break}}else if(!I()){if(console.error(`${U} ${this.environment}.${Q.toUpperCase()}: ${H}`),q)console.error(q)}if(!this.shouldLog(Q))return;let J=`${U} ${this.environment}.${Q.toUpperCase()}: ${H}
4
+ `;if(q)J+=`${q}
5
+ `;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!I()){let Y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:j.blue("\u25D0"),tag:Y,message:`${j.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),U=`${Q} completed in ${$}ms`,H=new Date,q=this.formatConsoleTimestamp(H),G=`${this.formatFileTimestamp(H)} ${this.environment}.INFO: ${U}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
6
+ `,G=G.replace(this.ANSI_PATTERN,""),this.fancy&&!I()){let _=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:q,icon:j.green("\u2713"),tag:_,message:`${U}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!I())console.error(G.trim());await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new jQ(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(I())throw Error("createReadStream is not supported in browser environments");if(!TQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return iQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=m.isBuffer(Q)?Q:m.from(Q,"base64"),$=Z.slice(0,16),U=Z.slice(-16),H=Z.slice(16,-16),q=fX("aes-256-gcm",Y,$);return q.setAuthTag(U),m.concat([q.update(H),q.final()]).toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return I()}isServerMode(){return!I()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!I()){let U=Q.split(`
7
+ `),H=Math.max(...U.map((_)=>_.length))+2,q=`\u250C${"\u2500".repeat(H)}\u2510`,J=`\u2514${"\u2500".repeat(H)}\u2518`,G=U.map((_)=>{let A=" ".repeat(H-_.length-2);return`\u2502 ${_}${A} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:j.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q)})),G.forEach((_)=>console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(_),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(J),showTimestamp:!1}))}else if(!I())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(I())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${j.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();V.stdin.removeListener("data",Y);try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!1)}catch{}V.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!0)}catch{}V.stdin.resume(),V.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let H=/%([sdijfo%])/g,q=0;if(Y=Q.replace(H,(J,G)=>{if(G==="%")return"%";if(q>=X.length)return J;let _=X[q++];switch(G){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return J}}),q<X.length)Y+=` ${X.slice(q).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!I()){let H=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",q=j.blue("\u25D0");console.error(`${q} ${H} ${j.cyan(Y)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}progress(Q,X=""){if(!this.enabled||!this.fancy||I()||Q<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:Q,current:0,message:X,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(H,q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||I())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,H)),q!==void 0)this.activeProgressBar.message=q;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(H)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||I())return;if(this.activeProgressBar.current=this.activeProgressBar.total,H!==void 0)this.activeProgressBar.message=H;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(H,q="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||I())return;V.stdout.write(`${"\r".padEnd(V.stdout.columns||80)}\r`),this.log(q,H),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||I()||!V.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,U=j.green("\u2501".repeat(Z)),H=j.gray("\u2501".repeat($)),q=`[${U}${H}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",_=X||Y===100?j.green("\u2713"):j.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",W=`\r${_}${A} ${q} ${J}${G}`,z=V.stdout.columns||80,D=" ".repeat(Math.max(0,z-W.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${W}${D}`,V.stdout.write(Q.lastRenderedLine),X)V.stdout.write(`
10
+ `)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||I()||!V.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(I()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await QQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let U=c(this.config.logDirectory,Z);if(Q.before)try{if((await g(U)).mtime>=Q.before)continue}catch(H){console.error(`Failed to get stats for file ${U}:`,H);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await XQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var pZ=new jQ("stacks");function GQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&w(X[0])&&"id"in X[0]&&X[0].id===3&&w(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(w(X)&&w(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(w(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&w(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&w(X[0])&&w(Q[0])){let Z=[...X];for(let $ of Q)if(w($)&&"name"in $){if(!Z.find((H)=>w(H)&&("name"in H)&&H.name===$.name))Z.push($)}else if(w($)&&"path"in $){if(!Z.find((H)=>w(H)&&("path"in H)&&H.path===$.path))Z.push($)}else if(!Z.some((U)=>RQ(U,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!w(X)||!w(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(w($)&&w(Y[Z]))Y[Z]=GQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&w($[0])&&w(Y[Z][0])){let U=[...$];for(let H of Y[Z])if(w(H)&&"name"in H){if(!U.find((J)=>w(J)&&("name"in J)&&J.name===H.name))U.push(H)}else if(w(H)&&"path"in H){if(!U.find((J)=>w(J)&&("path"in J)&&J.path===H.path))U.push(H)}else if(!U.some((q)=>RQ(q,H)))U.push(H);Y[Z]=U}else if($.every((U)=>typeof U==="string")&&Y[Z].every((U)=>typeof U==="string")){let U=[...$];for(let H of Y[Z])if(!U.includes(H))U.push(H);Y[Z]=U}else Y[Z]=$;else Y[Z]=$}return Y}function fQ(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:GQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:GQ(Q,X);if(!w(X)||!w(Q))return X;let Z={...Q};for(let $ of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,$))continue;let U=X[$],H=Z[$];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(H))if(Y==="replace")Z[$]=U;else Z[$]=GQ(H,U);else if(w(U)&&w(H))Z[$]=fQ(H,U,Y);else Z[$]=U}return Z}function RQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!RQ(Q[Y],X[Y]))return!1;return!0}if(w(Q)&&w(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!RQ(Q[$],X[$]))return!1}return!0}return!1}function w(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}var O=new jQ("bunfig",{showTags:!0});async function UQ(Q,X,Y="replace"){if(!WX(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return fQ(X,$,Y)}catch{return null}}catch{return null}}function AY(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function U(H,q=[]){let J={...H};for(let[G,_]of Object.entries(H)){let A=[...q,G],W=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),z=`${Z}_${A.map(W).join("_")}`,D=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(Y)O.info(`Checking environment variable ${z} for config ${Q}.${A.join(".")}`);if(typeof _==="object"&&_!==null&&!Array.isArray(_))J[G]=U(_,A);else{let B=t.env[z]||t.env[D];if(B!==void 0){if(Y)O.info(`Using environment variable ${B?z:D} for config ${Q}.${A.join(".")}`);if(typeof _==="number")J[G]=Number(B);else if(typeof _==="boolean")J[G]=B.toLowerCase()==="true";else if(Array.isArray(_))try{let K=JSON.parse(B);if(Array.isArray(K))J[G]=K;else J[G]=B.split(",").map((N)=>N.trim())}catch{J[G]=B.split(",").map((K)=>K.trim())}else J[G]=B}}}return J}return U($)}async function zY({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:U=!1,checkEnv:H=!0,arrayStrategy:q="replace"}){let J=H&&typeof $==="object"&&$!==null&&!Array.isArray($)?AY(Q,$,U):$,G=Y||t.cwd(),_=[".ts",".js",".mjs",".cjs",".json"];if(U)O.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${G}`);let A=[Q,`.${Q}`].filter(Boolean),W=[`${Q}.config`,`.${Q}.config`].filter(Boolean),z=X?[X,`.${X}`]:[],D=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([G,C(G,"config"),C(G,".config"),Z?C(G,Z):void 0].filter(Boolean)));for(let K of B){if(U)O.info(`Searching for configuration in: ${K}`);let S=[C(G,"config"),C(G,".config")].concat(Z?[C(G,Z)]:[]).includes(K)?[...A,...W,...z,...D]:[...W,...A,...D,...z];for(let v of S)for(let y of _){let P=C(K,`${v}${y}`),uQ=await UQ(P,J,q);if(uQ!==null){if(U)O.success(`Configuration loaded from: ${P}`);return uQ}}}if(Q){let K=C(IQ(),".config",Q),N=["config",`${Q}.config`];if(X)N.push(`${X}.config`);if(U)O.info(`Checking user config directory: ${K}`);for(let S of N)for(let v of _){let y=C(K,`${S}${v}`),P=await UQ(y,J,q);if(P!==null){if(U)O.success(`Configuration loaded from user config directory: ${y}`);return P}}}if(Q){let K=C(IQ(),".config"),N=[`.${Q}.config`];if(X)N.push(`.${X}.config`);if(U)O.info(`Checking user config directory for dotfile configs: ${K}`);for(let S of N)for(let v of _){let y=C(K,`${S}${v}`),P=await UQ(y,J,q);if(P!==null){if(U)O.success(`Configuration loaded from user config directory dotfile: ${y}`);return P}}}if(Q){let K=IQ(),N=[`.${Q}.config`,`.${Q}`];if(X)N.push(`.${X}.config`),N.push(`.${X}`);if(U)O.info(`Checking user home directory for dotfile configs: ${K}`);for(let S of N)for(let v of _){let y=C(K,`${S}${v}`),P=await UQ(y,J,q);if(P!==null){if(U)O.success(`Configuration loaded from user home directory: ${y}`);return P}}}try{let K=C(G,"package.json");if(WX(K)){let N=await import(K),S=N[Q];if(!S&&X){if(S=N[X],S&&U)O.success(`Using alias "${X}" configuration from package.json`)}if(S&&typeof S==="object"&&!Array.isArray(S))try{if(U)O.success(`Configuration loaded from package.json: ${S===N[Q]?Q:X}`);return fQ(J,S,q)}catch(v){if(U)O.warn("Failed to merge package.json config:",v)}}}catch(K){if(U)O.warn("Failed to load package.json:",K)}if(U)O.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return J}var mZ=C(t.cwd(),"config"),uZ=C(t.cwd(),"src/generated");function WY(Q,X={}){let Y=AQ.cwd();while(Y.includes("storage"))Y=lQ(Y,"..");let Z=lQ(Y,Q||"");if(X?.relative)return yX(AQ.cwd(),Z);return Z}var BY=AQ.env.CLARITY_LOG_DIR||bX(WY(),"logs"),xQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1};async function RY(){try{let Q=await zY({name:"clarity",alias:"logging",defaultConfig:xQ,cwd:AQ.cwd()});return{...xQ,...Q||{}}}catch{return xQ}}var qX=await RY();function M(){if(p.env.NODE_ENV==="test"||p.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function LY(){if(p.env.NODE_ENV==="test"||p.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p<"u"){let Q=p.type;if(Q==="renderer"||Q==="worker")return!1;return!!(p.versions&&(p.versions.node||p.versions.bun))}return!1}class LX{async format(Q){let X=await LY(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:s.pid,hostname:X(),environment:s.env.NODE_ENV||"development",platform:s.platform,version:s.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:s.env.NODE_ENV||s.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var T={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},L=T,gZ=T.red,wY=T.green,cZ=T.yellow,KY=T.blue,lZ=T.magenta,nZ=T.cyan,GX=T.white,iZ=T.gray,jY=T.bgRed,FY=T.bgYellow,sZ=T.bgGray,_X=T.bold,oZ=T.dim,rZ=T.italic,tZ=T.underline,aZ=T.strikethrough,eZ=T.reset,kQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},IY={debug:"\uD83D\uDD0D",info:KY("\u2139"),success:wY("\u2713"),warning:FY(GX(_X(" WARN "))),error:jY(GX(_X(" ERROR ")))};class FQ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,X={}){this.name=Q,this.config={...qX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new LX,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),U=this.generateKey();this.currentKeyId=$,this.keys.set($,U),this.encryptionKeys.set($,{key:U,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...kQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...kQ};return{...kQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:qX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!M()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,U=0,H=3,q=1000;while(U<H)try{try{try{await oX(this.config.logDirectory,YX.F_OK|YX.W_OK)}catch(G){if(G instanceof Error&&"code"in G)if(G.code==="ENOENT")await rX(this.config.logDirectory,{recursive:!0,mode:493});else if(G.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw G;else throw G}}catch(G){throw console.error("Debug: [writeToFile] Failed to create log directory:",G),G}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:h.from(Q);try{if(!YQ(this.currentLogFile))await OQ(this.currentLogFile,"",{mode:420});if($=XX(this.currentLogFile,"a",420),sX($,J,{flag:"a"}),QX($),$!==void 0)SQ($),$=void 0;if((await n(this.currentLogFile)).size===0){if(await OQ(this.currentLogFile,J,{flag:"w",mode:420}),(await n(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(G){let _=G;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(U<H-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${H}:`,A);let W=q*2**U;await new Promise((z)=>setTimeout(z,W)),U++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{SQ($)}catch(G){console.error("Debug: [writeToFile] Error closing file descriptor:",G)}}}catch(J){if(U===H-1){let _=J,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}U++;let G=q*2**(U-1);await new Promise((_)=>setTimeout(_,G))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 i(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 i(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return i(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(M())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,q],[,J])=>J.createdAt.getTime()-q.createdAt.getTime()),U=typeof X.maxKeys==="number"?X.maxKeys:1,H=Math.max(1,U);if($.length>H)for(let[q]of $.slice(H))this.encryptionKeys.delete(q),this.keys.delete(q)}generateKeyId(){return NQ(16).toString("hex")}generateKey(){return NQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=NQ(16),Z=lX("aes-256-gcm",X,Y),$=h.isBuffer(Q)?Q:h.from(Q,"utf8"),U=Z.update($),H=Z.final(),q=U.length+H.length,J=Z.getAuthTag(),G=h.allocUnsafe(16+q+16);return Y.copy(G,0),U.copy(G,16),H.copy(G,16+U.length),J.copy(G,16+q),{encrypted:G,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=$X(),$=[];Z.on("data",(U)=>$.push(U)),Z.on("end",()=>X(h.from(h.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(M())return;if(!this.shouldWriteToFile())return;let Q=await n(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await ZQ(this.config.logDirectory),U=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,G)=>{let _=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(G.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),H=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,q=`${Y}.${H}`;if(await n(Y).catch(()=>null))try{if(await ZX(Y,q),X.compress)try{let J=`${q}.gz`;await this.compressLogFile(q,J),await $Q(q)}catch(J){console.error("Error compressing rotated file:",J)}if(U.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await OQ(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),U=Y.replace(/\.log$/,`-${$}.log`);if(await n(Y).catch(()=>null))await ZX(Y,U)}if(this.currentLogFile=Z,X.maxFiles){let U=(await ZQ(this.config.logDirectory)).filter((H)=>H.startsWith(this.name)).sort((H,q)=>q.localeCompare(H));for(let H of U.slice(X.maxFiles))await $Q(i(this.config.logDirectory,H))}}}async compressLogFile(Q,X){let Y=eQ(Q),Z=iX(X),$=$X();await eX(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),YQ(this.currentLogFile))try{let Q=XX(this.currentLogFile,"r+");QX(Q),SQ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!M()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await ZQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await $Q(i(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?L.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M())return!1;let Q=typeof R.env.NO_COLOR<"u",X=R.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:U,showTimestamp:H=!0}=Q,q=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(H)z.push(X);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(Y)z.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)z.push(Z.replace(/[[\]]/g,""));return z.push($),z.join(" ")}let J=R.stdout.columns||120,G="";if(U==="warning"||U==="error")G=`${Y} ${$}`;else if(U==="info"||U==="success")G=`${Y} ${Z} ${$}`;else G=`${Y} ${Z} ${L.cyan($)}`;if(!H)return G.trim();let _=q(G).trim().length,A=q(X).length,W=Math.max(1,J-2-_-A);return`${G.trim()}${" ".repeat(W)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(U,H)=>{let q=Number.parseInt(H,10);return q<X[0].length?String(X[0][q]):U});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(U,H)=>{if(H==="%")return"%";if(Z>=X.length)return U;let q=X[Z++];switch(H){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return U}});if(Z<X.length)$+=` ${X.slice(Z).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let U=L.underline(L.blue(Z)),H=this.toAbsoluteFilePath($);if(H&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let q=`file://${encodeURI(H)}`,J="\x1B]8;;",G="\x1B\\";return`\x1B]8;;${q}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>L.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>L.strikethrough(Z)),X}supportsHyperlinks(){if(M())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=R.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(tX(X)||X.startsWith("./")||X.startsWith("../"))X=aX(X);else return null;return YQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),U=this.formatFileTimestamp(Z),H,q;if(X instanceof Error)H=X.message,q=X.stack;else H=this.formatMessage(X,Y);let{consoleText:J,fileText:G}=this.buildOutputTexts(H);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":IY[Q],W=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",z;switch(Q){case"debug":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:L.gray(J),level:Q}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:J,level:Q}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:L.green(J),level:Q}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:J,level:Q}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:$,icon:A,tag:W,message:J,level:Q}),console.error(z),q){let D=q.split(`
11
+ `);for(let B of D)if(B.trim()&&!B.includes(H))console.error(this.formatConsoleMessage({timestamp:$,message:L.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!M()){if(console.error(`${U} ${this.environment}.${Q.toUpperCase()}: ${H}`),q)console.error(q)}if(!this.shouldLog(Q))return;let _=`${U} ${this.environment}.${Q.toUpperCase()}: ${G}
12
+ `;if(q)_+=`${q}
13
+ `;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,X=""){let Y={update:(q,J)=>{},finish:(q)=>{},interrupt:(q,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!M()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(q,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,q),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!M()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(q)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,q)},interrupt:(q,J="info")=>{if(!M()&&R.stdout.isTTY)R.stdout.write(`
14
+ `);if(this[J==="warning"?"warn":J](q),this.activeProgressBar&&this.shouldStyleConsole()&&!M()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":L.blue("\u25D0"),tag:Y,message:`${L.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),U=`${Q} completed in ${$}ms`,H=new Date,q=this.formatConsoleTimestamp(H),G=`${this.formatFileTimestamp(H)} ${this.environment}.INFO: ${U}`;if(Y)G+=` ${JSON.stringify(Y)}`;if(G+=`
15
+ `,G=G.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:q,icon:this.options.showIcons===!1?"":L.green("\u2713"),tag:_,message:`${U}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M())console.error(G.trim());if(this.shouldWriteToFile())await this.writeToFile(G)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new FQ(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M())throw Error("createReadStream is not supported in browser environments");if(!YQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return eQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=h.isBuffer(Q)?Q:h.from(Q,"base64"),$=Z.subarray(0,16),U=Z.subarray(Z.length-16),H=Z.subarray(16,Z.length-16),q=nX("aes-256-gcm",Y,$);q.setAuthTag(U);let J=q.update(H),G=q.final(),_=J.length+G.length,A=h.allocUnsafe(_);return J.copy(A,0),G.copy(A,J.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M()}isServerMode(){return!M()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:U}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let q=$.split(`
16
+ `),J=Math.max(...q.map((W)=>W.length))+2,G=`\u250C${"\u2500".repeat(J)}\u2510`,_=`\u2514${"\u2500".repeat(J)}\u2518`,A=q.map((W)=>{return this.formatConsoleMessage({timestamp:Y,message:L.cyan(W),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(G),showTimestamp:!1})),A.forEach((W)=>console.error(W)),console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(_),showTimestamp:!1}))}else if(!M())console.error(`${Z} ${this.environment}.INFO: [BOX] ${U}`);let H=`${Z} ${this.environment}.INFO: [BOX] ${U}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(H)}async prompt(Q){if(M())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${L.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",Y);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let J=/%([sdijfo%])/g,G=0;if(Y=Q.replace(J,(_,A)=>{if(A==="%")return"%";if(G>=X.length)return _;let W=X[G++];switch(A){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return _}}),G<X.length)Y+=` ${X.slice(G).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",G=this.options.showIcons===!1?"":`${L.blue("\u25D0")} `;console.error(`${G}${J} ${L.cyan(Z)}`)}let q=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(q)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,U=L.green("\u2501".repeat(Z)),H=L.gray("\u2501".repeat($)),q=`[${U}${H}]`,J=`${Y}%`.padStart(4),G=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":X||Y===100?L.green("\u2713"):L.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",W=`\r${_}${A} ${q} ${J}${G}`,z=R.stdout.columns||80,D=" ".repeat(Math.max(0,z-W.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${W}${D}`,R.stdout.write(Q.lastRenderedLine),X)R.stdout.write(`
19
+ `)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||M()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(M()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await ZQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let U=i(this.config.logDirectory,Z);if(Q.before)try{if((await n(U)).mtime>=Q.before)continue}catch(H){console.error(`Failed to get stats for file ${U}:`,H);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await $Q(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var Q0=new FQ("stacks");class b extends Error{timestamp;context;constructor(Q,X={}){super(Q);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,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 Q=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Y])=>`${X}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Q}`}}class wX extends b{code="CONFIG_NOT_FOUND";constructor(Q,X,Y){let Z=Y?` or alias "${Y}"`:"";super(`Configuration "${Q}"${Z} not found`,{configName:Q,alias:Y,searchPaths:X,searchPathCount:X.length})}}class LQ extends b{code="CONFIG_LOAD_ERROR";constructor(Q,X,Y){super(`Failed to load configuration from "${Q}": ${X.message}`,{configPath:Q,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}}class KX extends b{code="CONFIG_VALIDATION_ERROR";constructor(Q,X,Y){super(`Configuration validation failed for "${Q}"`,{configPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class jX extends b{code="CONFIG_MERGE_ERROR";constructor(Q,X,Y,Z){super(`Failed to merge configuration from "${Q}" with "${X}": ${Y.message}`,{sourcePath:Q,targetPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class pQ extends b{code="ENV_VAR_ERROR";constructor(Q,X,Y,Z){super(`Failed to parse environment variable "${Q}" with value "${X}" as ${Y}`,{envKey:Q,envValue:X,expectedType:Y,configName:Z})}}class FX extends b{code="FILE_SYSTEM_ERROR";constructor(Q,X,Y){super(`File system ${Q} failed for "${X}": ${Y.message}`,{operation:Q,path:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class IX extends b{code="TYPE_GENERATION_ERROR";constructor(Q,X,Y){super(`Failed to generate types from "${Q}" to "${X}": ${Y.message}`,{configDir:Q,outputPath:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class wQ extends b{code="SCHEMA_VALIDATION_ERROR";constructor(Q,X,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class MX extends b{code="BROWSER_CONFIG_ERROR";constructor(Q,X,Y,Z){super(`Failed to fetch configuration from "${Q}": ${X} ${Y}`,{endpoint:Q,status:X,statusText:Y,configName:Z})}}class DX extends b{code="PLUGIN_ERROR";constructor(Q,X,Y){super(`Plugin "${Q}" failed during ${X}: ${Y.message}`,{pluginName:Q,operation:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var o={configNotFound(Q,X,Y){return new wX(Q,X,Y)},configLoad(Q,X,Y){return new LQ(Q,X,Y)},configValidation(Q,X,Y){return new KX(Q,X,Y)},configMerge(Q,X,Y,Z){return new jX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new pQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new FX(Q,X,Y)},typeGeneration(Q,X,Y){return new IX(Q,X,Y)},schemaValidation(Q,X,Y){return new wQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new MX(Q,X,Y,Z)},plugin(Q,X,Y){return new DX(Q,X,Y)}};async function MY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:U}=X,H=Error("Unknown error occurred");for(let q=0;q<=Y;q++)try{return await Q()}catch(J){if(H=J instanceof Error?J:Error(String(J)),q===Y||!$(H))break;if(Z>0)await new Promise((G)=>setTimeout(G,Z))}if(U!==void 0)return U;throw H instanceof Error?H:Error(`Unknown error: ${String(H)}`)}class mQ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:U=!0,customParsers:H={},verbose:q=!1,trackPerformance:J=!0}=Y,G=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let _=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],_,{useCamelCase:$,useBackwardCompatibility:U,customParsers:H,verbose:q,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return vQ.track("applyEnvironmentVariables",G,{configName:Q});return G()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,U]of Object.entries(Q)){let H=[...X,$],q=H.map((_)=>this.formatEnvKey(_,Z.useCamelCase)),J=`${Y}_${q.join("_")}`,G=Z.useBackwardCompatibility?`${Y}_${H.map((_)=>_.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,H,Y,Z);else{let _=HQ.env[J]||(G?HQ.env[G]:void 0);if(_!==void 0){if(Z.verbose){let A=HQ.env[J]?J:G}try{Q[$]=this.parseEnvironmentValue(_,typeof U,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof pQ)throw A;throw o.envVar(J,_,typeof U,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[U,H]of Object.entries(Z))try{return H(Q)}catch{continue}for(let U of this.defaultParsers)if(U.canParse(Q,X))try{return U.parse(Q)}catch{throw o.envVar(Y,Q,`${X} (via ${U.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(HQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,U=Z||this.generateEnvPrefix(Q),H=[];switch(this.extractEnvVarInfo(X,[],U,H),$){case"markdown":return this.formatAsMarkdown(H,Q);case"json":return JSON.stringify(H,null,2);default:return this.formatAsText(H,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,U]of Object.entries(Q)){let H=[...X,$],q=`${Y}_${H.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,H,Y,Z);else Z.push({key:q,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${H.join(".")}`,example:this.generateExample(U)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
20
+
21
+ `;for(let Z of Q)Y+=`${Z.key}
22
+ `,Y+=` Type: ${Z.type}
23
+ `,Y+=` Description: ${Z.description}
24
+ `,Y+=` Example: ${Z.example}
25
+
26
+ `;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
27
+
28
+ `;Y+=`| Variable | Type | Description | Example |
29
+ `,Y+=`|----------|------|-------------|----------|
30
+ `;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
31
+ `;return Y}}function DY(Q,X,Y={}){return TX(Q,X,Y,new WeakMap)}function TX(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:U=!1,customMerger:H}=Y;if(X===null||X===void 0)return U?Q:X;if(H){let q=H(Q,X);if(q!==void 0)return q}if(Array.isArray(X)||Array.isArray(Q))return VX(Q,X,$,Z);if(!k(X)||!k(Q))return X;return SY(Q,X,Y,Z)}function VX(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return TY(Q,X);case"smart":return VY(Q,X,Z);default:return X}return X}function TY(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>yQ($,Z)))Y.push(Z);return Y}function VY(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(k(X[0])&&k(Q[0]))return NY(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function NY(Q,X,Y){let Z=[...X];for(let $ of Q){if(!k($)){Z.push($);continue}let U=["id","name","key","path","type"],H=!1;for(let q of U)if(q in $){if(Z.find((G)=>k(G)&&(q in G)&&G[q]===$[q])){H=!0;break}}if(!H)Z.push($)}return Z}function SY(Q,X,Y,Z){let $=X;if(k($)&&Z.has($))return Z.get($);let U={...Q};if(k($))Z.set($,U);for(let H in $){if(!Object.prototype.hasOwnProperty.call($,H))continue;let q=$[H],J=U[H];if(Y.skipNullish&&(q===null||q===void 0))continue;if(q===null||q===void 0){U[H]=q;continue}if(k(q)&&k(J))U[H]=TX(J,q,Y,Z);else if(Array.isArray(q)||Array.isArray(J))U[H]=VX(J,q,Y.arrayMergeMode||"smart",Z);else U[H]=q}return U}function NX(Q,X,Y="replace"){return DY(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function yQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!yQ(Q[Y],X[Y]))return!1;return!0}if(k(Q)&&k(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!yQ(Q[$],X[$]))return!1}return!0}return!1}function k(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class SX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:U,trackPerformance:H=!0,verbose:q=!1}=Y;if($){let G=_Q.getWithFileCheck("file",Q);if(G){if(q)console.log(`Configuration loaded from cache: ${Q}`);return G}}let J=async()=>{if(!JQ(Q))return null;try{let G=`?t=${Date.now()}`,_=await import(Q+G),A=_.default||_,W="default"in _,z=Object.keys(_).length>0;if(!W&&!z)throw new LQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new LQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:NX(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)_Q.setWithFileCheck("file",K,Q,U);return K}catch(G){throw G instanceof Error?o.configLoad(Q,G):o.configLoad(Q,Error(String(G)))}};if(H)return vQ.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let U of Z)for(let H of this.extensions)$.push(PQ(X,`${U}${H}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(X){if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),Q)Y.push(`${Q}.${X}.config`,`.${Q}.${X}.config`)}return Y.filter(Boolean)}checkFileAccess(Q){return MY(async()=>{return JQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!JQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let U of $)for(let H of this.extensions){let q=PQ(Q,`${U}${H}`);if(await this.checkFileAccess(q))Z.push(q)}}else try{let{readdirSync:$}=await import("fs"),U=$(Q);for(let H of U)if(this.looksLikeConfigFile(H)){let q=PQ(Q,H);if(await this.checkFileAccess(q))Z.push(q)}}catch{return[]}return Z}looksLikeConfigFile(Q){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((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!JQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),U=$(Q,"utf8");JSON.parse(U)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var EY=/^https?:\/\//;class OX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:U=!0,customRules:H=[],trackPerformance:q=!0,verbose:J=!1}=Y,G=async()=>{let _=[],A=[],W={stopOnFirstError:Z,validateRequired:$,validateTypes:U,customRules:H,trackPerformance:q,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,W);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...H],W);else return this.validateWithJSONSchema(Q,X,W)}catch(z){return _.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:_,warnings:A}}};if(q)return await vQ.track("validateConfiguration",G);return G()}async validateWithSchemaFile(Q,X,Y){try{if(!OY(X))throw new wQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new wQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,U){if(U.validateTypes&&X.type){let H=Array.isArray(Q)?"array":typeof Q,q=Array.isArray(X.type)?X.type:[X.type];if(!q.includes(H)){if(Z.push({path:Y,message:`Expected type ${q.join(" or ")}, got ${H}`,expected:q.join(" or "),actual:H,rule:"type"}),U.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),U.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let H=0;H<Q.length;H++){let q=Y?`${Y}[${H}]`:`[${H}]`;if(this.validateObjectAgainstSchema(Q[H],X.items,q,Z,$,U),U.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let H=Q;if(U.validateRequired&&X.required){for(let q of X.required)if(!(q in H)){if(Z.push({path:Y?`${Y}.${q}`:q,message:`Missing required property '${q}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(X.properties){for(let[q,J]of Object.entries(X.properties))if(q in H){let G=Y?`${Y}.${q}`:q;if(this.validateObjectAgainstSchema(H[q],J,G,Z,$,U),U.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let q=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(H))if(!q.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let U of X)try{let H=this.getValueByPath(Q,U.path),q=this.validateWithRule(H,U,U.path);if(Z.push(...q),Y.stopOnFirstError&&Z.length>0)break}catch(H){Z.push({path:U.path,message:`Rule validation failed: ${H}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,U,H]=Z;X.push({path:$,required:!U,type:this.mapTypeScriptType(H)})}return X}mapTypeScriptType(Q){switch(Q.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:EY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var d=new FQ("bunfig",{showTags:!0});class EX{fileLoader=new SX;envProcessor=new mQ;validator=new OX;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:U,...H}=Q;try{if(Y?.enabled){let J=this.checkCache(H.name||"",H);if(J)return J}let q;try{q=await this.loadConfigurationStrategies(H,!0,Y)}catch(J){let G=H.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(G)throw J;q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:[`No configuration file found for "${H.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let _=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!_&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),W=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(G&&(W||_))throw J;if(A&&(!G||!W))q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!G)q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else q={...await this.applyEnvironmentVariables(H.name||"",H.defaultConfig,H.checkEnv!==!1,H.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||U)await this.validateConfiguration(q.config,$,U,H.name);if(Y?.enabled&&q)this.cacheResult(H.name||"",q,Y,H);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:H.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)d.warn(`Slow configuration loading detected: ${J.duration}ms for ${H.name}`);q.metrics=J}return q}catch(q){let J=Date.now()-X;throw d.error(`Configuration loading failed after ${J}ms:`,[q instanceof Error?q:Error(String(q))]),q}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:U,configDir:H,defaultConfig:q,checkEnv:J=!0,arrayStrategy:G="replace",verbose:_=!1}=Q,A=U||KQ.cwd(),W=[],z=await this.loadLocalConfiguration(Z,$,A,H,q,G,_,J,Y);if(z)return W.push(...this.getLocalSearchPaths(Z,$,A,H)),this.finalizeResult(z,W,J,Z,_);let D=await this.loadHomeConfiguration(Z,$,q,G,_,J);if(D)return W.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(D,W,J,Z,_);let B=await this.loadPackageJsonConfiguration(Z,$,A,q,G,_,J);if(B)return W.push(x(A,"package.json")),this.finalizeResult(B,W,J,Z,_);if(W.push(...this.getAllSearchPaths(Z,$,A,H)),X)throw o.configNotFound(Z,W,$);return{...await this.applyEnvironmentVariables(Z,q,J,_),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,U,H,q,J){let G=q?qQ(Q,$,H):$,_=this.getLocalDirectories(Y,Z);for(let A of _){if(H)d.info(`Searching for configuration in: ${A}`);let W=this.fileLoader.generateConfigPaths(Q,A,X),z=await this.fileLoader.tryLoadFromPaths(W,G,{arrayStrategy:U,verbose:H,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(z){if(H)d.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,U){if(!Q)return null;let H=U?qQ(Q,Y,$):Y,q=[x(u(),".config",Q),x(u(),".config"),u()];for(let J of q){if($)d.info(`Checking home directory: ${J}`);let G=this.fileLoader.generateConfigPaths(Q,J,X),_=await this.fileLoader.tryLoadFromPaths(G,H,{arrayStrategy:Z,verbose:$});if(_){if($)d.success(`Configuration loaded from home directory: ${_.source.path}`);return _}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,U,H){let q=H?qQ(Q,Z,U):Z;try{let J=x(Y,"package.json");if(!PX(J))return null;let G=await import(J),_=G[Q],A=Q;if(!_&&X)_=G[X],A=X;if(_&&typeof _==="object"&&!Array.isArray(_)){if(U)d.success(`Configuration loaded from package.json: ${A}`);return{config:NX(q,_,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(U)d.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:qQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let U=Y(Q);if(U)$.push(...U)}if(X){let U=await this.validator.validateConfiguration(Q,X);if(!U.isValid)$.push(...U.errors.map((H)=>H.path?`${H.path}: ${H.message}`:H.message))}if($.length>0)throw o.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return _Q.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);_Q.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias)Y.push(`alias:${X.alias}`);if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,x(Q,"config"),x(Q,".config"),X?x(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(x(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),U=[];for(let H of $)U.push(...this.fileLoader.generateConfigPaths(Q,H,X));return U}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[x(u(),".config",Q),x(u(),".config"),u()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var bQ=new EX;async function CX(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await bQ.loadConfig(Q);else Z=await bQ.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",U=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||U.includes("config"))&&Q.verbose)d.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let q=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await bQ.applyEnvironmentVariables(q.name||"",X,!0,q.verbose||!1))?.config??X;return X}}function qQ(Q,X,Y=!1){let Z=new mQ,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(H,q=[]){let J={...H};for(let[G,_]of Object.entries(H)){let A=[...q,G],W=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,D;for(let B of W)if(z=KQ.env[B],z!==void 0){D=B;break}if(z!==void 0&&D)if(typeof _==="boolean")J[G]=["true","1","yes"].includes(z.toLowerCase());else if(typeof _==="number"){let B=Number(z);if(!Number.isNaN(B))J[G]=B}else if(Array.isArray(_))try{J[G]=JSON.parse(z)}catch{J[G]=z.split(",").map((B)=>B.trim())}else J[G]=z;else if(_&&typeof _==="object"&&!Array.isArray(_))J[G]=U(_,A)}return J}return U(X)}var U0=x(KQ.cwd(),"config"),H0=x(KQ.cwd(),"src/generated");var e={cwd:kX.cwd(),root:"./src",entrypoints:["**/*.ts"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},PY=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function bY(Q=kX.cwd()){for(let X of PY){let Y=xY(Q,X);if(CY(Y))try{let $=await import(kY(Y).href),U=$.default||$.config||$,H=typeof U==="function"?await U():U;return{...e,...H,cwd:Q}}catch(Z){let $=Z instanceof Error?Z.message:String(Z);xX.warn(`Failed to load config from ${X}: ${$}`)}}return null}var a=null;async function B0(Q){if(!a){let X=await bY(Q);if(X)a=X;else a=await CX({name:"dts",defaultConfig:e})}return a}function R0(){a=null}function L0(Q){return{...e,...Q}}function w0(Q){return async()=>{let X=await Q();return{...e,...X}}}var K0=e;
32
+ export{e as Oc,B0 as Pc,R0 as Qc,L0 as Rc,w0 as Sc,K0 as Tc};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{a,b,c}from"./chunk-ggmn4a8c.js";import"./chunk-wfevdmvd.js";import"./chunk-p1d09y82.js";import"./chunk-74j5mydx.js";import"./chunk-rnt0wkrk.js";import"./chunk-xnq1xw73.js";import"./chunk-rw6j20e2.js";export{b as optimizeFile,a as optimizeDeclarations,c as minifyDts};
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{ec as $}from"./chunk-wfevdmvd.js";import{existsSync as U,readFileSync as O,writeFileSync as q}from"fs";function _(G){let j=[],H=/\b([A-Z][a-zA-Z0-9]*)\b/g,L;while((L=H.exec(G))!==null){let J=L[1];if(!N(J))j.push(J)}return[...new Set(j)]}function N(G){return new Set(["Array","Object","String","Number","Boolean","Symbol","BigInt","Function","Promise","Map","Set","WeakMap","WeakSet","Date","RegExp","Error","TypeError","RangeError","SyntaxError","Partial","Required","Readonly","Pick","Omit","Record","Exclude","Extract","NonNullable","ReturnType","Parameters","ConstructorParameters","InstanceType","ThisType","Uppercase","Lowercase","Capitalize","Uncapitalize","Awaited","NoInfer","Generator","AsyncGenerator","IterableIterator","AsyncIterableIterator","PropertyKey","Iterable","AsyncIterable","ArrayLike","PromiseLike","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]).has(G)}function C(G){if(G.kind!=="type")return!1;let j=G.typeAnnotation||"";if(G.generics)return!1;if(j.includes("{")||j.includes("(")||j.includes("<"))return!1;return/^[\w\s|&]+$/.test(j)}function E(G){if(G.kind!=="interface")return!1;if(!G.members||G.members.length===0){if(!G.extends)return!0}return!1}function F(G,j){let H={...G,members:[...G.members||[],...j.members||[]],leadingComments:[...G.leadingComments||[],...j.leadingComments||[]]};if(G.extends&&j.extends){let L=G.extends.split(",").map((K)=>K.trim()),J=j.extends.split(",").map((K)=>K.trim());H.extends=[...new Set([...L,...J])].join(", ")}else H.extends=G.extends||j.extends;return H}function D(G){let j=["import","interface","type","class","enum","function","variable","export"];return[...G].sort((H,L)=>{let J=j.indexOf(H.kind)-j.indexOf(L.kind);if(J!==0)return J;return H.name.localeCompare(L.name)})}function R(G){let j=G.filter((J)=>J.kind==="import"),H=G.filter((J)=>J.kind!=="import");return[...[...j].sort((J,K)=>{let M=J.source||"",Q=K.source||"",V=M.startsWith("node:")||M==="bun",W=Q.startsWith("node:")||Q==="bun";if(V&&!W)return-1;if(!V&&W)return 1;let Y=!M.startsWith("."),X=!Q.startsWith(".");if(Y&&!X)return-1;if(!Y&&X)return 1;return M.localeCompare(Q)}),...H]}function k(G){let j=new Set;for(let J of G){if(J.kind==="import")continue;let K=J.text||"",M=J.typeAnnotation||"",Q=J.returnType||"",V=J.extends||"",W=J.implements?.join(" ")||"",Y=`${K} ${M} ${Q} ${V} ${W}`;for(let X of _(Y))j.add(X);if(J.members)for(let X of J.members){let Z=`${X.typeAnnotation||""} ${X.returnType||""}`;for(let w of _(Z))j.add(w)}if(J.parameters){for(let X of J.parameters)if(X.type)for(let Z of _(X.type))j.add(Z)}}let H=0;return{declarations:G.map((J)=>{if(J.kind!=="import"||!J.specifiers)return J;let K=J.specifiers.filter((M)=>{let Q=M.alias||M.name;return j.has(Q)});if(K.length===0){if(!J.isSideEffect)return H++,null}if(K.length<(J.specifiers?.length||0))return H+=(J.specifiers?.length||0)-K.length,{...J,specifiers:K};return J}).filter((J)=>J!==null),removed:H}}function A(G){let j=new Map,H=0;for(let L of G){if(L.kind==="import"){let K=`import:${L.source}`;if(j.has(K)){let M=j.get(K),Q=[...M.specifiers||[],...L.specifiers||[]],V=Array.from(new Map(Q.map((W)=>[W.alias||W.name,W])).values());j.set(K,{...M,specifiers:V}),H++}else j.set(K,L);continue}let J=`${L.kind}:${L.name}`;if(j.has(J))H++;else j.set(J,L)}return{declarations:Array.from(j.values()),removed:H}}function z(G){let j=new Map,H=[];for(let K of G)if(K.kind==="interface"){let M=K.name;if(!j.has(M))j.set(M,[]);j.get(M).push(K)}else H.push(K);let L=0,J=[];for(let[K,M]of j)if(M.length>1){let Q=M[0];for(let V=1;V<M.length;V++)Q=F(Q,M[V]),L++;J.push(Q)}else J.push(M[0]);return{declarations:[...H,...J],merged:L}}function P(G){let j=new Map,H=new Set;for(let K of G)if(C(K))j.set(K.name,K.typeAnnotation||""),H.add(K.name);if(j.size===0)return{declarations:G,inlined:0};function L(K){let M=K;for(let[Q,V]of j){let W=new RegExp(`\\b${Q}\\b`,"g");M=M.replace(W,V)}return M}return{declarations:G.filter((K)=>K.kind!=="type"||!H.has(K.name)).map((K)=>{if(K.typeAnnotation)K={...K,typeAnnotation:L(K.typeAnnotation)};if(K.returnType)K={...K,returnType:L(K.returnType)};if(K.extends)K={...K,extends:L(K.extends)};return K}),inlined:j.size}}function v(G){let j=G.length,H=G.filter((L)=>!E(L));return{declarations:H,removed:j-H.length}}function B(G,j={}){let H=[...G],L={originalSize:0,optimizedSize:0,savings:0,savingsPercent:0,removedImports:0,removedDeclarations:0,mergedInterfaces:0,inlinedTypes:0};if(j.removeUnusedImports){let{declarations:J,removed:K}=k(H);H=J,L.removedImports=K}if(j.deduplicateDeclarations){let{declarations:J,removed:K}=A(H);H=J,L.removedDeclarations+=K}if(j.mergeInterfaces){let{declarations:J,merged:K}=z(H);H=J,L.mergedInterfaces=K}if(j.removeEmptyInterfaces){let{declarations:J,removed:K}=v(H);H=J,L.removedDeclarations+=K}if(j.inlineSimpleTypes){let{declarations:J,inlined:K}=P(H);H=J,L.inlinedTypes=K}if(j.sortImports)H=R(H);if(j.sortDeclarations)H=D(H);return{declarations:H,result:L}}async function g(G,j={}){if(!U(G))throw Error(`File not found: ${G}`);let H=O(G,"utf-8"),L=Buffer.byteLength(H,"utf-8"),J=$(H,G,!j.removeComments),{declarations:K,result:M}=B(J,j),Q=h(K,j);if(j.minify)Q=x(Q);let V=Buffer.byteLength(Q,"utf-8");return M.originalSize=L,M.optimizedSize=V,M.savings=L-V,M.savingsPercent=Math.round(M.savings/L*100),q(G,Q),M}function h(G,j){let H=[];for(let L of G){if(!j.removeComments&&L.leadingComments)for(let J of L.leadingComments)H.push(J);if(L.text)H.push(L.text);else H.push(I(L));H.push("")}return H.join(`
3
+ `)}function I(G){let j=[];if(G.isExported)j.push("export");if(G.isDefault)j.push("default");switch(G.kind){case"import":if(G.isTypeOnly)j.push("import type");else j.push("import");if(G.specifiers&&G.specifiers.length>0){let H=G.specifiers.map((L)=>{let J=L.isType?"type ":"";return L.alias?`${J}${L.name} as ${L.alias}`:`${J}${L.name}`}).join(", ");j.push(`{ ${H} }`)}j.push("from"),j.push(`'${G.source}'`);break;case"function":if(j.push("declare function"),j.push(G.name),G.generics)j.push(G.generics);if(j.push(`(${S(G.parameters)})`),G.returnType)j.push(`: ${G.returnType}`);break;case"variable":if(j.push("declare const"),j.push(G.name),G.typeAnnotation)j.push(`: ${G.typeAnnotation}`);break;case"interface":if(j.push("interface"),j.push(G.name),G.generics)j.push(G.generics);if(G.extends)j.push(`extends ${G.extends}`);if(j.push("{"),G.members)for(let H of G.members)j.push(` ${H.name}${H.typeAnnotation?`: ${H.typeAnnotation}`:""}`);j.push("}");break;case"type":if(j.push("type"),j.push(G.name),G.generics)j.push(G.generics);j.push("="),j.push(G.typeAnnotation||"unknown");break;case"class":if(j.push("declare class"),j.push(G.name),G.generics)j.push(G.generics);if(G.extends)j.push(`extends ${G.extends}`);if(G.implements?.length)j.push(`implements ${G.implements.join(", ")}`);j.push("{ }");break;case"enum":j.push("declare enum"),j.push(G.name),j.push("{ }");break;default:return G.text||""}return j.join(" ")}function S(G){if(!G)return"";return G.map((j)=>{let H="";if(j.rest)H+="...";if(H+=j.name,j.optional)H+="?";if(j.type)H+=`: ${j.type}`;return H}).join(", ")}function x(G){return G.replace(/(?<!\/\*\*)\/\/[^\n]*/g,"").replace(/^\s*[\r\n]/gm,"").replace(/ {2,}/g," ").replace(/\s*([{}[\]();,:])\s*/g,"$1").replace(/(\w)(\{)/g,"$1 $2").replace(/(\})([a-z])/gi,"$1 $2").replace(/(export|import|type|interface|class|function|const|let|var|extends|implements|declare)\s*/g,"$1 ").trim()}
4
+ export{B as a,g as b,x as c};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{lc as I}from"./chunk-74j5mydx.js";import{nc as H}from"./chunk-rnt0wkrk.js";import{Bc as G}from"./chunk-begk3j01.js";function N(q,v="stdin.ts",z=!0,B=["bun"],E=!1){let A=I(q,v,z,E);return G(A,{filePath:v,sourceCode:q,declarations:A},z,B)}function P(q,v="stdin.ts",z=!0,B=["bun"],E=!1){let A=H(q,v,z,E);return G(A,{filePath:v,sourceCode:q,declarations:A},z,B)}
3
+ export{N as ic,P as jc};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ic as a,jc as b}from"./chunk-hrmnrn4p.js";import"./chunk-74j5mydx.js";import"./chunk-rnt0wkrk.js";import"./chunk-begk3j01.js";import"./chunk-xnq1xw73.js";import"./chunk-rw6j20e2.js";export{b as processSourceDirect,a as processSource};