@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,684 +0,0 @@
1
- import type { Server } from 'bun'
2
- import type { EnhancedRequest, HTTPMethod, Route, ServerOptions } from '../types'
3
- import type { Router } from './router'
4
- import { getParsedCookies, getParsedURL, RequestWithMacros } from '../request/macros'
5
- import { runWithRequest, setCurrentRequest } from '../request/context'
6
- import { createHandlerInvoker } from './handler-resolver'
7
-
8
- // Helpers that frameworks layered on bun-router treat as guaranteed but
9
- // that aren't shaped as built-in macros. Registered once at module load —
10
- // they ride the shared macro prototype instead of being closure-assigned
11
- // per request. (`cookie` is already a built-in macro.)
12
- if (!RequestWithMacros.hasMacro('getParam')) {
13
- RequestWithMacros.macro('getParam', function (this: EnhancedRequest, name: string, defaultValue?: unknown) {
14
- const value = this.params?.[name]
15
- return value !== undefined ? value : defaultValue
16
- })
17
- }
18
- // `get(key)` — read query params (and only query params; the full input
19
- // merge with body etc. is provided by the `input` macro). Only registered
20
- // when no macro already claimed the name.
21
- if (!RequestWithMacros.hasMacro('get')) {
22
- RequestWithMacros.macro('get', function (this: EnhancedRequest, key: string, defaultValue?: unknown) {
23
- const value = getParsedURL(this).searchParams.get(key)
24
- return value !== null && value !== undefined ? value : defaultValue
25
- })
26
- }
27
- // `cookies` — dual-shape, mirroring the response macros (#1857): callable
28
- // as `req.cookies()` (the legacy built-in macro form, returns the parsed
29
- // map) while also carrying the name→value entries for direct access and
30
- // the get/set/delete/getAll utility methods `EnhancedRequest` declares.
31
- // Installed as a shared-prototype accessor: the hybrid materializes on
32
- // first access and is cached as an own property, so requests that never
33
- // touch cookies do zero cookie work.
34
- RequestWithMacros.macroAccessor('cookies', function (this: EnhancedRequest) {
35
- const req = this
36
- const cookies = (): Record<string, string> => ({ ...getParsedCookies(req) })
37
-
38
- // Direct map access (req.cookies.session). defineProperty instead of
39
- // Object.assign — a cookie literally named `name` or `length` would
40
- // collide with the function's own non-writable properties.
41
- for (const [key, value] of Object.entries(getParsedCookies(req))) {
42
- Object.defineProperty(cookies, key, {
43
- value,
44
- writable: true,
45
- enumerable: true,
46
- configurable: true,
47
- })
48
- }
49
-
50
- cookies.get = (name: string) => getParsedCookies(req)[name]
51
- cookies.set = (name: string, value: string, options: any = {}) => {
52
- if (!req._cookiesToSet) {
53
- req._cookiesToSet = []
54
- }
55
- req._cookiesToSet.push({ name, value, options })
56
- }
57
- cookies.delete = (name: string, options: any = {}) => {
58
- if (!req._cookiesToDelete) {
59
- req._cookiesToDelete = []
60
- }
61
- req._cookiesToDelete.push({ name, options })
62
- }
63
- cookies.getAll = () => ({ ...getParsedCookies(req) })
64
-
65
- Object.defineProperty(req, 'cookies', {
66
- value: cookies,
67
- writable: true,
68
- configurable: true,
69
- enumerable: true,
70
- })
71
- return cookies
72
- })
73
-
74
- /**
75
- * Server handling extension for Router class
76
- */
77
- // eslint-disable-next-line pickier/no-unused-vars -- false positive: used on the next line
78
- export function registerServerHandling(RouterClass: typeof Router): void {
79
- Object.defineProperties(RouterClass.prototype, {
80
- /**
81
- * Start the HTTP server
82
- */
83
- serve: {
84
- async value(options: ServerOptions = {}): Promise<Server<any>> {
85
- // Initialize automatic file-based routing (discovers views from src/views, views, etc.)
86
- if (this._initFileRoutes) {
87
- await this._initFileRoutes()
88
- }
89
-
90
- // Initialize automatic API route discovery (from routes/ directory)
91
- if (this._initApiRoutes) {
92
- await this._initApiRoutes()
93
- }
94
-
95
- // Invalidate route cache before starting server
96
- this.invalidateCache()
97
-
98
- // Create server options
99
- const serverOptions: any = {
100
- idleTimeout: 255, // Max allowed timeout (255 seconds)
101
- ...options,
102
- fetch: this.handleRequest.bind(this),
103
- }
104
-
105
- // Build Bun's static option from registered static Response routes.
106
- // Static responses use Bun's native zero-allocation dispatch (~15% faster).
107
- const staticRouteMap: Record<string, Response> = {}
108
- if (this.staticResponses && this.staticResponses.size > 0) {
109
- for (const [path, response] of this.staticResponses) {
110
- staticRouteMap[path] = response
111
- }
112
- }
113
- // Merge with user-provided static routes (user options take precedence)
114
- if (options.static) {
115
- Object.assign(staticRouteMap, options.static)
116
- }
117
- if (Object.keys(staticRouteMap).length > 0) {
118
- serverOptions.static = staticRouteMap
119
- }
120
-
121
- // Forward development options for HMR and console streaming
122
- if (options.development !== undefined) {
123
- serverOptions.development = options.development
124
- }
125
-
126
- // Opt-in: hand compatible routes to Bun's native router so they
127
- // skip the fetch handler's URL parsing and matching entirely.
128
- // Incompatible routes and 404/405/HEAD/preflight semantics keep
129
- // flowing through the fetch fallback unchanged.
130
- this._nativeRoutesEnabled = options.nativeRoutes === true
131
- if (this._nativeRoutesEnabled) {
132
- const nativeRoutes = this._buildNativeRoutes()
133
- if (nativeRoutes) {
134
- serverOptions.routes = nativeRoutes
135
- }
136
- }
137
-
138
- // Apply WebSocket configuration if provided
139
- if (this.wsConfig) {
140
- serverOptions.websocket = this.wsConfig
141
- }
142
-
143
- // Start the server
144
- this.serverInstance = Bun.serve(serverOptions)
145
-
146
- if (this.config.verbose) {
147
- const port = this.serverInstance.port
148
- const hostname = this.serverInstance.hostname
149
- console.log(`\n🚀 Server running at http://${hostname}:${port}\n`)
150
- }
151
-
152
- return this.serverInstance
153
- },
154
- writable: true,
155
- configurable: true,
156
- },
157
-
158
- /**
159
- * Reload the HTTP server
160
- */
161
- reload: {
162
- async value(): Promise<void> {
163
- if (!this.serverInstance) {
164
- throw new Error('Server not started, cannot reload')
165
- }
166
-
167
- // Invalidate route cache before reloading
168
- this.invalidateCache()
169
-
170
- // Save the current server port and hostname
171
- const port = this.serverInstance.port
172
- const hostname = this.serverInstance.hostname
173
-
174
- // Close the current server
175
- this.serverInstance.stop()
176
-
177
- // Start a new server with the same configuration. The native
178
- // route table is rebuilt so routes registered since serve()
179
- // join it.
180
- const reloadOptions: any = {
181
- port,
182
- hostname,
183
- fetch: this.handleRequest.bind(this),
184
- websocket: this.wsConfig || undefined,
185
- }
186
- if (this._nativeRoutesEnabled) {
187
- const nativeRoutes = this._buildNativeRoutes()
188
- if (nativeRoutes) {
189
- reloadOptions.routes = nativeRoutes
190
- }
191
- }
192
- this.serverInstance = Bun.serve(reloadOptions)
193
-
194
- if (this.config.verbose) {
195
- console.log(`🔄 Server reloaded at http://${hostname}:${port}`)
196
- }
197
- },
198
- writable: true,
199
- configurable: true,
200
- },
201
-
202
- /**
203
- * Handle HTTP requests
204
- */
205
- handleRequest: {
206
- async value(req: Request): Promise<Response> {
207
- // The prototype is mutated via defineProperties; the static type doesn't see
208
- // handleRequestImpl as a public method, so we cast through unknown.
209
- const self = this as unknown as { handleRequestImpl: (r: Request) => Promise<Response> }
210
- return runWithRequest(req as EnhancedRequest, () => self.handleRequestImpl(req))
211
- },
212
- writable: true,
213
- configurable: true,
214
- },
215
-
216
- /**
217
- * Internal: dispatch a matched route — enhance the request, run the
218
- * cached middleware chain (global + route middleware + handler) and
219
- * apply queued cookies. Shared by the fetch handler and the native
220
- * Bun route wrappers.
221
- */
222
- _dispatchMatchedRoute: {
223
- async value(matchedRoute: Route, req: Request, params: Record<string, string>): Promise<Response> {
224
- const enhancedReq = this.enhanceRequest(req, params)
225
- setCurrentRequest(enhancedReq)
226
-
227
- // Add the matched route to the request
228
- enhancedReq.route = matchedRoute
229
-
230
- // Resolve the middleware chain for this route. The composed
231
- // chain is cached on the route and only rebuilt when `use()`
232
- // registers new global middleware or the route's own stack
233
- // changes — building the closure chain per request was a
234
- // hot-path cost.
235
- const route = matchedRoute as Route & {
236
- _compiledChain?: (req: EnhancedRequest) => Promise<Response | null>
237
- _chainEpoch?: number
238
- _chainMwLen?: number
239
- }
240
- const epoch: number = this._mwEpoch || 0
241
- const routeMwLen = route.middleware ? route.middleware.length : 0
242
-
243
- let chain = route._compiledChain
244
- if (!chain || route._chainEpoch !== epoch || route._chainMwLen !== routeMwLen) {
245
- // The handler's dispatch branch (function vs class vs string
246
- // action) is resolved once here instead of per request
247
- const invoke = createHandlerInvoker(route.handler, this.config)
248
-
249
- if (routeMwLen === 0 && this.globalMiddleware.length === 0) {
250
- // No middleware: the chain is the bare invoker — no
251
- // closure tower, no next() allocations per request
252
- chain = invoke
253
- }
254
- else {
255
- const middlewareStack = routeMwLen > 0
256
- ? [...this.globalMiddleware, ...route.middleware]
257
- : [...this.globalMiddleware]
258
- middlewareStack.push((handlerReq: EnhancedRequest, _next: any) => invoke(handlerReq))
259
- chain = this.buildMiddlewareChain(middlewareStack)!
260
- }
261
- route._compiledChain = chain
262
- route._chainEpoch = epoch
263
- route._chainMwLen = routeMwLen
264
- }
265
-
266
- let response: Response | null
267
- try {
268
- response = await chain!(enhancedReq)
269
- }
270
- catch (error) {
271
- if (this.errorHandler) {
272
- response = await this.errorHandler(error as Error)
273
- }
274
- else {
275
- throw error
276
- }
277
- }
278
-
279
- // Apply modified cookies to the response
280
- if (response) {
281
- return this.applyModifiedCookies(response, enhancedReq)
282
- }
283
-
284
- // This should not happen since we're always returning a response now
285
- return new Response('No response from middleware chain', { status: 500 })
286
- },
287
- writable: true,
288
- configurable: true,
289
- },
290
-
291
- /**
292
- * Internal: build Bun.serve's native `routes` table from compatible
293
- * registered routes (see `ServerOptions.nativeRoutes`). Returns null
294
- * when nothing qualifies.
295
- */
296
- _buildNativeRoutes: {
297
- value(): Record<string, Record<string, (req: Request) => Promise<Response>>> | null {
298
- const NATIVE_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'])
299
-
300
- // Convert `{param}` paths to Bun's `:param` syntax. Returns null
301
- // for shapes the native router can't express with our semantics:
302
- // optional params, constraints, mixed segments like `user-{id}`,
303
- // and non-trailing wildcards.
304
- const convertPath = (path: string): string | null => {
305
- if (path === '*') {
306
- return '/*'
307
- }
308
- const segments = path.split('/')
309
- const converted: string[] = []
310
- for (let i = 0; i < segments.length; i++) {
311
- const segment = segments[i]
312
- if (segment === '') {
313
- converted.push(segment)
314
- continue
315
- }
316
- if (segment === '*') {
317
- // Wildcards only in the trailing position
318
- return i === segments.length - 1 ? [...converted, '*'].join('/') : null
319
- }
320
- const paramMatch = segment.match(/^\{([A-Z_$][\w$]*)\}$/i)
321
- if (paramMatch) {
322
- converted.push(`:${paramMatch[1]}`)
323
- continue
324
- }
325
- if (segment.includes('{') || segment.includes(':') || segment.includes('*')) {
326
- return null
327
- }
328
- converted.push(segment)
329
- }
330
- return converted.join('/')
331
- }
332
-
333
- // Wrap a route in the same context/error envelope the fetch
334
- // handler provides, so handlers can't tell which router matched
335
- const self = this
336
- const wrapRoute = (route: Route, isWildcard: boolean) => {
337
- return (req: Request & { params?: Record<string, string> }) => {
338
- return runWithRequest(req as EnhancedRequest, async () => {
339
- try {
340
- let params: Record<string, string> = req.params ?? {}
341
- if (isWildcard) {
342
- // Bun doesn't expose the wildcard remainder as a param;
343
- // mirror the fetch matcher's `wildcard` key
344
- const pathname = new URL(req.url).pathname
345
- const basePath = route.path === '*' ? '/' : route.path.slice(0, -1)
346
- params = { ...params, wildcard: pathname.slice(basePath.length) }
347
- }
348
- return await self._dispatchMatchedRoute(route, req, params)
349
- }
350
- catch (error) {
351
- console.error('Error handling request:', error)
352
- if (self.errorHandler) {
353
- return self.errorHandler(error as Error)
354
- }
355
- return new Response(JSON.stringify({
356
- success: false,
357
- message: 'Internal Server Error',
358
- error: error instanceof Error ? error.message : String(error),
359
- }), {
360
- status: 500,
361
- headers: {
362
- 'Content-Type': 'application/json',
363
- 'Access-Control-Allow-Origin': '*',
364
- 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
365
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With, Accept, Origin',
366
- },
367
- })
368
- }
369
- })
370
- }
371
- }
372
-
373
- const natives: Record<string, Record<string, (req: Request) => Promise<Response>>> = {}
374
- // Bun resolves same-shape patterns by specificity, not by our
375
- // registration order — only the first registration of a given
376
- // shape goes native; later ones would silently shadow it
377
- const claimedShapes = new Map<string, string>()
378
-
379
- for (const route of this.routes as Route[]) {
380
- if (!NATIVE_METHODS.has(route.method)) {
381
- continue
382
- }
383
- // Explicit per-route opt-out (router.withoutNativeDispatch())
384
- if (route.nativeDispatch === false) {
385
- continue
386
- }
387
- // Constrained params need our matcher
388
- if (route.constraints && Object.keys(route.constraints).length > 0) {
389
- continue
390
- }
391
- // Response-handler routes are already served via Bun's static map
392
- if (route.handler instanceof Response) {
393
- continue
394
- }
395
- const bunPath = convertPath(route.path)
396
- if (!bunPath) {
397
- continue
398
- }
399
-
400
- const shape = bunPath.replace(/:[^/]+/g, ':p')
401
- const claimedBy = claimedShapes.get(shape)
402
- if (claimedBy && claimedBy !== bunPath) {
403
- continue
404
- }
405
- claimedShapes.set(shape, bunPath)
406
-
407
- const entry = (natives[bunPath] ??= {})
408
- if (entry[route.method]) {
409
- continue // first registration wins, matching the fetch matcher
410
- }
411
- entry[route.method] = wrapRoute(route, route.path.endsWith('*'))
412
- }
413
-
414
- // GET routes answer HEAD automatically (mirrors the fetch
415
- // matcher's HEAD→GET fallback, but stays on the native fast path)
416
- for (const entry of Object.values(natives)) {
417
- if (entry.GET && !entry.HEAD) {
418
- entry.HEAD = entry.GET
419
- }
420
- }
421
-
422
- return Object.keys(natives).length > 0 ? natives : null
423
- },
424
- writable: true,
425
- configurable: true,
426
- },
427
-
428
- /**
429
- * Internal: actual request handling, executed inside the request context scope.
430
- */
431
- handleRequestImpl: {
432
- async value(req: Request): Promise<Response> {
433
- try {
434
- // Create URL for route matching, and share it with the request
435
- // macros (path()/root()/get()/fingerprint() reuse it instead of
436
- // reparsing req.url)
437
- const url = new URL(req.url)
438
- ;(req as any)._parsedURL = url
439
-
440
- // Get domain from the host header
441
- const hostname = url.hostname || req.headers.get('host')?.split(':')[0] || 'localhost'
442
-
443
- // Find a matching route
444
- const match = this.matchRoute(url.pathname, req.method as HTTPMethod, hostname)
445
-
446
- // CORS preflight: when no explicit OPTIONS route is registered,
447
- // answer with a generic preflight response. A request with an
448
- // Origin header gets that origin reflected (plus Vary: Origin)
449
- // so credentials stay usable — `Access-Control-Allow-Credentials`
450
- // combined with a wildcard origin is rejected by browsers.
451
- if (req.method === 'OPTIONS' && !match) {
452
- const origin = req.headers.get('origin')
453
- const preflightHeaders: Record<string, string> = {
454
- 'Access-Control-Allow-Origin': origin || '*',
455
- 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
456
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With, Accept, Origin',
457
- 'Access-Control-Max-Age': '86400',
458
- }
459
- if (origin) {
460
- preflightHeaders['Access-Control-Allow-Credentials'] = 'true'
461
- preflightHeaders.Vary = 'Origin'
462
- }
463
- return new Response(null, { status: 204, headers: preflightHeaders })
464
- }
465
-
466
- if (match) {
467
- return await this._dispatchMatchedRoute(match.route, req, match.params)
468
- }
469
-
470
- // Enhance the request with params and other utilities (the
471
- // matched-route path enhances inside _dispatchMatchedRoute)
472
- const enhancedReq = this.enhanceRequest(req, {})
473
- setCurrentRequest(enhancedReq)
474
-
475
- // No route found - check if the path exists with a different method (405 vs 404).
476
- // The 404/405 responses below now (a) include path + method in the body so client
477
- // debugging is one grep away, and (b) flow through globalMiddleware so cross-cutting
478
- // concerns (X-Request-ID, Server-Timing, audit logging, custom CORS) can observe
479
- // them. Previously these paths short-circuited entirely.
480
- const allowedMethods = this.getAllowedMethods(url.pathname, hostname)
481
- const corsHeaders = {
482
- 'Content-Type': 'application/json',
483
- 'Access-Control-Allow-Origin': '*',
484
- 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
485
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With, Accept, Origin',
486
- }
487
-
488
- if (allowedMethods.length > 0) {
489
- const methodNotAllowedHandler = async (_req: EnhancedRequest, _next: any) => {
490
- return new Response(JSON.stringify({
491
- success: false,
492
- message: 'Method Not Allowed',
493
- path: url.pathname,
494
- method: req.method,
495
- allowed: allowedMethods,
496
- }), {
497
- status: 405,
498
- headers: { ...corsHeaders, Allow: allowedMethods.join(', ') },
499
- })
500
- }
501
- if (this.globalMiddleware.length > 0) {
502
- const stack = [...this.globalMiddleware, methodNotAllowedHandler]
503
- const response = await this.runMiddleware(enhancedReq, stack)
504
- if (response) return this.applyModifiedCookies(response, enhancedReq)
505
- }
506
- return await methodNotAllowedHandler(enhancedReq, async () => null as any)
507
- }
508
-
509
- // No route found, try the fallback handler
510
- if (this.fallbackHandler) {
511
- const response = await this.resolveHandler(this.fallbackHandler, enhancedReq)
512
- return this.applyModifiedCookies(response, enhancedReq)
513
- }
514
-
515
- // No fallback — emit a 404 enriched with path + method, also through
516
- // globalMiddleware so user middleware sees it.
517
- const notFoundHandler = async (_req: EnhancedRequest, _next: any) => {
518
- return new Response(JSON.stringify({
519
- success: false,
520
- message: 'Not Found',
521
- path: url.pathname,
522
- method: req.method,
523
- }), { status: 404, headers: corsHeaders })
524
- }
525
- if (this.globalMiddleware.length > 0) {
526
- const stack = [...this.globalMiddleware, notFoundHandler]
527
- const response = await this.runMiddleware(enhancedReq, stack)
528
- if (response) return this.applyModifiedCookies(response, enhancedReq)
529
- }
530
- return await notFoundHandler(enhancedReq, async () => null as any)
531
- }
532
- catch (error) {
533
- console.error('Error handling request:', error)
534
-
535
- // Use custom error handler if available
536
- if (this.errorHandler) {
537
- return this.errorHandler(error as Error)
538
- }
539
-
540
- // Default error response with CORS headers
541
- return new Response(JSON.stringify({
542
- success: false,
543
- message: 'Internal Server Error',
544
- error: error instanceof Error ? error.message : String(error),
545
- }), {
546
- status: 500,
547
- headers: {
548
- 'Content-Type': 'application/json',
549
- 'Access-Control-Allow-Origin': '*',
550
- 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
551
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With, Accept, Origin',
552
- },
553
- })
554
- }
555
- },
556
- writable: true,
557
- configurable: true,
558
- },
559
-
560
- /**
561
- * Enhance a request with params and other utilities.
562
- *
563
- * Per-request work is intentionally minimal: assign `params` and
564
- * insert the shared macro prototype. Everything else (cookies,
565
- * input helpers, URL parsing) lives on the prototype and
566
- * materializes lazily on first access.
567
- */
568
- enhanceRequest: {
569
- value(req: Request, params: Record<string, string> = {}): EnhancedRequest {
570
- const enhancedReq = req as unknown as EnhancedRequest
571
- if ('params' in req) {
572
- // Bun's native-route requests expose `params` as a readonly
573
- // prototype getter — plain assignment throws. An own property
574
- // shadows it (and carries our augmentations, e.g. `wildcard`).
575
- Object.defineProperty(enhancedReq, 'params', {
576
- value: params,
577
- writable: true,
578
- configurable: true,
579
- enumerable: true,
580
- })
581
- }
582
- else {
583
- enhancedReq.params = params
584
- }
585
- RequestWithMacros.applyMacros(enhancedReq)
586
- return enhancedReq
587
- },
588
- writable: true,
589
- configurable: true,
590
- },
591
-
592
- /**
593
- * Apply modified cookies to a response
594
- */
595
- applyModifiedCookies: {
596
- value(response: Response, req: EnhancedRequest): Response {
597
- // Fast path: nothing to apply — return the response untouched
598
- // instead of paying for a clone on every request
599
- const hasSet = req._cookiesToSet && req._cookiesToSet.length > 0
600
- const hasDelete = req._cookiesToDelete && req._cookiesToDelete.length > 0
601
- if (!hasSet && !hasDelete) {
602
- return response
603
- }
604
-
605
- // Clone the response to modify headers
606
- const newResponse = new Response(response.body, {
607
- status: response.status,
608
- statusText: response.statusText,
609
- headers: response.headers,
610
- })
611
-
612
- // Apply cookies to set
613
- if (req._cookiesToSet && req._cookiesToSet.length > 0) {
614
- for (const { name, value, options } of req._cookiesToSet) {
615
- const cookieString = this.serializeCookie(name, value, options)
616
- newResponse.headers.append('Set-Cookie', cookieString)
617
- }
618
- }
619
-
620
- // Apply cookies to delete
621
- if (req._cookiesToDelete && req._cookiesToDelete.length > 0) {
622
- for (const { name, options } of req._cookiesToDelete) {
623
- const deletionOptions = {
624
- ...options,
625
- expires: new Date(0), // Set expiration to past date
626
- maxAge: 0,
627
- }
628
- const cookieString = this.serializeCookie(name, '', deletionOptions)
629
- newResponse.headers.append('Set-Cookie', cookieString)
630
- }
631
- }
632
-
633
- return newResponse
634
- },
635
- writable: true,
636
- configurable: true,
637
- },
638
-
639
- /**
640
- * Serialize a cookie for the Set-Cookie header
641
- */
642
- serializeCookie: {
643
- value(name: string, value: string, options: any = {}): string {
644
- let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`
645
-
646
- if (options.maxAge !== undefined) {
647
- cookie += `; Max-Age=${options.maxAge}`
648
- }
649
-
650
- if (options.expires && options.expires instanceof Date) {
651
- cookie += `; Expires=${options.expires.toUTCString()}`
652
- }
653
-
654
- if (options.path) {
655
- cookie += `; Path=${options.path}`
656
- }
657
- else {
658
- cookie += '; Path=/'
659
- }
660
-
661
- if (options.domain) {
662
- cookie += `; Domain=${options.domain}`
663
- }
664
-
665
- if (options.secure) {
666
- cookie += '; Secure'
667
- }
668
-
669
- if (options.httpOnly) {
670
- cookie += '; HttpOnly'
671
- }
672
-
673
- if (options.sameSite) {
674
- const sameSite = options.sameSite.toLowerCase()
675
- cookie += `; SameSite=${sameSite.charAt(0).toUpperCase() + sameSite.slice(1)}`
676
- }
677
-
678
- return cookie
679
- },
680
- writable: true,
681
- configurable: true,
682
- },
683
- })
684
- }