@stacksjs/bun-router 0.1.11 → 0.1.13

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.
@@ -1,8 +1,8 @@
1
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:
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 d 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 X extends t{constructor(e="Authentication required",n){super({code:"AUTHENTICATION_ERROR",message:e,statusCode:401,context:n,retryable:!1,severity:"medium",category:"authentication"})}}class Y 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 Q extends t{resource;resourceId;constructor(e="Resource not found",n,r,s){super({code:"NOT_FOUND",message:e,statusCode:404,context:s,retryable:!1,severity:"low",category:"business"});this.resource=n,this.resourceId=r}}class Z 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 x 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 ee extends t{retryAfter;limit;remaining;constructor(e="Rate limit exceeded",n,r,s=0,c){super({code:"RATE_LIMIT_EXCEEDED",message:e,statusCode:429,context:c,retryable:!0,severity:"medium",category:"network"});this.retryAfter=n,this.limit=r,this.remaining=s}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 te 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 re 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 ne extends t{query;operation;constructor(e,n,r,s,c){super({code:"DATABASE_ERROR",message:e,statusCode:500,context:c,cause:s,retryable:!0,severity:"high",category:"database"});this.operation=n,this.query=r}}class T extends t{service;endpoint;constructor(e,n,r,s=502,c,g){super({code:"EXTERNAL_SERVICE_ERROR",message:e,statusCode:s,context:g,cause:c,retryable:!0,severity:"medium",category:"external"});this.service=n,this.endpoint=r}}class C 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 se 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 ie 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 oe extends t{path;operation;constructor(e,n,r,s,c){super({code:"FILESYSTEM_ERROR",message:e,statusCode:500,context:c,cause:s,retryable:!1,severity:"medium",category:"system"});this.path=n,this.operation=r}}var i={validation:(e,n,r)=>new d(e,n,r),authentication:(e,n)=>new X(e,n),authorization:(e,n,r)=>new Y(e,n,r),notFound:(e,n,r)=>new Q(void 0,e,n,r),methodNotAllowed:(e,n,r)=>new Z(e,n,r),timeout:(e,n,r)=>new x(n,e,r),rateLimit:(e,n,r,s)=>new ee(void 0,e,n,r,s),internalServer:(e,n,r)=>new te(e,n,r),serviceUnavailable:(e,n,r)=>new re(e,n,r),database:(e,n,r,s,c)=>new ne(e,n,r,s,c),externalService:(e,n,r,s,c,g)=>new T(e,n,r,s,c,g),circuitBreakerOpen:(e,n,r)=>new C(e,n,r),businessLogic:(e,n,r)=>new se(e,n,r),configuration:(e,n,r)=>new ie(e,n,r),fileSystem:(e,n,r,s,c)=>new oe(e,n,r,s,c)};class P extends t{conflictingRoutes;suggestion;constructor(e,n){let r=P.buildMessage(e),s=P.buildSuggestion(e);super({code:"ROUTE_CONFLICT",message:r,statusCode:500,context:n,retryable:!1,severity:"critical",category:"system"});this.conflictingRoutes=e,this.suggestion=s}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((h)=>!h.path.includes("{")),s=e.some((h)=>h.path.includes("{"));if(r&&s)n.push("\u2022 Static routes should be defined before dynamic routes","\u2022 Consider using route constraints (whereNumber, whereUuid) to differentiate");if(e.filter((h)=>h.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((h)=>h.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
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(`
5
+ `)}`}toJSON(){return{...super.toJSON(),conflictingRoutes:this.conflictingRoutes,suggestion:this.suggestion}}}class p extends t{dependencyChain;suggestion;constructor(e,n){let r=p.buildMessage(e),s=p.buildSuggestion(e);super({code:"CIRCULAR_DEPENDENCY",message:r,statusCode:500,context:n,retryable:!1,severity:"critical",category:"system"});this.dependencyChain=e,this.suggestion=s}static buildMessage(e){let n=["Circular dependency detected in the dependency injection container!","","Dependency chain:",""];for(let r=0;r<e.length;r++){let s=r===e.length-1,c=r===0?"\u250C\u2500\u25BA":s?"\u2514\u2500\u25BA":"\u251C\u2500\u25BA";if(n.push(` ${c} ${e[r]}`),!s)n.push(" \u2502")}return n.push(" \u2502"),n.push(` \u2514\u2500\u2500 cycles back to: ${e[0]}`),n.join(`
6
6
  `)}static buildSuggestion(e){return`How to fix:
7
7
 
8
8
  1. Break the cycle by introducing an interface:
@@ -23,9 +23,9 @@ ${n.join(`
23
23
 
24
24
  Dependency chain involved:
25
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:
26
+ `)}`}toJSON(){return{...super.toJSON(),dependencyChain:this.dependencyChain,suggestion:this.suggestion}}}class ae extends t{middlewareName;configErrors;suggestion;constructor(e,n,r){let s=`Middleware "${e}" configuration error:
27
+ ${n.map((c)=>` \u2022 ${c}`).join(`
28
+ `)}`;super({code:"MIDDLEWARE_CONFIGURATION_ERROR",message:s,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
29
  \u2022 Check the middleware documentation for required options
30
30
  \u2022 Ensure all required configuration values are provided
31
31
  \u2022 Verify configuration value types match expected types
@@ -33,17 +33,17 @@ ${n.map((l)=>` \u2022 ${l}`).join(`
33
33
  Example configuration:
34
34
  router.use(new ${this.middlewareName}({
35
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(`
36
+ }))`}}class U extends t{requestedPath;requestedMethod;similarRoutes;suggestion;constructor(e,n,r=[],s){let c=U.buildMessage(e,n,r);super({code:"ROUTE_NOT_FOUND",message:c,statusCode:404,context:s,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 s=[`Route not found: ${e} ${n}`];if(r.length>0){s.push(""),s.push("Did you mean one of these routes?");for(let c of r.slice(0,5))if(s.push(` \u2022 ${c.method} ${c.path}`),c.similarity)s.push(` (${Math.round(c.similarity*100)}% match)`)}return s.join(`
37
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
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
39
+ `)}`}}class ce extends t{handlerRef;suggestion;constructor(e,n,r){let s=`Failed to resolve handler "${e}": ${n}`;super({code:"HANDLER_RESOLUTION_ERROR",message:s,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[s,c]=e.split("@");return`How to fix:
40
+ \u2022 Ensure the controller "${s}" is registered in the container
41
+ \u2022 Verify the method "${c}" exists and is public
42
42
  \u2022 Check the controller file is imported
43
43
 
44
44
  Example:
45
45
  // Register the controller
46
- container.singleton('${a}', ${a})
46
+ container.singleton('${s}', ${s})
47
47
 
48
48
  // Define the route
49
49
  router.get('/path', '${e}')`}if(r)return`How to fix:
@@ -60,7 +60,7 @@ Example:
60
60
  }`;return`How to fix:
61
61
  \u2022 Verify the handler reference is correct
62
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:
63
+ \u2022 Check for circular dependencies in the handler module`}}class le extends t{modelName;paramName;paramValue;suggestion;constructor(e,n,r,s,c){let g=`Failed to bind model "${e}" for parameter "${n}" with value "${r}": ${s}`;super({code:"MODEL_BINDING_ERROR",message:g,statusCode:404,context:c,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
64
  \u2022 Verify the ${this.paramName} "${this.paramValue}" exists in your data source
65
65
  \u2022 Check if the model resolver is correctly configured
66
66
  \u2022 Ensure the route parameter matches the model's identifier field
@@ -74,9 +74,9 @@ Example model binding:
74
74
  throw new Error('${this.modelName} not found')
75
75
  }
76
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}).
77
+ })`}}function ot(e,n,r=5){let s=[];for(let c of n){let g=v(e,c.path);if(g>0.3)s.push({method:c.method,path:c.path,similarity:g})}return s.sort((c,g)=>(g.similarity||0)-(c.similarity||0)).slice(0,r)}function v(e,n){let r=e.length,s=n.length;if(r===0)return s===0?1:0;if(s===0)return 0;let c=[];for(let u=0;u<=r;u++)c[u]=[u];for(let u=0;u<=s;u++)c[0][u]=u;for(let u=1;u<=r;u++)for(let m=1;m<=s;m++){let y=e[u-1]===n[m-1]?0:1;c[u][m]=Math.min(c[u-1][m]+1,c[u][m-1]+1,c[u-1][m-1]+y)}let g=c[r][s],h=Math.max(r,s);return 1-g/h}function at(e){let n=[],r=new Set;for(let s=0;s<e.length;s++){let c=e[s],g=`${c.method}:${c.path}`;if(r.has(g))continue;let h=[];for(let u=s+1;u<e.length;u++){let m=e[u];if(c.method===m.method&&b(c.path,m.path)){if(h.length===0)h.push({method:c.method,path:c.path,name:c.name});h.push({method:m.method,path:m.path,name:m.name}),r.add(`${m.method}:${m.path}`)}}if(h.length>0)n.push(h);r.add(g)}return n}function b(e,n){if(e===n)return!0;let r=e.split("/").filter(Boolean),s=n.split("/").filter(Boolean);if(r.length!==s.length){let g=e.includes("*"),h=n.includes("*");if(!g&&!h)return!1}let c=Math.max(r.length,s.length);for(let g=0;g<c;g++){let h=r[g]||"",u=s[g]||"";if(h==="*"||u==="*")return!0;let m=h.startsWith("{")&&h.endsWith("}"),y=u.startsWith("{")&&u.endsWith("}");if(!m&&!y){if(h!==u)return!1}}return!0}var ct={routeConflict:(e,n)=>new P(e,n),circularDependency:(e,n)=>new p(e,n),middlewareConfig:(e,n,r)=>new ae(e,n,r),routeNotFound:(e,n,r,s)=>new U(e,n,r,s),handlerResolution:(e,n,r)=>new ce(e,n,r),modelBinding:(e,n,r,s,c)=>new le(e,n,r,s,c)};var L=Symbol("injectable"),o=Symbol("inject"),M=Symbol("optional"),k=Symbol("tagged");class a{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 _(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 s=this.tagIndex.get(r);if(!s)s=new Set,this.tagIndex.set(r,s);s.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 s of n){let c=this.bindings.get(s);if(c)r.push(c)}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 a({...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((s)=>this.tokenToString(s));throw r.push(this.tokenToString(e)),new p(r)}if(n.depth>this.options.maxDepth){let r=Array.from(n.resolving).map((s)=>this.tokenToString(s));throw Error(`Maximum resolution depth exceeded (${this.options.maxDepth}).
78
78
  This usually indicates a circular or very deep dependency chain.
79
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};
80
+ ${r.map((s,c)=>` ${c+1}. ${s}`).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 s={resolving:new Set,depth:0,container:this.parent,token:e};return this.parent.resolveInternal(e,s)}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 c=this.scopedInstances.get(n.requestId);if(c?.has(e.token))r=c.get(e.token);else{if(r=this.createNewInstance(e,n),!c)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 s=this.tokenToString(e.token);if(this.interceptors.has(s)){let c=this.interceptors.get(s);for(let g of c)r=g(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),s=this.resolveDependencies(r,n),c=new e(...s);if(this.options.enableDecorators)this.applyDecorators(c,e);return c}getConstructorDependencies(e){let n=Reflect.getMetadata?.(o,e)||e[o];if(!n&&e.constructor)n=e.constructor[o];if(!n&&typeof e==="function"&&e.prototype){let s=e[o];if(s)n=s}if(!n&&typeof e==="function"){let s=e[o];if(s)n=s}if(n)return n.map((s)=>s.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((s)=>s.trim().split(":")[0].trim()).filter((s)=>s.length>0)}resolveDependencies(e,n){return e.map((r)=>this.resolveInternal(r,n))}autoRegisterAndResolve(e,n){let r=Reflect.getMetadata?.(L,e),s={token:e,implementation:e,metadata:{scope:r?.scope||this.options.defaultScope,tags:r?.tags}};return this.register(s),this.resolveInternal(e,n)}applyDecorators(e,n){let r=Reflect.getMetadata?.("decorators",n);if(r)for(let s of r)s(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 _{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 we(){if(!f)f=new a;return f}function be(e){f=e}function Re(e){return new a(e)}class z{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 ve{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 ue extends a{contextualBindings=new Map;environmentManager;constructor(e){super(e);this.environmentManager=new z}bindContextual(e){return new ve(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,s)=>s.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},s=this.findContextualBinding(e,r);if(s)return this.createInstanceFromContextualBinding(s,r);return super.resolve(e,r)}findContextualBinding(e,n){let r=this.contextualBindings.get(e);if(!r)return;for(let s of r)if(this.evaluateConditions(s.conditions,n))return s;return}evaluateConditions(e,n){return e.every((r)=>{try{return r.predicate(n)}catch(s){return console.warn(`Error evaluating binding condition: ${r.description}`,s),!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 lt{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 ut{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 l{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 xe extends l{isDeferred(){return!0}}class de{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 s of r.dependencies)if(!n.has(s))throw Error(`Provider ${r.name} depends on ${s}, but it's not registered`)}}isDeferredProvider(e){return"provides"in e&&"isDeferred"in e}isConditionalProvider(e){return"shouldLoad"in e}}class dt extends l{name="config";priority=100;register(e){e.singleton("config",Te),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 pt extends l{name="logging";priority=90;register(e){e.factory("logger",(n)=>new V(n.get("logging",{}))),this.forEnvironment(e,"development").bind("logger").toFactory(()=>new Ce),this.forEnvironment(e,"production").bind("logger").toFactory((n)=>new Se(n.get("logging.file","./app.log")))}}class ht extends l{name="database";dependencies=["config","logging"];register(e){e.singleton("database",Ee),e.transient("userRepository",Pe),e.transient("postRepository",Me)}async boot(e){await e.resolve("database").connect()}async shutdown(e){await e.resolve("database").disconnect()}}class mt extends l{name="cache";dependencies=["config"];register(e){e.singleton("cache",ke),this.forEnvironment(e,"development").bind("cache.store").toFactory(()=>new $e),this.forEnvironment(e,"production").bind("cache.store").toFactory((n)=>new Ae(n.get("cache.redis")))}}class gt extends l{name="auth";dependencies=["config","database"];register(e){e.singleton("authService",Oe),e.singleton("jwtService",Ie),e.transient("authGuard",Fe)}}class ft extends l{name="validation";register(e){e.singleton("validator",De),e.factory("validationPipe",(n)=>new Ne(n))}}class yt extends xe{name="events";provides(){return["eventBus","eventDispatcher",pe,he]}register(e){e.singleton("eventBus",pe),e.singleton("eventDispatcher",he)}}class Te{get(e,n){return n}}class V{config;constructor(e){this.config=e}log(e){console.log(e)}}class Ce extends V{constructor(){super({})}}class Se extends V{filePath;constructor(e){super({});this.filePath=e}}class Ee{async connect(){}async disconnect(){}}class Pe{db;constructor(e){this.db=e}}class Me{db;constructor(e){this.db=e}}class ke{store;constructor(e){this.store=e}}class $e{cache=new Map}class Ae{config;constructor(e){this.config=e}}class Oe{jwt;userRepo;constructor(e,n){this.jwt=e;this.userRepo=n}}class Ie{config;constructor(e){this.config=e}}class Fe{auth;constructor(e){this.auth=e}}class De{validate(e,n){return!0}}class Ne{validator;constructor(e){this.validator=e}}class pe{emit(e,n){}}class he{bus;constructor(e){this.bus=e}}
82
+ export{t,d,X,Y,Q,Z,x,ee,te,re,ne,T,C,se,ie,oe,i,P,p,ae,U,ce,le,ot,at,ct,L,o,M,k,a,_,we,be,Re,z,ve,ue,lt,ut,l,xe,de,dt,pt,ht,mt,gt,ft,yt,Te,V,Ce,Se,Ee,Pe,Me,ke,$e,Ae,Oe,Ie,Fe,De,Ne,pe,he};
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{K}from"./chunk-trm3jyqk.js";import g from"process";import{CLI as ue}from"@stacksjs/clapp";var F="0.1.11";import f from"fs/promises";import I from"path";import T from"process";var p={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},o={red:(e)=>`${p.red}${e}${p.reset}`,green:(e)=>`${p.green}${e}${p.reset}`,yellow:(e)=>`${p.yellow}${e}${p.reset}`,blue:(e)=>`${p.blue}${e}${p.reset}`,cyan:(e)=>`${p.cyan}${e}${p.reset}`,white:(e)=>`${p.white}${e}${p.reset}`,gray:(e)=>`${p.gray}${e}${p.reset}`,bold:(e)=>`${p.bold}${e}${p.reset}`,dim:(e)=>`${p.dim}${e}${p.reset}`,hex:(e)=>(t)=>t};async function v(e){let t=Object.entries(K).map(([n,c])=>({name:n,className:c.constructor.name})),r=`/**
3
+ import{J}from"./chunk-7s1kcj7w.js";import g from"process";import{CLI as ue}from"@stacksjs/clapp";var F="0.1.13";import f from"fs/promises";import I from"path";import T from"process";var p={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"},o={red:(e)=>`${p.red}${e}${p.reset}`,green:(e)=>`${p.green}${e}${p.reset}`,yellow:(e)=>`${p.yellow}${e}${p.reset}`,blue:(e)=>`${p.blue}${e}${p.reset}`,cyan:(e)=>`${p.cyan}${e}${p.reset}`,white:(e)=>`${p.white}${e}${p.reset}`,gray:(e)=>`${p.gray}${e}${p.reset}`,bold:(e)=>`${p.bold}${e}${p.reset}`,dim:(e)=>`${p.dim}${e}${p.reset}`,hex:(e)=>(t)=>t};async function v(e){let t=Object.entries(J).map(([n,c])=>({name:n,className:c.constructor.name})),r=`/**
4
4
  * This file is auto-generated.
5
5
  * DO NOT EDIT THIS FILE DIRECTLY.
6
6
  * To update, run 'bun router middleware:types'
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{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}from"../chunk-7g1et0fb.js";var y=Symbol("controller"),p=Symbol("route"),d=Symbol("middleware"),u=Symbol("param");function D(t={}){return(e)=>(e[U]=t,e)}function b(t,e){return function(n,r,s){let a=n.constructor===Function?n:n.constructor;if(!a[i])a[i]=[];let g={token:t,optional:e?.optional,tags:e?.tags,when:e?.when};a[i][s]=g}}function x(){return(t,e,n)=>{if(!t[P])t[P]=[];t[P][n]=!0}}function T(t){return function(e,n,r){if(!e[M])e[M]=[];e[M][r]=t}}function E(t,e){return function(n){let r={prefix:t||"",middleware:e?.middleware||[],tags:e?.tags||[]};return n[y]=r,n}}function h(t="",e){return l("GET",t,e)}function w(t="",e){return l("POST",t,e)}function F(t="",e){return l("PUT",t,e)}function C(t="",e){return l("DELETE",t,e)}function I(t="",e){return l("PATCH",t,e)}function R(t="",e){return l("OPTIONS",t,e)}function O(t="",e){return l("HEAD",t,e)}function l(t,e,n){return function(r,s,a){if(!r.constructor[p])r.constructor[p]=[];let g={method:t,path:e,middleware:n?.middleware||[],tags:n?.tags||[]};return r.constructor[p].push({...g,propertyKey:s,handler:a.value}),a}}function j(...t){return function(e,n,r){if(n&&r){if(!e.constructor[d])e.constructor[d]=new Map;e.constructor[d].set(n,t)}else e[d]=t;return r||e}}function Y(t){return m("param",t)}function K(t){return m("query",t)}function q(){return m("body")}function v(t){return m("header",t)}function H(t){return m("cookie",t)}function N(t){return m("param",void 0,t)}function m(t,e,n){return function(r,s,a){if(!r.constructor[u])r.constructor[u]=new Map;if(!r.constructor[u].has(s))r.constructor[u].set(s,[]);let g={type:t,key:e,token:n};r.constructor[u].get(s)[a]=g}}class f{static getInjectableMetadata(t){return t[U]}static getInjectMetadata(t){return t[i]||[]}static getOptionalMetadata(t){return t[P]||[]}static getTaggedMetadata(t){return t[M]||[]}static getControllerMetadata(t){return t[y]}static getAllRoutes(t){return t[p]||[]}static getMiddlewareMetadata(t,e){if(e)return t[d]?.get(e)||[];return t[d]||[]}static getParamMetadata(t,e){return t[u]?.get(e)||[]}}class A extends o{registerController(t){if(!f.getControllerMetadata(t))throw Error(`Class ${t.name} is not decorated with @Controller`);this.singleton(t,t);let n=f.getAllRoutes(t);for(let r of n);}resolve(t,e){if(typeof t==="function"){let n=f.getInjectableMetadata(t);if(n)try{return super.resolve(t,e)}catch{switch(n.scope||"transient"){case"singleton":this.singleton(t,t);break;case"transient":this.transient(t,t);break;default:this.transient(t,t)}}}return super.resolve(t,e)}}var S=new A;export{Ie as AuthGuard,Ae as AuthService,ht as AuthServiceProvider,ve as BaseDeferredServiceProvider,c as BaseServiceProvider,L as BindingBuilder,ct as BindingConditions,q as Body,y as CONTROLLER_METADATA_KEY,Me as CacheManager,pt as CacheServiceProvider,xe as ConfigService,lt as ConfigServiceProvider,Te as ConsoleLogger,o as Container,le as ContextualContainer,E as Controller,H as Cookie,o as DIContainer,Se as DatabaseConnection,dt as DatabaseServiceProvider,A as DecoratorContainer,Re as DefaultContextualBindingBuilder,ue as DefaultServiceProviderManager,C as Delete,_ as EnvironmentManager,at as EnvironmentPresets,de as EventBus,pe as EventDispatcher,gt as EventServiceProvider,Ce as FileLogger,h as Get,O as Head,v as Header,U as INJECTABLE_METADATA_KEY,i as INJECT_METADATA_KEY,b as Inject,N as InjectParam,D as Injectable,Oe as JwtService,z as Logger,ut as LoggingServiceProvider,d as MIDDLEWARE_METADATA_KEY,ke as MemoryCache,f as MetadataReader,P as OPTIONAL_METADATA_KEY,x as Optional,R as Options,u as PARAM_METADATA_KEY,Y as Param,I as Patch,w as Post,Pe as PostRepository,F as Put,K as Query,p as ROUTE_METADATA_KEY,$e as RedisCache,M as TAGGED_METADATA_KEY,T as Tagged,j as UseMiddleware,Ee as UserRepository,De as ValidationPipe,mt as ValidationServiceProvider,Fe as Validator,be as createContainer,S as decoratorContainer,ye as getContainer,we as setContainer};
2
+ import{L,o,M,k,a,_,we,be,Re,z,ve,ue,lt,ut,l,xe,de,dt,pt,ht,mt,gt,ft,yt,Te,V,Ce,Se,Ee,Pe,Me,ke,$e,Ae,Oe,Ie,Fe,De,Ne,pe,he}from"../chunk-sccx6r6k.js";var y=Symbol("controller"),p=Symbol("route"),u=Symbol("middleware"),c=Symbol("param");function D(t={}){return(e)=>(e[L]=t,e)}function b(t,e){return function(n,r,s){let i=n.constructor===Function?n:n.constructor;if(!i[o])i[o]=[];let g={token:t,optional:e?.optional,tags:e?.tags,when:e?.when};i[o][s]=g}}function x(){return(t,e,n)=>{if(!t[M])t[M]=[];t[M][n]=!0}}function T(t){return function(e,n,r){if(!e[k])e[k]=[];e[k][r]=t}}function E(t,e){return function(n){let r={prefix:t||"",middleware:e?.middleware||[],tags:e?.tags||[]};return n[y]=r,n}}function P(t="",e){return d("GET",t,e)}function h(t="",e){return d("POST",t,e)}function w(t="",e){return d("PUT",t,e)}function F(t="",e){return d("DELETE",t,e)}function C(t="",e){return d("PATCH",t,e)}function I(t="",e){return d("OPTIONS",t,e)}function R(t="",e){return d("HEAD",t,e)}function d(t,e,n){return function(r,s,i){if(!r.constructor[p])r.constructor[p]=[];let g={method:t,path:e,middleware:n?.middleware||[],tags:n?.tags||[]};return r.constructor[p].push({...g,propertyKey:s,handler:i.value}),i}}function O(...t){return function(e,n,r){if(n&&r){if(!e.constructor[u])e.constructor[u]=new Map;e.constructor[u].set(n,t)}else e[u]=t;return r||e}}function j(t){return m("param",t)}function Y(t){return m("query",t)}function K(){return m("body")}function q(t){return m("header",t)}function v(t){return m("cookie",t)}function H(t){return m("param",void 0,t)}function m(t,e,n){return function(r,s,i){if(!r.constructor[c])r.constructor[c]=new Map;if(!r.constructor[c].has(s))r.constructor[c].set(s,[]);let g={type:t,key:e,token:n};r.constructor[c].get(s)[i]=g}}class f{static getInjectableMetadata(t){return t[L]}static getInjectMetadata(t){return t[o]||[]}static getOptionalMetadata(t){return t[M]||[]}static getTaggedMetadata(t){return t[k]||[]}static getControllerMetadata(t){return t[y]}static getAllRoutes(t){return t[p]||[]}static getMiddlewareMetadata(t,e){if(e)return t[u]?.get(e)||[];return t[u]||[]}static getParamMetadata(t,e){return t[c]?.get(e)||[]}}class A extends a{registerController(t){if(!f.getControllerMetadata(t))throw Error(`Class ${t.name} is not decorated with @Controller`);this.singleton(t,t);let n=f.getAllRoutes(t);for(let r of n);}resolve(t,e){if(typeof t==="function"){let n=f.getInjectableMetadata(t);if(n)try{return super.resolve(t,e)}catch{switch(n.scope||"transient"){case"singleton":this.singleton(t,t);break;case"transient":this.transient(t,t);break;default:this.transient(t,t)}}}return super.resolve(t,e)}}var N=new A;export{Fe as AuthGuard,Oe as AuthService,gt as AuthServiceProvider,xe as BaseDeferredServiceProvider,l as BaseServiceProvider,_ as BindingBuilder,ut as BindingConditions,K as Body,y as CONTROLLER_METADATA_KEY,ke as CacheManager,mt as CacheServiceProvider,Te as ConfigService,dt as ConfigServiceProvider,Ce as ConsoleLogger,a as Container,ue as ContextualContainer,E as Controller,v as Cookie,a as DIContainer,Ee as DatabaseConnection,ht as DatabaseServiceProvider,A as DecoratorContainer,ve as DefaultContextualBindingBuilder,de as DefaultServiceProviderManager,F as Delete,z as EnvironmentManager,lt as EnvironmentPresets,pe as EventBus,he as EventDispatcher,yt as EventServiceProvider,Se as FileLogger,P as Get,R as Head,q as Header,L as INJECTABLE_METADATA_KEY,o as INJECT_METADATA_KEY,b as Inject,H as InjectParam,D as Injectable,Ie as JwtService,V as Logger,pt as LoggingServiceProvider,u as MIDDLEWARE_METADATA_KEY,$e as MemoryCache,f as MetadataReader,M as OPTIONAL_METADATA_KEY,x as Optional,I as Options,c as PARAM_METADATA_KEY,j as Param,C as Patch,h as Post,Me as PostRepository,w as Put,Y as Query,p as ROUTE_METADATA_KEY,Ae as RedisCache,k as TAGGED_METADATA_KEY,T as Tagged,O as UseMiddleware,Pe as UserRepository,Ne as ValidationPipe,ft as ValidationServiceProvider,De as Validator,Re as createContainer,N as decoratorContainer,we as getContainer,be as setContainer};
@@ -0,0 +1,2 @@
1
+ /** Load native crypto only when authentication or middleware needs it. */
2
+ export declare function getNodeCrypto(): typeof import('node:crypto');
package/dist/index.d.ts CHANGED
@@ -21,7 +21,7 @@ export * from './middleware';
21
21
  export { decodeParam } from './utils/decode-param';
22
22
  export { createCookieAccessor, createInMemoryCookieAccessor } from './request/cookie-accessor';
23
23
  export type { CookieAccessorSinks } from './request/cookie-accessor';
24
- export { enableRequestContext, getCurrentRequest, request, runWithRequest, setCurrentRequest } from './request/context';
24
+ export { enableRequestContext, getCurrentRequest, request, runWithRequest, runWithRequestArguments, setCurrentRequest } from './request/context';
25
25
  export * from './session';
26
26
  export * from './response/compression';
27
27
  export * from './response/response-factory';