@stacksjs/bun-router 0.0.17 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/dist/chunk-2mx7fq49.js +4 -0
  2. package/dist/chunk-a8p83068.js +103 -0
  3. package/dist/{chunk-cgptvjdf.js → chunk-y3xq6wq6.js} +1 -1
  4. package/dist/cli.js +4 -3
  5. package/dist/container/index.js +1149 -211
  6. package/dist/container/service-provider.d.ts +3 -3
  7. package/dist/development/performance-profiler.d.ts +3 -3
  8. package/dist/development/route-debugger.d.ts +1 -1
  9. package/dist/development/route-inspector.d.ts +2 -2
  10. package/dist/index.js +369 -2209
  11. package/dist/observability/integration.d.ts +1 -1
  12. package/dist/response/macros.d.ts +1 -1
  13. package/dist/router/index.d.ts +7 -7
  14. package/dist/router/router.d.ts +0 -32
  15. package/dist/testing/performance-testing.d.ts +2 -2
  16. package/dist/testing/test-client.d.ts +1 -1
  17. package/dist/testing/websocket-testing.d.ts +1 -1
  18. package/package.json +7 -7
  19. package/dist/chunk-1ahs68ys.js +0 -18
  20. package/dist/chunk-g3ybefhg.js +0 -1923
  21. package/src/auth.ts +0 -489
  22. package/src/cache/lru-cache.ts +0 -457
  23. package/src/cache/middleware-memoization.ts +0 -531
  24. package/src/cache/route-cache-warmer.ts +0 -486
  25. package/src/cache/sqlite-cache.ts +0 -783
  26. package/src/cache/streaming-cache.ts +0 -572
  27. package/src/cli/colors.ts +0 -29
  28. package/src/cli/index.ts +0 -287
  29. package/src/cli/middleware.ts +0 -291
  30. package/src/cli/openapi.ts +0 -407
  31. package/src/cli/router.ts +0 -188
  32. package/src/cli/routes.ts +0 -265
  33. package/src/cli/utils.ts +0 -531
  34. package/src/cli.ts +0 -5
  35. package/src/config.ts +0 -322
  36. package/src/container/container.ts +0 -786
  37. package/src/container/contextual-binding.ts +0 -606
  38. package/src/container/decorators.ts +0 -368
  39. package/src/container/index.ts +0 -49
  40. package/src/container/service-provider.ts +0 -596
  41. package/src/development/hot-reload.ts +0 -673
  42. package/src/development/index.ts +0 -499
  43. package/src/development/performance-profiler.ts +0 -717
  44. package/src/development/route-debugger.ts +0 -527
  45. package/src/development/route-inspector.ts +0 -749
  46. package/src/development/typescript-utilities.ts +0 -682
  47. package/src/docs.ts +0 -397
  48. package/src/errors/circuit-breaker.ts +0 -733
  49. package/src/errors/error-handler.ts +0 -569
  50. package/src/errors/error-reporting.ts +0 -672
  51. package/src/errors/exceptions.ts +0 -536
  52. package/src/errors/graceful-degradation.ts +0 -623
  53. package/src/errors/index.ts +0 -21
  54. package/src/errors/router-errors.ts +0 -632
  55. package/src/file-serving/static-files.ts +0 -718
  56. package/src/index.ts +0 -66
  57. package/src/middleware/auth.ts +0 -220
  58. package/src/middleware/content_security_policy.ts +0 -215
  59. package/src/middleware/cors.ts +0 -142
  60. package/src/middleware/csrf.ts +0 -166
  61. package/src/middleware/ddos_protection.ts +0 -279
  62. package/src/middleware/file_security.ts +0 -191
  63. package/src/middleware/file_upload.ts +0 -275
  64. package/src/middleware/helmet.ts +0 -268
  65. package/src/middleware/index.ts +0 -117
  66. package/src/middleware/input_validation.ts +0 -453
  67. package/src/middleware/json_body.ts +0 -37
  68. package/src/middleware/performance_alerting.ts +0 -540
  69. package/src/middleware/performance_dashboard.ts +0 -661
  70. package/src/middleware/performance_monitor.ts +0 -945
  71. package/src/middleware/pipeline.ts +0 -489
  72. package/src/middleware/rate_limit.ts +0 -251
  73. package/src/middleware/request_id.ts +0 -36
  74. package/src/middleware/request_signing.ts +0 -638
  75. package/src/middleware/request_tracer.ts +0 -653
  76. package/src/middleware/response_cache.ts +0 -778
  77. package/src/middleware/security.ts +0 -482
  78. package/src/middleware/security_suite.ts +0 -257
  79. package/src/middleware/session.ts +0 -91
  80. package/src/model-binding/index.ts +0 -18
  81. package/src/model-binding/model-middleware.ts +0 -425
  82. package/src/model-binding/model-registry.ts +0 -550
  83. package/src/model-binding.ts +0 -370
  84. package/src/model-resolver-factory.ts +0 -106
  85. package/src/observability/correlation.ts +0 -691
  86. package/src/observability/health-checks.ts +0 -729
  87. package/src/observability/index.ts +0 -184
  88. package/src/observability/integration.ts +0 -548
  89. package/src/observability/metrics.ts +0 -753
  90. package/src/observability/tracing.ts +0 -638
  91. package/src/optimization/bun-utilities.ts +0 -778
  92. package/src/query-builder-integration.ts +0 -137
  93. package/src/request/context.ts +0 -109
  94. package/src/request/enhanced-request.ts +0 -876
  95. package/src/request/macros.ts +0 -822
  96. package/src/response/macros.ts +0 -665
  97. package/src/response/response-factory.ts +0 -596
  98. package/src/router/api-routes.ts +0 -243
  99. package/src/router/file-based-routing.ts +0 -697
  100. package/src/router/file-streaming.ts +0 -383
  101. package/src/router/fluent-routing.ts +0 -866
  102. package/src/router/group-organization.ts +0 -229
  103. package/src/router/handler-resolver.ts +0 -327
  104. package/src/router/http-methods.ts +0 -407
  105. package/src/router/index.ts +0 -193
  106. package/src/router/middleware-groups.ts +0 -222
  107. package/src/router/middleware-integration.ts +0 -399
  108. package/src/router/middleware.ts +0 -234
  109. package/src/router/model-binding.ts +0 -215
  110. package/src/router/optimized-route-matching.ts +0 -302
  111. package/src/router/route-building.ts +0 -221
  112. package/src/router/route-compiler.ts +0 -691
  113. package/src/router/route-matching.ts +0 -368
  114. package/src/router/route-trie.ts +0 -450
  115. package/src/router/router.ts +0 -1616
  116. package/src/router/server.ts +0 -684
  117. package/src/router/validation-integration.ts +0 -449
  118. package/src/router/view-rendering.ts +0 -233
  119. package/src/router/websocket.ts +0 -100
  120. package/src/routing/route-caching.ts +0 -402
  121. package/src/routing/route-throttling.ts +0 -469
  122. package/src/routing/subdomain-routing.ts +0 -492
  123. package/src/session/database-store.ts +0 -109
  124. package/src/session/file-store.ts +0 -148
  125. package/src/session/index.ts +0 -244
  126. package/src/session/memory-store.ts +0 -88
  127. package/src/session/redis-store.ts +0 -93
  128. package/src/streaming/index.ts +0 -17
  129. package/src/streaming/sse-handler.ts +0 -482
  130. package/src/streaming/stream-handler.ts +0 -552
  131. package/src/testing/auth-testing.ts +0 -448
  132. package/src/testing/file-upload-testing.ts +0 -543
  133. package/src/testing/index.ts +0 -10
  134. package/src/testing/middleware-testing.ts +0 -322
  135. package/src/testing/model-binding-testing.ts +0 -645
  136. package/src/testing/performance-testing.ts +0 -738
  137. package/src/testing/test-client.ts +0 -310
  138. package/src/testing/test-request.ts +0 -315
  139. package/src/testing/test-response.ts +0 -332
  140. package/src/testing/types.ts +0 -224
  141. package/src/testing/websocket-testing.ts +0 -590
  142. package/src/types/controller-types.ts +0 -385
  143. package/src/types/core.ts +0 -683
  144. package/src/types/middleware-types.ts +0 -422
  145. package/src/types/request-response-augmentation.ts +0 -489
  146. package/src/types/route-inference.ts +0 -372
  147. package/src/types.ts +0 -2123
  148. package/src/url.ts +0 -131
  149. package/src/utils/index.ts +0 -1
  150. package/src/utils/query-preservation.ts +0 -201
  151. package/src/utils.ts +0 -395
  152. package/src/validation/validator.ts +0 -688
  153. package/src/websocket/clustering.ts +0 -769
@@ -1,1923 +0,0 @@
1
- // @bun
2
- // src/errors/exceptions.ts
3
- class RouterException extends Error {
4
- code;
5
- statusCode;
6
- context;
7
- retryable;
8
- severity;
9
- category;
10
- timestamp;
11
- cause;
12
- constructor(details) {
13
- super(details.message);
14
- this.name = this.constructor.name;
15
- this.code = details.code;
16
- this.statusCode = details.statusCode || 500;
17
- this.context = details.context || {};
18
- this.retryable = details.retryable || false;
19
- this.severity = details.severity || "medium";
20
- this.category = details.category || "system";
21
- this.timestamp = new Date;
22
- this.cause = details.cause;
23
- if (Error.captureStackTrace) {
24
- Error.captureStackTrace(this, this.constructor);
25
- }
26
- }
27
- toJSON() {
28
- return {
29
- name: this.name,
30
- code: this.code,
31
- message: this.message,
32
- statusCode: this.statusCode,
33
- context: this.context,
34
- retryable: this.retryable,
35
- severity: this.severity,
36
- category: this.category,
37
- timestamp: this.timestamp.toISOString(),
38
- stack: this.stack,
39
- cause: this.cause ? {
40
- name: this.cause.name,
41
- message: this.cause.message,
42
- stack: this.cause.stack
43
- } : undefined
44
- };
45
- }
46
- toResponse() {
47
- const body = {
48
- error: {
49
- code: this.code,
50
- message: this.message,
51
- statusCode: this.statusCode,
52
- timestamp: this.timestamp.toISOString(),
53
- requestId: this.context.requestId
54
- }
55
- };
56
- return new Response(JSON.stringify(body), {
57
- status: this.statusCode,
58
- headers: {
59
- "Content-Type": "application/json",
60
- "X-Error-Code": this.code,
61
- "X-Request-ID": this.context.requestId || ""
62
- }
63
- });
64
- }
65
- }
66
-
67
- class ValidationException extends RouterException {
68
- fields;
69
- constructor(message, fields = {}, context) {
70
- super({
71
- code: "VALIDATION_ERROR",
72
- message,
73
- statusCode: 400,
74
- context,
75
- retryable: false,
76
- severity: "low",
77
- category: "validation"
78
- });
79
- this.fields = fields;
80
- }
81
- toResponse() {
82
- const body = {
83
- error: {
84
- code: this.code,
85
- message: this.message,
86
- statusCode: this.statusCode,
87
- timestamp: this.timestamp.toISOString(),
88
- requestId: this.context.requestId,
89
- fields: this.fields
90
- }
91
- };
92
- return new Response(JSON.stringify(body), {
93
- status: this.statusCode,
94
- headers: {
95
- "Content-Type": "application/json",
96
- "X-Error-Code": this.code,
97
- "X-Request-ID": this.context.requestId || ""
98
- }
99
- });
100
- }
101
- }
102
-
103
- class AuthenticationException extends RouterException {
104
- constructor(message = "Authentication required", context) {
105
- super({
106
- code: "AUTHENTICATION_ERROR",
107
- message,
108
- statusCode: 401,
109
- context,
110
- retryable: false,
111
- severity: "medium",
112
- category: "authentication"
113
- });
114
- }
115
- }
116
-
117
- class AuthorizationException extends RouterException {
118
- requiredPermissions;
119
- constructor(message = "Access denied", requiredPermissions, context) {
120
- super({
121
- code: "AUTHORIZATION_ERROR",
122
- message,
123
- statusCode: 403,
124
- context,
125
- retryable: false,
126
- severity: "medium",
127
- category: "authorization"
128
- });
129
- this.requiredPermissions = requiredPermissions;
130
- }
131
- }
132
-
133
- class NotFoundException extends RouterException {
134
- resource;
135
- resourceId;
136
- constructor(message = "Resource not found", resource, resourceId, context) {
137
- super({
138
- code: "NOT_FOUND",
139
- message,
140
- statusCode: 404,
141
- context,
142
- retryable: false,
143
- severity: "low",
144
- category: "business"
145
- });
146
- this.resource = resource;
147
- this.resourceId = resourceId;
148
- }
149
- }
150
-
151
- class MethodNotAllowedException extends RouterException {
152
- allowedMethods;
153
- constructor(method, allowedMethods, context) {
154
- super({
155
- code: "METHOD_NOT_ALLOWED",
156
- message: `Method ${method} not allowed. Allowed methods: ${allowedMethods.join(", ")}`,
157
- statusCode: 405,
158
- context,
159
- retryable: false,
160
- severity: "low",
161
- category: "business"
162
- });
163
- this.allowedMethods = allowedMethods;
164
- }
165
- toResponse() {
166
- const response = super.toResponse();
167
- response.headers.set("Allow", this.allowedMethods.join(", "));
168
- return response;
169
- }
170
- }
171
-
172
- class TimeoutException extends RouterException {
173
- timeoutMs;
174
- constructor(message = "Request timeout", timeoutMs, context) {
175
- super({
176
- code: "REQUEST_TIMEOUT",
177
- message,
178
- statusCode: 408,
179
- context,
180
- retryable: true,
181
- severity: "medium",
182
- category: "network"
183
- });
184
- this.timeoutMs = timeoutMs;
185
- }
186
- }
187
-
188
- class RateLimitException extends RouterException {
189
- retryAfter;
190
- limit;
191
- remaining;
192
- constructor(message = "Rate limit exceeded", retryAfter, limit, remaining = 0, context) {
193
- super({
194
- code: "RATE_LIMIT_EXCEEDED",
195
- message,
196
- statusCode: 429,
197
- context,
198
- retryable: true,
199
- severity: "medium",
200
- category: "network"
201
- });
202
- this.retryAfter = retryAfter;
203
- this.limit = limit;
204
- this.remaining = remaining;
205
- }
206
- toResponse() {
207
- const response = super.toResponse();
208
- response.headers.set("Retry-After", this.retryAfter.toString());
209
- response.headers.set("X-RateLimit-Limit", this.limit.toString());
210
- response.headers.set("X-RateLimit-Remaining", this.remaining.toString());
211
- return response;
212
- }
213
- }
214
-
215
- class InternalServerException extends RouterException {
216
- constructor(message = "Internal server error", cause, context) {
217
- super({
218
- code: "INTERNAL_SERVER_ERROR",
219
- message,
220
- statusCode: 500,
221
- context,
222
- cause,
223
- retryable: true,
224
- severity: "high",
225
- category: "system"
226
- });
227
- }
228
- }
229
-
230
- class ServiceUnavailableException extends RouterException {
231
- retryAfter;
232
- constructor(message = "Service unavailable", retryAfter, context) {
233
- super({
234
- code: "SERVICE_UNAVAILABLE",
235
- message,
236
- statusCode: 503,
237
- context,
238
- retryable: true,
239
- severity: "high",
240
- category: "system"
241
- });
242
- this.retryAfter = retryAfter;
243
- }
244
- toResponse() {
245
- const response = super.toResponse();
246
- if (this.retryAfter) {
247
- response.headers.set("Retry-After", this.retryAfter.toString());
248
- }
249
- return response;
250
- }
251
- }
252
-
253
- class DatabaseException extends RouterException {
254
- query;
255
- operation;
256
- constructor(message, operation, query, cause, context) {
257
- super({
258
- code: "DATABASE_ERROR",
259
- message,
260
- statusCode: 500,
261
- context,
262
- cause,
263
- retryable: true,
264
- severity: "high",
265
- category: "database"
266
- });
267
- this.operation = operation;
268
- this.query = query;
269
- }
270
- }
271
-
272
- class ExternalServiceException extends RouterException {
273
- service;
274
- endpoint;
275
- constructor(message, service, endpoint, statusCode = 502, cause, context) {
276
- super({
277
- code: "EXTERNAL_SERVICE_ERROR",
278
- message,
279
- statusCode,
280
- context,
281
- cause,
282
- retryable: true,
283
- severity: "medium",
284
- category: "external"
285
- });
286
- this.service = service;
287
- this.endpoint = endpoint;
288
- }
289
- }
290
-
291
- class CircuitBreakerOpenException extends RouterException {
292
- service;
293
- nextAttemptAt;
294
- constructor(service, nextAttemptAt, context) {
295
- super({
296
- code: "CIRCUIT_BREAKER_OPEN",
297
- message: `Circuit breaker is open for service: ${service}. Next attempt at: ${nextAttemptAt.toISOString()}`,
298
- statusCode: 503,
299
- context,
300
- retryable: true,
301
- severity: "medium",
302
- category: "external"
303
- });
304
- this.service = service;
305
- this.nextAttemptAt = nextAttemptAt;
306
- }
307
- }
308
-
309
- class BusinessLogicException extends RouterException {
310
- businessRule;
311
- constructor(message, businessRule, context) {
312
- super({
313
- code: "BUSINESS_LOGIC_ERROR",
314
- message,
315
- statusCode: 422,
316
- context,
317
- retryable: false,
318
- severity: "low",
319
- category: "business"
320
- });
321
- this.businessRule = businessRule;
322
- }
323
- }
324
-
325
- class ConfigurationException extends RouterException {
326
- configKey;
327
- constructor(message, configKey, context) {
328
- super({
329
- code: "CONFIGURATION_ERROR",
330
- message,
331
- statusCode: 500,
332
- context,
333
- retryable: false,
334
- severity: "critical",
335
- category: "system"
336
- });
337
- this.configKey = configKey;
338
- }
339
- }
340
-
341
- class FileSystemException extends RouterException {
342
- path;
343
- operation;
344
- constructor(message, path, operation, cause, context) {
345
- super({
346
- code: "FILESYSTEM_ERROR",
347
- message,
348
- statusCode: 500,
349
- context,
350
- cause,
351
- retryable: false,
352
- severity: "medium",
353
- category: "system"
354
- });
355
- this.path = path;
356
- this.operation = operation;
357
- }
358
- }
359
- var ErrorFactory = {
360
- validation: (message, fields, context) => new ValidationException(message, fields, context),
361
- authentication: (message, context) => new AuthenticationException(message, context),
362
- authorization: (message, requiredPermissions, context) => new AuthorizationException(message, requiredPermissions, context),
363
- notFound: (resource, resourceId, context) => new NotFoundException(undefined, resource, resourceId, context),
364
- methodNotAllowed: (method, allowedMethods, context) => new MethodNotAllowedException(method, allowedMethods, context),
365
- timeout: (timeoutMs, message, context) => new TimeoutException(message, timeoutMs, context),
366
- rateLimit: (retryAfter, limit, remaining, context) => new RateLimitException(undefined, retryAfter, limit, remaining, context),
367
- internalServer: (message, cause, context) => new InternalServerException(message, cause, context),
368
- serviceUnavailable: (message, retryAfter, context) => new ServiceUnavailableException(message, retryAfter, context),
369
- database: (message, operation, query, cause, context) => new DatabaseException(message, operation, query, cause, context),
370
- externalService: (message, service, endpoint, statusCode, cause, context) => new ExternalServiceException(message, service, endpoint, statusCode, cause, context),
371
- circuitBreakerOpen: (service, nextAttemptAt, context) => new CircuitBreakerOpenException(service, nextAttemptAt, context),
372
- businessLogic: (message, businessRule, context) => new BusinessLogicException(message, businessRule, context),
373
- configuration: (message, configKey, context) => new ConfigurationException(message, configKey, context),
374
- fileSystem: (message, path, operation, cause, context) => new FileSystemException(message, path, operation, cause, context)
375
- };
376
-
377
- // src/errors/router-errors.ts
378
- class RouteConflictException extends RouterException {
379
- conflictingRoutes;
380
- suggestion;
381
- constructor(conflictingRoutes, context) {
382
- const message = RouteConflictException.buildMessage(conflictingRoutes);
383
- const suggestion = RouteConflictException.buildSuggestion(conflictingRoutes);
384
- super({
385
- code: "ROUTE_CONFLICT",
386
- message,
387
- statusCode: 500,
388
- context,
389
- retryable: false,
390
- severity: "critical",
391
- category: "system"
392
- });
393
- this.conflictingRoutes = conflictingRoutes;
394
- this.suggestion = suggestion;
395
- }
396
- static buildMessage(routes) {
397
- const lines = [
398
- "Route conflict detected! Multiple routes match the same path pattern.",
399
- "",
400
- "Conflicting routes:"
401
- ];
402
- for (const route of routes) {
403
- lines.push(` \u2022 ${route.method} ${route.path}`);
404
- if (route.name) {
405
- lines.push(` Name: "${route.name}"`);
406
- }
407
- if (route.definedAt) {
408
- lines.push(` Defined at: ${route.definedAt}`);
409
- }
410
- }
411
- return lines.join(`
412
- `);
413
- }
414
- static buildSuggestion(routes) {
415
- const suggestions = [];
416
- const hasStatic = routes.some((r) => !r.path.includes("{"));
417
- const hasDynamic = routes.some((r) => r.path.includes("{"));
418
- if (hasStatic && hasDynamic) {
419
- suggestions.push("\u2022 Static routes should be defined before dynamic routes", "\u2022 Consider using route constraints (whereNumber, whereUuid) to differentiate");
420
- }
421
- const dynamicRoutes = routes.filter((r) => r.path.includes("{"));
422
- if (dynamicRoutes.length > 1) {
423
- suggestions.push("\u2022 Use different parameter names or add constraints:", ' router.get("/users/{id}").whereNumber("id")', ' router.get("/users/{slug}").whereAlpha("slug")');
424
- }
425
- const hasWildcard = routes.some((r) => r.path.includes("*"));
426
- if (hasWildcard) {
427
- suggestions.push("\u2022 Wildcard routes should be defined last", "\u2022 Consider using more specific path prefixes");
428
- }
429
- if (suggestions.length === 0) {
430
- suggestions.push("\u2022 Rename one of the conflicting routes", "\u2022 Use route groups with different prefixes", "\u2022 Add parameter constraints to differentiate routes");
431
- }
432
- return `How to fix:
433
- ${suggestions.join(`
434
- `)}`;
435
- }
436
- toJSON() {
437
- return {
438
- ...super.toJSON(),
439
- conflictingRoutes: this.conflictingRoutes,
440
- suggestion: this.suggestion
441
- };
442
- }
443
- }
444
-
445
- class CircularDependencyException extends RouterException {
446
- dependencyChain;
447
- suggestion;
448
- constructor(dependencyChain, context) {
449
- const message = CircularDependencyException.buildMessage(dependencyChain);
450
- const suggestion = CircularDependencyException.buildSuggestion(dependencyChain);
451
- super({
452
- code: "CIRCULAR_DEPENDENCY",
453
- message,
454
- statusCode: 500,
455
- context,
456
- retryable: false,
457
- severity: "critical",
458
- category: "system"
459
- });
460
- this.dependencyChain = dependencyChain;
461
- this.suggestion = suggestion;
462
- }
463
- static buildMessage(chain) {
464
- const lines = [
465
- "Circular dependency detected in the dependency injection container!",
466
- "",
467
- "Dependency chain:",
468
- ""
469
- ];
470
- for (let i = 0;i < chain.length; i++) {
471
- const isLast = i === chain.length - 1;
472
- const prefix = i === 0 ? "\u250C\u2500\u25BA" : isLast ? "\u2514\u2500\u25BA" : "\u251C\u2500\u25BA";
473
- lines.push(` ${prefix} ${chain[i]}`);
474
- if (!isLast) {
475
- lines.push(" \u2502");
476
- }
477
- }
478
- lines.push(" \u2502");
479
- lines.push(` \u2514\u2500\u2500 cycles back to: ${chain[0]}`);
480
- return lines.join(`
481
- `);
482
- }
483
- static buildSuggestion(chain) {
484
- return `How to fix:
485
-
486
- 1. Break the cycle by introducing an interface:
487
- \u2022 Create an interface for one of the dependencies
488
- \u2022 Use lazy injection: container.bind('${chain[0]}').lazy()
489
-
490
- 2. Restructure your dependencies:
491
- \u2022 Extract shared logic into a separate service
492
- \u2022 Use events/callbacks instead of direct dependencies
493
-
494
- 3. Use setter injection instead of constructor injection:
495
- \u2022 Remove the dependency from the constructor
496
- \u2022 Set it after instantiation using a setter method
497
-
498
- 4. Check if the dependency is actually needed:
499
- \u2022 Sometimes circular dependencies indicate a design issue
500
- \u2022 Consider if the classes have too many responsibilities
501
-
502
- Dependency chain involved:
503
- ${chain.map((dep, i) => ` ${i + 1}. ${dep}`).join(`
504
- `)}`;
505
- }
506
- toJSON() {
507
- return {
508
- ...super.toJSON(),
509
- dependencyChain: this.dependencyChain,
510
- suggestion: this.suggestion
511
- };
512
- }
513
- }
514
-
515
- class MiddlewareConfigurationException extends RouterException {
516
- middlewareName;
517
- configErrors;
518
- suggestion;
519
- constructor(middlewareName, configErrors, context) {
520
- const message = `Middleware "${middlewareName}" configuration error:
521
- ${configErrors.map((e) => ` \u2022 ${e}`).join(`
522
- `)}`;
523
- super({
524
- code: "MIDDLEWARE_CONFIGURATION_ERROR",
525
- message,
526
- statusCode: 500,
527
- context,
528
- retryable: false,
529
- severity: "high",
530
- category: "system"
531
- });
532
- this.middlewareName = middlewareName;
533
- this.configErrors = configErrors;
534
- this.suggestion = this.buildSuggestion();
535
- }
536
- buildSuggestion() {
537
- return `How to fix:
538
- \u2022 Check the middleware documentation for required options
539
- \u2022 Ensure all required configuration values are provided
540
- \u2022 Verify configuration value types match expected types
541
-
542
- Example configuration:
543
- router.use(new ${this.middlewareName}({
544
- // Add required options here
545
- }))`;
546
- }
547
- }
548
-
549
- class RouteNotFoundException extends RouterException {
550
- requestedPath;
551
- requestedMethod;
552
- similarRoutes;
553
- suggestion;
554
- constructor(requestedMethod, requestedPath, similarRoutes = [], context) {
555
- const message = RouteNotFoundException.buildMessage(requestedMethod, requestedPath, similarRoutes);
556
- super({
557
- code: "ROUTE_NOT_FOUND",
558
- message,
559
- statusCode: 404,
560
- context,
561
- retryable: false,
562
- severity: "low",
563
- category: "business"
564
- });
565
- this.requestedPath = requestedPath;
566
- this.requestedMethod = requestedMethod;
567
- this.similarRoutes = similarRoutes;
568
- this.suggestion = this.buildSuggestion();
569
- }
570
- static buildMessage(method, path, similarRoutes) {
571
- const lines = [
572
- `Route not found: ${method} ${path}`
573
- ];
574
- if (similarRoutes.length > 0) {
575
- lines.push("");
576
- lines.push("Did you mean one of these routes?");
577
- for (const route of similarRoutes.slice(0, 5)) {
578
- lines.push(` \u2022 ${route.method} ${route.path}`);
579
- if (route.similarity) {
580
- lines.push(` (${Math.round(route.similarity * 100)}% match)`);
581
- }
582
- }
583
- }
584
- return lines.join(`
585
- `);
586
- }
587
- buildSuggestion() {
588
- const suggestions = [
589
- `\u2022 Verify the HTTP method is correct (you used ${this.requestedMethod})`,
590
- "\u2022 Check for typos in the URL path",
591
- "\u2022 Ensure the route is registered before the server starts",
592
- "\u2022 Check if the route requires specific middleware (e.g., auth)"
593
- ];
594
- if (this.requestedPath.includes("//")) {
595
- suggestions.push("\u2022 Remove duplicate slashes from the URL");
596
- }
597
- if (!this.requestedPath.startsWith("/")) {
598
- suggestions.push("\u2022 Ensure the path starts with a forward slash (/)");
599
- }
600
- return `How to fix:
601
- ${suggestions.join(`
602
- `)}`;
603
- }
604
- }
605
-
606
- class HandlerResolutionException extends RouterException {
607
- handlerRef;
608
- suggestion;
609
- constructor(handlerRef, reason, context) {
610
- const message = `Failed to resolve handler "${handlerRef}": ${reason}`;
611
- super({
612
- code: "HANDLER_RESOLUTION_ERROR",
613
- message,
614
- statusCode: 500,
615
- context,
616
- retryable: false,
617
- severity: "high",
618
- category: "system"
619
- });
620
- this.handlerRef = handlerRef;
621
- this.suggestion = this.buildSuggestion(handlerRef);
622
- }
623
- buildSuggestion(handlerRef) {
624
- const isControllerMethod = handlerRef.includes("@");
625
- const isActionPath = handlerRef.includes("/");
626
- if (isControllerMethod) {
627
- const [controller, method] = handlerRef.split("@");
628
- return `How to fix:
629
- \u2022 Ensure the controller "${controller}" is registered in the container
630
- \u2022 Verify the method "${method}" exists and is public
631
- \u2022 Check the controller file is imported
632
-
633
- Example:
634
- // Register the controller
635
- container.singleton('${controller}', ${controller})
636
-
637
- // Define the route
638
- router.get('/path', '${handlerRef}')`;
639
- }
640
- if (isActionPath) {
641
- return `How to fix:
642
- \u2022 Ensure the action class exists at the specified path
643
- \u2022 Verify the action has a "handle" method
644
- \u2022 Check the action file is properly exported
645
-
646
- Example:
647
- // Action class at ${handlerRef}.ts
648
- export default class ${handlerRef.split("/").pop()} {
649
- handle(req: Request): Response {
650
- return new Response('OK')
651
- }
652
- }`;
653
- }
654
- return `How to fix:
655
- \u2022 Verify the handler reference is correct
656
- \u2022 Ensure the handler function/class is exported
657
- \u2022 Check for circular dependencies in the handler module`;
658
- }
659
- }
660
-
661
- class ModelBindingException extends RouterException {
662
- modelName;
663
- paramName;
664
- paramValue;
665
- suggestion;
666
- constructor(modelName, paramName, paramValue, reason, context) {
667
- const message = `Failed to bind model "${modelName}" for parameter "${paramName}" with value "${paramValue}": ${reason}`;
668
- super({
669
- code: "MODEL_BINDING_ERROR",
670
- message,
671
- statusCode: 404,
672
- context,
673
- retryable: false,
674
- severity: "low",
675
- category: "business"
676
- });
677
- this.modelName = modelName;
678
- this.paramName = paramName;
679
- this.paramValue = paramValue;
680
- this.suggestion = this.buildSuggestion();
681
- }
682
- buildSuggestion() {
683
- return `How to fix:
684
- \u2022 Verify the ${this.paramName} "${this.paramValue}" exists in your data source
685
- \u2022 Check if the model resolver is correctly configured
686
- \u2022 Ensure the route parameter matches the model's identifier field
687
-
688
- Example model binding:
689
- router.model('${this.paramName}', async (value) => {
690
- const ${this.modelName.toLowerCase()} = await db.${this.modelName.toLowerCase()}s.findUnique({
691
- where: { id: value }
692
- })
693
- if (!${this.modelName.toLowerCase()}) {
694
- throw new Error('${this.modelName} not found')
695
- }
696
- return ${this.modelName.toLowerCase()}
697
- })`;
698
- }
699
- }
700
- function findSimilarRoutes(requestedPath, availableRoutes, maxResults = 5) {
701
- const results = [];
702
- for (const route of availableRoutes) {
703
- const similarity = calculateSimilarity(requestedPath, route.path);
704
- if (similarity > 0.3) {
705
- results.push({
706
- method: route.method,
707
- path: route.path,
708
- similarity
709
- });
710
- }
711
- }
712
- return results.sort((a, b) => (b.similarity || 0) - (a.similarity || 0)).slice(0, maxResults);
713
- }
714
- function calculateSimilarity(str1, str2) {
715
- const len1 = str1.length;
716
- const len2 = str2.length;
717
- if (len1 === 0)
718
- return len2 === 0 ? 1 : 0;
719
- if (len2 === 0)
720
- return 0;
721
- const matrix = [];
722
- for (let i = 0;i <= len1; i++) {
723
- matrix[i] = [i];
724
- }
725
- for (let j = 0;j <= len2; j++) {
726
- matrix[0][j] = j;
727
- }
728
- for (let i = 1;i <= len1; i++) {
729
- for (let j = 1;j <= len2; j++) {
730
- const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
731
- matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
732
- }
733
- }
734
- const distance = matrix[len1][len2];
735
- const maxLen = Math.max(len1, len2);
736
- return 1 - distance / maxLen;
737
- }
738
- function detectRouteConflicts(routes) {
739
- const conflicts = [];
740
- const checked = new Set;
741
- for (let i = 0;i < routes.length; i++) {
742
- const route1 = routes[i];
743
- const key1 = `${route1.method}:${route1.path}`;
744
- if (checked.has(key1))
745
- continue;
746
- const conflicting = [];
747
- for (let j = i + 1;j < routes.length; j++) {
748
- const route2 = routes[j];
749
- if (route1.method === route2.method && routesConflict(route1.path, route2.path)) {
750
- if (conflicting.length === 0) {
751
- conflicting.push({
752
- method: route1.method,
753
- path: route1.path,
754
- name: route1.name
755
- });
756
- }
757
- conflicting.push({
758
- method: route2.method,
759
- path: route2.path,
760
- name: route2.name
761
- });
762
- checked.add(`${route2.method}:${route2.path}`);
763
- }
764
- }
765
- if (conflicting.length > 0) {
766
- conflicts.push(conflicting);
767
- }
768
- checked.add(key1);
769
- }
770
- return conflicts;
771
- }
772
- function routesConflict(path1, path2) {
773
- if (path1 === path2)
774
- return true;
775
- const segments1 = path1.split("/").filter(Boolean);
776
- const segments2 = path2.split("/").filter(Boolean);
777
- if (segments1.length !== segments2.length) {
778
- const hasWildcard1 = path1.includes("*");
779
- const hasWildcard2 = path2.includes("*");
780
- if (!hasWildcard1 && !hasWildcard2)
781
- return false;
782
- }
783
- const maxLen = Math.max(segments1.length, segments2.length);
784
- for (let i = 0;i < maxLen; i++) {
785
- const seg1 = segments1[i] || "";
786
- const seg2 = segments2[i] || "";
787
- if (seg1 === "*" || seg2 === "*")
788
- return true;
789
- const isDynamic1 = seg1.startsWith("{") && seg1.endsWith("}");
790
- const isDynamic2 = seg2.startsWith("{") && seg2.endsWith("}");
791
- if (!isDynamic1 && !isDynamic2) {
792
- if (seg1 !== seg2)
793
- return false;
794
- }
795
- }
796
- return true;
797
- }
798
- var RouterErrorFactory = {
799
- routeConflict: (routes, context) => new RouteConflictException(routes, context),
800
- circularDependency: (chain, context) => new CircularDependencyException(chain, context),
801
- middlewareConfig: (name, errors, context) => new MiddlewareConfigurationException(name, errors, context),
802
- routeNotFound: (method, path, similarRoutes, context) => new RouteNotFoundException(method, path, similarRoutes, context),
803
- handlerResolution: (ref, reason, context) => new HandlerResolutionException(ref, reason, context),
804
- modelBinding: (model, param, value, reason, context) => new ModelBindingException(model, param, value, reason, context)
805
- };
806
-
807
- // src/container/container.ts
808
- var INJECTABLE_METADATA_KEY = Symbol("injectable");
809
- var INJECT_METADATA_KEY = Symbol("inject");
810
- var OPTIONAL_METADATA_KEY = Symbol("optional");
811
- var TAGGED_METADATA_KEY = Symbol("tagged");
812
-
813
- class Container {
814
- bindings = new Map;
815
- tagIndex = new Map;
816
- instances = new Map;
817
- scopedInstances = new Map;
818
- interceptors = new Map;
819
- parent;
820
- children = new Set;
821
- options;
822
- constructor(options = {}) {
823
- this.options = {
824
- autoRegister: options.autoRegister ?? true,
825
- strictMode: options.strictMode ?? false,
826
- maxDepth: options.maxDepth ?? 50,
827
- enableDecorators: options.enableDecorators ?? true,
828
- enableInterception: options.enableInterception ?? false,
829
- defaultScope: options.defaultScope ?? "transient"
830
- };
831
- }
832
- bind(token) {
833
- return new BindingBuilder(this, token);
834
- }
835
- register(binding) {
836
- const existing = this.bindings.get(binding.token);
837
- if (existing?.metadata?.tags) {
838
- for (const tag of existing.metadata.tags) {
839
- this.tagIndex.get(tag)?.delete(binding.token);
840
- }
841
- }
842
- this.bindings.set(binding.token, binding);
843
- if (binding.metadata?.tags) {
844
- for (const tag of binding.metadata.tags) {
845
- let tokens = this.tagIndex.get(tag);
846
- if (!tokens) {
847
- tokens = new Set;
848
- this.tagIndex.set(tag, tokens);
849
- }
850
- tokens.add(binding.token);
851
- }
852
- }
853
- return this;
854
- }
855
- singleton(token, implementation) {
856
- return this.bind(token).to(implementation).inSingletonScope().build();
857
- }
858
- transient(token, implementation) {
859
- return this.bind(token).to(implementation).inTransientScope().build();
860
- }
861
- value(token, value) {
862
- return this.bind(token).toValue(value).build();
863
- }
864
- factory(token, factory) {
865
- return this.bind(token).toFactory(factory).build();
866
- }
867
- resolve(token, context) {
868
- const resolutionContext = {
869
- container: this,
870
- token,
871
- environment: context?.environment || "development",
872
- requestId: context?.requestId || this.generateRequestId(),
873
- depth: context?.depth || 0,
874
- resolving: context?.resolving || new Set,
875
- parent: context?.parent
876
- };
877
- return this.resolveInternal(token, resolutionContext);
878
- }
879
- resolveAll(token) {
880
- const tokens = new Set;
881
- if (this.bindings.has(token)) {
882
- tokens.add(token);
883
- }
884
- if (typeof token === "string") {
885
- for (const tagged of this.tagIndex.get(token) ?? []) {
886
- tokens.add(tagged);
887
- }
888
- }
889
- return Array.from(tokens, (t) => this.resolve(t));
890
- }
891
- resolveTagged(tag) {
892
- const tokens = this.tagIndex.get(tag);
893
- if (!tokens || tokens.size === 0) {
894
- return [];
895
- }
896
- return Array.from(tokens, (token) => this.resolve(token));
897
- }
898
- getTaggedBindings(tag) {
899
- const tokens = this.tagIndex.get(tag);
900
- if (!tokens || tokens.size === 0) {
901
- return [];
902
- }
903
- const bindings = [];
904
- for (const token of tokens) {
905
- const binding = this.bindings.get(token);
906
- if (binding) {
907
- bindings.push(binding);
908
- }
909
- }
910
- return bindings;
911
- }
912
- addInterceptor(token, interceptor) {
913
- const key = this.tokenToString(token);
914
- if (!this.interceptors.has(key)) {
915
- this.interceptors.set(key, []);
916
- }
917
- this.interceptors.get(key).push(interceptor);
918
- }
919
- registerController(controller) {
920
- this.singleton(controller, controller);
921
- }
922
- getController(controller) {
923
- return this.resolve(controller);
924
- }
925
- isBound(token) {
926
- return this.bindings.has(token) || (this.parent?.isBound(token) ?? false);
927
- }
928
- unbind(token) {
929
- const binding = this.bindings.get(token);
930
- if (binding?.metadata?.tags) {
931
- for (const tag of binding.metadata.tags) {
932
- this.tagIndex.get(tag)?.delete(token);
933
- }
934
- }
935
- this.bindings.delete(token);
936
- this.instances.delete(token);
937
- return this;
938
- }
939
- createChild(options) {
940
- const child = new Container({ ...this.options, ...options });
941
- child.parent = this;
942
- this.children.add(child);
943
- return child;
944
- }
945
- createScope(scopeId) {
946
- const scope = this.createChild();
947
- scope.scopedInstances.set(scopeId, new Map);
948
- return scope;
949
- }
950
- getBindings() {
951
- return new Map(this.bindings);
952
- }
953
- clear() {
954
- this.bindings.clear();
955
- this.tagIndex.clear();
956
- this.instances.clear();
957
- this.scopedInstances.clear();
958
- return this;
959
- }
960
- intercept(token, interceptor) {
961
- if (!this.interceptors.has(token)) {
962
- this.interceptors.set(token, []);
963
- }
964
- this.interceptors.get(token).push(interceptor);
965
- return this;
966
- }
967
- resolveInternal(token, context) {
968
- if (context.resolving.has(token)) {
969
- const chain = Array.from(context.resolving).map((t) => this.tokenToString(t));
970
- chain.push(this.tokenToString(token));
971
- throw new CircularDependencyException(chain);
972
- }
973
- if (context.depth > this.options.maxDepth) {
974
- const chain = Array.from(context.resolving).map((t) => this.tokenToString(t));
975
- throw new Error(`Maximum resolution depth exceeded (${this.options.maxDepth}).
976
- ` + `This usually indicates a circular or very deep dependency chain.
977
- ` + `Current resolution chain:
978
- ${chain.map((t, i) => ` ${i + 1}. ${t}`).join(`
979
- `)}`);
980
- }
981
- context.resolving.add(token);
982
- context.depth++;
983
- try {
984
- const binding = this.bindings.get(token);
985
- if (binding) {
986
- if (binding.metadata.when && !binding.metadata.when(context)) {
987
- throw new Error(`Contextual binding condition not met for: ${this.tokenToString(token)}`);
988
- }
989
- return this.createInstance(binding, context);
990
- }
991
- if (this.parent) {
992
- const parentContext = {
993
- resolving: new Set,
994
- depth: 0,
995
- container: this.parent,
996
- token
997
- };
998
- return this.parent.resolveInternal(token, parentContext);
999
- }
1000
- if (this.options.autoRegister && typeof token === "function") {
1001
- return this.autoRegisterAndResolve(token, context);
1002
- }
1003
- if (this.options.strictMode) {
1004
- throw new Error(`No binding found for: ${this.tokenToString(token)}`);
1005
- }
1006
- if (typeof token === "function") {
1007
- return this.createInstanceFromConstructor(token, context);
1008
- }
1009
- throw new Error(`Cannot resolve: ${this.tokenToString(token)}`);
1010
- } finally {
1011
- context.resolving.delete(token);
1012
- context.depth--;
1013
- }
1014
- }
1015
- createInstance(binding, context) {
1016
- let instance;
1017
- if (binding.metadata.scope === "singleton" && this.instances.has(binding.token)) {
1018
- instance = this.instances.get(binding.token);
1019
- } else if (binding.metadata.scope === "scoped" && context.requestId) {
1020
- const scopedMap = this.scopedInstances.get(context.requestId);
1021
- if (scopedMap?.has(binding.token)) {
1022
- instance = scopedMap.get(binding.token);
1023
- } else {
1024
- instance = this.createNewInstance(binding, context);
1025
- if (!scopedMap) {
1026
- this.scopedInstances.set(context.requestId, new Map);
1027
- }
1028
- this.scopedInstances.get(context.requestId).set(binding.token, instance);
1029
- }
1030
- } else {
1031
- instance = this.createNewInstance(binding, context);
1032
- if (binding.metadata.scope === "singleton") {
1033
- this.instances.set(binding.token, instance);
1034
- }
1035
- }
1036
- const tokenKey = this.tokenToString(binding.token);
1037
- if (this.interceptors.has(tokenKey)) {
1038
- const interceptors = this.interceptors.get(tokenKey);
1039
- for (const interceptor of interceptors) {
1040
- instance = interceptor(instance);
1041
- }
1042
- }
1043
- return instance;
1044
- }
1045
- createNewInstance(binding, context) {
1046
- if (binding.value !== undefined) {
1047
- return binding.value;
1048
- }
1049
- if (binding.factory) {
1050
- const dependencies = this.resolveDependencies(binding.metadata.dependencies || [], context);
1051
- return binding.factory(...dependencies);
1052
- }
1053
- if (binding.instance) {
1054
- return binding.instance;
1055
- }
1056
- if (binding.implementation) {
1057
- return this.createInstanceFromConstructor(binding.implementation, context);
1058
- }
1059
- throw new Error(`Invalid binding configuration for: ${this.tokenToString(binding.token)}`);
1060
- }
1061
- createInstanceFromConstructor(constructor, context) {
1062
- const dependencies = this.getConstructorDependencies(constructor);
1063
- const resolvedDependencies = this.resolveDependencies(dependencies, context);
1064
- const instance = new constructor(...resolvedDependencies);
1065
- if (this.options.enableDecorators) {
1066
- this.applyDecorators(instance, constructor);
1067
- }
1068
- return instance;
1069
- }
1070
- getConstructorDependencies(constructor) {
1071
- let injectMetadata = Reflect.getMetadata?.(INJECT_METADATA_KEY, constructor) || constructor[INJECT_METADATA_KEY];
1072
- if (!injectMetadata && constructor.constructor) {
1073
- injectMetadata = constructor.constructor[INJECT_METADATA_KEY];
1074
- }
1075
- if (!injectMetadata && typeof constructor === "function" && constructor.prototype) {
1076
- const classMetadata = constructor[INJECT_METADATA_KEY];
1077
- if (classMetadata) {
1078
- injectMetadata = classMetadata;
1079
- }
1080
- }
1081
- if (!injectMetadata && typeof constructor === "function") {
1082
- const directMetadata = constructor[INJECT_METADATA_KEY];
1083
- if (directMetadata) {
1084
- injectMetadata = directMetadata;
1085
- }
1086
- }
1087
- if (injectMetadata) {
1088
- return injectMetadata.map((meta) => meta.token);
1089
- }
1090
- const paramTypes = Reflect.getMetadata?.("design:paramtypes", constructor);
1091
- if (paramTypes) {
1092
- return paramTypes;
1093
- }
1094
- return this.parseConstructorDependencies(constructor);
1095
- }
1096
- parseConstructorDependencies(constructor) {
1097
- const constructorString = constructor.toString();
1098
- const match = constructorString.match(/constructor\s*\(([^)]*)\)/);
1099
- if (!match || !match[1]) {
1100
- return [];
1101
- }
1102
- return match[1].split(",").map((param) => param.trim().split(":")[0].trim()).filter((param) => param.length > 0);
1103
- }
1104
- resolveDependencies(dependencies, context) {
1105
- return dependencies.map((dep) => this.resolveInternal(dep, context));
1106
- }
1107
- autoRegisterAndResolve(constructor, context) {
1108
- const metadata = Reflect.getMetadata?.(INJECTABLE_METADATA_KEY, constructor);
1109
- const binding = {
1110
- token: constructor,
1111
- implementation: constructor,
1112
- metadata: {
1113
- scope: metadata?.scope || this.options.defaultScope,
1114
- tags: metadata?.tags
1115
- }
1116
- };
1117
- this.register(binding);
1118
- return this.resolveInternal(constructor, context);
1119
- }
1120
- applyDecorators(instance, constructor) {
1121
- const decorators = Reflect.getMetadata?.("decorators", constructor);
1122
- if (decorators) {
1123
- for (const decorator of decorators) {
1124
- decorator(instance);
1125
- }
1126
- }
1127
- }
1128
- hasTag(binding, tag) {
1129
- return binding.metadata.tags?.includes(tag) ?? false;
1130
- }
1131
- tokenToString(token) {
1132
- if (typeof token === "string")
1133
- return token;
1134
- if (typeof token === "symbol")
1135
- return token.toString();
1136
- if (typeof token === "function")
1137
- return token.name || "anonymous";
1138
- return "unknown";
1139
- }
1140
- generateRequestId() {
1141
- return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1142
- }
1143
- }
1144
-
1145
- class BindingBuilder {
1146
- container;
1147
- binding;
1148
- constructor(container, token) {
1149
- this.container = container;
1150
- this.binding = {
1151
- token,
1152
- metadata: {
1153
- scope: "transient"
1154
- }
1155
- };
1156
- }
1157
- to(implementation) {
1158
- this.binding.implementation = implementation;
1159
- return this;
1160
- }
1161
- toValue(value) {
1162
- this.binding.value = value;
1163
- this.binding.metadata.scope = "singleton";
1164
- return this;
1165
- }
1166
- toFactory(factory) {
1167
- this.binding.factory = factory;
1168
- return this;
1169
- }
1170
- toInstance(instance) {
1171
- this.binding.instance = instance;
1172
- this.binding.metadata.scope = "singleton";
1173
- return this;
1174
- }
1175
- inSingletonScope() {
1176
- this.binding.metadata.scope = "singleton";
1177
- return this;
1178
- }
1179
- inTransientScope() {
1180
- this.binding.metadata.scope = "transient";
1181
- return this;
1182
- }
1183
- inScopedScope() {
1184
- this.binding.metadata.scope = "scoped";
1185
- return this;
1186
- }
1187
- inRequestScope() {
1188
- this.binding.metadata.scope = "request";
1189
- return this;
1190
- }
1191
- withTags(...tags) {
1192
- this.binding.metadata.tags = [...this.binding.metadata.tags || [], ...tags];
1193
- return this;
1194
- }
1195
- when(condition) {
1196
- this.binding.metadata.when = condition;
1197
- return this;
1198
- }
1199
- lazy() {
1200
- this.binding.metadata.lazy = true;
1201
- return this;
1202
- }
1203
- build() {
1204
- this.container.register(this.binding);
1205
- return this.container;
1206
- }
1207
- }
1208
- var globalContainer = null;
1209
- function getContainer() {
1210
- if (!globalContainer) {
1211
- globalContainer = new Container;
1212
- }
1213
- return globalContainer;
1214
- }
1215
- function setContainer(container) {
1216
- globalContainer = container;
1217
- }
1218
- function createContainer(options) {
1219
- return new Container(options);
1220
- }
1221
-
1222
- // src/container/contextual-binding.ts
1223
- class EnvironmentManager {
1224
- environments = new Map;
1225
- currentEnvironment;
1226
- variables = new Map;
1227
- constructor(defaultEnvironment = "development") {
1228
- this.currentEnvironment = defaultEnvironment;
1229
- this.loadEnvironmentVariables();
1230
- }
1231
- register(config) {
1232
- this.environments.set(config.name, config);
1233
- return this;
1234
- }
1235
- setEnvironment(name) {
1236
- if (!this.environments.has(name)) {
1237
- throw new Error(`Environment ${name} is not registered`);
1238
- }
1239
- this.currentEnvironment = name;
1240
- this.loadEnvironmentVariables();
1241
- return this;
1242
- }
1243
- getCurrentEnvironment() {
1244
- return this.currentEnvironment;
1245
- }
1246
- getEnvironment(name) {
1247
- return this.environments.get(name || this.currentEnvironment);
1248
- }
1249
- is(...environments) {
1250
- return environments.includes(this.currentEnvironment);
1251
- }
1252
- get(key, defaultValue) {
1253
- return this.variables.get(key) ?? defaultValue;
1254
- }
1255
- set(key, value) {
1256
- this.variables.set(key, value);
1257
- return this;
1258
- }
1259
- hasFeature(feature) {
1260
- const env = this.getEnvironment();
1261
- return env?.features.includes(feature) ?? false;
1262
- }
1263
- loadEnvironmentVariables() {
1264
- const env = this.getEnvironment();
1265
- if (env) {
1266
- for (const [key, value] of Object.entries(env.variables)) {
1267
- this.variables.set(key, value);
1268
- }
1269
- }
1270
- }
1271
- }
1272
-
1273
- class DefaultContextualBindingBuilder {
1274
- container;
1275
- binding;
1276
- constructor(container, token) {
1277
- this.container = container;
1278
- this.binding = {
1279
- token,
1280
- conditions: [],
1281
- priority: 0,
1282
- metadata: {
1283
- scope: "transient"
1284
- }
1285
- };
1286
- }
1287
- when(condition) {
1288
- this.binding.conditions.push(condition);
1289
- return this;
1290
- }
1291
- whenEnvironment(...environments) {
1292
- const condition = {
1293
- type: "environment",
1294
- predicate: (context) => environments.includes(context.environment || "development"),
1295
- description: `Environment is one of: ${environments.join(", ")}`
1296
- };
1297
- return this.when(condition);
1298
- }
1299
- whenTag(tag) {
1300
- const condition = {
1301
- type: "tag",
1302
- predicate: (context) => {
1303
- return context.parent?.token?.toString().includes(tag) ?? false;
1304
- },
1305
- description: `Parent has tag: ${tag}`
1306
- };
1307
- return this.when(condition);
1308
- }
1309
- whenParent(parentToken) {
1310
- const condition = {
1311
- type: "parent",
1312
- predicate: (context) => context.parent?.token === parentToken,
1313
- description: `Parent token is: ${parentToken.toString()}`
1314
- };
1315
- return this.when(condition);
1316
- }
1317
- whenRequest(predicate) {
1318
- const condition = {
1319
- type: "request",
1320
- predicate,
1321
- description: "Custom request condition"
1322
- };
1323
- return this.when(condition);
1324
- }
1325
- withPriority(priority) {
1326
- this.binding.priority = priority;
1327
- return this;
1328
- }
1329
- withFallback(fallback) {
1330
- this.binding.fallback = fallback;
1331
- return this;
1332
- }
1333
- to(implementation) {
1334
- this.binding.implementation = implementation;
1335
- return this;
1336
- }
1337
- toValue(value) {
1338
- this.binding.value = value;
1339
- this.binding.metadata.scope = "singleton";
1340
- return this;
1341
- }
1342
- toFactory(factory) {
1343
- this.binding.factory = factory;
1344
- return this;
1345
- }
1346
- inSingletonScope() {
1347
- this.binding.metadata.scope = "singleton";
1348
- return this;
1349
- }
1350
- inTransientScope() {
1351
- this.binding.metadata.scope = "transient";
1352
- return this;
1353
- }
1354
- build() {
1355
- this.container.registerContextualBinding(this.binding);
1356
- return this.container;
1357
- }
1358
- }
1359
-
1360
- class ContextualContainer extends Container {
1361
- contextualBindings = new Map;
1362
- environmentManager;
1363
- constructor(options) {
1364
- super(options);
1365
- this.environmentManager = new EnvironmentManager;
1366
- }
1367
- bindContextual(token) {
1368
- return new DefaultContextualBindingBuilder(this, token);
1369
- }
1370
- registerContextualBinding(binding) {
1371
- if (!this.contextualBindings.has(binding.token)) {
1372
- this.contextualBindings.set(binding.token, []);
1373
- }
1374
- const bindings = this.contextualBindings.get(binding.token);
1375
- bindings.push(binding);
1376
- bindings.sort((a, b) => b.priority - a.priority);
1377
- return this;
1378
- }
1379
- getEnvironmentManager() {
1380
- return this.environmentManager;
1381
- }
1382
- forDevelopment(token) {
1383
- return this.bindContextual(token).whenEnvironment("development");
1384
- }
1385
- forProduction(token) {
1386
- return this.bindContextual(token).whenEnvironment("production");
1387
- }
1388
- forTesting(token) {
1389
- return this.bindContextual(token).whenEnvironment("test", "testing");
1390
- }
1391
- forStaging(token) {
1392
- return this.bindContextual(token).whenEnvironment("staging");
1393
- }
1394
- resolve(token, context) {
1395
- const resolutionContext = {
1396
- container: this,
1397
- token,
1398
- environment: context?.environment || this.environmentManager.getCurrentEnvironment(),
1399
- requestId: context?.requestId || this.generateContextualRequestId(),
1400
- depth: context?.depth || 0,
1401
- resolving: context?.resolving || new Set,
1402
- parent: context?.parent
1403
- };
1404
- const contextualBinding = this.findContextualBinding(token, resolutionContext);
1405
- if (contextualBinding) {
1406
- return this.createInstanceFromContextualBinding(contextualBinding, resolutionContext);
1407
- }
1408
- return super.resolve(token, resolutionContext);
1409
- }
1410
- findContextualBinding(token, context) {
1411
- const bindings = this.contextualBindings.get(token);
1412
- if (!bindings)
1413
- return;
1414
- for (const binding of bindings) {
1415
- if (this.evaluateConditions(binding.conditions, context)) {
1416
- return binding;
1417
- }
1418
- }
1419
- return;
1420
- }
1421
- evaluateConditions(conditions, context) {
1422
- return conditions.every((condition) => {
1423
- try {
1424
- return condition.predicate(context);
1425
- } catch (error) {
1426
- console.warn(`Error evaluating binding condition: ${condition.description}`, error);
1427
- return false;
1428
- }
1429
- });
1430
- }
1431
- createInstanceFromContextualBinding(binding, context) {
1432
- try {
1433
- return this.createInstance(binding, context);
1434
- } catch (error) {
1435
- if (binding.fallback) {
1436
- console.warn(`Contextual binding failed, using fallback for ${binding.token.toString()}`);
1437
- return this.createInstance(binding.fallback, context);
1438
- }
1439
- throw error;
1440
- }
1441
- }
1442
- generateContextualRequestId() {
1443
- return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1444
- }
1445
- }
1446
-
1447
- class EnvironmentPresets {
1448
- static development() {
1449
- return {
1450
- name: "development",
1451
- variables: {
1452
- DEBUG: true,
1453
- LOG_LEVEL: "debug",
1454
- CACHE_TTL: 60,
1455
- DB_POOL_SIZE: 5
1456
- },
1457
- services: {
1458
- logger: "ConsoleLogger",
1459
- cache: "MemoryCache",
1460
- database: "SQLiteDatabase"
1461
- },
1462
- features: ["hot-reload", "debug-toolbar", "detailed-errors"]
1463
- };
1464
- }
1465
- static production() {
1466
- return {
1467
- name: "production",
1468
- variables: {
1469
- DEBUG: false,
1470
- LOG_LEVEL: "error",
1471
- CACHE_TTL: 3600,
1472
- DB_POOL_SIZE: 20
1473
- },
1474
- services: {
1475
- logger: "FileLogger",
1476
- cache: "RedisCache",
1477
- database: "PostgreSQLDatabase"
1478
- },
1479
- features: ["performance-monitoring", "error-tracking"]
1480
- };
1481
- }
1482
- static testing() {
1483
- return {
1484
- name: "test",
1485
- variables: {
1486
- DEBUG: false,
1487
- LOG_LEVEL: "warn",
1488
- CACHE_TTL: 1,
1489
- DB_POOL_SIZE: 1
1490
- },
1491
- services: {
1492
- logger: "NullLogger",
1493
- cache: "MemoryCache",
1494
- database: "InMemoryDatabase"
1495
- },
1496
- features: ["test-doubles", "fast-teardown"]
1497
- };
1498
- }
1499
- static staging() {
1500
- return {
1501
- name: "staging",
1502
- variables: {
1503
- DEBUG: true,
1504
- LOG_LEVEL: "info",
1505
- CACHE_TTL: 1800,
1506
- DB_POOL_SIZE: 10
1507
- },
1508
- services: {
1509
- logger: "FileLogger",
1510
- cache: "RedisCache",
1511
- database: "PostgreSQLDatabase"
1512
- },
1513
- features: ["performance-monitoring", "debug-toolbar"]
1514
- };
1515
- }
1516
- }
1517
-
1518
- class BindingConditions {
1519
- static environment(...environments) {
1520
- return {
1521
- type: "environment",
1522
- predicate: (context) => environments.includes(context.environment || "development"),
1523
- description: `Environment is one of: ${environments.join(", ")}`
1524
- };
1525
- }
1526
- static feature(featureName) {
1527
- return {
1528
- type: "custom",
1529
- predicate: (context) => {
1530
- const container = context.container;
1531
- return container.getEnvironmentManager().hasFeature(featureName);
1532
- },
1533
- description: `Feature ${featureName} is enabled`
1534
- };
1535
- }
1536
- static envVar(key, value) {
1537
- return {
1538
- type: "custom",
1539
- predicate: (context) => {
1540
- const container = context.container;
1541
- return container.getEnvironmentManager().get(key) === value;
1542
- },
1543
- description: `Environment variable ${key} equals ${value}`
1544
- };
1545
- }
1546
- static requestPattern(pattern) {
1547
- return {
1548
- type: "request",
1549
- predicate: (context) => pattern.test(context.requestId || ""),
1550
- description: `Request ID matches pattern: ${pattern.toString()}`
1551
- };
1552
- }
1553
- static timeRange(startHour, endHour) {
1554
- return {
1555
- type: "custom",
1556
- predicate: () => {
1557
- const hour = new Date().getHours();
1558
- return hour >= startHour && hour <= endHour;
1559
- },
1560
- description: `Time is between ${startHour}:00 and ${endHour}:00`
1561
- };
1562
- }
1563
- static custom(predicate, description) {
1564
- return {
1565
- type: "custom",
1566
- predicate,
1567
- description: description || "Custom condition"
1568
- };
1569
- }
1570
- }
1571
-
1572
- // src/container/service-provider.ts
1573
- class BaseServiceProvider {
1574
- version;
1575
- dependencies;
1576
- environment;
1577
- priority = 0;
1578
- boot(_container) {}
1579
- shutdown(_container) {}
1580
- singleton(container, token, implementation) {
1581
- container.singleton(token, implementation);
1582
- }
1583
- transient(container, token, implementation) {
1584
- container.transient(token, implementation);
1585
- }
1586
- value(container, token, value) {
1587
- container.value(token, value);
1588
- }
1589
- factory(container, token, factory) {
1590
- container.factory(token, factory);
1591
- }
1592
- when(container, condition) {
1593
- return {
1594
- bind: (token) => {
1595
- return container.bind(token).when(condition);
1596
- }
1597
- };
1598
- }
1599
- forEnvironment(container, ...environments) {
1600
- return this.when(container, (context) => environments.includes(context.environment || "development"));
1601
- }
1602
- }
1603
-
1604
- class BaseDeferredServiceProvider extends BaseServiceProvider {
1605
- isDeferred() {
1606
- return true;
1607
- }
1608
- }
1609
-
1610
- class DefaultServiceProviderManager {
1611
- providers = new Map;
1612
- deferredProviders = new Map;
1613
- loadedProviders = new Set;
1614
- bootedProviders = new Set;
1615
- container;
1616
- constructor(container) {
1617
- this.container = container;
1618
- }
1619
- register(provider) {
1620
- if (this.isConditionalProvider(provider)) {
1621
- const shouldLoad = provider.shouldLoad(this.container);
1622
- if (shouldLoad instanceof Promise) {
1623
- shouldLoad.then((load) => {
1624
- if (load) {
1625
- this.doRegister(provider);
1626
- }
1627
- });
1628
- } else if (!shouldLoad) {
1629
- return this;
1630
- }
1631
- }
1632
- this.doRegister(provider);
1633
- return this;
1634
- }
1635
- async boot() {
1636
- const providers = Array.from(this.providers.values()).sort((a, b) => (b.priority || 0) - (a.priority || 0));
1637
- this.validateDependencies(providers);
1638
- for (const provider of providers) {
1639
- if (!this.loadedProviders.has(provider.name)) {
1640
- await this.loadProvider(provider);
1641
- }
1642
- }
1643
- for (const provider of providers) {
1644
- if (!this.bootedProviders.has(provider.name)) {
1645
- await this.bootProvider(provider);
1646
- }
1647
- }
1648
- }
1649
- async shutdown() {
1650
- const providers = Array.from(this.providers.values()).reverse();
1651
- for (const provider of providers) {
1652
- if (provider.shutdown) {
1653
- try {
1654
- await provider.shutdown(this.container);
1655
- } catch (error) {
1656
- console.error(`Error shutting down provider ${provider.name}:`, error);
1657
- }
1658
- }
1659
- }
1660
- this.providers.clear();
1661
- this.deferredProviders.clear();
1662
- this.loadedProviders.clear();
1663
- this.bootedProviders.clear();
1664
- }
1665
- getProvider(name) {
1666
- return this.providers.get(name);
1667
- }
1668
- getProviders() {
1669
- return Array.from(this.providers.values());
1670
- }
1671
- async loadDeferredProvider(token) {
1672
- for (const [name, provider] of this.deferredProviders) {
1673
- if (provider.provides().includes(token) && !this.loadedProviders.has(name)) {
1674
- await this.loadProvider(provider);
1675
- await this.bootProvider(provider);
1676
- this.deferredProviders.delete(name);
1677
- }
1678
- }
1679
- }
1680
- doRegister(provider) {
1681
- if (this.providers.has(provider.name)) {
1682
- throw new Error(`Provider ${provider.name} is already registered`);
1683
- }
1684
- this.providers.set(provider.name, provider);
1685
- if (this.isDeferredProvider(provider)) {
1686
- this.deferredProviders.set(provider.name, provider);
1687
- }
1688
- }
1689
- async loadProvider(provider) {
1690
- try {
1691
- await provider.register(this.container);
1692
- this.loadedProviders.add(provider.name);
1693
- } catch (error) {
1694
- throw new Error(`Failed to load provider ${provider.name}: ${error}`);
1695
- }
1696
- }
1697
- async bootProvider(provider) {
1698
- if (provider.boot) {
1699
- try {
1700
- await provider.boot(this.container);
1701
- this.bootedProviders.add(provider.name);
1702
- } catch (error) {
1703
- throw new Error(`Failed to boot provider ${provider.name}: ${error}`);
1704
- }
1705
- } else {
1706
- this.bootedProviders.add(provider.name);
1707
- }
1708
- }
1709
- validateDependencies(providers) {
1710
- const providerNames = new Set(providers.map((p) => p.name));
1711
- for (const provider of providers) {
1712
- if (provider.dependencies) {
1713
- for (const dependency of provider.dependencies) {
1714
- if (!providerNames.has(dependency)) {
1715
- throw new Error(`Provider ${provider.name} depends on ${dependency}, but it's not registered`);
1716
- }
1717
- }
1718
- }
1719
- }
1720
- }
1721
- isDeferredProvider(provider) {
1722
- return "provides" in provider && "isDeferred" in provider;
1723
- }
1724
- isConditionalProvider(provider) {
1725
- return "shouldLoad" in provider;
1726
- }
1727
- }
1728
-
1729
- class ConfigServiceProvider extends BaseServiceProvider {
1730
- name = "config";
1731
- priority = 100;
1732
- register(container) {
1733
- container.singleton("config", ConfigService);
1734
- this.forEnvironment(container, "development").bind("config.debug").toValue(true);
1735
- this.forEnvironment(container, "production").bind("config.debug").toValue(false);
1736
- this.forEnvironment(container, "test").bind("config.debug").toValue(false);
1737
- }
1738
- }
1739
-
1740
- class LoggingServiceProvider extends BaseServiceProvider {
1741
- name = "logging";
1742
- priority = 90;
1743
- register(container) {
1744
- container.factory("logger", (config) => {
1745
- return new Logger(config.get("logging", {}));
1746
- });
1747
- this.forEnvironment(container, "development").bind("logger").toFactory(() => new ConsoleLogger);
1748
- this.forEnvironment(container, "production").bind("logger").toFactory((config) => new FileLogger(config.get("logging.file", "./app.log")));
1749
- }
1750
- }
1751
-
1752
- class DatabaseServiceProvider extends BaseServiceProvider {
1753
- name = "database";
1754
- dependencies = ["config", "logging"];
1755
- register(container) {
1756
- container.singleton("database", DatabaseConnection);
1757
- container.transient("userRepository", UserRepository);
1758
- container.transient("postRepository", PostRepository);
1759
- }
1760
- async boot(container) {
1761
- const db = container.resolve("database");
1762
- await db.connect();
1763
- }
1764
- async shutdown(container) {
1765
- const db = container.resolve("database");
1766
- await db.disconnect();
1767
- }
1768
- }
1769
-
1770
- class CacheServiceProvider extends BaseServiceProvider {
1771
- name = "cache";
1772
- dependencies = ["config"];
1773
- register(container) {
1774
- container.singleton("cache", CacheManager);
1775
- this.forEnvironment(container, "development").bind("cache.store").toFactory(() => new MemoryCache);
1776
- this.forEnvironment(container, "production").bind("cache.store").toFactory((config) => new RedisCache(config.get("cache.redis")));
1777
- }
1778
- }
1779
-
1780
- class AuthServiceProvider extends BaseServiceProvider {
1781
- name = "auth";
1782
- dependencies = ["config", "database"];
1783
- register(container) {
1784
- container.singleton("authService", AuthService);
1785
- container.singleton("jwtService", JwtService);
1786
- container.transient("authGuard", AuthGuard);
1787
- }
1788
- }
1789
-
1790
- class ValidationServiceProvider extends BaseServiceProvider {
1791
- name = "validation";
1792
- register(container) {
1793
- container.singleton("validator", Validator);
1794
- container.factory("validationPipe", (validator) => new ValidationPipe(validator));
1795
- }
1796
- }
1797
-
1798
- class EventServiceProvider extends BaseDeferredServiceProvider {
1799
- name = "events";
1800
- provides() {
1801
- return ["eventBus", "eventDispatcher", EventBus, EventDispatcher];
1802
- }
1803
- register(container) {
1804
- container.singleton("eventBus", EventBus);
1805
- container.singleton("eventDispatcher", EventDispatcher);
1806
- }
1807
- }
1808
-
1809
- class ConfigService {
1810
- get(key, defaultValue) {
1811
- return defaultValue;
1812
- }
1813
- }
1814
-
1815
- class Logger {
1816
- config;
1817
- constructor(config) {
1818
- this.config = config;
1819
- }
1820
- log(message) {
1821
- console.log(message);
1822
- }
1823
- }
1824
-
1825
- class ConsoleLogger extends Logger {
1826
- constructor() {
1827
- super({});
1828
- }
1829
- }
1830
-
1831
- class FileLogger extends Logger {
1832
- filePath;
1833
- constructor(filePath) {
1834
- super({});
1835
- this.filePath = filePath;
1836
- }
1837
- }
1838
-
1839
- class DatabaseConnection {
1840
- async connect() {}
1841
- async disconnect() {}
1842
- }
1843
-
1844
- class UserRepository {
1845
- db;
1846
- constructor(db) {
1847
- this.db = db;
1848
- }
1849
- }
1850
-
1851
- class PostRepository {
1852
- db;
1853
- constructor(db) {
1854
- this.db = db;
1855
- }
1856
- }
1857
-
1858
- class CacheManager {
1859
- store;
1860
- constructor(store) {
1861
- this.store = store;
1862
- }
1863
- }
1864
-
1865
- class MemoryCache {
1866
- cache = new Map;
1867
- }
1868
-
1869
- class RedisCache {
1870
- config;
1871
- constructor(config) {
1872
- this.config = config;
1873
- }
1874
- }
1875
-
1876
- class AuthService {
1877
- jwt;
1878
- userRepo;
1879
- constructor(jwt, userRepo) {
1880
- this.jwt = jwt;
1881
- this.userRepo = userRepo;
1882
- }
1883
- }
1884
-
1885
- class JwtService {
1886
- config;
1887
- constructor(config) {
1888
- this.config = config;
1889
- }
1890
- }
1891
-
1892
- class AuthGuard {
1893
- auth;
1894
- constructor(auth) {
1895
- this.auth = auth;
1896
- }
1897
- }
1898
-
1899
- class Validator {
1900
- validate(_data, _rules) {
1901
- return true;
1902
- }
1903
- }
1904
-
1905
- class ValidationPipe {
1906
- validator;
1907
- constructor(validator) {
1908
- this.validator = validator;
1909
- }
1910
- }
1911
-
1912
- class EventBus {
1913
- emit(_event, _data) {}
1914
- }
1915
-
1916
- class EventDispatcher {
1917
- bus;
1918
- constructor(bus) {
1919
- this.bus = bus;
1920
- }
1921
- }
1922
-
1923
- export { RouterException, ValidationException, AuthenticationException, AuthorizationException, NotFoundException, MethodNotAllowedException, TimeoutException, RateLimitException, InternalServerException, ServiceUnavailableException, DatabaseException, ExternalServiceException, CircuitBreakerOpenException, BusinessLogicException, ConfigurationException, FileSystemException, ErrorFactory, RouteConflictException, CircularDependencyException, MiddlewareConfigurationException, RouteNotFoundException, HandlerResolutionException, ModelBindingException, findSimilarRoutes, detectRouteConflicts, RouterErrorFactory, INJECTABLE_METADATA_KEY, INJECT_METADATA_KEY, OPTIONAL_METADATA_KEY, TAGGED_METADATA_KEY, Container, BindingBuilder, getContainer, setContainer, createContainer, EnvironmentManager, DefaultContextualBindingBuilder, ContextualContainer, EnvironmentPresets, BindingConditions, BaseServiceProvider, BaseDeferredServiceProvider, DefaultServiceProviderManager, ConfigServiceProvider, LoggingServiceProvider, DatabaseServiceProvider, CacheServiceProvider, AuthServiceProvider, ValidationServiceProvider, EventServiceProvider, ConfigService, Logger, ConsoleLogger, FileLogger, DatabaseConnection, UserRepository, PostRepository, CacheManager, MemoryCache, RedisCache, AuthService, JwtService, AuthGuard, Validator, ValidationPipe, EventBus, EventDispatcher };