@stacksjs/bun-router 0.0.16 → 0.0.18

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 (176) hide show
  1. package/dist/auth.d.ts +22 -8
  2. package/dist/chunk-1ahs68ys.js +18 -0
  3. package/dist/{chunk-0145g1me.js → chunk-cgptvjdf.js} +147 -75
  4. package/dist/chunk-g3ybefhg.js +1923 -0
  5. package/dist/cli.js +3 -2
  6. package/dist/container/container.d.ts +1 -0
  7. package/dist/container/contextual-binding.d.ts +0 -1
  8. package/dist/container/decorators.d.ts +2 -5
  9. package/dist/container/index.d.ts +16 -0
  10. package/dist/container/index.js +322 -0
  11. package/dist/container/service-provider.d.ts +3 -3
  12. package/dist/development/performance-profiler.d.ts +3 -3
  13. package/dist/development/route-debugger.d.ts +1 -1
  14. package/dist/development/route-inspector.d.ts +2 -2
  15. package/dist/file-serving/static-files.d.ts +16 -0
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +1159 -1380
  18. package/dist/middleware/cors.d.ts +9 -0
  19. package/dist/middleware/csrf.d.ts +7 -0
  20. package/dist/middleware/ddos_protection.d.ts +16 -1
  21. package/dist/middleware/rate_limit.d.ts +7 -1
  22. package/dist/middleware/request_tracer.d.ts +15 -9
  23. package/dist/middleware/response_cache.d.ts +2 -1
  24. package/dist/observability/integration.d.ts +1 -1
  25. package/dist/request/context.d.ts +12 -1
  26. package/dist/request/macros.d.ts +40 -2
  27. package/dist/response/macros.d.ts +4 -4
  28. package/dist/router/fluent-routing.d.ts +50 -13
  29. package/dist/router/handler-resolver.d.ts +8 -0
  30. package/dist/router/index.d.ts +9 -7
  31. package/dist/router/route-compiler.d.ts +8 -10
  32. package/dist/router/route-trie.d.ts +7 -1
  33. package/dist/router/router.d.ts +13 -34
  34. package/dist/router/validation-integration.d.ts +10 -4
  35. package/dist/testing/performance-testing.d.ts +2 -2
  36. package/dist/testing/test-client.d.ts +1 -1
  37. package/dist/testing/websocket-testing.d.ts +1 -1
  38. package/dist/types/middleware-types.d.ts +1 -1
  39. package/dist/types/route-inference.d.ts +9 -2
  40. package/dist/types.d.ts +62 -9
  41. package/dist/utils.d.ts +1 -1
  42. package/package.json +12 -3
  43. package/dist/router/fluent-router.d.ts +0 -315
  44. package/src/auth.ts +0 -469
  45. package/src/cache/lru-cache.ts +0 -457
  46. package/src/cache/middleware-memoization.ts +0 -531
  47. package/src/cache/route-cache-warmer.ts +0 -486
  48. package/src/cache/sqlite-cache.ts +0 -783
  49. package/src/cache/streaming-cache.ts +0 -572
  50. package/src/cli/colors.ts +0 -29
  51. package/src/cli/index.ts +0 -287
  52. package/src/cli/middleware.ts +0 -291
  53. package/src/cli/openapi.ts +0 -407
  54. package/src/cli/router.ts +0 -188
  55. package/src/cli/routes.ts +0 -265
  56. package/src/cli/utils.ts +0 -531
  57. package/src/cli.ts +0 -5
  58. package/src/config.ts +0 -322
  59. package/src/container/container.ts +0 -740
  60. package/src/container/contextual-binding.ts +0 -603
  61. package/src/container/decorators.ts +0 -359
  62. package/src/container/service-provider.ts +0 -596
  63. package/src/development/hot-reload.ts +0 -673
  64. package/src/development/index.ts +0 -499
  65. package/src/development/performance-profiler.ts +0 -717
  66. package/src/development/route-debugger.ts +0 -527
  67. package/src/development/route-inspector.ts +0 -749
  68. package/src/development/typescript-utilities.ts +0 -682
  69. package/src/docs.ts +0 -397
  70. package/src/errors/circuit-breaker.ts +0 -732
  71. package/src/errors/error-handler.ts +0 -569
  72. package/src/errors/error-reporting.ts +0 -672
  73. package/src/errors/exceptions.ts +0 -536
  74. package/src/errors/graceful-degradation.ts +0 -621
  75. package/src/errors/index.ts +0 -21
  76. package/src/errors/router-errors.ts +0 -632
  77. package/src/file-serving/static-files.ts +0 -581
  78. package/src/index.ts +0 -14
  79. package/src/middleware/auth.ts +0 -220
  80. package/src/middleware/content_security_policy.ts +0 -215
  81. package/src/middleware/cors.ts +0 -74
  82. package/src/middleware/csrf.ts +0 -118
  83. package/src/middleware/ddos_protection.ts +0 -255
  84. package/src/middleware/file_security.ts +0 -191
  85. package/src/middleware/file_upload.ts +0 -275
  86. package/src/middleware/helmet.ts +0 -268
  87. package/src/middleware/index.ts +0 -117
  88. package/src/middleware/input_validation.ts +0 -449
  89. package/src/middleware/json_body.ts +0 -37
  90. package/src/middleware/performance_alerting.ts +0 -538
  91. package/src/middleware/performance_dashboard.ts +0 -661
  92. package/src/middleware/performance_monitor.ts +0 -943
  93. package/src/middleware/pipeline.ts +0 -489
  94. package/src/middleware/rate_limit.ts +0 -245
  95. package/src/middleware/request_id.ts +0 -36
  96. package/src/middleware/request_signing.ts +0 -636
  97. package/src/middleware/request_tracer.ts +0 -636
  98. package/src/middleware/response_cache.ts +0 -743
  99. package/src/middleware/security.ts +0 -482
  100. package/src/middleware/security_suite.ts +0 -257
  101. package/src/middleware/session.ts +0 -91
  102. package/src/model-binding/index.ts +0 -18
  103. package/src/model-binding/model-middleware.ts +0 -425
  104. package/src/model-binding/model-registry.ts +0 -550
  105. package/src/model-binding.ts +0 -370
  106. package/src/model-resolver-factory.ts +0 -106
  107. package/src/observability/correlation.ts +0 -691
  108. package/src/observability/health-checks.ts +0 -729
  109. package/src/observability/index.ts +0 -184
  110. package/src/observability/integration.ts +0 -548
  111. package/src/observability/metrics.ts +0 -753
  112. package/src/observability/tracing.ts +0 -638
  113. package/src/optimization/bun-utilities.ts +0 -778
  114. package/src/query-builder-integration.ts +0 -137
  115. package/src/request/context.ts +0 -62
  116. package/src/request/enhanced-request.ts +0 -857
  117. package/src/request/macros.ts +0 -688
  118. package/src/response/macros.ts +0 -665
  119. package/src/response/response-factory.ts +0 -596
  120. package/src/router/api-routes.ts +0 -243
  121. package/src/router/file-based-routing.ts +0 -690
  122. package/src/router/file-streaming.ts +0 -383
  123. package/src/router/fluent-router.ts +0 -927
  124. package/src/router/fluent-routing.ts +0 -797
  125. package/src/router/group-organization.ts +0 -213
  126. package/src/router/handler-resolver.ts +0 -291
  127. package/src/router/http-methods.ts +0 -377
  128. package/src/router/index.ts +0 -187
  129. package/src/router/middleware-groups.ts +0 -222
  130. package/src/router/middleware-integration.ts +0 -399
  131. package/src/router/middleware.ts +0 -231
  132. package/src/router/model-binding.ts +0 -215
  133. package/src/router/optimized-route-matching.ts +0 -253
  134. package/src/router/route-building.ts +0 -221
  135. package/src/router/route-compiler.ts +0 -702
  136. package/src/router/route-matching.ts +0 -349
  137. package/src/router/route-trie.ts +0 -464
  138. package/src/router/router.ts +0 -1604
  139. package/src/router/server.ts +0 -462
  140. package/src/router/validation-integration.ts +0 -443
  141. package/src/router/view-rendering.ts +0 -233
  142. package/src/router/websocket.ts +0 -100
  143. package/src/routing/route-caching.ts +0 -402
  144. package/src/routing/route-throttling.ts +0 -469
  145. package/src/routing/subdomain-routing.ts +0 -492
  146. package/src/session/database-store.ts +0 -109
  147. package/src/session/file-store.ts +0 -148
  148. package/src/session/index.ts +0 -244
  149. package/src/session/memory-store.ts +0 -88
  150. package/src/session/redis-store.ts +0 -93
  151. package/src/streaming/index.ts +0 -17
  152. package/src/streaming/sse-handler.ts +0 -482
  153. package/src/streaming/stream-handler.ts +0 -552
  154. package/src/testing/auth-testing.ts +0 -446
  155. package/src/testing/file-upload-testing.ts +0 -543
  156. package/src/testing/index.ts +0 -10
  157. package/src/testing/middleware-testing.ts +0 -322
  158. package/src/testing/model-binding-testing.ts +0 -645
  159. package/src/testing/performance-testing.ts +0 -738
  160. package/src/testing/test-client.ts +0 -310
  161. package/src/testing/test-request.ts +0 -315
  162. package/src/testing/test-response.ts +0 -332
  163. package/src/testing/types.ts +0 -224
  164. package/src/testing/websocket-testing.ts +0 -590
  165. package/src/types/controller-types.ts +0 -385
  166. package/src/types/core.ts +0 -683
  167. package/src/types/middleware-types.ts +0 -419
  168. package/src/types/request-response-augmentation.ts +0 -489
  169. package/src/types/route-inference.ts +0 -357
  170. package/src/types.ts +0 -2067
  171. package/src/url.ts +0 -126
  172. package/src/utils/index.ts +0 -1
  173. package/src/utils/query-preservation.ts +0 -201
  174. package/src/utils.ts +0 -392
  175. package/src/validation/validator.ts +0 -685
  176. package/src/websocket/clustering.ts +0 -762
@@ -1,636 +0,0 @@
1
- import type { EnhancedRequest, NextFunction } from '../types'
2
- import { config } from '../config'
3
-
4
- export interface TraceSpan {
5
- traceId: string
6
- spanId: string
7
- parentSpanId?: string
8
- operationName: string
9
- startTime: number
10
- endTime?: number
11
- duration?: number
12
- tags: Record<string, any>
13
- logs: Array<{
14
- timestamp: number
15
- level: 'debug' | 'info' | 'warn' | 'error'
16
- message: string
17
- fields?: Record<string, any>
18
- }>
19
- status: 'ok' | 'error' | 'timeout'
20
- error?: string
21
- stackTrace?: string[]
22
- }
23
-
24
- export interface TracingOptions {
25
- enabled?: boolean
26
- sampleRate?: number
27
- maxSpans?: number
28
- includeHeaders?: boolean
29
- includeQueryParams?: boolean
30
- includeRequestBody?: boolean
31
- includeResponseBody?: boolean
32
- maxBodySize?: number
33
- exporters?: Array<{
34
- type: 'console' | 'jaeger' | 'zipkin' | 'otlp' | 'custom'
35
- endpoint?: string
36
- headers?: Record<string, string>
37
- customExporter?: (spans: TraceSpan[]) => Promise<void>
38
- }>
39
- propagation?: {
40
- enabled?: boolean
41
- headers?: string[]
42
- }
43
- }
44
-
45
- export default class RequestTracer {
46
- private options: TracingOptions
47
- private spans: Map<string, TraceSpan> = new Map()
48
- private activeSpans: Map<string, string> = new Map() // requestId -> spanId
49
- private exportQueue: TraceSpan[] = []
50
- private exportInterval?: ReturnType<typeof setInterval>
51
-
52
- constructor(options: TracingOptions = {}) {
53
- const tracingConfig = (config.server?.performance?.monitoring as any)?.tracing || {}
54
-
55
- this.options = {
56
- enabled: options.enabled ?? tracingConfig.enabled ?? false,
57
- sampleRate: options.sampleRate ?? tracingConfig.sampleRate ?? 1.0,
58
- maxSpans: options.maxSpans ?? 10000,
59
- includeHeaders: options.includeHeaders ?? false,
60
- includeQueryParams: options.includeQueryParams ?? true,
61
- includeRequestBody: options.includeRequestBody ?? false,
62
- includeResponseBody: options.includeResponseBody ?? false,
63
- maxBodySize: options.maxBodySize ?? 1024 * 1024, // 1MB
64
- exporters: options.exporters ?? [{ type: 'console' }],
65
- propagation: {
66
- enabled: true,
67
- headers: ['x-trace-id', 'x-span-id', 'x-parent-span-id'],
68
- ...options.propagation,
69
- },
70
- }
71
-
72
- if (this.options.enabled) {
73
- this.startExportInterval()
74
- }
75
- }
76
-
77
- private startExportInterval(): void {
78
- this.exportInterval = setInterval(async () => {
79
- try {
80
- await this.exportSpans()
81
- }
82
- catch (error) {
83
- console.warn('Error exporting spans:', error)
84
- }
85
- }, 100) // Export every 100ms for faster testing
86
- }
87
-
88
- private shouldSample(): boolean {
89
- return Math.random() < (this.options.sampleRate || 1.0)
90
- }
91
-
92
- private generateId(): string {
93
- return Math.random().toString(36).substring(2, 15)
94
- + Math.random().toString(36).substring(2, 15)
95
- }
96
-
97
- private extractPropagationHeaders(req: EnhancedRequest): {
98
- traceId?: string
99
- parentSpanId?: string
100
- } {
101
- if (!this.options.propagation?.enabled) {
102
- return {}
103
- }
104
-
105
- const headers = this.options.propagation.headers || []
106
- let traceId: string | undefined
107
-
108
- // Try to find trace ID from configured headers
109
- for (const header of headers) {
110
- const value = req.headers.get(header)
111
- if (value) {
112
- traceId = value
113
- break
114
- }
115
- }
116
-
117
- // Look for parent span ID
118
- const parentSpanId = req.headers.get('x-parent-span-id') || undefined
119
-
120
- return { traceId, parentSpanId }
121
- }
122
-
123
- private async captureRequestBody(req: EnhancedRequest): Promise<any> {
124
- if (!this.options.includeRequestBody)
125
- return undefined
126
-
127
- try {
128
- const contentType = req.headers.get('content-type') || ''
129
- const contentLength = Number.parseInt(req.headers.get('content-length') || '0', 10)
130
-
131
- if (contentLength > (this.options.maxBodySize || 1024 * 1024)) {
132
- return { truncated: true, reason: 'Body too large', size: contentLength }
133
- }
134
-
135
- if (contentType.includes('application/json')) {
136
- const cloned = req.clone()
137
- return await cloned.json()
138
- }
139
- else if (contentType.includes('application/x-www-form-urlencoded')) {
140
- const cloned = req.clone()
141
- const formData = await cloned.formData()
142
- const result: Record<string, any> = {}
143
- for (const [key, value] of (formData as any).entries()) {
144
- result[key] = value
145
- }
146
- return result
147
- }
148
- else if (contentType.includes('text/')) {
149
- const cloned = req.clone()
150
- return await cloned.text()
151
- }
152
- }
153
- catch (error) {
154
- return { error: 'Failed to capture body', message: error instanceof Error ? error.message : String(error) }
155
- }
156
-
157
- return undefined
158
- }
159
-
160
- private async captureResponseBody(response: Response): Promise<any> {
161
- if (!this.options.includeResponseBody)
162
- return undefined
163
-
164
- try {
165
- const contentType = response.headers.get('content-type') || ''
166
- const contentLength = Number.parseInt(response.headers.get('content-length') || '0', 10)
167
-
168
- if (contentLength > (this.options.maxBodySize || 1024 * 1024)) {
169
- return { truncated: true, reason: 'Body too large', size: contentLength }
170
- }
171
-
172
- if (contentType.includes('application/json')) {
173
- const cloned = response.clone()
174
- return await cloned.json()
175
- }
176
- else if (contentType.includes('text/')) {
177
- const cloned = response.clone()
178
- return await cloned.text()
179
- }
180
- }
181
- catch (error) {
182
- return { error: 'Failed to capture body', message: error instanceof Error ? error.message : String(error) }
183
- }
184
-
185
- return undefined
186
- }
187
-
188
- private createSpan(
189
- traceId: string,
190
- spanId: string,
191
- operationName: string,
192
- parentSpanId?: string,
193
- ): TraceSpan {
194
- return {
195
- traceId,
196
- spanId,
197
- parentSpanId,
198
- operationName,
199
- startTime: performance.now(),
200
- tags: {},
201
- logs: [],
202
- status: 'ok',
203
- }
204
- }
205
-
206
- private addSpanTag(spanId: string, key: string, value: any): void {
207
- const span = this.spans.get(spanId)
208
- if (span) {
209
- span.tags[key] = value
210
- }
211
- }
212
-
213
- private addSpanLog(
214
- spanId: string,
215
- level: 'debug' | 'info' | 'warn' | 'error',
216
- message: string,
217
- fields?: Record<string, any>,
218
- ): void {
219
- const span = this.spans.get(spanId)
220
- if (span) {
221
- span.logs.push({
222
- timestamp: performance.now(),
223
- level,
224
- message,
225
- fields,
226
- })
227
- }
228
- }
229
-
230
- private finishSpan(spanId: string, status: 'ok' | 'error' | 'timeout' = 'ok', error?: string): void {
231
- const span = this.spans.get(spanId)
232
- if (span) {
233
- span.endTime = performance.now()
234
- span.duration = span.endTime - span.startTime
235
- span.status = status
236
- if (error) {
237
- span.error = error
238
- if (this.options.includeHeaders) {
239
- span.stackTrace = new Error('Trace error stack').stack?.split('\n')
240
- }
241
- }
242
-
243
- // Move to export queue
244
- this.exportQueue.push(span)
245
- this.spans.delete(spanId)
246
- }
247
- }
248
-
249
- private async exportSpans(): Promise<void> {
250
- // For debugging
251
- console.warn(`[RequestTracer] Exporting spans, queue size: ${this.exportQueue.length}, active spans: ${this.spans.size}`)
252
-
253
- if (this.exportQueue.length === 0) {
254
- // Also check if there are any finished spans that need to be exported
255
- // This ensures spans are exported even if they weren't properly moved to the queue
256
- const finishedSpans = Array.from(this.spans.values()).filter(span => span.endTime !== undefined)
257
- if (finishedSpans.length > 0) {
258
- console.warn(`[RequestTracer] Found ${finishedSpans.length} finished spans to export`)
259
- // Move finished spans to export queue
260
- this.exportQueue.push(...finishedSpans)
261
- // Remove them from the spans map
262
- for (const span of finishedSpans) {
263
- this.spans.delete(span.spanId)
264
- }
265
- }
266
-
267
- // If still no spans to export, return
268
- if (this.exportQueue.length === 0) {
269
- return
270
- }
271
- }
272
-
273
- const spansToExport = [...this.exportQueue]
274
- this.exportQueue = []
275
-
276
- // Make sure we have exporters configured
277
- const exporters = this.options.exporters || []
278
- if (exporters.length === 0) {
279
- // Default to console if no exporters configured
280
- this.exportToConsole(spansToExport)
281
- return
282
- }
283
-
284
- for (const exporter of exporters) {
285
- try {
286
- switch (exporter.type) {
287
- case 'console':
288
- this.exportToConsole(spansToExport)
289
- break
290
- case 'jaeger':
291
- await this.exportToJaeger(spansToExport, exporter)
292
- break
293
- case 'zipkin':
294
- await this.exportToZipkin(spansToExport, exporter)
295
- break
296
- case 'custom':
297
- if (typeof exporter.customExporter === 'function') {
298
- await exporter.customExporter(spansToExport)
299
- }
300
- break
301
- }
302
- }
303
- catch (error) {
304
- // Use allowed console method
305
- console.warn(`Failed to export spans to ${exporter.type}:`, error)
306
- }
307
- }
308
- }
309
-
310
- private exportToConsole(spans: TraceSpan[]): void {
311
- for (const span of spans) {
312
- // Use allowed console method
313
- console.warn('Trace Span:', {
314
- traceId: span.traceId,
315
- spanId: span.spanId,
316
- operation: span.operationName,
317
- duration: `${Math.round((span.duration || 0) * 100) / 100}ms`,
318
- status: span.status,
319
- tags: span.tags,
320
- logs: span.logs.length,
321
- error: span.error,
322
- })
323
- }
324
- }
325
-
326
- private async exportToJaeger(spans: TraceSpan[], exporter: any): Promise<void> {
327
- if (!exporter.endpoint)
328
- return
329
-
330
- const jaegerSpans = spans.map(span => ({
331
- traceID: span.traceId,
332
- spanID: span.spanId,
333
- parentSpanID: span.parentSpanId,
334
- operationName: span.operationName,
335
- startTime: Math.floor(span.startTime * 1000), // microseconds
336
- duration: Math.floor((span.duration || 0) * 1000),
337
- tags: Object.entries(span.tags).map(([key, value]) => ({
338
- key,
339
- type: typeof value === 'string' ? 'string' : 'number',
340
- value: String(value),
341
- })),
342
- logs: span.logs.map(log => ({
343
- timestamp: Math.floor(log.timestamp * 1000),
344
- fields: [
345
- { key: 'level', value: log.level },
346
- { key: 'message', value: log.message },
347
- ...(log.fields ? Object.entries(log.fields).map(([k, v]) => ({ key: k, value: String(v) })) : []),
348
- ],
349
- })),
350
- process: {
351
- serviceName: 'bun-router',
352
- tags: [
353
- { key: 'hostname', value: Bun.env.HOSTNAME || 'localhost' },
354
- { key: 'pid', value: String(123) }, // Use a placeholder since Bun.pid is not available
355
- ],
356
- },
357
- }))
358
-
359
- await fetch(`${exporter.endpoint}/api/traces`, {
360
- method: 'POST',
361
- headers: {
362
- 'Content-Type': 'application/json',
363
- ...exporter.headers,
364
- },
365
- body: JSON.stringify({ data: [{ spans: jaegerSpans }] }),
366
- })
367
- }
368
-
369
- private async exportToZipkin(spans: TraceSpan[], exporter: any): Promise<void> {
370
- if (!exporter.endpoint)
371
- return
372
-
373
- const zipkinSpans = spans.map(span => ({
374
- traceId: span.traceId,
375
- id: span.spanId,
376
- parentId: span.parentSpanId,
377
- name: span.operationName,
378
- timestamp: Math.floor(span.startTime * 1000), // microseconds
379
- duration: Math.floor((span.duration || 0) * 1000),
380
- kind: 'SERVER',
381
- localEndpoint: {
382
- serviceName: 'bun-router',
383
- },
384
- tags: span.tags,
385
- annotations: span.logs.map(log => ({
386
- timestamp: Math.floor(log.timestamp * 1000),
387
- value: `${log.level}: ${log.message}`,
388
- })),
389
- }))
390
-
391
- await fetch(`${exporter.endpoint}/api/v2/spans`, {
392
- method: 'POST',
393
- headers: {
394
- 'Content-Type': 'application/json',
395
- ...exporter.headers,
396
- },
397
- body: JSON.stringify(zipkinSpans),
398
- })
399
- }
400
-
401
- async handle(req: EnhancedRequest, next: NextFunction): Promise<Response> {
402
- if (!this.options.enabled || !this.shouldSample()) {
403
- const response = await next()
404
- return response || new Response('Internal Server Error', { status: 500 })
405
- }
406
-
407
- const requestId = req.requestId || this.generateId()
408
- const propagation = this.extractPropagationHeaders(req)
409
- const traceId = propagation.traceId || this.generateId()
410
- const spanId = this.generateId()
411
- const url = new URL(req.url)
412
-
413
- // For debugging
414
- console.warn(`[RequestTracer] Creating span for ${req.method} ${url.pathname}, traceId=${traceId}, spanId=${spanId}`)
415
-
416
- // Create main request span
417
- const span = this.createSpan(
418
- traceId,
419
- spanId,
420
- `${req.method} ${url.pathname}`,
421
- propagation.parentSpanId,
422
- )
423
-
424
- this.spans.set(spanId, span)
425
- this.activeSpans.set(requestId, spanId)
426
-
427
- // Add trace info to request
428
- req.traceId = traceId
429
- req.spanId = spanId
430
-
431
- // Ensure these properties are accessible
432
- Object.defineProperties(req, {
433
- traceId: {
434
- value: traceId,
435
- writable: true,
436
- enumerable: true,
437
- configurable: true,
438
- },
439
- spanId: {
440
- value: spanId,
441
- writable: true,
442
- enumerable: true,
443
- configurable: true,
444
- },
445
- })
446
-
447
- // Add basic tags
448
- this.addSpanTag(spanId, 'http.method', req.method)
449
- this.addSpanTag(spanId, 'http.url', req.url)
450
- this.addSpanTag(spanId, 'http.path', url.pathname)
451
- this.addSpanTag(spanId, 'user_agent', req.headers.get('user-agent'))
452
-
453
- if (this.options.includeHeaders) {
454
- const headers: Record<string, string> = {}
455
- for (const [key, value] of req.headers.entries()) {
456
- headers[key] = value
457
- }
458
- this.addSpanTag(spanId, 'http.headers', headers)
459
- }
460
-
461
- if (this.options.includeQueryParams && url.searchParams.size > 0) {
462
- const params: Record<string, string> = {}
463
- for (const [key, value] of url.searchParams.entries()) {
464
- params[key] = value
465
- }
466
- this.addSpanTag(spanId, 'http.query_params', params)
467
- }
468
-
469
- // Capture request body if enabled
470
- if (this.options.includeRequestBody && req.method !== 'GET' && req.method !== 'HEAD') {
471
- try {
472
- const body = await this.captureRequestBody(req)
473
- if (body !== undefined) {
474
- this.addSpanTag(spanId, 'http.request_body', body)
475
- }
476
- }
477
- catch (error) {
478
- this.addSpanLog(spanId, 'warn', 'Failed to capture request body', { error: String(error) })
479
- }
480
- }
481
-
482
- this.addSpanLog(spanId, 'info', 'Request started')
483
-
484
- let response: Response
485
- let error: string | undefined
486
-
487
- try {
488
- const nextResponse = await next()
489
- response = nextResponse || new Response('Internal Server Error', { status: 500 })
490
-
491
- // Add response tags
492
- this.addSpanTag(spanId, 'http.status_code', response.status)
493
- this.addSpanTag(spanId, 'http.status_text', response.statusText)
494
-
495
- if (this.options.includeResponseBody) {
496
- try {
497
- const body = await this.captureResponseBody(response)
498
- if (body !== undefined) {
499
- this.addSpanTag(spanId, 'http.response_body', body)
500
- }
501
- }
502
- catch (err) {
503
- this.addSpanLog(spanId, 'warn', 'Failed to capture response body', { error: String(err) })
504
- }
505
- }
506
-
507
- this.addSpanLog(spanId, 'info', 'Request completed', {
508
- status: response.status,
509
- statusText: response.statusText,
510
- })
511
-
512
- // Mark as error if status code is 4xx or 5xx
513
- const isError = response.status >= 400
514
- if (isError) {
515
- this.addSpanTag(spanId, 'error', true)
516
- this.addSpanTag(spanId, 'error.status_code', response.status)
517
- }
518
-
519
- this.finishSpan(spanId, isError ? 'error' : 'ok', isError ? `HTTP ${response.status}` : undefined)
520
- }
521
- catch (err) {
522
- error = err instanceof Error ? err.message : String(err)
523
- this.addSpanTag(spanId, 'error', true)
524
- this.addSpanTag(spanId, 'error.message', error)
525
- this.addSpanTag(spanId, 'error.type', err instanceof Error ? err.constructor.name : 'Unknown')
526
- this.addSpanLog(spanId, 'error', 'Request failed', { error })
527
-
528
- // Ensure the span is properly finished with error status
529
- this.finishSpan(spanId, 'error', error)
530
-
531
- // Force immediate export of this error span
532
- const errorSpan = this.spans.get(spanId)
533
- if (errorSpan) {
534
- // Make sure it's finished
535
- if (errorSpan.endTime === undefined) {
536
- errorSpan.endTime = performance.now()
537
- errorSpan.duration = errorSpan.endTime - errorSpan.startTime
538
- errorSpan.status = 'error'
539
- errorSpan.error = error
540
- }
541
-
542
- // Add to export queue and remove from spans
543
- this.exportQueue.push(errorSpan)
544
- this.spans.delete(spanId)
545
-
546
- // Force immediate export
547
- this.exportSpans().catch((exportErr) => {
548
- console.warn('Failed to export error span:', exportErr)
549
- })
550
- }
551
-
552
- response = new Response('Internal Server Error', { status: 500 })
553
- }
554
-
555
- // Cleanup
556
- this.activeSpans.delete(requestId)
557
-
558
- // Add trace headers to response for propagation
559
- if (this.options.propagation?.enabled) {
560
- response.headers.set('x-trace-id', traceId)
561
- response.headers.set('x-span-id', spanId)
562
- }
563
-
564
- return response
565
- }
566
-
567
- // Public API methods
568
- getActiveSpans(): TraceSpan[] {
569
- return Array.from(this.spans.values())
570
- }
571
-
572
- getSpanById(spanId: string): TraceSpan | undefined {
573
- return this.spans.get(spanId)
574
- }
575
-
576
- createChildSpan(parentSpanId: string, operationName: string): string | null {
577
- const parentSpan = this.spans.get(parentSpanId)
578
- if (!parentSpan)
579
- return null
580
-
581
- const childSpanId = this.generateId()
582
- const childSpan = this.createSpan(
583
- parentSpan.traceId,
584
- childSpanId,
585
- operationName,
586
- parentSpanId,
587
- )
588
-
589
- this.spans.set(childSpanId, childSpan)
590
- return childSpanId
591
- }
592
-
593
- addTag(spanId: string, key: string, value: any): void {
594
- this.addSpanTag(spanId, key, value)
595
- }
596
-
597
- addLog(spanId: string, level: 'debug' | 'info' | 'warn' | 'error', message: string, fields?: Record<string, any>): void {
598
- this.addSpanLog(spanId, level, message, fields)
599
- }
600
-
601
- finish(spanId: string, status: 'ok' | 'error' | 'timeout' = 'ok', error?: string): void {
602
- this.finishSpan(spanId, status, error)
603
- }
604
-
605
- async flush(): Promise<void> {
606
- // Force all active spans to be finished and exported
607
- const activeSpanIds = Array.from(this.spans.keys())
608
- console.warn(`[RequestTracer] Flushing ${activeSpanIds.length} active spans`)
609
-
610
- // Finish any active spans
611
- for (const spanId of activeSpanIds) {
612
- const span = this.spans.get(spanId)
613
- if (span && !span.endTime) {
614
- this.finishSpan(spanId, 'ok')
615
- }
616
- }
617
-
618
- // Export all spans in the queue
619
- await this.exportSpans()
620
- }
621
-
622
- destroy(): void {
623
- if (this.exportInterval) {
624
- clearInterval(this.exportInterval)
625
- }
626
- this.spans.clear()
627
- this.activeSpans.clear()
628
- this.exportQueue = []
629
- }
630
- }
631
-
632
- // Factory function for easy use
633
- export function requestTracer(options: TracingOptions = {}): (req: EnhancedRequest, next: NextFunction) => Promise<Response> {
634
- const instance = new RequestTracer(options)
635
- return async (req: EnhancedRequest, next: NextFunction) => instance.handle(req, next)
636
- }