@stacksjs/bun-router 0.0.4 → 0.0.6

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 (272) hide show
  1. package/README.md +2 -2
  2. package/dist/auth.d.ts +134 -0
  3. package/dist/cache/lru-cache.d.ts +139 -0
  4. package/dist/cache/middleware-memoization.d.ts +151 -0
  5. package/dist/cache/route-cache-warmer.d.ts +161 -0
  6. package/dist/cache/sqlite-cache.d.ts +209 -0
  7. package/dist/cache/streaming-cache.d.ts +132 -0
  8. package/dist/chunk-jhsk5c5b.js +15758 -0
  9. package/dist/cli/colors.d.ts +15 -0
  10. package/dist/cli/index.d.ts +10 -0
  11. package/dist/cli/middleware.d.ts +31 -0
  12. package/dist/cli/openapi.d.ts +17 -0
  13. package/dist/cli/router.d.ts +15 -0
  14. package/dist/cli/routes.d.ts +29 -0
  15. package/dist/cli/utils.d.ts +74 -0
  16. package/dist/cli.d.ts +1 -1
  17. package/dist/cli.js +2 -2
  18. package/dist/config.d.ts +7 -0
  19. package/dist/container/container.d.ts +273 -0
  20. package/dist/container/contextual-binding.d.ts +240 -0
  21. package/dist/container/decorators.d.ts +141 -0
  22. package/dist/container/service-provider.d.ts +285 -0
  23. package/dist/development/hot-reload.d.ts +187 -0
  24. package/dist/development/index.d.ts +167 -0
  25. package/dist/development/performance-profiler.d.ts +217 -0
  26. package/dist/development/route-debugger.d.ts +154 -0
  27. package/dist/development/route-inspector.d.ts +211 -0
  28. package/dist/development/typescript-utilities.d.ts +209 -0
  29. package/dist/docs.d.ts +11 -0
  30. package/dist/errors/circuit-breaker.d.ts +195 -0
  31. package/dist/errors/error-handler.d.ts +88 -0
  32. package/dist/errors/error-reporting.d.ts +144 -0
  33. package/dist/errors/exceptions.d.ts +184 -0
  34. package/dist/errors/graceful-degradation.d.ts +154 -0
  35. package/dist/errors/index.d.ts +9 -0
  36. package/dist/errors/router-errors.d.ts +110 -0
  37. package/dist/file-serving/static-files.d.ts +143 -0
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +320 -206
  40. package/dist/middleware/auth.d.ts +63 -0
  41. package/dist/middleware/content_security_policy.d.ts +53 -0
  42. package/dist/middleware/cors.d.ts +5 -0
  43. package/dist/middleware/csrf.d.ts +7 -0
  44. package/dist/middleware/ddos_protection.d.ts +39 -0
  45. package/dist/middleware/file_security.d.ts +26 -0
  46. package/dist/middleware/file_upload.d.ts +38 -0
  47. package/dist/middleware/helmet.d.ts +54 -0
  48. package/dist/middleware/index.d.ts +44 -0
  49. package/dist/middleware/input_validation.d.ts +45 -0
  50. package/dist/middleware/json_body.d.ts +4 -0
  51. package/dist/middleware/performance_alerting.d.ts +87 -0
  52. package/dist/middleware/performance_dashboard.d.ts +87 -0
  53. package/dist/middleware/performance_monitor.d.ts +209 -0
  54. package/dist/middleware/pipeline.d.ts +131 -0
  55. package/dist/middleware/rate_limit.d.ts +36 -0
  56. package/dist/middleware/request_id.d.ts +4 -0
  57. package/dist/middleware/request_signing.d.ts +153 -0
  58. package/dist/middleware/request_tracer.d.ts +72 -0
  59. package/dist/middleware/response_cache.d.ts +97 -0
  60. package/dist/middleware/security.d.ts +69 -0
  61. package/dist/middleware/security_suite.d.ts +46 -0
  62. package/dist/middleware/session.d.ts +23 -0
  63. package/dist/model-binding/index.d.ts +2 -0
  64. package/dist/model-binding/model-middleware.d.ts +118 -0
  65. package/dist/model-binding/model-registry.d.ts +164 -0
  66. package/dist/model-binding.d.ts +185 -0
  67. package/dist/model-resolver-factory.d.ts +31 -0
  68. package/dist/observability/correlation.d.ts +187 -0
  69. package/dist/observability/health-checks.d.ts +186 -0
  70. package/dist/observability/index.d.ts +60 -0
  71. package/dist/observability/integration.d.ts +147 -0
  72. package/dist/observability/metrics.d.ts +184 -0
  73. package/dist/observability/tracing.d.ts +187 -0
  74. package/dist/optimization/bun-utilities.d.ts +224 -0
  75. package/dist/query-builder-integration.d.ts +36 -0
  76. package/dist/request/context.d.ts +34 -0
  77. package/dist/request/enhanced-request.d.ts +213 -0
  78. package/dist/request/macros.d.ts +300 -0
  79. package/dist/response/macros.d.ts +245 -0
  80. package/dist/response/response-factory.d.ts +133 -0
  81. package/dist/router/api-routes.d.ts +5 -0
  82. package/dist/router/file-based-routing.d.ts +118 -0
  83. package/dist/router/file-streaming.d.ts +5 -0
  84. package/dist/router/fluent-router.d.ts +315 -0
  85. package/dist/router/fluent-routing.d.ts +271 -0
  86. package/dist/router/group-organization.d.ts +5 -0
  87. package/dist/router/handler-resolver.d.ts +24 -0
  88. package/dist/router/http-methods.d.ts +10 -0
  89. package/dist/router/index.d.ts +113 -0
  90. package/dist/router/middleware-groups.d.ts +94 -0
  91. package/dist/router/middleware-integration.d.ts +112 -0
  92. package/dist/router/middleware.d.ts +5 -0
  93. package/dist/router/model-binding.d.ts +5 -0
  94. package/dist/router/optimized-route-matching.d.ts +6 -0
  95. package/dist/router/route-building.d.ts +5 -0
  96. package/dist/router/route-compiler.d.ts +153 -0
  97. package/dist/router/route-matching.d.ts +5 -0
  98. package/dist/router/route-trie.d.ts +114 -0
  99. package/dist/router/router.d.ts +276 -0
  100. package/dist/router/server.d.ts +5 -0
  101. package/dist/router/validation-integration.d.ts +170 -0
  102. package/dist/router/view-rendering.d.ts +5 -0
  103. package/dist/router/websocket.d.ts +5 -0
  104. package/dist/routing/route-caching.d.ts +129 -0
  105. package/dist/routing/route-throttling.d.ts +150 -0
  106. package/dist/routing/subdomain-routing.d.ts +206 -0
  107. package/dist/session/database-store.d.ts +51 -0
  108. package/dist/session/file-store.d.ts +22 -0
  109. package/dist/session/index.d.ts +106 -0
  110. package/dist/session/memory-store.d.ts +21 -0
  111. package/dist/session/redis-store.d.ts +31 -0
  112. package/dist/streaming/index.d.ts +3 -0
  113. package/dist/streaming/sse-handler.d.ts +138 -0
  114. package/dist/streaming/stream-handler.d.ts +114 -0
  115. package/dist/testing/auth-testing.d.ts +156 -0
  116. package/dist/testing/file-upload-testing.d.ts +190 -0
  117. package/dist/testing/index.d.ts +10 -0
  118. package/dist/testing/middleware-testing.d.ts +138 -0
  119. package/dist/testing/model-binding-testing.d.ts +186 -0
  120. package/dist/testing/performance-testing.d.ts +235 -0
  121. package/dist/testing/test-client.d.ts +117 -0
  122. package/dist/testing/test-request.d.ts +85 -0
  123. package/dist/testing/test-response.d.ts +90 -0
  124. package/dist/testing/types.d.ts +207 -0
  125. package/dist/testing/websocket-testing.d.ts +227 -0
  126. package/dist/types/controller-types.d.ts +208 -0
  127. package/dist/types/core.d.ts +543 -0
  128. package/dist/types/middleware-types.d.ts +227 -0
  129. package/dist/types/request-response-augmentation.d.ts +261 -0
  130. package/dist/types/route-inference.d.ts +168 -0
  131. package/dist/types.d.ts +1776 -0
  132. package/dist/url.d.ts +56 -0
  133. package/dist/utils/index.d.ts +1 -0
  134. package/dist/utils/query-preservation.d.ts +48 -0
  135. package/dist/utils.d.ts +69 -0
  136. package/dist/validation/validator.d.ts +140 -0
  137. package/dist/websocket/clustering.d.ts +185 -0
  138. package/package.json +18 -4
  139. package/src/auth.ts +469 -0
  140. package/src/cache/lru-cache.ts +457 -0
  141. package/src/cache/middleware-memoization.ts +531 -0
  142. package/src/cache/route-cache-warmer.ts +486 -0
  143. package/src/cache/sqlite-cache.ts +783 -0
  144. package/src/cache/streaming-cache.ts +572 -0
  145. package/src/cli/colors.ts +29 -0
  146. package/src/cli/index.ts +287 -0
  147. package/src/cli/middleware.ts +291 -0
  148. package/src/cli/openapi.ts +407 -0
  149. package/src/cli/router.ts +188 -0
  150. package/src/cli/routes.ts +265 -0
  151. package/src/cli/utils.ts +531 -0
  152. package/src/cli.ts +5 -0
  153. package/src/config.ts +322 -0
  154. package/src/container/container.ts +740 -0
  155. package/src/container/contextual-binding.ts +603 -0
  156. package/src/container/decorators.ts +359 -0
  157. package/src/container/service-provider.ts +596 -0
  158. package/src/development/hot-reload.ts +673 -0
  159. package/src/development/index.ts +499 -0
  160. package/src/development/performance-profiler.ts +717 -0
  161. package/src/development/route-debugger.ts +527 -0
  162. package/src/development/route-inspector.ts +749 -0
  163. package/src/development/typescript-utilities.ts +678 -0
  164. package/src/docs.ts +397 -0
  165. package/src/errors/circuit-breaker.ts +732 -0
  166. package/src/errors/error-handler.ts +569 -0
  167. package/src/errors/error-reporting.ts +672 -0
  168. package/src/errors/exceptions.ts +536 -0
  169. package/src/errors/graceful-degradation.ts +621 -0
  170. package/src/errors/index.ts +21 -0
  171. package/src/errors/router-errors.ts +632 -0
  172. package/src/file-serving/static-files.ts +581 -0
  173. package/src/index.ts +14 -0
  174. package/src/middleware/auth.ts +219 -0
  175. package/src/middleware/content_security_policy.ts +215 -0
  176. package/src/middleware/cors.ts +74 -0
  177. package/src/middleware/csrf.ts +108 -0
  178. package/src/middleware/ddos_protection.ts +255 -0
  179. package/src/middleware/file_security.ts +191 -0
  180. package/src/middleware/file_upload.ts +264 -0
  181. package/src/middleware/helmet.ts +268 -0
  182. package/src/middleware/index.ts +117 -0
  183. package/src/middleware/input_validation.ts +449 -0
  184. package/src/middleware/json_body.ts +37 -0
  185. package/src/middleware/performance_alerting.ts +538 -0
  186. package/src/middleware/performance_dashboard.ts +661 -0
  187. package/src/middleware/performance_monitor.ts +943 -0
  188. package/src/middleware/pipeline.ts +489 -0
  189. package/src/middleware/rate_limit.ts +245 -0
  190. package/src/middleware/request_id.ts +36 -0
  191. package/src/middleware/request_signing.ts +636 -0
  192. package/src/middleware/request_tracer.ts +636 -0
  193. package/src/middleware/response_cache.ts +743 -0
  194. package/src/middleware/security.ts +482 -0
  195. package/src/middleware/security_suite.ts +257 -0
  196. package/src/middleware/session.ts +91 -0
  197. package/src/model-binding/index.ts +18 -0
  198. package/src/model-binding/model-middleware.ts +425 -0
  199. package/src/model-binding/model-registry.ts +550 -0
  200. package/src/model-binding.ts +370 -0
  201. package/src/model-resolver-factory.ts +106 -0
  202. package/src/observability/correlation.ts +691 -0
  203. package/src/observability/health-checks.ts +729 -0
  204. package/src/observability/index.ts +184 -0
  205. package/src/observability/integration.ts +548 -0
  206. package/src/observability/metrics.ts +753 -0
  207. package/src/observability/tracing.ts +638 -0
  208. package/src/optimization/bun-utilities.ts +778 -0
  209. package/src/query-builder-integration.ts +137 -0
  210. package/src/request/context.ts +62 -0
  211. package/src/request/enhanced-request.ts +857 -0
  212. package/src/request/macros.ts +688 -0
  213. package/src/response/macros.ts +612 -0
  214. package/src/response/response-factory.ts +588 -0
  215. package/src/router/api-routes.ts +243 -0
  216. package/src/router/file-based-routing.ts +670 -0
  217. package/src/router/file-streaming.ts +372 -0
  218. package/src/router/fluent-router.ts +927 -0
  219. package/src/router/fluent-routing.ts +797 -0
  220. package/src/router/group-organization.ts +213 -0
  221. package/src/router/handler-resolver.ts +291 -0
  222. package/src/router/http-methods.ts +377 -0
  223. package/src/router/index.ts +185 -0
  224. package/src/router/middleware-groups.ts +222 -0
  225. package/src/router/middleware-integration.ts +399 -0
  226. package/src/router/middleware.ts +231 -0
  227. package/src/router/model-binding.ts +215 -0
  228. package/src/router/optimized-route-matching.ts +253 -0
  229. package/src/router/route-building.ts +212 -0
  230. package/src/router/route-compiler.ts +702 -0
  231. package/src/router/route-matching.ts +349 -0
  232. package/src/router/route-trie.ts +464 -0
  233. package/src/router/router.ts +1508 -0
  234. package/src/router/server.ts +406 -0
  235. package/src/router/validation-integration.ts +443 -0
  236. package/src/router/view-rendering.ts +233 -0
  237. package/src/router/websocket.ts +100 -0
  238. package/src/routing/route-caching.ts +402 -0
  239. package/src/routing/route-throttling.ts +469 -0
  240. package/src/routing/subdomain-routing.ts +492 -0
  241. package/src/session/database-store.ts +109 -0
  242. package/src/session/file-store.ts +148 -0
  243. package/src/session/index.ts +244 -0
  244. package/src/session/memory-store.ts +88 -0
  245. package/src/session/redis-store.ts +93 -0
  246. package/src/streaming/index.ts +17 -0
  247. package/src/streaming/sse-handler.ts +482 -0
  248. package/src/streaming/stream-handler.ts +552 -0
  249. package/src/testing/auth-testing.ts +446 -0
  250. package/src/testing/file-upload-testing.ts +543 -0
  251. package/src/testing/index.ts +10 -0
  252. package/src/testing/middleware-testing.ts +322 -0
  253. package/src/testing/model-binding-testing.ts +645 -0
  254. package/src/testing/performance-testing.ts +738 -0
  255. package/src/testing/test-client.ts +310 -0
  256. package/src/testing/test-request.ts +315 -0
  257. package/src/testing/test-response.ts +332 -0
  258. package/src/testing/types.ts +224 -0
  259. package/src/testing/websocket-testing.ts +590 -0
  260. package/src/types/controller-types.ts +385 -0
  261. package/src/types/core.ts +683 -0
  262. package/src/types/middleware-types.ts +419 -0
  263. package/src/types/request-response-augmentation.ts +489 -0
  264. package/src/types/route-inference.ts +357 -0
  265. package/src/types.ts +2049 -0
  266. package/src/url.ts +126 -0
  267. package/src/utils/index.ts +1 -0
  268. package/src/utils/query-preservation.ts +201 -0
  269. package/src/utils.ts +327 -0
  270. package/src/validation/validator.ts +685 -0
  271. package/src/websocket/clustering.ts +762 -0
  272. package/dist/chunk-cjdekj87.js +0 -25886
@@ -0,0 +1,636 @@
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
+ }