@stacksjs/bun-router 0.1.17 → 0.1.20

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,82 +0,0 @@
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 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
- ${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
- `)}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 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
- \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 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
- `)}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 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
- \u2022 Check the controller file is imported
43
-
44
- Example:
45
- // Register the controller
46
- container.singleton('${s}', ${s})
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 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
- \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 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
- This usually indicates a circular or very deep dependency chain.
79
- Current resolution chain:
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};