@stacksjs/bun-router 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-7g1et0fb.js +82 -0
- package/dist/chunk-9y37n6xs.js +61 -0
- package/dist/chunk-trm3jyqk.js +357 -0
- package/dist/cli.js +30 -59
- package/dist/container/index.js +1 -1
- package/dist/index.js +29 -29
- package/dist/middleware/rate_limit.d.ts +2 -1
- package/dist/response/compression.d.ts +6 -0
- package/package.json +10 -2
- package/dist/chunk-03m2j6h7.js +0 -2
- package/dist/chunk-08cw7ejr.js +0 -3
- package/dist/chunk-0e4g0fyv.js +0 -62
- package/dist/chunk-0mmn02yw.js +0 -2
- package/dist/chunk-126c9qm3.js +0 -2
- package/dist/chunk-12p13817.js +0 -2
- package/dist/chunk-14v65c37.js +0 -4
- package/dist/chunk-1b6a7t3v.js +0 -231
- package/dist/chunk-1wenkmk0.js +0 -2
- package/dist/chunk-2152npfd.js +0 -2
- package/dist/chunk-26w23krx.js +0 -2
- package/dist/chunk-2g8m379z.js +0 -10
- package/dist/chunk-2rr178et.js +0 -1654
- package/dist/chunk-2w8f3swz.js +0 -29
- package/dist/chunk-3y4gaz7v.js +0 -82
- package/dist/chunk-4r1x4afz.js +0 -12
- package/dist/chunk-4wyw66zk.js +0 -2
- package/dist/chunk-4z5sf8ag.js +0 -2
- package/dist/chunk-58tfvayh.js +0 -4
- package/dist/chunk-5be9x5cq.js +0 -3
- package/dist/chunk-5dp83qcx.js +0 -397
- package/dist/chunk-5f0d9j9a.js +0 -2
- package/dist/chunk-5z52b0fc.js +0 -28
- package/dist/chunk-5zrnk2kq.js +0 -4
- package/dist/chunk-6bbmkwng.js +0 -3
- package/dist/chunk-6dmqtdnq.js +0 -2
- package/dist/chunk-6e91956t.js +0 -3
- package/dist/chunk-6rv8w5jk.js +0 -2
- package/dist/chunk-6x1feysm.js +0 -3
- package/dist/chunk-7qnxdedn.js +0 -321
- package/dist/chunk-7y72hm1x.js +0 -2
- package/dist/chunk-8hbhfh6b.js +0 -194
- package/dist/chunk-8kfzygg5.js +0 -3
- package/dist/chunk-8wpj3fqe.js +0 -351
- package/dist/chunk-8wydx2we.js +0 -2
- package/dist/chunk-8zjnjvv7.js +0 -2
- package/dist/chunk-9805tt8n.js +0 -341
- package/dist/chunk-988h4bzr.js +0 -2
- package/dist/chunk-9b6a58ac.js +0 -2
- package/dist/chunk-a8fcaywb.js +0 -2
- package/dist/chunk-bfjwn7yg.js +0 -2
- package/dist/chunk-bp2522mm.js +0 -2
- package/dist/chunk-brpgjyqg.js +0 -3
- package/dist/chunk-bswe62q4.js +0 -48
- package/dist/chunk-c3v796c8.js +0 -943
- package/dist/chunk-ccqmwdry.js +0 -2
- package/dist/chunk-ck0crwnx.js +0 -2
- package/dist/chunk-cqgkxcb4.js +0 -2
- package/dist/chunk-dntnakjy.js +0 -2
- package/dist/chunk-dxg045wj.js +0 -5
- package/dist/chunk-e3qej0jr.js +0 -4
- package/dist/chunk-ettdpnrw.js +0 -60
- package/dist/chunk-ezqwq17j.js +0 -185
- package/dist/chunk-ezx3qsez.js +0 -2
- package/dist/chunk-f72nnjy4.js +0 -15413
- package/dist/chunk-fna5n0ey.js +0 -246
- package/dist/chunk-fqhckdt8.js +0 -2
- package/dist/chunk-fr6hbx25.js +0 -2
- package/dist/chunk-g9cwng6w.js +0 -3
- package/dist/chunk-gd3za5x0.js +0 -2
- package/dist/chunk-gf28608k.js +0 -2
- package/dist/chunk-h1dj6v8q.js +0 -3
- package/dist/chunk-hjxe7k2g.js +0 -2
- package/dist/chunk-hrkgznbn.js +0 -2
- package/dist/chunk-j6h5v0br.js +0 -2
- package/dist/chunk-kjtjbcq4.js +0 -71
- package/dist/chunk-mgb01qdv.js +0 -14
- package/dist/chunk-n24c9whp.js +0 -2
- package/dist/chunk-n2j24b0h.js +0 -4540
- package/dist/chunk-nf3kv7kv.js +0 -3
- package/dist/chunk-nhmtg01n.js +0 -84
- package/dist/chunk-p0qhpnqh.js +0 -70
- package/dist/chunk-p0w1x8y2.js +0 -3
- package/dist/chunk-p3dk1w2w.js +0 -216
- package/dist/chunk-q4e9pxs7.js +0 -3
- package/dist/chunk-q5dv1kyy.js +0 -2
- package/dist/chunk-qnqgf9tq.js +0 -2
- package/dist/chunk-qvwy1808.js +0 -898
- package/dist/chunk-r18f77vc.js +0 -12
- package/dist/chunk-r63za1mr.js +0 -2
- package/dist/chunk-rft8gw92.js +0 -7851
- package/dist/chunk-ryvmyskt.js +0 -4211
- package/dist/chunk-sa6mx308.js +0 -2
- package/dist/chunk-sw0chtw4.js +0 -4
- package/dist/chunk-va0pc7hx.js +0 -2
- package/dist/chunk-vcp8dnjq.js +0 -412
- package/dist/chunk-vg1erq1q.js +0 -2
- package/dist/chunk-vsh4390q.js +0 -358
- package/dist/chunk-w0jv49ch.js +0 -11
- package/dist/chunk-wm805tte.js +0 -35
- package/dist/chunk-xg9xscqz.js +0 -1
- package/dist/chunk-xj9h6mc9.js +0 -2
- package/dist/chunk-ytvzwrq3.js +0 -51
- package/dist/chunk-zde7ebc4.js +0 -288
- package/dist/chunk-zmqsv2xy.js +0 -2
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
class t extends Error{code;statusCode;context;retryable;severity;category;timestamp;cause;constructor(e){super(e.message);if(this.name=this.constructor.name,this.code=e.code,this.statusCode=e.statusCode||500,this.context=e.context||{},this.retryable=e.retryable||!1,this.severity=e.severity||"medium",this.category=e.category||"system",this.timestamp=new Date,this.cause=e.cause,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,statusCode:this.statusCode,context:this.context,retryable:this.retryable,severity:this.severity,category:this.category,timestamp:this.timestamp.toISOString(),stack:this.stack,cause:this.cause?{name:this.cause.name,message:this.cause.message,stack:this.cause.stack}:void 0}}toResponse(){let e={error:{code:this.code,message:this.message,statusCode:this.statusCode,timestamp:this.timestamp.toISOString(),requestId:this.context.requestId}};return new Response(JSON.stringify(e),{status:this.statusCode,headers:{"Content-Type":"application/json","X-Error-Code":this.code,"X-Request-ID":this.context.requestId||""}})}}class u extends t{fields;constructor(e,n={},r){super({code:"VALIDATION_ERROR",message:e,statusCode:400,context:r,retryable:!1,severity:"low",category:"validation"});this.fields=n}toResponse(){let e={error:{code:this.code,message:this.message,statusCode:this.statusCode,timestamp:this.timestamp.toISOString(),requestId:this.context.requestId,fields:this.fields}};return new Response(JSON.stringify(e),{status:this.statusCode,headers:{"Content-Type":"application/json","X-Error-Code":this.code,"X-Request-ID":this.context.requestId||""}})}}class J extends t{constructor(e="Authentication required",n){super({code:"AUTHENTICATION_ERROR",message:e,statusCode:401,context:n,retryable:!1,severity:"medium",category:"authentication"})}}class X extends t{requiredPermissions;constructor(e="Access denied",n,r){super({code:"AUTHORIZATION_ERROR",message:e,statusCode:403,context:r,retryable:!1,severity:"medium",category:"authorization"});this.requiredPermissions=n}}class Y extends t{resource;resourceId;constructor(e="Resource not found",n,r,a){super({code:"NOT_FOUND",message:e,statusCode:404,context:a,retryable:!1,severity:"low",category:"business"});this.resource=n,this.resourceId=r}}class Q extends t{allowedMethods;constructor(e,n,r){super({code:"METHOD_NOT_ALLOWED",message:`Method ${e} not allowed. Allowed methods: ${n.join(", ")}`,statusCode:405,context:r,retryable:!1,severity:"low",category:"business"});this.allowedMethods=n}toResponse(){let e=super.toResponse();return e.headers.set("Allow",this.allowedMethods.join(", ")),e}}class v extends t{timeoutMs;constructor(e="Request timeout",n,r){super({code:"REQUEST_TIMEOUT",message:e,statusCode:408,context:r,retryable:!0,severity:"medium",category:"network"});this.timeoutMs=n}}class Z extends t{retryAfter;limit;remaining;constructor(e="Rate limit exceeded",n,r,a=0,l){super({code:"RATE_LIMIT_EXCEEDED",message:e,statusCode:429,context:l,retryable:!0,severity:"medium",category:"network"});this.retryAfter=n,this.limit=r,this.remaining=a}toResponse(){let e=super.toResponse();return e.headers.set("Retry-After",this.retryAfter.toString()),e.headers.set("X-RateLimit-Limit",this.limit.toString()),e.headers.set("X-RateLimit-Remaining",this.remaining.toString()),e}}class ee extends t{constructor(e="Internal server error",n,r){super({code:"INTERNAL_SERVER_ERROR",message:e,statusCode:500,context:r,cause:n,retryable:!0,severity:"high",category:"system"})}}class te extends t{retryAfter;constructor(e="Service unavailable",n,r){super({code:"SERVICE_UNAVAILABLE",message:e,statusCode:503,context:r,retryable:!0,severity:"high",category:"system"});this.retryAfter=n}toResponse(){let e=super.toResponse();if(this.retryAfter)e.headers.set("Retry-After",this.retryAfter.toString());return e}}class re extends t{query;operation;constructor(e,n,r,a,l){super({code:"DATABASE_ERROR",message:e,statusCode:500,context:l,cause:a,retryable:!0,severity:"high",category:"database"});this.operation=n,this.query=r}}class x extends t{service;endpoint;constructor(e,n,r,a=502,l,h){super({code:"EXTERNAL_SERVICE_ERROR",message:e,statusCode:a,context:h,cause:l,retryable:!0,severity:"medium",category:"external"});this.service=n,this.endpoint=r}}class T extends t{service;nextAttemptAt;constructor(e,n,r){super({code:"CIRCUIT_BREAKER_OPEN",message:`Circuit breaker is open for service: ${e}. Next attempt at: ${n.toISOString()}`,statusCode:503,context:r,retryable:!0,severity:"medium",category:"external"});this.service=e,this.nextAttemptAt=n}}class ne extends t{businessRule;constructor(e,n,r){super({code:"BUSINESS_LOGIC_ERROR",message:e,statusCode:422,context:r,retryable:!1,severity:"low",category:"business"});this.businessRule=n}}class se extends t{configKey;constructor(e,n,r){super({code:"CONFIGURATION_ERROR",message:e,statusCode:500,context:r,retryable:!1,severity:"critical",category:"system"});this.configKey=n}}class ie extends t{path;operation;constructor(e,n,r,a,l){super({code:"FILESYSTEM_ERROR",message:e,statusCode:500,context:l,cause:a,retryable:!1,severity:"medium",category:"system"});this.path=n,this.operation=r}}var s={validation:(e,n,r)=>new u(e,n,r),authentication:(e,n)=>new J(e,n),authorization:(e,n,r)=>new X(e,n,r),notFound:(e,n,r)=>new Y(void 0,e,n,r),methodNotAllowed:(e,n,r)=>new Q(e,n,r),timeout:(e,n,r)=>new v(n,e,r),rateLimit:(e,n,r,a)=>new Z(void 0,e,n,r,a),internalServer:(e,n,r)=>new ee(e,n,r),serviceUnavailable:(e,n,r)=>new te(e,n,r),database:(e,n,r,a,l)=>new re(e,n,r,a,l),externalService:(e,n,r,a,l,h)=>new x(e,n,r,a,l,h),circuitBreakerOpen:(e,n,r)=>new T(e,n,r),businessLogic:(e,n,r)=>new ne(e,n,r),configuration:(e,n,r)=>new se(e,n,r),fileSystem:(e,n,r,a,l)=>new ie(e,n,r,a,l)};class E extends t{conflictingRoutes;suggestion;constructor(e,n){let r=E.buildMessage(e),a=E.buildSuggestion(e);super({code:"ROUTE_CONFLICT",message:r,statusCode:500,context:n,retryable:!1,severity:"critical",category:"system"});this.conflictingRoutes=e,this.suggestion=a}static buildMessage(e){let n=["Route conflict detected! Multiple routes match the same path pattern.","","Conflicting routes:"];for(let r of e){if(n.push(` \u2022 ${r.method} ${r.path}`),r.name)n.push(` Name: "${r.name}"`);if(r.definedAt)n.push(` Defined at: ${r.definedAt}`)}return n.join(`
|
|
3
|
+
`)}static buildSuggestion(e){let n=[],r=e.some((p)=>!p.path.includes("{")),a=e.some((p)=>p.path.includes("{"));if(r&&a)n.push("\u2022 Static routes should be defined before dynamic routes","\u2022 Consider using route constraints (whereNumber, whereUuid) to differentiate");if(e.filter((p)=>p.path.includes("{")).length>1)n.push("\u2022 Use different parameter names or add constraints:",' router.get("/users/{id}").whereNumber("id")',' router.get("/users/{slug}").whereAlpha("slug")');if(e.some((p)=>p.path.includes("*")))n.push("\u2022 Wildcard routes should be defined last","\u2022 Consider using more specific path prefixes");if(n.length===0)n.push("\u2022 Rename one of the conflicting routes","\u2022 Use route groups with different prefixes","\u2022 Add parameter constraints to differentiate routes");return`How to fix:
|
|
4
|
+
${n.join(`
|
|
5
|
+
`)}`}toJSON(){return{...super.toJSON(),conflictingRoutes:this.conflictingRoutes,suggestion:this.suggestion}}}class d extends t{dependencyChain;suggestion;constructor(e,n){let r=d.buildMessage(e),a=d.buildSuggestion(e);super({code:"CIRCULAR_DEPENDENCY",message:r,statusCode:500,context:n,retryable:!1,severity:"critical",category:"system"});this.dependencyChain=e,this.suggestion=a}static buildMessage(e){let n=["Circular dependency detected in the dependency injection container!","","Dependency chain:",""];for(let r=0;r<e.length;r++){let a=r===e.length-1,l=r===0?"\u250C\u2500\u25BA":a?"\u2514\u2500\u25BA":"\u251C\u2500\u25BA";if(n.push(` ${l} ${e[r]}`),!a)n.push(" \u2502")}return n.push(" \u2502"),n.push(` \u2514\u2500\u2500 cycles back to: ${e[0]}`),n.join(`
|
|
6
|
+
`)}static buildSuggestion(e){return`How to fix:
|
|
7
|
+
|
|
8
|
+
1. Break the cycle by introducing an interface:
|
|
9
|
+
\u2022 Create an interface for one of the dependencies
|
|
10
|
+
\u2022 Use lazy injection: container.bind('${e[0]}').lazy()
|
|
11
|
+
|
|
12
|
+
2. Restructure your dependencies:
|
|
13
|
+
\u2022 Extract shared logic into a separate service
|
|
14
|
+
\u2022 Use events/callbacks instead of direct dependencies
|
|
15
|
+
|
|
16
|
+
3. Use setter injection instead of constructor injection:
|
|
17
|
+
\u2022 Remove the dependency from the constructor
|
|
18
|
+
\u2022 Set it after instantiation using a setter method
|
|
19
|
+
|
|
20
|
+
4. Check if the dependency is actually needed:
|
|
21
|
+
\u2022 Sometimes circular dependencies indicate a design issue
|
|
22
|
+
\u2022 Consider if the classes have too many responsibilities
|
|
23
|
+
|
|
24
|
+
Dependency chain involved:
|
|
25
|
+
${e.map((n,r)=>` ${r+1}. ${n}`).join(`
|
|
26
|
+
`)}`}toJSON(){return{...super.toJSON(),dependencyChain:this.dependencyChain,suggestion:this.suggestion}}}class oe extends t{middlewareName;configErrors;suggestion;constructor(e,n,r){let a=`Middleware "${e}" configuration error:
|
|
27
|
+
${n.map((l)=>` \u2022 ${l}`).join(`
|
|
28
|
+
`)}`;super({code:"MIDDLEWARE_CONFIGURATION_ERROR",message:a,statusCode:500,context:r,retryable:!1,severity:"high",category:"system"});this.middlewareName=e,this.configErrors=n,this.suggestion=this.buildSuggestion()}buildSuggestion(){return`How to fix:
|
|
29
|
+
\u2022 Check the middleware documentation for required options
|
|
30
|
+
\u2022 Ensure all required configuration values are provided
|
|
31
|
+
\u2022 Verify configuration value types match expected types
|
|
32
|
+
|
|
33
|
+
Example configuration:
|
|
34
|
+
router.use(new ${this.middlewareName}({
|
|
35
|
+
// Add required options here
|
|
36
|
+
}))`}}class j extends t{requestedPath;requestedMethod;similarRoutes;suggestion;constructor(e,n,r=[],a){let l=j.buildMessage(e,n,r);super({code:"ROUTE_NOT_FOUND",message:l,statusCode:404,context:a,retryable:!1,severity:"low",category:"business"});this.requestedPath=n,this.requestedMethod=e,this.similarRoutes=r,this.suggestion=this.buildSuggestion()}static buildMessage(e,n,r){let a=[`Route not found: ${e} ${n}`];if(r.length>0){a.push(""),a.push("Did you mean one of these routes?");for(let l of r.slice(0,5))if(a.push(` \u2022 ${l.method} ${l.path}`),l.similarity)a.push(` (${Math.round(l.similarity*100)}% match)`)}return a.join(`
|
|
37
|
+
`)}buildSuggestion(){let e=[`\u2022 Verify the HTTP method is correct (you used ${this.requestedMethod})`,"\u2022 Check for typos in the URL path","\u2022 Ensure the route is registered before the server starts","\u2022 Check if the route requires specific middleware (e.g., auth)"];if(this.requestedPath.includes("//"))e.push("\u2022 Remove duplicate slashes from the URL");if(!this.requestedPath.startsWith("/"))e.push("\u2022 Ensure the path starts with a forward slash (/)");return`How to fix:
|
|
38
|
+
${e.join(`
|
|
39
|
+
`)}`}}class ae extends t{handlerRef;suggestion;constructor(e,n,r){let a=`Failed to resolve handler "${e}": ${n}`;super({code:"HANDLER_RESOLUTION_ERROR",message:a,statusCode:500,context:r,retryable:!1,severity:"high",category:"system"});this.handlerRef=e,this.suggestion=this.buildSuggestion(e)}buildSuggestion(e){let n=e.includes("@"),r=e.includes("/");if(n){let[a,l]=e.split("@");return`How to fix:
|
|
40
|
+
\u2022 Ensure the controller "${a}" is registered in the container
|
|
41
|
+
\u2022 Verify the method "${l}" exists and is public
|
|
42
|
+
\u2022 Check the controller file is imported
|
|
43
|
+
|
|
44
|
+
Example:
|
|
45
|
+
// Register the controller
|
|
46
|
+
container.singleton('${a}', ${a})
|
|
47
|
+
|
|
48
|
+
// Define the route
|
|
49
|
+
router.get('/path', '${e}')`}if(r)return`How to fix:
|
|
50
|
+
\u2022 Ensure the action class exists at the specified path
|
|
51
|
+
\u2022 Verify the action has a "handle" method
|
|
52
|
+
\u2022 Check the action file is properly exported
|
|
53
|
+
|
|
54
|
+
Example:
|
|
55
|
+
// Action class at ${e}.ts
|
|
56
|
+
export default class ${e.split("/").pop()} {
|
|
57
|
+
handle(req: Request): Response {
|
|
58
|
+
return new Response('OK')
|
|
59
|
+
}
|
|
60
|
+
}`;return`How to fix:
|
|
61
|
+
\u2022 Verify the handler reference is correct
|
|
62
|
+
\u2022 Ensure the handler function/class is exported
|
|
63
|
+
\u2022 Check for circular dependencies in the handler module`}}class ce extends t{modelName;paramName;paramValue;suggestion;constructor(e,n,r,a,l){let h=`Failed to bind model "${e}" for parameter "${n}" with value "${r}": ${a}`;super({code:"MODEL_BINDING_ERROR",message:h,statusCode:404,context:l,retryable:!1,severity:"low",category:"business"});this.modelName=e,this.paramName=n,this.paramValue=r,this.suggestion=this.buildSuggestion()}buildSuggestion(){return`How to fix:
|
|
64
|
+
\u2022 Verify the ${this.paramName} "${this.paramValue}" exists in your data source
|
|
65
|
+
\u2022 Check if the model resolver is correctly configured
|
|
66
|
+
\u2022 Ensure the route parameter matches the model's identifier field
|
|
67
|
+
|
|
68
|
+
Example model binding:
|
|
69
|
+
router.model('${this.paramName}', async (value) => {
|
|
70
|
+
const ${this.modelName.toLowerCase()} = await db.${this.modelName.toLowerCase()}s.findUnique({
|
|
71
|
+
where: { id: value }
|
|
72
|
+
})
|
|
73
|
+
if (!${this.modelName.toLowerCase()}) {
|
|
74
|
+
throw new Error('${this.modelName} not found')
|
|
75
|
+
}
|
|
76
|
+
return ${this.modelName.toLowerCase()}
|
|
77
|
+
})`}}function st(e,n,r=5){let a=[];for(let l of n){let h=b(e,l.path);if(h>0.3)a.push({method:l.method,path:l.path,similarity:h})}return a.sort((l,h)=>(h.similarity||0)-(l.similarity||0)).slice(0,r)}function b(e,n){let r=e.length,a=n.length;if(r===0)return a===0?1:0;if(a===0)return 0;let l=[];for(let g=0;g<=r;g++)l[g]=[g];for(let g=0;g<=a;g++)l[0][g]=g;for(let g=1;g<=r;g++)for(let m=1;m<=a;m++){let y=e[g-1]===n[m-1]?0:1;l[g][m]=Math.min(l[g-1][m]+1,l[g][m-1]+1,l[g-1][m-1]+y)}let h=l[r][a],p=Math.max(r,a);return 1-h/p}function it(e){let n=[],r=new Set;for(let a=0;a<e.length;a++){let l=e[a],h=`${l.method}:${l.path}`;if(r.has(h))continue;let p=[];for(let g=a+1;g<e.length;g++){let m=e[g];if(l.method===m.method&&C(l.path,m.path)){if(p.length===0)p.push({method:l.method,path:l.path,name:l.name});p.push({method:m.method,path:m.path,name:m.name}),r.add(`${m.method}:${m.path}`)}}if(p.length>0)n.push(p);r.add(h)}return n}function C(e,n){if(e===n)return!0;let r=e.split("/").filter(Boolean),a=n.split("/").filter(Boolean);if(r.length!==a.length){let h=e.includes("*"),p=n.includes("*");if(!h&&!p)return!1}let l=Math.max(r.length,a.length);for(let h=0;h<l;h++){let p=r[h]||"",g=a[h]||"";if(p==="*"||g==="*")return!0;let m=p.startsWith("{")&&p.endsWith("}"),y=g.startsWith("{")&&g.endsWith("}");if(!m&&!y){if(p!==g)return!1}}return!0}var ot={routeConflict:(e,n)=>new E(e,n),circularDependency:(e,n)=>new d(e,n),middlewareConfig:(e,n,r)=>new oe(e,n,r),routeNotFound:(e,n,r,a)=>new j(e,n,r,a),handlerResolution:(e,n,r)=>new ae(e,n,r),modelBinding:(e,n,r,a,l)=>new ce(e,n,r,a,l)};var U=Symbol("injectable"),i=Symbol("inject"),P=Symbol("optional"),M=Symbol("tagged");class o{bindings=new Map;tagIndex=new Map;instances=new Map;scopedInstances=new Map;interceptors=new Map;parent;children=new Set;options;constructor(e={}){this.options={autoRegister:e.autoRegister??!0,strictMode:e.strictMode??!1,maxDepth:e.maxDepth??50,enableDecorators:e.enableDecorators??!0,enableInterception:e.enableInterception??!1,defaultScope:e.defaultScope??"transient"}}bind(e){return new L(this,e)}register(e){let n=this.bindings.get(e.token);if(n?.metadata?.tags)for(let r of n.metadata.tags)this.tagIndex.get(r)?.delete(e.token);if(this.bindings.set(e.token,e),e.metadata?.tags)for(let r of e.metadata.tags){let a=this.tagIndex.get(r);if(!a)a=new Set,this.tagIndex.set(r,a);a.add(e.token)}return this}singleton(e,n){return this.bind(e).to(n).inSingletonScope().build()}transient(e,n){return this.bind(e).to(n).inTransientScope().build()}value(e,n){return this.bind(e).toValue(n).build()}factory(e,n){return this.bind(e).toFactory(n).build()}resolve(e,n){let r={container:this,token:e,environment:n?.environment||"development",requestId:n?.requestId||this.generateRequestId(),depth:n?.depth||0,resolving:n?.resolving||new Set,parent:n?.parent};return this.resolveInternal(e,r)}resolveAll(e){let n=new Set;if(this.bindings.has(e))n.add(e);if(typeof e==="string")for(let r of this.tagIndex.get(e)??[])n.add(r);return Array.from(n,(r)=>this.resolve(r))}resolveTagged(e){let n=this.tagIndex.get(e);if(!n||n.size===0)return[];return Array.from(n,(r)=>this.resolve(r))}getTaggedBindings(e){let n=this.tagIndex.get(e);if(!n||n.size===0)return[];let r=[];for(let a of n){let l=this.bindings.get(a);if(l)r.push(l)}return r}addInterceptor(e,n){let r=this.tokenToString(e);if(!this.interceptors.has(r))this.interceptors.set(r,[]);this.interceptors.get(r).push(n)}registerController(e){this.singleton(e,e)}getController(e){return this.resolve(e)}isBound(e){return this.bindings.has(e)||(this.parent?.isBound(e)??!1)}unbind(e){let n=this.bindings.get(e);if(n?.metadata?.tags)for(let r of n.metadata.tags)this.tagIndex.get(r)?.delete(e);return this.bindings.delete(e),this.instances.delete(e),this}createChild(e){let n=new o({...this.options,...e});return n.parent=this,this.children.add(n),n}createScope(e){let n=this.createChild();return n.scopedInstances.set(e,new Map),n}getBindings(){return new Map(this.bindings)}clear(){return this.bindings.clear(),this.tagIndex.clear(),this.instances.clear(),this.scopedInstances.clear(),this}intercept(e,n){if(!this.interceptors.has(e))this.interceptors.set(e,[]);return this.interceptors.get(e).push(n),this}resolveInternal(e,n){if(n.resolving.has(e)){let r=Array.from(n.resolving).map((a)=>this.tokenToString(a));throw r.push(this.tokenToString(e)),new d(r)}if(n.depth>this.options.maxDepth){let r=Array.from(n.resolving).map((a)=>this.tokenToString(a));throw Error(`Maximum resolution depth exceeded (${this.options.maxDepth}).
|
|
78
|
+
This usually indicates a circular or very deep dependency chain.
|
|
79
|
+
Current resolution chain:
|
|
80
|
+
${r.map((a,l)=>` ${l+1}. ${a}`).join(`
|
|
81
|
+
`)}`)}n.resolving.add(e),n.depth++;try{let r=this.bindings.get(e);if(r){if(r.metadata.when&&!r.metadata.when(n))throw Error(`Contextual binding condition not met for: ${this.tokenToString(e)}`);return this.createInstance(r,n)}if(this.parent){let a={resolving:new Set,depth:0,container:this.parent,token:e};return this.parent.resolveInternal(e,a)}if(this.options.autoRegister&&typeof e==="function")return this.autoRegisterAndResolve(e,n);if(this.options.strictMode)throw Error(`No binding found for: ${this.tokenToString(e)}`);if(typeof e==="function")return this.createInstanceFromConstructor(e,n);throw Error(`Cannot resolve: ${this.tokenToString(e)}`)}finally{n.resolving.delete(e),n.depth--}}createInstance(e,n){let r;if(e.metadata.scope==="singleton"&&this.instances.has(e.token))r=this.instances.get(e.token);else if(e.metadata.scope==="scoped"&&n.requestId){let l=this.scopedInstances.get(n.requestId);if(l?.has(e.token))r=l.get(e.token);else{if(r=this.createNewInstance(e,n),!l)this.scopedInstances.set(n.requestId,new Map);this.scopedInstances.get(n.requestId).set(e.token,r)}}else if(r=this.createNewInstance(e,n),e.metadata.scope==="singleton")this.instances.set(e.token,r);let a=this.tokenToString(e.token);if(this.interceptors.has(a)){let l=this.interceptors.get(a);for(let h of l)r=h(r)}return r}createNewInstance(e,n){if(e.value!==void 0)return e.value;if(e.factory){let r=this.resolveDependencies(e.metadata.dependencies||[],n);return e.factory(...r)}if(e.instance)return e.instance;if(e.implementation)return this.createInstanceFromConstructor(e.implementation,n);throw Error(`Invalid binding configuration for: ${this.tokenToString(e.token)}`)}createInstanceFromConstructor(e,n){let r=this.getConstructorDependencies(e),a=this.resolveDependencies(r,n),l=new e(...a);if(this.options.enableDecorators)this.applyDecorators(l,e);return l}getConstructorDependencies(e){let n=Reflect.getMetadata?.(i,e)||e[i];if(!n&&e.constructor)n=e.constructor[i];if(!n&&typeof e==="function"&&e.prototype){let a=e[i];if(a)n=a}if(!n&&typeof e==="function"){let a=e[i];if(a)n=a}if(n)return n.map((a)=>a.token);let r=Reflect.getMetadata?.("design:paramtypes",e);if(r)return r;return this.parseConstructorDependencies(e)}parseConstructorDependencies(e){let r=e.toString().match(/constructor\s*\(([^)]*)\)/);if(!r||!r[1])return[];return r[1].split(",").map((a)=>a.trim().split(":")[0].trim()).filter((a)=>a.length>0)}resolveDependencies(e,n){return e.map((r)=>this.resolveInternal(r,n))}autoRegisterAndResolve(e,n){let r=Reflect.getMetadata?.(U,e),a={token:e,implementation:e,metadata:{scope:r?.scope||this.options.defaultScope,tags:r?.tags}};return this.register(a),this.resolveInternal(e,n)}applyDecorators(e,n){let r=Reflect.getMetadata?.("decorators",n);if(r)for(let a of r)a(e)}hasTag(e,n){return e.metadata.tags?.includes(n)??!1}tokenToString(e){if(typeof e==="string")return e;if(typeof e==="symbol")return e.toString();if(typeof e==="function")return e.name||"anonymous";return"unknown"}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}class L{container;binding;constructor(e,n){this.container=e;this.binding={token:n,metadata:{scope:"transient"}}}to(e){return this.binding.implementation=e,this}toValue(e){return this.binding.value=e,this.binding.metadata.scope="singleton",this}toFactory(e){return this.binding.factory=e,this}toInstance(e){return this.binding.instance=e,this.binding.metadata.scope="singleton",this}inSingletonScope(){return this.binding.metadata.scope="singleton",this}inTransientScope(){return this.binding.metadata.scope="transient",this}inScopedScope(){return this.binding.metadata.scope="scoped",this}inRequestScope(){return this.binding.metadata.scope="request",this}withTags(...e){return this.binding.metadata.tags=[...this.binding.metadata.tags||[],...e],this}when(e){return this.binding.metadata.when=e,this}lazy(){return this.binding.metadata.lazy=!0,this}build(){return this.container.register(this.binding),this.container}}var f=null;function ye(){if(!f)f=new o;return f}function we(e){f=e}function be(e){return new o(e)}class _{environments=new Map;currentEnvironment;variables=new Map;constructor(e="development"){this.currentEnvironment=e,this.loadEnvironmentVariables()}register(e){return this.environments.set(e.name,e),this}setEnvironment(e){if(!this.environments.has(e))throw Error(`Environment ${e} is not registered`);return this.currentEnvironment=e,this.loadEnvironmentVariables(),this}getCurrentEnvironment(){return this.currentEnvironment}getEnvironment(e){return this.environments.get(e||this.currentEnvironment)}is(...e){return e.includes(this.currentEnvironment)}get(e,n){return this.variables.get(e)??n}set(e,n){return this.variables.set(e,n),this}hasFeature(e){return this.getEnvironment()?.features.includes(e)??!1}loadEnvironmentVariables(){let e=this.getEnvironment();if(e)for(let[n,r]of Object.entries(e.variables))this.variables.set(n,r)}}class Re{container;binding;constructor(e,n){this.container=e;this.binding={token:n,conditions:[],priority:0,metadata:{scope:"transient"}}}when(e){return this.binding.conditions.push(e),this}whenEnvironment(...e){let n={type:"environment",predicate:(r)=>e.includes(r.environment||"development"),description:`Environment is one of: ${e.join(", ")}`};return this.when(n)}whenTag(e){let n={type:"tag",predicate:(r)=>r.parent?.token?.toString().includes(e)??!1,description:`Parent has tag: ${e}`};return this.when(n)}whenParent(e){let n={type:"parent",predicate:(r)=>r.parent?.token===e,description:`Parent token is: ${e.toString()}`};return this.when(n)}whenRequest(e){let n={type:"request",predicate:e,description:"Custom request condition"};return this.when(n)}withPriority(e){return this.binding.priority=e,this}withFallback(e){return this.binding.fallback=e,this}to(e){return this.binding.implementation=e,this}toValue(e){return this.binding.value=e,this.binding.metadata.scope="singleton",this}toFactory(e){return this.binding.factory=e,this}inSingletonScope(){return this.binding.metadata.scope="singleton",this}inTransientScope(){return this.binding.metadata.scope="transient",this}build(){return this.container.registerContextualBinding(this.binding),this.container}}class le extends o{contextualBindings=new Map;environmentManager;constructor(e){super(e);this.environmentManager=new _}bindContextual(e){return new Re(this,e)}registerContextualBinding(e){if(!this.contextualBindings.has(e.token))this.contextualBindings.set(e.token,[]);let n=this.contextualBindings.get(e.token);return n.push(e),n.sort((r,a)=>a.priority-r.priority),this}getEnvironmentManager(){return this.environmentManager}forDevelopment(e){return this.bindContextual(e).whenEnvironment("development")}forProduction(e){return this.bindContextual(e).whenEnvironment("production")}forTesting(e){return this.bindContextual(e).whenEnvironment("test","testing")}forStaging(e){return this.bindContextual(e).whenEnvironment("staging")}resolve(e,n){let r={container:this,token:e,environment:n?.environment||this.environmentManager.getCurrentEnvironment(),requestId:n?.requestId||this.generateContextualRequestId(),depth:n?.depth||0,resolving:n?.resolving||new Set,parent:n?.parent},a=this.findContextualBinding(e,r);if(a)return this.createInstanceFromContextualBinding(a,r);return super.resolve(e,r)}findContextualBinding(e,n){let r=this.contextualBindings.get(e);if(!r)return;for(let a of r)if(this.evaluateConditions(a.conditions,n))return a;return}evaluateConditions(e,n){return e.every((r)=>{try{return r.predicate(n)}catch(a){return console.warn(`Error evaluating binding condition: ${r.description}`,a),!1}})}createInstanceFromContextualBinding(e,n){try{return this.createInstance(e,n)}catch(r){if(e.fallback)return console.warn(`Contextual binding failed, using fallback for ${e.token.toString()}`),this.createInstance(e.fallback,n);throw r}}generateContextualRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}class at{static development(){return{name:"development",variables:{DEBUG:!0,LOG_LEVEL:"debug",CACHE_TTL:60,DB_POOL_SIZE:5},services:{logger:"ConsoleLogger",cache:"MemoryCache",database:"SQLiteDatabase"},features:["hot-reload","debug-toolbar","detailed-errors"]}}static production(){return{name:"production",variables:{DEBUG:!1,LOG_LEVEL:"error",CACHE_TTL:3600,DB_POOL_SIZE:20},services:{logger:"FileLogger",cache:"RedisCache",database:"PostgreSQLDatabase"},features:["performance-monitoring","error-tracking"]}}static testing(){return{name:"test",variables:{DEBUG:!1,LOG_LEVEL:"warn",CACHE_TTL:1,DB_POOL_SIZE:1},services:{logger:"NullLogger",cache:"MemoryCache",database:"InMemoryDatabase"},features:["test-doubles","fast-teardown"]}}static staging(){return{name:"staging",variables:{DEBUG:!0,LOG_LEVEL:"info",CACHE_TTL:1800,DB_POOL_SIZE:10},services:{logger:"FileLogger",cache:"RedisCache",database:"PostgreSQLDatabase"},features:["performance-monitoring","debug-toolbar"]}}}class ct{static environment(...e){return{type:"environment",predicate:(n)=>e.includes(n.environment||"development"),description:`Environment is one of: ${e.join(", ")}`}}static feature(e){return{type:"custom",predicate:(n)=>n.container.getEnvironmentManager().hasFeature(e),description:`Feature ${e} is enabled`}}static envVar(e,n){return{type:"custom",predicate:(r)=>r.container.getEnvironmentManager().get(e)===n,description:`Environment variable ${e} equals ${n}`}}static requestPattern(e){return{type:"request",predicate:(n)=>e.test(n.requestId||""),description:`Request ID matches pattern: ${e.toString()}`}}static timeRange(e,n){return{type:"custom",predicate:()=>{let r=new Date().getHours();return r>=e&&r<=n},description:`Time is between ${e}:00 and ${n}:00`}}static custom(e,n){return{type:"custom",predicate:e,description:n||"Custom condition"}}}class c{version;dependencies;environment;priority=0;boot(e){}shutdown(e){}singleton(e,n,r){e.singleton(n,r)}transient(e,n,r){e.transient(n,r)}value(e,n,r){e.value(n,r)}factory(e,n,r){e.factory(n,r)}when(e,n){return{bind:(r)=>e.bind(r).when(n)}}forEnvironment(e,...n){return this.when(e,(r)=>n.includes(r.environment||"development"))}}class ve extends c{isDeferred(){return!0}}class ue{providers=new Map;deferredProviders=new Map;loadedProviders=new Set;bootedProviders=new Set;container;constructor(e){this.container=e}register(e){if(this.isConditionalProvider(e)){let n=e.shouldLoad(this.container);if(n instanceof Promise)n.then((r)=>{if(r)this.doRegister(e)});else if(!n)return this}return this.doRegister(e),this}async boot(){let e=Array.from(this.providers.values()).sort((n,r)=>(r.priority||0)-(n.priority||0));this.validateDependencies(e);for(let n of e)if(!this.loadedProviders.has(n.name))await this.loadProvider(n);for(let n of e)if(!this.bootedProviders.has(n.name))await this.bootProvider(n)}async shutdown(){let e=Array.from(this.providers.values()).reverse();for(let n of e)if(n.shutdown)try{await n.shutdown(this.container)}catch(r){console.error(`Error shutting down provider ${n.name}:`,r)}this.providers.clear(),this.deferredProviders.clear(),this.loadedProviders.clear(),this.bootedProviders.clear()}getProvider(e){return this.providers.get(e)}getProviders(){return Array.from(this.providers.values())}async loadDeferredProvider(e){for(let[n,r]of this.deferredProviders)if(r.provides().includes(e)&&!this.loadedProviders.has(n))await this.loadProvider(r),await this.bootProvider(r),this.deferredProviders.delete(n)}doRegister(e){if(this.providers.has(e.name))throw Error(`Provider ${e.name} is already registered`);if(this.providers.set(e.name,e),this.isDeferredProvider(e))this.deferredProviders.set(e.name,e)}async loadProvider(e){try{await e.register(this.container),this.loadedProviders.add(e.name)}catch(n){throw Error(`Failed to load provider ${e.name}: ${n}`)}}async bootProvider(e){if(e.boot)try{await e.boot(this.container),this.bootedProviders.add(e.name)}catch(n){throw Error(`Failed to boot provider ${e.name}: ${n}`)}else this.bootedProviders.add(e.name)}validateDependencies(e){let n=new Set(e.map((r)=>r.name));for(let r of e)if(r.dependencies){for(let a of r.dependencies)if(!n.has(a))throw Error(`Provider ${r.name} depends on ${a}, but it's not registered`)}}isDeferredProvider(e){return"provides"in e&&"isDeferred"in e}isConditionalProvider(e){return"shouldLoad"in e}}class lt extends c{name="config";priority=100;register(e){e.singleton("config",xe),this.forEnvironment(e,"development").bind("config.debug").toValue(!0),this.forEnvironment(e,"production").bind("config.debug").toValue(!1),this.forEnvironment(e,"test").bind("config.debug").toValue(!1)}}class ut extends c{name="logging";priority=90;register(e){e.factory("logger",(n)=>new z(n.get("logging",{}))),this.forEnvironment(e,"development").bind("logger").toFactory(()=>new Te),this.forEnvironment(e,"production").bind("logger").toFactory((n)=>new Ce(n.get("logging.file","./app.log")))}}class dt extends c{name="database";dependencies=["config","logging"];register(e){e.singleton("database",Se),e.transient("userRepository",Ee),e.transient("postRepository",Pe)}async boot(e){await e.resolve("database").connect()}async shutdown(e){await e.resolve("database").disconnect()}}class pt extends c{name="cache";dependencies=["config"];register(e){e.singleton("cache",Me),this.forEnvironment(e,"development").bind("cache.store").toFactory(()=>new ke),this.forEnvironment(e,"production").bind("cache.store").toFactory((n)=>new $e(n.get("cache.redis")))}}class ht extends c{name="auth";dependencies=["config","database"];register(e){e.singleton("authService",Ae),e.singleton("jwtService",Oe),e.transient("authGuard",Ie)}}class mt extends c{name="validation";register(e){e.singleton("validator",Fe),e.factory("validationPipe",(n)=>new De(n))}}class gt extends ve{name="events";provides(){return["eventBus","eventDispatcher",de,pe]}register(e){e.singleton("eventBus",de),e.singleton("eventDispatcher",pe)}}class xe{get(e,n){return n}}class z{config;constructor(e){this.config=e}log(e){console.log(e)}}class Te extends z{constructor(){super({})}}class Ce extends z{filePath;constructor(e){super({});this.filePath=e}}class Se{async connect(){}async disconnect(){}}class Ee{db;constructor(e){this.db=e}}class Pe{db;constructor(e){this.db=e}}class Me{store;constructor(e){this.store=e}}class ke{cache=new Map}class $e{config;constructor(e){this.config=e}}class Ae{jwt;userRepo;constructor(e,n){this.jwt=e;this.userRepo=n}}class Oe{config;constructor(e){this.config=e}}class Ie{auth;constructor(e){this.auth=e}}class Fe{validate(e,n){return!0}}class De{validator;constructor(e){this.validator=e}}class de{emit(e,n){}}class pe{bus;constructor(e){this.bus=e}}
|
|
82
|
+
export{t,u,J,X,Y,Q,v,Z,ee,te,re,x,T,ne,se,ie,s,E,d,oe,j,ae,ce,st,it,ot,U,i,P,M,o,L,ye,we,be,_,Re,le,at,ct,c,ve,ue,lt,ut,dt,pt,ht,mt,gt,xe,z,Te,Ce,Se,Ee,Pe,Me,ke,$e,Ae,Oe,Ie,Fe,De,de,pe};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{existsSync as Jt,statSync as Gt}from"fs";import{resolve as pe}from"path";import wn from"process";import{existsSync as Cn,mkdirSync as Ps,readdirSync as Ds,readFileSync as En,writeFileSync as Ms}from"fs";import{homedir as ne}from"os";import{dirname as Bs,resolve as J}from"path";import et from"process";import{existsSync as qt,statSync as Yt}from"fs";import{existsSync as bt,mkdirSync as bn,readdirSync as xn,writeFileSync as Sn}from"fs";import{homedir as ie}from"os";import{dirname as Ht,resolve as L}from"path";import re from"process";import{join as Tn,relative as kn,resolve as Zt}from"path";import Ke from"process";import{existsSync as jr,mkdirSync as qs,readdirSync as Ys,writeFileSync as Hs}from"fs";import{homedir as it}from"os";import{dirname as Qs,resolve as M}from"path";import we from"process";import{join as An,relative as Fn,resolve as Xt}from"path";import Ve from"process";import{existsSync as Br,mkdirSync as io,readdirSync as so,writeFileSync as oo}from"fs";import{dirname as co,resolve as We}from"path";import xt from"process";import{Buffer as Q}from"buffer";import{createCipheriv as On,createDecipheriv as Rn,randomBytes as st}from"crypto";import{closeSync as ot,createReadStream as Qt,createWriteStream as Nn,existsSync as at,fsyncSync as er,openSync as tr,writeFileSync as Pn}from"fs";import{access as Dn,constants as rr,mkdir as Mn,readdir as Ee,rename as nr,stat as se,unlink as be,writeFile as ct}from"fs/promises";import{join as oe}from"path";import N from"process";import{pipeline as Ln}from"stream/promises";import{createGzip as ir}from"zlib";import ae from"process";import Y from"process";import{Buffer as G}from"buffer";import{createCipheriv as jn,createDecipheriv as Bn,randomBytes as lt}from"crypto";import{closeSync as ft,createReadStream as sr,createWriteStream as In,existsSync as xe,fsyncSync as or,openSync as ar,writeFileSync as _n}from"fs";import{access as Kn,constants as cr,mkdir as Vn,readdir as Se,rename as lr,stat as ce,unlink as Te,writeFile as ut}from"fs/promises";import{isAbsolute as Wn,join as le,resolve as zn}from"path";import v from"process";import{pipeline as Un}from"stream/promises";import{createGzip as fr}from"zlib";import fe from"process";import H from"process";import ke from"process";import{existsSync as Ae}from"fs";import{resolve as gt}from"path";import{existsSync as Jn}from"fs";import{existsSync as Gn,readdirSync as qn}from"fs";import{extname as ht,resolve as ur}from"path";import Yn from"process";import{join as Hn,relative as Zn,resolve as gr}from"path";import ze from"process";import{Buffer as q}from"buffer";import{createCipheriv as Xn,createDecipheriv as Qn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as hr,createWriteStream as ei,existsSync as Fe,fsyncSync as mr,openSync as dr,writeFileSync as ti}from"fs";import{access as ri,constants as pr,mkdir as ni,readdir as Oe,rename as yr,stat as ue,unlink as Re,writeFile as pt}from"fs/promises";import{isAbsolute as ii,join as ge,resolve as si}from"path";import C from"process";import{pipeline as oi}from"stream/promises";import{createGzip as wr}from"zlib";import he from"process";import Z from"process";import Pe from"process";import{existsSync as De}from"fs";import{resolve as Nr}from"path";import{existsSync as Ts}from"fs";class Pr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Jt(e))return!0;return Gt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Jt(r)?Gt(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Dr{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var _e=new Pr,Mt=new Dr;var Mr=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Lr(e={}){let{name:t="",alias:r}=e,n=["config",".config"];if(t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let i=r===void 0?[]:Array.isArray(r)?r:[r];for(let s of i){if(!s)continue;if(n.push(s,`.${s}.config`,`${s}.config`,`.${s}`),t)n.push(`${t}.${s}.config`,`.${t}.${s}.config`)}return Array.from(new Set(n.filter(Boolean)))}function vn(e){return Lr(e).flatMap((r)=>Mr.map((n)=>pe(e.directory,`${r}${n}`)))}function $n(e={}){let t=pe(e.cwd||wn.cwd());return Array.from(new Set([t,pe(t,"config"),pe(t,".config"),e.configDir?pe(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var ai=Object.defineProperty,ci=(e)=>e;function li(e,t){this[e]=ci.bind(null,t)}var fi=(e,t)=>{for(var r in t)ai(e,r,{get:t[r],enumerable:!0,configurable:!0,set:li.bind(t,r)})},ui=(e,t)=>()=>(e&&(t=e(e=0)),t),Ir={};fi(Ir,{withErrorRecovery:()=>Vr,tryLoadConfig:()=>Di,loadConfigWithResult:()=>Ni,loadConfig:()=>Gr,isRetryableError:()=>Ti,isConfigNotFoundError:()=>Si,isBunfigError:()=>Wr,globalPerformanceMonitor:()=>Ce,globalCache:()=>me,getEnvOrDefault:()=>ki,generateConfigTypes:()=>Mi,defaultGeneratedDir:()=>tn,defaultConfigDir:()=>en,deepMergeWithArrayStrategy:()=>_t,deepMerge:()=>zr,createLibraryConfig:()=>Li,config:()=>Pi,bunfigPlugin:()=>ji,applyEnvVarsToConfig:()=>ye,TypeGenerationError:()=>Rt,SchemaValidationError:()=>$e,PluginError:()=>Pt,PerformanceMonitor:()=>jt,FileSystemError:()=>Ot,ErrorFactory:()=>ee,EnvVarError:()=>He,EnvProcessor:()=>tt,ConfigValidator:()=>Kt,ConfigValidationError:()=>At,ConfigNotFoundError:()=>Ye,ConfigMergeError:()=>Ft,ConfigLoader:()=>Vt,ConfigLoadError:()=>ve,ConfigFileLoader:()=>rt,ConfigCache:()=>Lt,CacheUtils:()=>Yr,BunfigError:()=>B,BrowserConfigError:()=>Nt,ArrayMergeStrategies:()=>Xr});class Lt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!qt(e))return!0;return Yt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=qt(r)?Yt(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class jt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function gi(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function hi(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function mi(e){return e.getStats().size*2}function Bt(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&x(t[0])&&"id"in t[0]&&t[0].id===3&&x(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(x(t)&&x(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(x(e)&&"arr"in e&&Array.isArray(e.arr)&&x(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&x(t[0])&&x(e[0])){let n=[...t];for(let i of e)if(x(i)&&"name"in i){if(!n.find((o)=>x(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(x(i)&&"path"in i){if(!n.find((o)=>x(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Ue(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!x(t)||!x(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(x(i)&&x(r[n]))r[n]=Bt(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&x(i[0])&&x(r[n][0])){let s=[...i];for(let o of r[n])if(x(o)&&"name"in o){if(!s.find((a)=>x(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(x(o)&&"path"in o){if(!s.find((a)=>x(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Ue(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Ue(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ue(e[r],t[r]))return!1;return!0}if(x(e)&&x(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ue(e[i],t[i]))return!1}return!0}return!1}function x(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function di(e,t){if(!Br(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Bt(t,n)}catch{return null}}catch{return null}}async function pi({name:e="",cwd:t,defaultConfig:r}){let n=t||xt.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=We(n,`${o}${c}`),l=await di(a,r);if(l!==null)return l}try{let o=We(n,"package.json");if(Br(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Bt(r,a)}catch{}}}catch{}return r}function yi(e,t={}){let r=Ve.cwd();while(r.includes("storage"))r=Xt(r,"..");let n=Xt(r,e||"");if(t?.relative)return Fn(Ve.cwd(),n);return n}async function wi(){try{let e=await pi({name:"clarity",defaultConfig:Le,cwd:Ve.cwd(),endpoint:"",headers:{}});return{...Le,...e}}catch{return Le}}function S(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vi(){if(Y.env.NODE_ENV==="test"||Y.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Y<"u"){let e=Y.type;if(e==="renderer"||e==="worker")return!1;return!!(Y.versions&&(Y.versions.node||Y.versions.bun))}return!1}class _r{async format(e){let t=await vi(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ae.pid,hostname:t(),environment:ae.env.NODE_ENV||"development",platform:ae.platform,version:ae.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ae.env.NODE_ENV||ae.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Je{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Tt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new _r,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...je,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...je};return{...je,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Tt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await Dn(this.config.logDirectory,rr.F_OK|rr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Mn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Q.from(e);try{if(!at(this.currentLogFile))await ct(this.currentLogFile,"",{mode:420});if(i=tr(this.currentLogFile,"a",420),Pn(i,a,{flag:"a"}),er(i),i!==void 0)ot(i),i=void 0;if((await se(this.currentLogFile)).size===0){if(await ct(this.currentLogFile,a,{flag:"w",mode:420}),(await se(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{ot(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 oe(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 oe(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return oe(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return st(16).toString("hex")}generateKey(){return st(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=st(16),n=On("aes-256-gcm",t,r),i=Q.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:Q.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=ir(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Q.from(Q.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(S())return;let e=await se(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Ee(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await se(r).catch(()=>null))try{if(await nr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await be(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ct(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await se(r).catch(()=>null))await nr(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Ee(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await be(oe(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Qt(e),n=Nn(t),i=ir();await Ln(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),at(this.currentLogFile))try{let e=tr(this.currentLogFile,"r+");er(e),ot(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ee(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await be(oe(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?b.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=N.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${b.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!S()){let l=Hr[e],f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:b.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:b.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:i,icon:l,tag:f,message:o,level:e}),console.error(u),c){let h=c.split(`
|
|
3
|
+
`);for(let g of h)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:b.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
4
|
+
`;if(c)a+=`${c}
|
|
5
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!S()){let r=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:b.blue("\u25D0"),tag:r,message:`${b.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
6
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!S()){let f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:b.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!S())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Je(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!at(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Qt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Q.isBuffer(e)?e:Q.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=Rn("aes-256-gcm",r,i);return c.setAuthTag(s),Q.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!S()){let s=e.split(`
|
|
7
|
+
`),o=Math.max(...s.map((f)=>f.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,a=`\u2514${"\u2500".repeat(o)}\u2518`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`\u2502 ${f}${u} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:b.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(c)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(a),showTimestamp:!1}))}else if(!S())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(S())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${b.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();N.stdin.removeListener("data",r);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let f=t[c++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!S()){let o=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",c=b.blue("\u25D0");console.error(`${c} ${o} ${b.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||S()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=b.green("\u2501".repeat(n)),o=b.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?b.green("\u2713"):b.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=N.stdout.columns||80,w=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${w}`,N.stdout.write(e.lastRenderedLine),t)N.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ee(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=oe(this.config.logDirectory,n);if(e.before)try{if((await se(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await be(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Me(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&E(t[0])&&"id"in t[0]&&t[0].id===3&&E(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(E(t)&&E(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(E(e)&&"arr"in e&&Array.isArray(e.arr)&&E(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&E(t[0])&&E(e[0])){let n=[...t];for(let i of e)if(E(i)&&"name"in i){if(!n.find((o)=>E(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(E(i)&&"path"in i){if(!n.find((o)=>E(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Ge(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!E(t)||!E(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(E(i)&&E(r[n]))r[n]=Me(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&E(i[0])&&E(r[n][0])){let s=[...i];for(let o of r[n])if(E(o)&&"name"in o){if(!s.find((a)=>E(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(E(o)&&"path"in o){if(!s.find((a)=>E(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Ge(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function It(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Me(e,t);if(Array.isArray(e))return r==="replace"?t:Me(e,t);if(!E(t)||!E(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=Me(o,s);else if(E(s)&&E(o))n[i]=It(o,s,r);else n[i]=s}return n}function Ge(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ge(e[r],t[r]))return!1;return!0}if(E(e)&&E(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ge(e[i],t[i]))return!1}return!0}return!1}function E(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ne(e,t,r="replace"){if(!jr(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return It(t,i,r)}catch{return null}}catch{return null}}function $i(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=(m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase(),g=`${n}_${u.map(h).join("_")}`,w=`${n}_${u.map((m)=>m.toUpperCase()).join("_")}`;if(r)D.info(`Checking environment variable ${g} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))a[l]=s(f,u);else{let m=we.env[g]||we.env[w];if(m!==void 0){if(r)D.info(`Using environment variable ${m?g:w} for config ${e}.${u.join(".")}`);if(typeof f==="number")a[l]=Number(m);else if(typeof f==="boolean")a[l]=m.toLowerCase()==="true";else if(Array.isArray(f))try{let d=JSON.parse(m);if(Array.isArray(d))a[l]=d;else a[l]=m.split(",").map((R)=>R.trim())}catch{a[l]=m.split(",").map((d)=>d.trim())}else a[l]=m}}}return a}return s(i)}async function Ci({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?$i(e,i,s):i,l=r||we.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)D.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),g=t?[t,`.${t}`]:[],w=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([l,M(l,"config"),M(l,".config"),n?M(l,n):void 0].filter(Boolean)));for(let d of m){if(s)D.info(`Searching for configuration in: ${d}`);let T=[M(l,"config"),M(l,".config")].concat(n?[M(l,n)]:[]).includes(d)?[...u,...h,...g,...w]:[...h,...u,...w,...g];for(let K of T)for(let j of f){let V=M(d,`${K}${j}`),Ut=await Ne(V,a,c);if(Ut!==null){if(s)D.success(`Configuration loaded from: ${V}`);return Ut}}}if(e){let d=M(it(),".config",e),R=["config",`${e}.config`];if(t)R.push(`${t}.config`);if(s)D.info(`Checking user config directory: ${d}`);for(let T of R)for(let K of f){let j=M(d,`${T}${K}`),V=await Ne(j,a,c);if(V!==null){if(s)D.success(`Configuration loaded from user config directory: ${j}`);return V}}}if(e){let d=M(it(),".config"),R=[`.${e}.config`];if(t)R.push(`.${t}.config`);if(s)D.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of R)for(let K of f){let j=M(d,`${T}${K}`),V=await Ne(j,a,c);if(V!==null){if(s)D.success(`Configuration loaded from user config directory dotfile: ${j}`);return V}}}if(e){let d=it(),R=[`.${e}.config`,`.${e}`];if(t)R.push(`.${t}.config`),R.push(`.${t}`);if(s)D.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of R)for(let K of f){let j=M(d,`${T}${K}`),V=await Ne(j,a,c);if(V!==null){if(s)D.success(`Configuration loaded from user home directory: ${j}`);return V}}}try{let d=M(l,"package.json");if(jr(d)){let R=await import(d),T=R[e];if(!T&&t){if(T=R[t],T&&s)D.success(`Using alias "${t}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(s)D.success(`Configuration loaded from package.json: ${T===R[e]?e:t}`);return It(a,T,c)}catch(K){if(s)D.warn("Failed to merge package.json config:",K)}}}catch(d){if(s)D.warn("Failed to load package.json:",d)}if(s)D.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Ei(e,t={}){let r=Ke.cwd();while(r.includes("storage"))r=Zt(r,"..");let n=Zt(r,e||"");if(t?.relative)return kn(Ke.cwd(),n);return n}async function bi(){try{let e=await Ci({name:"clarity",alias:"logging",defaultConfig:Be,cwd:Ke.cwd()});return{...Be,...e||{}}}catch{return Be}}function k(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xi(){if(H.env.NODE_ENV==="test"||H.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof H<"u"){let e=H.type;if(e==="renderer"||e==="worker")return!1;return!!(H.versions&&(H.versions.node||H.versions.bun))}return!1}class Kr{async format(e){let t=await xi(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:fe.pid,hostname:t(),environment:fe.env.NODE_ENV||"development",platform:fe.platform,version:fe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fe.env.NODE_ENV||fe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qe{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...kt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Kr,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??v.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ie,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ie};return{...Ie,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:kt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!k()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await Kn(this.config.logDirectory,cr.F_OK|cr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Vn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:G.from(e);try{if(!xe(this.currentLogFile))await ut(this.currentLogFile,"",{mode:420});if(i=ar(this.currentLogFile,"a",420),_n(i,a,{flag:"a"}),or(i),i!==void 0)ft(i),i=void 0;if((await ce(this.currentLogFile)).size===0){if(await ut(this.currentLogFile,a,{flag:"w",mode:420}),(await ce(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{ft(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 le(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 le(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return le(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(k())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return lt(16).toString("hex")}generateKey(){return lt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=lt(16),n=jn("aes-256-gcm",t,r),i=G.isBuffer(e)?e:G.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=G.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=fr(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(G.from(G.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(k())return;if(!this.shouldWriteToFile())return;let e=await ce(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Se(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ce(r).catch(()=>null))try{if(await lr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Te(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ut(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ce(r).catch(()=>null))await lr(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Se(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Te(le(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=sr(e),n=In(t),i=fr();await Un(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),xe(this.currentLogFile))try{let e=ar(this.currentLogFile,"r+");or(e),ft(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Se(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Te(le(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?p.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||k())return!1;let e=typeof v.env.NO_COLOR<"u",t=v.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof v.stderr<"u"&&v.stderr.isTTY||typeof v.stdout<"u"&&v.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=v.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${p.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=p.underline(p.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>p.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>p.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>p.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>p.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>p.strikethrough(n)),t}supportsHyperlinks(){if(k())return!1;let e=v.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=v.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Wn(t)||t.startsWith("./")||t.startsWith("../"))t=zn(t);else return null;return xe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Zr[e],h=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:p.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:p.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let w=c.split(`
|
|
11
|
+
`);for(let m of w)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:p.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
12
|
+
`;if(c)f+=`${c}
|
|
13
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!k()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!k()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!k()&&v.stdout.isTTY)v.stdout.write(`
|
|
14
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!k()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":p.blue("\u25D0"),tag:r,message:`${p.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
15
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":p.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!k())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new qe(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!xe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return sr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=G.isBuffer(e)?e:G.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=Bn("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=G.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
16
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:p.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(f),showTimestamp:!1}))}else if(!k())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(k())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${p.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();v.stdin.removeListener("data",r);try{if(typeof v.stdin.setRawMode==="function")v.stdin.setRawMode(!1)}catch{}v.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof v.stdin.setRawMode==="function")v.stdin.setRawMode(!0)}catch{}v.stdin.resume(),v.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${p.blue("\u25D0")} `;console.error(`${l}${a} ${p.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!v.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=p.green("\u2501".repeat(n)),o=p.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?p.green("\u2713"):p.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${p.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=v.stdout.columns||80,w=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${w}`,v.stdout.write(e.lastRenderedLine),t)v.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||k()||!v.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Se(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=le(this.config.logDirectory,n);if(e.before)try{if((await ce(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Te(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Vr(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Wr(e){return e instanceof B}function Si(e){return e instanceof Ye}function Ti(e){if(Wr(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class tt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=n||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Ce.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((f)=>this.formatEnvKey(f,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let f=ke.env[a]||(l?ke.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=ke.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(f,typeof s,a,n.customParsers,n.configName)}catch(u){if(u instanceof He)throw u;throw ee.envVar(a,f,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw ee.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(ke.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
20
|
+
|
|
21
|
+
`;for(let n of e)r+=`${n.key}
|
|
22
|
+
`,r+=` Type: ${n.type}
|
|
23
|
+
`,r+=` Description: ${n.description}
|
|
24
|
+
`,r+=` Example: ${n.example}
|
|
25
|
+
|
|
26
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
27
|
+
|
|
28
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,r+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
31
|
+
`;return r}}function ki(e,t){let r=qr("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function zr(e,t,r={}){return Ur(e,t,r,new WeakMap)}function Ur(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Jr(e,t,i,n);if(!I(t)||!I(e))return t;return Ri(e,t,r,n)}function Jr(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Ai(e,t);case"smart":return Fi(e,t,n);default:return t}return t}function Ai(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>St(i,n)))r.push(n);return r}function Fi(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(I(t[0])&&I(e[0]))return Oi(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Oi(e,t,r){let n=[...t];for(let i of e){if(!I(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>I(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function Ri(e,t,r,n){let i=t;if(I(i)&&n.has(i))return n.get(i);let s={...e};if(I(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(I(c)&&I(a))s[o]=Ur(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=Jr(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function _t(e,t,r="replace"){return zr(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function St(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!St(e[r],t[r]))return!1;return!0}if(I(e)&&I(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!St(e[i],t[i]))return!1}return!0}return!1}function I(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class rt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=me.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Ae(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new ve(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new ve(e,Error("Configuration must export a valid object"),"unknown");let d={config:_t(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)me.setWithFileCheck("file",d,e,s);return d}catch(l){throw l instanceof Error?ee.configLoad(e,l):ee.configLoad(e,Error(String(l)))}};if(o)return Ce.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(gt(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Vr(async()=>Ae(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Ae(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=gt(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=gt(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Ae(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Kt{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await Ce.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Jn(t))throw new $e(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new $e(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Qr},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Vt{fileLoader=new rt;envProcessor=new tt;validator=new Kt;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw a;if(u&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)z.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw z.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||re.cwd(),h=[],g=await this.loadLocalConfiguration(n,i,u,o,c,l,f,a,r);if(g)return h.push(...this.getLocalSearchPaths(n,i,u,o)),this.finalizeResult(g,h,a,n,f);let w=await this.loadHomeConfiguration(n,i,c,l,f,a);if(w)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(w,h,a,n,f);let m=await this.loadPackageJsonConfiguration(n,i,u,c,l,f,a);if(m)return h.push(L(u,"package.json")),this.finalizeResult(m,h,a,n,f);if(h.push(...this.getAllSearchPaths(n,i,u,o)),t)throw ee.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,f),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?ye(e,i,o):i,f=this.getLocalDirectories(r,n);for(let u of f){if(o)z.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)z.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?ye(e,r,i):r,c=[L(ie(),".config",e),L(ie(),".config"),ie()];for(let a of c){if(i)z.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(f){if(i)z.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?ye(e,n,s):n;try{let a=L(r,"package.json");if(!bt(a))return null;let l=await import(a),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)z.success(`Configuration loaded from package.json: ${u}`);return{config:_t(c,f,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)z.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ye(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw ee.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return me.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);me.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,L(e,"config"),L(e,".config"),t?L(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(L(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[L(ie(),".config",e),L(ie(),".config"),ie()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function vr(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function Ni(e){return X.loadConfig({...e,__strictErrorHandling:!0})}async function Gr(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await X.loadConfig(e);else n=await X.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)z.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await X.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Pi(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await X.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&vr(r)))return(await X.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await X.loadConfig({...e,cwd:e.cwd||re.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&vr(t)))return(await X.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Di(e,t,r="replace"){let n=new rt;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function ye(e,t,r=!1){let n=new tt,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${i}_${u.join("_").toUpperCase()}`,`${i}_${u.map((m)=>m.toUpperCase()).join("")}`,`${i}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,w;for(let m of h)if(g=re.env[m],g!==void 0){w=m;break}if(g!==void 0&&w)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let m=Number(g);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(g)}catch{a[l]=g.split(",").map((m)=>m.trim())}else a[l]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=s(f,u)}return a}return s(t)}function Mi(e){let t=L(re.cwd(),e.configDir),r=L(re.cwd(),e.generatedDir),n=L(r,"config-types.ts");if(!bt(Ht(n)))bn(Ht(n),{recursive:!0,mode:511});let i=bt(t)?xn(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${fs}
|
|
32
|
+
export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
|
|
33
|
+
`;Sn(n,s,{mode:438})}function Li(e){let t=null,r=null,n=()=>{if(!r)r=Gr(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)z.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function ji(e){let t=ur(Yn.cwd(),e?.configDir||"./config");function r(){if(!Gn(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=qn(t).filter((a)=>i.has(ht(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let f=ht(l).toLowerCase(),u=c.get(a);if(!u){c.set(a,l);continue}let h=ht(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
|
|
34
|
+
${i.map((l)=>{let f=ur(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
|
|
35
|
+
`)}
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
37
|
+
export type ConfigByName = ${c}
|
|
38
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
|
+
export type ConfigOf = Config
|
|
40
|
+
`}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}var qr,me,Ce,Yr,Bi,Ii,$r,Le,Tt,P,b,_i,Cr,Ki,Er,Vi,Wi,yt,zi,br,xr,wt,Ui,Ji,Gi,qi,je,Hr,Yi,D,Hi,Zi,Sr,Be,kt,A,p,Xi,Tr,Qi,kr,es,ts,vt,rs,Ar,Fr,ns,$t,is,ss,os,as,cs,Ie,Zr,ls,fs="0.15.6",B,Ye,ve,At,Ft,He,Ot,Rt,$e,Nt,Pt,ee,Xr,Qr,z,X,en,tn,us=ui(async()=>{qr=import.meta.require,me=new Lt,Ce=new jt,Yr={createKey:gi,isEquivalent:hi,estimateMemoryUsage:mi},Bi=We(xt.cwd(),"config"),Ii=We(xt.cwd(),"src/generated"),$r=Ve.env.CLARITY_LOG_DIR||An(yi(),"logs"),Le={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$r,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Tt=await wi(),P={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},b=P,_i=P.red,Cr=P.green,Ki=P.yellow,Er=P.blue,Vi=P.magenta,Wi=P.cyan,yt=P.white,zi=P.gray,br=P.bgRed,xr=P.bgYellow,wt=P.bold,Ui=P.dim,Ji=P.italic,Gi=P.underline,qi=P.reset,je={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Hr={debug:"\uD83D\uDD0D",info:Er("\u2139"),success:Cr("\u2713"),warning:xr(yt(wt(" WARN "))),error:br(yt(wt(" ERROR ")))},Yi=new Je("stacks"),D=new Je("bunfig",{showTags:!0}),Hi=M(we.cwd(),"config"),Zi=M(we.cwd(),"src/generated"),Sr=Ke.env.CLARITY_LOG_DIR||Tn(Ei(),"logs"),Be={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},kt=await bi(),A={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},p=A,Xi=A.red,Tr=A.green,Qi=A.yellow,kr=A.blue,es=A.magenta,ts=A.cyan,vt=A.white,rs=A.gray,Ar=A.bgRed,Fr=A.bgYellow,ns=A.bgGray,$t=A.bold,is=A.dim,ss=A.italic,os=A.underline,as=A.strikethrough,cs=A.reset,Ie={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Zr={debug:"\uD83D\uDD0D",info:kr("\u2139"),success:Tr("\u2713"),warning:Fr(vt($t(" WARN "))),error:Ar(vt($t(" ERROR ")))},ls=new qe("stacks"),B=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Ye=class extends B{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},ve=class extends B{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},At=class extends B{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Ft=class extends B{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},He=class extends B{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},Ot=class extends B{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Rt=class extends B{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},$e=class extends B{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Nt=class extends B{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},Pt=class extends B{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ee={configNotFound(e,t,r){return new Ye(e,t,r)},configLoad(e,t,r){return new ve(e,t,r)},configValidation(e,t,r){return new At(e,t,r)},configMerge(e,t,r,n){return new Ft(e,t,r,n)},envVar(e,t,r,n){return new He(e,t,r,n)},fileSystem(e,t,r){return new Ot(e,t,r)},typeGeneration(e,t,r){return new Rt(e,t,r)},schemaValidation(e,t,r){return new $e(e,t,r)},browserConfig(e,t,r,n){return new Nt(e,t,r,n)},plugin(e,t,r){return new Pt(e,t,r)}},Xr={replace:"replace",concat:"concat",smart:"smart"},Qr=/^https?:\/\//,z=new qe("bunfig",{showTags:!0}),X=new Vt,en=L(re.cwd(),"config"),tn=L(re.cwd(),"src/generated")});function gs(e,t={}){let r=ze.cwd();while(r.includes("storage"))r=gr(r,"..");let n=gr(r,e||"");if(t?.relative)return Zn(ze.cwd(),n);return n}var hs=ze.env.CLARITY_LOG_DIR||Hn(gs(),"logs"),rn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ze={...rn},Ho=(async()=>{try{let{loadConfig:e}=await us().then(()=>Ir),t=await e({name:"clarity",alias:"logging",defaultConfig:rn,cwd:ze.cwd()});if(t)Object.assign(Ze,t)}catch{}return Ze})();function F(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ms(){if(Z.env.NODE_ENV==="test"||Z.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z<"u"){let e=Z.type;if(e==="renderer"||e==="worker")return!1;return!!(Z.versions&&(Z.versions.node||Z.versions.bun))}return!1}class nn{async format(e){let t=await ms(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:he.pid,hostname:t(),environment:he.env.NODE_ENV||"development",platform:he.platform,version:he.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:he.env.NODE_ENV||he.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var O={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},y=O,{red:Zo,green:ds,yellow:Xo,blue:ps,magenta:Qo,cyan:ea,white:Or,gray:ta,bgRed:ys,bgYellow:ws,bgGray:ra,bold:Rr,dim:na,italic:ia,underline:sa,strikethrough:oa,reset:aa}=O,Ct={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vs={debug:"\uD83D\uDD0D",info:ps("\u2139"),success:ds("\u2713"),warning:ws(Or(Rr(" WARN "))),error:ys(Or(Rr(" ERROR ")))};class nt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Ze},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new nn,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??C.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ct,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ct};return{...Ct,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ze.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!F()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await ri(this.config.logDirectory,pr.F_OK|pr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ni(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:q.from(e);try{if(!Fe(this.currentLogFile))await pt(this.currentLogFile,"",{mode:420});if(i=dr(this.currentLogFile,"a",420),ti(i,a,{flag:"a"}),mr(i),i!==void 0)dt(i),i=void 0;if((await ue(this.currentLogFile)).size===0){if(await pt(this.currentLogFile,a,{flag:"w",mode:420}),(await ue(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=c*2**s;await new Promise((g)=>setTimeout(g,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(i!==void 0)try{dt(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let f=a,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),a}s++;let l=c*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 ge(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 ge(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ge(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(F())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return mt(16).toString("hex")}generateKey(){return mt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=mt(16),n=Xn("aes-256-gcm",t,r),i=q.isBuffer(e)?e:q.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=q.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=wr(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(q.from(q.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(F())return;if(!this.shouldWriteToFile())return;let e=await ue(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Oe(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let f=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ue(r).catch(()=>null))try{if(await yr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Re(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await pt(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ue(r).catch(()=>null))await yr(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Oe(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Re(ge(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=hr(e),n=ei(t),i=wr();await oi(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Fe(this.currentLogFile))try{let e=dr(this.currentLogFile,"r+");mr(e),dt(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!F()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Oe(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Re(ge(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?y.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F())return!1;let e=typeof C.env.NO_COLOR<"u",t=C.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(g)=>g.replace(this.ANSI_PATTERN,"");if(!this.fancy){let g=[];if(o)g.push(t);if(s==="warning")g.push("WARN");else if(s==="error")g.push("ERROR");else if(r)g.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)g.push(n.replace(/[[\]]/g,""));return g.push(i),g.join(" ")}let a=C.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${y.cyan(i)}`;if(!o)return l.trim();let f=c(l).trim().length,u=c(t).length,h=Math.max(1,a-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=y.underline(y.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>y.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>y.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>y.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>y.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>y.strikethrough(n)),t}supportsHyperlinks(){if(F())return!1;let e=C.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=C.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ii(t)||t.startsWith("./")||t.startsWith("../"))t=si(t);else return null;return Fe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":vs[e],h=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",g;switch(e){case"debug":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:y.gray(a),level:e}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"success":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:y.green(a),level:e}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:i,icon:u,tag:h,message:a,level:e}),console.error(g),c){let w=c.split(`
|
|
41
|
+
`);for(let m of w)if(m.trim()&&!m.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:y.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!F()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
42
|
+
`;if(c)f+=`${c}
|
|
43
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!F()&&C.stdout.isTTY)C.stdout.write(`
|
|
44
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":y.blue("\u25D0"),tag:r,message:`${y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
45
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":y.green("\u2713"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!F())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new nt(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(F())throw Error("createReadStream is not supported in browser environments");if(!Fe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return hr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=q.isBuffer(e)?e:q.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=Qn("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),f=a.length+l.length,u=q.allocUnsafe(f);return a.copy(u,0),l.copy(u,a.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F()}isServerMode(){return!F()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
|
|
46
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,f=`\u2514${"\u2500".repeat(a)}\u2518`,u=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:y.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(f),showTimestamp:!1}))}else if(!F())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(F())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${y.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();C.stdin.removeListener("data",r);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${y.blue("\u25D0")} `;console.error(`${l}${a} ${y.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!C.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=y.green("\u2501".repeat(n)),o=y.gray("\u2501".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?y.green("\u2713"):y.blue("\u25B6"),u=this.options.showTags!==!1&&this.name?` ${y.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${c} ${a}${l}`,g=C.stdout.columns||80,w=" ".repeat(Math.max(0,g-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${w}`,C.stdout.write(e.lastRenderedLine),t)C.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||F()||!C.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(F()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Oe(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=ge(this.config.logDirectory,n);if(e.before)try{if((await ue(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Re(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var ca=new nt("stacks");class U extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class sn extends U{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class Xe extends U{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class on extends U{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class an extends U{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Wt extends U{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}}class cn extends U{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class ln extends U{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Qe extends U{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class fn extends U{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}}class un extends U{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var te={configNotFound(e,t,r){return new sn(e,t,r)},configLoad(e,t,r){return new Xe(e,t,r)},configValidation(e,t,r){return new on(e,t,r)},configMerge(e,t,r,n){return new an(e,t,r,n)},envVar(e,t,r,n){return new Wt(e,t,r,n)},fileSystem(e,t,r){return new cn(e,t,r)},typeGeneration(e,t,r){return new ln(e,t,r)},schemaValidation(e,t,r){return new Qe(e,t,r)},browserConfig(e,t,r,n){return new fn(e,t,r,n)},plugin(e,t,r){return new un(e,t,r)}};async function $s(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class zt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=n||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Mt.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((f)=>this.formatEnvKey(f,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let f=Pe.env[a]||(l?Pe.env[l]:void 0);if(f!==void 0){if(n.verbose){let u=Pe.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(f,typeof s,a,n.customParsers,n.configName)}catch(u){if(u instanceof Wt)throw u;throw te.envVar(a,f,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw te.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Pe.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
50
|
+
|
|
51
|
+
`;for(let n of e)r+=`${n.key}
|
|
52
|
+
`,r+=` Type: ${n.type}
|
|
53
|
+
`,r+=` Description: ${n.description}
|
|
54
|
+
`,r+=` Example: ${n.example}
|
|
55
|
+
|
|
56
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
57
|
+
|
|
58
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
59
|
+
`,r+=`|----------|------|-------------|----------|
|
|
60
|
+
`;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
61
|
+
`;return r}}function Cs(e,t,r={}){return gn(e,t,r,new WeakMap)}function gn(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return hn(e,t,i,n);if(!_(t)||!_(e))return t;return Ss(e,t,r,n)}function hn(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Es(e,t);case"smart":return bs(e,t,n);default:return t}return t}function Es(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Dt(i,n)))r.push(n);return r}function bs(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(_(t[0])&&_(e[0]))return xs(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function xs(e,t,r){let n=[...t];for(let i of e){if(!_(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>_(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function Ss(e,t,r,n){let i=t;if(_(i)&&n.has(i))return n.get(i);let s={...e};if(_(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(_(c)&&_(a))s[o]=gn(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=hn(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function mn(e,t,r="replace"){return Cs(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Dt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Dt(e[r],t[r]))return!1;return!0}if(_(e)&&_(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Dt(e[i],t[i]))return!1}return!0}return!1}function _(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class dn{extensions=Mr;async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=_e.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!De(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,g=Object.keys(f).length>0;if(!h&&!g)throw new Xe(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Xe(e,Error("Configuration must export a valid object"),"unknown");let d={config:mn(t,u,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)_e.setWithFileCheck("file",d,e,s);return d}catch(l){throw l instanceof Error?te.configLoad(e,l):te.configLoad(e,Error(String(l)))}};if(o)return Mt.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){return vn({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return Lr({name:e,alias:t})}checkFileAccess(e){return $s(async()=>De(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!De(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=Nr(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Nr(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!De(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}var ks=/^https?:\/\//;class pn{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(g){return f.push({path:"",message:`Validation failed: ${g}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(c)return await Mt.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Ts(t))throw new Qe(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Qe(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ks},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var W=new nt("bunfig",{showTags:!0});function As(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class yn{fileLoader=new dn;envProcessor=new zt;validator=new pn;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){if(o.configFile)throw a;let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let f=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),u=!f&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw a;if(u&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)W.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw W.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,configFile:s,cwd:o,configDir:c,defaultConfig:a,checkEnv:l=!0,arrayStrategy:f="replace",verbose:u=!1}=e,h=o||et.cwd(),g=[];if(s){let T=J(h,s);g.push(T);let K=l?de(n,a,u):a,j=await this.fileLoader.tryLoadFromPaths([T],K,{arrayStrategy:f,verbose:u,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!j)throw te.configNotFound(n||s,g,i);if(u)W.success(`Configuration loaded from explicit path: ${T}`);return this.finalizeResult(j,g,l,n,u)}let w=await this.loadLocalConfiguration(n,i,h,c,a,f,u,l,r);if(w)return g.push(...this.getLocalSearchPaths(n,i,h,c)),this.finalizeResult(w,g,l,n,u);let m=await this.loadHomeConfiguration(n,i,a,f,u,l);if(m)return g.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(m,g,l,n,u);let d=await this.loadPackageJsonConfiguration(n,i,h,a,f,u,l);if(d)return g.push(J(h,"package.json")),this.finalizeResult(d,g,l,n,u);if(g.push(...this.getAllSearchPaths(n,i,h,c)),t)throw te.configNotFound(n,g,i);return{...await this.applyEnvironmentVariables(n,a,l,u),warnings:[`No configuration file found for "${n}"${As(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?de(e,i,o):i,f=this.getLocalDirectories(r,n);for(let u of f){if(o)W.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),g=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(g){if(o)W.success(`Configuration loaded from: ${g.source.path}`);return g}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?de(e,r,i):r,c=[J(ne(),".config",e),J(ne(),".config"),ne()];for(let a of c){if(i)W.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(f){if(i)W.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?de(e,n,s):n;try{let a=J(r,"package.json");if(!Cn(a))return null;let l={};try{l=JSON.parse(En(a,"utf8"))}catch(h){if(s)W.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let g of h){if(!g)continue;if(l[g]){f=l[g],u=g;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)W.success(`Configuration loaded from package.json: ${u}`);return{config:mn(c,f,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)W.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:de(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw te.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return _e.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);_e.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return $n({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(J(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[J(ne(),".config",e),J(ne(),".config"),ne()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}var Et=new yn;async function ha(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Et.loadConfig(e);else n=await Et.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){if(e.configFile)throw n;let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)W.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Et.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function de(e,t,r=!1){let n=new zt,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,f]of Object.entries(o)){let u=[...c,l],h=[`${i}_${u.join("_").toUpperCase()}`,`${i}_${u.map((m)=>m.toUpperCase()).join("")}`,`${i}_${u.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],g,w;for(let m of h)if(g=et.env[m],g!==void 0){w=m;break}if(g!==void 0&&w)if(typeof f==="boolean")a[l]=["true","1","yes"].includes(g.toLowerCase());else if(typeof f==="number"){let m=Number(g);if(!Number.isNaN(m))a[l]=m}else if(Array.isArray(f))try{a[l]=JSON.parse(g)}catch{a[l]=g.split(",").map((m)=>m.trim())}else a[l]=g;else if(f&&typeof f==="object"&&!Array.isArray(f))a[l]=s(f,u)}return a}return s(t)}var ma=J(et.cwd(),"config"),da=J(et.cwd(),"src/generated");export{ha as loadConfig};
|