@stacksjs/bun-router 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-7g1et0fb.js +82 -0
- package/dist/chunk-9y37n6xs.js +61 -0
- package/dist/chunk-trm3jyqk.js +357 -0
- package/dist/cli.js +8 -8
- package/dist/container/index.js +1 -1
- package/dist/index.js +29 -29
- package/dist/middleware/rate_limit.d.ts +2 -1
- package/dist/response/compression.d.ts +6 -0
- package/package.json +2 -2
- package/dist/chunk-4wd1d6ay.js +0 -416
- package/dist/chunk-8rrs7556.js +0 -3
- package/dist/chunk-m4aaj9ay.js +0 -82
package/dist/chunk-8rrs7556.js
DELETED
package/dist/chunk-m4aaj9ay.js
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
class a 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 x extends a{fields;constructor(e,t={},n){super({code:"VALIDATION_ERROR",message:e,statusCode:400,context:n,retryable:!1,severity:"low",category:"validation"});this.fields=t}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 T extends a{constructor(e="Authentication required",t){super({code:"AUTHENTICATION_ERROR",message:e,statusCode:401,context:t,retryable:!1,severity:"medium",category:"authentication"})}}class E extends a{requiredPermissions;constructor(e="Access denied",t,n){super({code:"AUTHORIZATION_ERROR",message:e,statusCode:403,context:n,retryable:!1,severity:"medium",category:"authorization"});this.requiredPermissions=t}}class w extends a{resource;resourceId;constructor(e="Resource not found",t,n,r){super({code:"NOT_FOUND",message:e,statusCode:404,context:r,retryable:!1,severity:"low",category:"business"});this.resource=t,this.resourceId=n}}class R extends a{allowedMethods;constructor(e,t,n){super({code:"METHOD_NOT_ALLOWED",message:`Method ${e} not allowed. Allowed methods: ${t.join(", ")}`,statusCode:405,context:n,retryable:!1,severity:"low",category:"business"});this.allowedMethods=t}toResponse(){let e=super.toResponse();return e.headers.set("Allow",this.allowedMethods.join(", ")),e}}class S extends a{timeoutMs;constructor(e="Request timeout",t,n){super({code:"REQUEST_TIMEOUT",message:e,statusCode:408,context:n,retryable:!0,severity:"medium",category:"network"});this.timeoutMs=t}}class B extends a{retryAfter;limit;remaining;constructor(e="Rate limit exceeded",t,n,r=0,i){super({code:"RATE_LIMIT_EXCEEDED",message:e,statusCode:429,context:i,retryable:!0,severity:"medium",category:"network"});this.retryAfter=t,this.limit=n,this.remaining=r}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 I extends a{constructor(e="Internal server error",t,n){super({code:"INTERNAL_SERVER_ERROR",message:e,statusCode:500,context:n,cause:t,retryable:!0,severity:"high",category:"system"})}}class P extends a{retryAfter;constructor(e="Service unavailable",t,n){super({code:"SERVICE_UNAVAILABLE",message:e,statusCode:503,context:n,retryable:!0,severity:"high",category:"system"});this.retryAfter=t}toResponse(){let e=super.toResponse();if(this.retryAfter)e.headers.set("Retry-After",this.retryAfter.toString());return e}}class D extends a{query;operation;constructor(e,t,n,r,i){super({code:"DATABASE_ERROR",message:e,statusCode:500,context:i,cause:r,retryable:!0,severity:"high",category:"database"});this.operation=t,this.query=n}}class k extends a{service;endpoint;constructor(e,t,n,r=502,i,o){super({code:"EXTERNAL_SERVICE_ERROR",message:e,statusCode:r,context:o,cause:i,retryable:!0,severity:"medium",category:"external"});this.service=t,this.endpoint=n}}class M extends a{service;nextAttemptAt;constructor(e,t,n){super({code:"CIRCUIT_BREAKER_OPEN",message:`Circuit breaker is open for service: ${e}. Next attempt at: ${t.toISOString()}`,statusCode:503,context:n,retryable:!0,severity:"medium",category:"external"});this.service=e,this.nextAttemptAt=t}}class _ extends a{businessRule;constructor(e,t,n){super({code:"BUSINESS_LOGIC_ERROR",message:e,statusCode:422,context:n,retryable:!1,severity:"low",category:"business"});this.businessRule=t}}class A extends a{configKey;constructor(e,t,n){super({code:"CONFIGURATION_ERROR",message:e,statusCode:500,context:n,retryable:!1,severity:"critical",category:"system"});this.configKey=t}}class O extends a{path;operation;constructor(e,t,n,r,i){super({code:"FILESYSTEM_ERROR",message:e,statusCode:500,context:i,cause:r,retryable:!1,severity:"medium",category:"system"});this.path=t,this.operation=n}}var ve={validation:(e,t,n)=>new x(e,t,n),authentication:(e,t)=>new T(e,t),authorization:(e,t,n)=>new E(e,t,n),notFound:(e,t,n)=>new w(void 0,e,t,n),methodNotAllowed:(e,t,n)=>new R(e,t,n),timeout:(e,t,n)=>new S(t,e,n),rateLimit:(e,t,n,r)=>new B(void 0,e,t,n,r),internalServer:(e,t,n)=>new I(e,t,n),serviceUnavailable:(e,t,n)=>new P(e,t,n),database:(e,t,n,r,i)=>new D(e,t,n,r,i),externalService:(e,t,n,r,i,o)=>new k(e,t,n,r,i,o),circuitBreakerOpen:(e,t,n)=>new M(e,t,n),businessLogic:(e,t,n)=>new _(e,t,n),configuration:(e,t,n)=>new A(e,t,n),fileSystem:(e,t,n,r,i)=>new O(e,t,n,r,i)};class p extends a{conflictingRoutes;suggestion;constructor(e,t){let n=p.buildMessage(e),r=p.buildSuggestion(e);super({code:"ROUTE_CONFLICT",message:n,statusCode:500,context:t,retryable:!1,severity:"critical",category:"system"});this.conflictingRoutes=e,this.suggestion=r}static buildMessage(e){let t=["Route conflict detected! Multiple routes match the same path pattern.","","Conflicting routes:"];for(let n of e){if(t.push(` \u2022 ${n.method} ${n.path}`),n.name)t.push(` Name: "${n.name}"`);if(n.definedAt)t.push(` Defined at: ${n.definedAt}`)}return t.join(`
|
|
3
|
-
`)}static buildSuggestion(e){let t=[],n=e.some((d)=>!d.path.includes("{")),r=e.some((d)=>d.path.includes("{"));if(n&&r)t.push("\u2022 Static routes should be defined before dynamic routes","\u2022 Consider using route constraints (whereNumber, whereUuid) to differentiate");if(e.filter((d)=>d.path.includes("{")).length>1)t.push("\u2022 Use different parameter names or add constraints:",' router.get("/users/{id}").whereNumber("id")',' router.get("/users/{slug}").whereAlpha("slug")');if(e.some((d)=>d.path.includes("*")))t.push("\u2022 Wildcard routes should be defined last","\u2022 Consider using more specific path prefixes");if(t.length===0)t.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
|
-
${t.join(`
|
|
5
|
-
`)}`}toJSON(){return{...super.toJSON(),conflictingRoutes:this.conflictingRoutes,suggestion:this.suggestion}}}class l extends a{dependencyChain;suggestion;constructor(e,t){let n=l.buildMessage(e),r=l.buildSuggestion(e);super({code:"CIRCULAR_DEPENDENCY",message:n,statusCode:500,context:t,retryable:!1,severity:"critical",category:"system"});this.dependencyChain=e,this.suggestion=r}static buildMessage(e){let t=["Circular dependency detected in the dependency injection container!","","Dependency chain:",""];for(let n=0;n<e.length;n++){let r=n===e.length-1,i=n===0?"\u250C\u2500\u25BA":r?"\u2514\u2500\u25BA":"\u251C\u2500\u25BA";if(t.push(` ${i} ${e[n]}`),!r)t.push(" \u2502")}return t.push(" \u2502"),t.push(` \u2514\u2500\u2500 cycles back to: ${e[0]}`),t.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((t,n)=>` ${n+1}. ${t}`).join(`
|
|
26
|
-
`)}`}toJSON(){return{...super.toJSON(),dependencyChain:this.dependencyChain,suggestion:this.suggestion}}}class L extends a{middlewareName;configErrors;suggestion;constructor(e,t,n){let r=`Middleware "${e}" configuration error:
|
|
27
|
-
${t.map((i)=>` \u2022 ${i}`).join(`
|
|
28
|
-
`)}`;super({code:"MIDDLEWARE_CONFIGURATION_ERROR",message:r,statusCode:500,context:n,retryable:!1,severity:"high",category:"system"});this.middlewareName=e,this.configErrors=t,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 v extends a{requestedPath;requestedMethod;similarRoutes;suggestion;constructor(e,t,n=[],r){let i=v.buildMessage(e,t,n);super({code:"ROUTE_NOT_FOUND",message:i,statusCode:404,context:r,retryable:!1,severity:"low",category:"business"});this.requestedPath=t,this.requestedMethod=e,this.similarRoutes=n,this.suggestion=this.buildSuggestion()}static buildMessage(e,t,n){let r=[`Route not found: ${e} ${t}`];if(n.length>0){r.push(""),r.push("Did you mean one of these routes?");for(let i of n.slice(0,5))if(r.push(` \u2022 ${i.method} ${i.path}`),i.similarity)r.push(` (${Math.round(i.similarity*100)}% match)`)}return r.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 q extends a{handlerRef;suggestion;constructor(e,t,n){let r=`Failed to resolve handler "${e}": ${t}`;super({code:"HANDLER_RESOLUTION_ERROR",message:r,statusCode:500,context:n,retryable:!1,severity:"high",category:"system"});this.handlerRef=e,this.suggestion=this.buildSuggestion(e)}buildSuggestion(e){let t=e.includes("@"),n=e.includes("/");if(t){let[r,i]=e.split("@");return`How to fix:
|
|
40
|
-
\u2022 Ensure the controller "${r}" is registered in the container
|
|
41
|
-
\u2022 Verify the method "${i}" exists and is public
|
|
42
|
-
\u2022 Check the controller file is imported
|
|
43
|
-
|
|
44
|
-
Example:
|
|
45
|
-
// Register the controller
|
|
46
|
-
container.singleton('${r}', ${r})
|
|
47
|
-
|
|
48
|
-
// Define the route
|
|
49
|
-
router.get('/path', '${e}')`}if(n)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 N extends a{modelName;paramName;paramValue;suggestion;constructor(e,t,n,r,i){let o=`Failed to bind model "${e}" for parameter "${t}" with value "${n}": ${r}`;super({code:"MODEL_BINDING_ERROR",message:o,statusCode:404,context:i,retryable:!1,severity:"low",category:"business"});this.modelName=e,this.paramName=t,this.paramValue=n,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 xe(e,t,n=5){let r=[];for(let i of t){let o=ie(e,i.path);if(o>0.3)r.push({method:i.method,path:i.path,similarity:o})}return r.sort((i,o)=>(o.similarity||0)-(i.similarity||0)).slice(0,n)}function ie(e,t){let n=e.length,r=t.length;if(n===0)return r===0?1:0;if(r===0)return 0;let i=[];for(let s=0;s<=n;s++)i[s]=[s];for(let s=0;s<=r;s++)i[0][s]=s;for(let s=1;s<=n;s++)for(let c=1;c<=r;c++){let y=e[s-1]===t[c-1]?0:1;i[s][c]=Math.min(i[s-1][c]+1,i[s][c-1]+1,i[s-1][c-1]+y)}let o=i[n][r],d=Math.max(n,r);return 1-o/d}function Te(e){let t=[],n=new Set;for(let r=0;r<e.length;r++){let i=e[r],o=`${i.method}:${i.path}`;if(n.has(o))continue;let d=[];for(let s=r+1;s<e.length;s++){let c=e[s];if(i.method===c.method&&se(i.path,c.path)){if(d.length===0)d.push({method:i.method,path:i.path,name:i.name});d.push({method:c.method,path:c.path,name:c.name}),n.add(`${c.method}:${c.path}`)}}if(d.length>0)t.push(d);n.add(o)}return t}function se(e,t){if(e===t)return!0;let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);if(n.length!==r.length){let o=e.includes("*"),d=t.includes("*");if(!o&&!d)return!1}let i=Math.max(n.length,r.length);for(let o=0;o<i;o++){let d=n[o]||"",s=r[o]||"";if(d==="*"||s==="*")return!0;let c=d.startsWith("{")&&d.endsWith("}"),y=s.startsWith("{")&&s.endsWith("}");if(!c&&!y){if(d!==s)return!1}}return!0}var Ee={routeConflict:(e,t)=>new p(e,t),circularDependency:(e,t)=>new l(e,t),middlewareConfig:(e,t,n)=>new L(e,t,n),routeNotFound:(e,t,n,r)=>new v(e,t,n,r),handlerResolution:(e,t,n)=>new q(e,t,n),modelBinding:(e,t,n,r,i)=>new N(e,t,n,r,i)};var oe=Symbol("injectable"),h=Symbol("inject"),Se=Symbol("optional"),Be=Symbol("tagged");class g{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 F(this,e)}register(e){let t=this.bindings.get(e.token);if(t?.metadata?.tags)for(let n of t.metadata.tags)this.tagIndex.get(n)?.delete(e.token);if(this.bindings.set(e.token,e),e.metadata?.tags)for(let n of e.metadata.tags){let r=this.tagIndex.get(n);if(!r)r=new Set,this.tagIndex.set(n,r);r.add(e.token)}return this}singleton(e,t){return this.bind(e).to(t).inSingletonScope().build()}transient(e,t){return this.bind(e).to(t).inTransientScope().build()}value(e,t){return this.bind(e).toValue(t).build()}factory(e,t){return this.bind(e).toFactory(t).build()}resolve(e,t){let n={container:this,token:e,environment:t?.environment||"development",requestId:t?.requestId||this.generateRequestId(),depth:t?.depth||0,resolving:t?.resolving||new Set,parent:t?.parent};return this.resolveInternal(e,n)}resolveAll(e){let t=new Set;if(this.bindings.has(e))t.add(e);if(typeof e==="string")for(let n of this.tagIndex.get(e)??[])t.add(n);return Array.from(t,(n)=>this.resolve(n))}resolveTagged(e){let t=this.tagIndex.get(e);if(!t||t.size===0)return[];return Array.from(t,(n)=>this.resolve(n))}getTaggedBindings(e){let t=this.tagIndex.get(e);if(!t||t.size===0)return[];let n=[];for(let r of t){let i=this.bindings.get(r);if(i)n.push(i)}return n}addInterceptor(e,t){let n=this.tokenToString(e);if(!this.interceptors.has(n))this.interceptors.set(n,[]);this.interceptors.get(n).push(t)}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 t=this.bindings.get(e);if(t?.metadata?.tags)for(let n of t.metadata.tags)this.tagIndex.get(n)?.delete(e);return this.bindings.delete(e),this.instances.delete(e),this}createChild(e){let t=new g({...this.options,...e});return t.parent=this,this.children.add(t),t}createScope(e){let t=this.createChild();return t.scopedInstances.set(e,new Map),t}getBindings(){return new Map(this.bindings)}clear(){return this.bindings.clear(),this.tagIndex.clear(),this.instances.clear(),this.scopedInstances.clear(),this}intercept(e,t){if(!this.interceptors.has(e))this.interceptors.set(e,[]);return this.interceptors.get(e).push(t),this}resolveInternal(e,t){if(t.resolving.has(e)){let n=Array.from(t.resolving).map((r)=>this.tokenToString(r));throw n.push(this.tokenToString(e)),new l(n)}if(t.depth>this.options.maxDepth){let n=Array.from(t.resolving).map((r)=>this.tokenToString(r));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
|
-
${n.map((r,i)=>` ${i+1}. ${r}`).join(`
|
|
81
|
-
`)}`)}t.resolving.add(e),t.depth++;try{let n=this.bindings.get(e);if(n){if(n.metadata.when&&!n.metadata.when(t))throw Error(`Contextual binding condition not met for: ${this.tokenToString(e)}`);return this.createInstance(n,t)}if(this.parent){let r={resolving:new Set,depth:0,container:this.parent,token:e};return this.parent.resolveInternal(e,r)}if(this.options.autoRegister&&typeof e==="function")return this.autoRegisterAndResolve(e,t);if(this.options.strictMode)throw Error(`No binding found for: ${this.tokenToString(e)}`);if(typeof e==="function")return this.createInstanceFromConstructor(e,t);throw Error(`Cannot resolve: ${this.tokenToString(e)}`)}finally{t.resolving.delete(e),t.depth--}}createInstance(e,t){let n;if(e.metadata.scope==="singleton"&&this.instances.has(e.token))n=this.instances.get(e.token);else if(e.metadata.scope==="scoped"&&t.requestId){let i=this.scopedInstances.get(t.requestId);if(i?.has(e.token))n=i.get(e.token);else{if(n=this.createNewInstance(e,t),!i)this.scopedInstances.set(t.requestId,new Map);this.scopedInstances.get(t.requestId).set(e.token,n)}}else if(n=this.createNewInstance(e,t),e.metadata.scope==="singleton")this.instances.set(e.token,n);let r=this.tokenToString(e.token);if(this.interceptors.has(r)){let i=this.interceptors.get(r);for(let o of i)n=o(n)}return n}createNewInstance(e,t){if(e.value!==void 0)return e.value;if(e.factory){let n=this.resolveDependencies(e.metadata.dependencies||[],t);return e.factory(...n)}if(e.instance)return e.instance;if(e.implementation)return this.createInstanceFromConstructor(e.implementation,t);throw Error(`Invalid binding configuration for: ${this.tokenToString(e.token)}`)}createInstanceFromConstructor(e,t){let n=this.getConstructorDependencies(e),r=this.resolveDependencies(n,t),i=new e(...r);if(this.options.enableDecorators)this.applyDecorators(i,e);return i}getConstructorDependencies(e){let t=Reflect.getMetadata?.(h,e)||e[h];if(!t&&e.constructor)t=e.constructor[h];if(!t&&typeof e==="function"&&e.prototype){let r=e[h];if(r)t=r}if(!t&&typeof e==="function"){let r=e[h];if(r)t=r}if(t)return t.map((r)=>r.token);let n=Reflect.getMetadata?.("design:paramtypes",e);if(n)return n;return this.parseConstructorDependencies(e)}parseConstructorDependencies(e){let n=e.toString().match(/constructor\s*\(([^)]*)\)/);if(!n||!n[1])return[];return n[1].split(",").map((r)=>r.trim().split(":")[0].trim()).filter((r)=>r.length>0)}resolveDependencies(e,t){return e.map((n)=>this.resolveInternal(n,t))}autoRegisterAndResolve(e,t){let n=Reflect.getMetadata?.(oe,e),r={token:e,implementation:e,metadata:{scope:n?.scope||this.options.defaultScope,tags:n?.tags}};return this.register(r),this.resolveInternal(e,t)}applyDecorators(e,t){let n=Reflect.getMetadata?.("decorators",t);if(n)for(let r of n)r(e)}hasTag(e,t){return e.metadata.tags?.includes(t)??!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 F{container;binding;constructor(e,t){this.container=e;this.binding={token:t,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 m=null;function Ie(){if(!m)m=new g;return m}function Pe(e){m=e}function De(e){return new g(e)}class j{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,t){return this.variables.get(e)??t}set(e,t){return this.variables.set(e,t),this}hasFeature(e){return this.getEnvironment()?.features.includes(e)??!1}loadEnvironmentVariables(){let e=this.getEnvironment();if(e)for(let[t,n]of Object.entries(e.variables))this.variables.set(t,n)}}class V{container;binding;constructor(e,t){this.container=e;this.binding={token:t,conditions:[],priority:0,metadata:{scope:"transient"}}}when(e){return this.binding.conditions.push(e),this}whenEnvironment(...e){let t={type:"environment",predicate:(n)=>e.includes(n.environment||"development"),description:`Environment is one of: ${e.join(", ")}`};return this.when(t)}whenTag(e){let t={type:"tag",predicate:(n)=>n.parent?.token?.toString().includes(e)??!1,description:`Parent has tag: ${e}`};return this.when(t)}whenParent(e){let t={type:"parent",predicate:(n)=>n.parent?.token===e,description:`Parent token is: ${e.toString()}`};return this.when(t)}whenRequest(e){let t={type:"request",predicate:e,description:"Custom request condition"};return this.when(t)}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 ae extends g{contextualBindings=new Map;environmentManager;constructor(e){super(e);this.environmentManager=new j}bindContextual(e){return new V(this,e)}registerContextualBinding(e){if(!this.contextualBindings.has(e.token))this.contextualBindings.set(e.token,[]);let t=this.contextualBindings.get(e.token);return t.push(e),t.sort((n,r)=>r.priority-n.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,t){let n={container:this,token:e,environment:t?.environment||this.environmentManager.getCurrentEnvironment(),requestId:t?.requestId||this.generateContextualRequestId(),depth:t?.depth||0,resolving:t?.resolving||new Set,parent:t?.parent},r=this.findContextualBinding(e,n);if(r)return this.createInstanceFromContextualBinding(r,n);return super.resolve(e,n)}findContextualBinding(e,t){let n=this.contextualBindings.get(e);if(!n)return;for(let r of n)if(this.evaluateConditions(r.conditions,t))return r;return}evaluateConditions(e,t){return e.every((n)=>{try{return n.predicate(t)}catch(r){return console.warn(`Error evaluating binding condition: ${n.description}`,r),!1}})}createInstanceFromContextualBinding(e,t){try{return this.createInstance(e,t)}catch(n){if(e.fallback)return console.warn(`Contextual binding failed, using fallback for ${e.token.toString()}`),this.createInstance(e.fallback,t);throw n}}generateContextualRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}class de{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 ce{static environment(...e){return{type:"environment",predicate:(t)=>e.includes(t.environment||"development"),description:`Environment is one of: ${e.join(", ")}`}}static feature(e){return{type:"custom",predicate:(t)=>t.container.getEnvironmentManager().hasFeature(e),description:`Feature ${e} is enabled`}}static envVar(e,t){return{type:"custom",predicate:(n)=>n.container.getEnvironmentManager().get(e)===t,description:`Environment variable ${e} equals ${t}`}}static requestPattern(e){return{type:"request",predicate:(t)=>e.test(t.requestId||""),description:`Request ID matches pattern: ${e.toString()}`}}static timeRange(e,t){return{type:"custom",predicate:()=>{let n=new Date().getHours();return n>=e&&n<=t},description:`Time is between ${e}:00 and ${t}:00`}}static custom(e,t){return{type:"custom",predicate:e,description:t||"Custom condition"}}}class u{version;dependencies;environment;priority=0;boot(e){}shutdown(e){}singleton(e,t,n){e.singleton(t,n)}transient(e,t,n){e.transient(t,n)}value(e,t,n){e.value(t,n)}factory(e,t,n){e.factory(t,n)}when(e,t){return{bind:(n)=>e.bind(n).when(t)}}forEnvironment(e,...t){return this.when(e,(n)=>t.includes(n.environment||"development"))}}class U extends u{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 t=e.shouldLoad(this.container);if(t instanceof Promise)t.then((n)=>{if(n)this.doRegister(e)});else if(!t)return this}return this.doRegister(e),this}async boot(){let e=Array.from(this.providers.values()).sort((t,n)=>(n.priority||0)-(t.priority||0));this.validateDependencies(e);for(let t of e)if(!this.loadedProviders.has(t.name))await this.loadProvider(t);for(let t of e)if(!this.bootedProviders.has(t.name))await this.bootProvider(t)}async shutdown(){let e=Array.from(this.providers.values()).reverse();for(let t of e)if(t.shutdown)try{await t.shutdown(this.container)}catch(n){console.error(`Error shutting down provider ${t.name}:`,n)}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[t,n]of this.deferredProviders)if(n.provides().includes(e)&&!this.loadedProviders.has(t))await this.loadProvider(n),await this.bootProvider(n),this.deferredProviders.delete(t)}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(t){throw Error(`Failed to load provider ${e.name}: ${t}`)}}async bootProvider(e){if(e.boot)try{await e.boot(this.container),this.bootedProviders.add(e.name)}catch(t){throw Error(`Failed to boot provider ${e.name}: ${t}`)}else this.bootedProviders.add(e.name)}validateDependencies(e){let t=new Set(e.map((n)=>n.name));for(let n of e)if(n.dependencies){for(let r of n.dependencies)if(!t.has(r))throw Error(`Provider ${n.name} depends on ${r}, but it's not registered`)}}isDeferredProvider(e){return"provides"in e&&"isDeferred"in e}isConditionalProvider(e){return"shouldLoad"in e}}class le extends u{name="config";priority=100;register(e){e.singleton("config",H),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 ge extends u{name="logging";priority=90;register(e){e.factory("logger",(t)=>new f(t.get("logging",{}))),this.forEnvironment(e,"development").bind("logger").toFactory(()=>new G),this.forEnvironment(e,"production").bind("logger").toFactory((t)=>new K(t.get("logging.file","./app.log")))}}class he extends u{name="database";dependencies=["config","logging"];register(e){e.singleton("database",W),e.transient("userRepository",z),e.transient("postRepository",J)}async boot(e){await e.resolve("database").connect()}async shutdown(e){await e.resolve("database").disconnect()}}class pe extends u{name="cache";dependencies=["config"];register(e){e.singleton("cache",X),this.forEnvironment(e,"development").bind("cache.store").toFactory(()=>new Y),this.forEnvironment(e,"production").bind("cache.store").toFactory((t)=>new Z(t.get("cache.redis")))}}class me extends u{name="auth";dependencies=["config","database"];register(e){e.singleton("authService",Q),e.singleton("jwtService",ee),e.transient("authGuard",te)}}class fe extends u{name="validation";register(e){e.singleton("validator",ne),e.factory("validationPipe",(t)=>new re(t))}}class ye extends U{name="events";provides(){return["eventBus","eventDispatcher",b,C]}register(e){e.singleton("eventBus",b),e.singleton("eventDispatcher",C)}}class H{get(e,t){return t}}class f{config;constructor(e){this.config=e}log(e){console.log(e)}}class G extends f{constructor(){super({})}}class K extends f{filePath;constructor(e){super({});this.filePath=e}}class W{async connect(){}async disconnect(){}}class z{db;constructor(e){this.db=e}}class J{db;constructor(e){this.db=e}}class X{store;constructor(e){this.store=e}}class Y{cache=new Map}class Z{config;constructor(e){this.config=e}}class Q{jwt;userRepo;constructor(e,t){this.jwt=e;this.userRepo=t}}class ee{config;constructor(e){this.config=e}}class te{auth;constructor(e){this.auth=e}}class ne{validate(e,t){return!0}}class re{validator;constructor(e){this.validator=e}}class b{emit(e,t){}}class C{bus;constructor(e){this.bus=e}}
|
|
82
|
-
export{a as ka,x as la,T as ma,E as na,w as oa,R as pa,S as qa,B as ra,I as sa,P as ta,D as ua,k as va,M as wa,_ as xa,A as ya,O as za,ve as Aa,p as Ba,l as Ca,L as Da,v as Ea,q as Fa,N as Ga,xe as Ha,Te as Ia,Ee as Ja,oe as Ka,h as La,Se as Ma,Be as Na,g as Oa,F as Pa,Ie as Qa,Pe as Ra,De as Sa,j as Ta,V as Ua,ae as Va,de as Wa,ce as Xa,u as Ya,U as Za,ue as _a,le as $a,ge as ab,he as bb,pe as cb,me as db,fe as eb,ye as fb,H as gb,f as hb,G as ib,K as jb,W as kb,z as lb,J as mb,X as nb,Y as ob,Z as pb,Q as qb,ee as rb,te as sb,ne as tb,re as ub,b as vb,C as wb};
|