burger-api 0.9.6 → 1.0.0-beta

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 (175) hide show
  1. package/README.md +84 -241
  2. package/dist/src/adapter/bun/index.d.ts +14 -0
  3. package/dist/src/adapter/bun/index.js +73 -0
  4. package/dist/src/adapter/bun/types.d.ts +15 -0
  5. package/dist/src/adapter/bun/types.js +1 -0
  6. package/dist/src/adapter/index.d.ts +1 -0
  7. package/dist/src/adapter/index.js +1 -0
  8. package/dist/src/adapter/types.d.ts +49 -0
  9. package/dist/src/adapter/types.js +1 -0
  10. package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
  11. package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
  12. package/dist/src/adapter/web-standard/index.d.ts +8 -0
  13. package/dist/src/adapter/web-standard/index.js +7 -0
  14. package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
  15. package/dist/src/analysis/route-access-analyzer.js +287 -0
  16. package/dist/src/chain/chain.d.ts +16 -0
  17. package/dist/src/chain/chain.js +17 -0
  18. package/dist/src/chain/flattener.d.ts +3 -0
  19. package/dist/src/chain/flattener.js +78 -0
  20. package/dist/src/chain/node.d.ts +25 -0
  21. package/dist/src/chain/node.js +1 -0
  22. package/dist/src/compiler/conventions.d.ts +67 -0
  23. package/dist/src/compiler/conventions.js +129 -0
  24. package/dist/src/compiler/index.d.ts +13 -0
  25. package/dist/src/compiler/index.js +11 -0
  26. package/dist/src/compiler/module-loader.d.ts +75 -0
  27. package/dist/src/compiler/module-loader.js +276 -0
  28. package/dist/src/compiler/route-module.d.ts +97 -0
  29. package/dist/src/compiler/route-module.js +1 -0
  30. package/dist/src/compiler/route-tree.d.ts +19 -0
  31. package/dist/src/compiler/route-tree.js +28 -0
  32. package/dist/src/compiler/scanner.d.ts +42 -0
  33. package/dist/src/compiler/scanner.js +201 -0
  34. package/dist/src/context/context-set.d.ts +26 -0
  35. package/dist/src/context/context-set.js +45 -0
  36. package/dist/src/context/context.d.ts +357 -0
  37. package/dist/src/context/context.js +401 -0
  38. package/dist/src/context/query-parser.d.ts +23 -0
  39. package/dist/src/context/query-parser.js +132 -0
  40. package/dist/src/context/route-access.d.ts +7 -0
  41. package/dist/src/context/route-access.js +18 -0
  42. package/dist/src/context/types.d.ts +62 -0
  43. package/dist/src/context/types.js +5 -0
  44. package/dist/src/core/asset-mime.d.ts +9 -0
  45. package/dist/src/core/asset-mime.js +35 -0
  46. package/dist/src/core/assets.d.ts +30 -0
  47. package/dist/src/core/assets.js +67 -0
  48. package/dist/src/core/docs-providers.d.ts +13 -0
  49. package/dist/src/core/docs-providers.js +89 -0
  50. package/dist/src/core/embedded-assets.d.ts +18 -0
  51. package/dist/src/core/embedded-assets.js +13 -0
  52. package/dist/src/core/openapi.d.ts +9 -10
  53. package/dist/src/core/openapi.js +333 -127
  54. package/dist/src/core/page-router.d.ts +13 -17
  55. package/dist/src/core/page-router.js +86 -55
  56. package/dist/src/core/server.d.ts +20 -11
  57. package/dist/src/core/server.js +41 -45
  58. package/dist/src/errors/forbidden.d.ts +14 -0
  59. package/dist/src/errors/forbidden.js +16 -0
  60. package/dist/src/errors/http-error.d.ts +47 -0
  61. package/dist/src/errors/http-error.js +146 -0
  62. package/dist/src/errors/method-not-allowed.d.ts +13 -0
  63. package/dist/src/errors/method-not-allowed.js +15 -0
  64. package/dist/src/errors/not-found.d.ts +14 -0
  65. package/dist/src/errors/not-found.js +16 -0
  66. package/dist/src/errors/unauthorized.d.ts +14 -0
  67. package/dist/src/errors/unauthorized.js +16 -0
  68. package/dist/src/index.d.ts +263 -50
  69. package/dist/src/index.js +919 -332
  70. package/dist/src/lifecycle/executor.d.ts +64 -0
  71. package/dist/src/lifecycle/executor.js +201 -0
  72. package/dist/src/lifecycle/hook-runner.d.ts +11 -0
  73. package/dist/src/lifecycle/hook-runner.js +156 -0
  74. package/dist/src/lifecycle/jit.d.ts +50 -0
  75. package/dist/src/lifecycle/jit.js +258 -0
  76. package/dist/src/lifecycle/transform.d.ts +26 -0
  77. package/dist/src/lifecycle/transform.js +99 -0
  78. package/dist/src/lifecycle/types.d.ts +135 -0
  79. package/dist/src/lifecycle/types.js +1 -0
  80. package/dist/src/plugin/composer.d.ts +3 -0
  81. package/dist/src/plugin/composer.js +28 -0
  82. package/dist/src/plugin/registry.d.ts +25 -0
  83. package/dist/src/plugin/registry.js +107 -0
  84. package/dist/src/plugin/types.d.ts +20 -0
  85. package/dist/src/plugin/types.js +1 -0
  86. package/dist/src/router/allow-cache.d.ts +20 -0
  87. package/dist/src/router/allow-cache.js +26 -0
  88. package/dist/src/router/compiler.d.ts +39 -0
  89. package/dist/src/router/compiler.js +817 -0
  90. package/dist/src/router/define.d.ts +67 -0
  91. package/dist/src/router/define.js +34 -0
  92. package/dist/src/router/index.d.ts +6 -0
  93. package/dist/src/router/index.js +5 -0
  94. package/dist/src/router/param-extract.d.ts +33 -0
  95. package/dist/src/router/param-extract.js +87 -0
  96. package/dist/src/router/regex-matcher.d.ts +42 -0
  97. package/dist/src/router/regex-matcher.js +216 -0
  98. package/dist/src/router/router.d.ts +201 -0
  99. package/dist/src/router/router.js +600 -0
  100. package/dist/src/router/static-map.d.ts +39 -0
  101. package/dist/src/router/static-map.js +48 -0
  102. package/dist/src/router/trie.d.ts +69 -0
  103. package/dist/src/router/trie.js +572 -0
  104. package/dist/src/router/types.d.ts +104 -0
  105. package/dist/src/router/types.js +1 -0
  106. package/dist/src/runtime/capabilities.d.ts +29 -0
  107. package/dist/src/runtime/capabilities.js +48 -0
  108. package/dist/src/types/index.d.ts +260 -109
  109. package/dist/src/types/index.js +1 -1
  110. package/dist/src/types/inference.d.ts +78 -0
  111. package/dist/src/types/inference.js +20 -0
  112. package/dist/src/types/openapi-config.d.ts +164 -0
  113. package/dist/src/types/openapi-config.js +8 -0
  114. package/dist/src/utils/env.d.ts +13 -0
  115. package/dist/src/utils/env.js +24 -0
  116. package/dist/src/utils/fs.d.ts +29 -0
  117. package/dist/src/utils/fs.js +75 -0
  118. package/dist/src/utils/index.d.ts +1 -1
  119. package/dist/src/utils/index.js +2 -2
  120. package/dist/src/utils/pathConversion.js +13 -7
  121. package/dist/src/utils/response.d.ts +42 -6
  122. package/dist/src/utils/response.js +172 -7
  123. package/dist/src/utils/routing.d.ts +32 -13
  124. package/dist/src/utils/routing.js +41 -18
  125. package/dist/src/utils/thenable.d.ts +8 -0
  126. package/dist/src/utils/thenable.js +12 -0
  127. package/dist/src/utils/timing-safe.d.ts +9 -0
  128. package/dist/src/utils/timing-safe.js +20 -0
  129. package/dist/src/utils/wildcard.d.ts +2 -9
  130. package/dist/src/utils/wildcard.js +20 -58
  131. package/dist/src/validation/adapter.d.ts +54 -0
  132. package/dist/src/validation/adapter.js +75 -0
  133. package/dist/src/validation/adapters/standard.d.ts +11 -0
  134. package/dist/src/validation/adapters/standard.js +110 -0
  135. package/dist/src/validation/adapters/zod.d.ts +9 -0
  136. package/dist/src/validation/adapters/zod.js +128 -0
  137. package/dist/src/validation/cache.d.ts +26 -0
  138. package/dist/src/validation/cache.js +35 -0
  139. package/dist/src/validation/coerce.d.ts +28 -0
  140. package/dist/src/validation/coerce.js +176 -0
  141. package/dist/src/validation/compiler.d.ts +27 -0
  142. package/dist/src/validation/compiler.js +191 -0
  143. package/dist/src/validation/error.d.ts +69 -0
  144. package/dist/src/validation/error.js +137 -0
  145. package/dist/src/validation/index.d.ts +16 -0
  146. package/dist/src/validation/index.js +12 -0
  147. package/dist/src/validation/response.d.ts +25 -0
  148. package/dist/src/validation/response.js +79 -0
  149. package/dist/src/validation/types.d.ts +148 -0
  150. package/dist/src/validation/types.js +6 -0
  151. package/dist/src/validation/validator.d.ts +39 -0
  152. package/dist/src/validation/validator.js +441 -0
  153. package/dist/src/ws/adapter.d.ts +219 -0
  154. package/dist/src/ws/adapter.js +623 -0
  155. package/dist/src/ws/compiler.d.ts +37 -0
  156. package/dist/src/ws/compiler.js +156 -0
  157. package/dist/src/ws/index.d.ts +11 -0
  158. package/dist/src/ws/index.js +8 -0
  159. package/dist/src/ws/platform.d.ts +81 -0
  160. package/dist/src/ws/platform.js +113 -0
  161. package/dist/src/ws/router.d.ts +48 -0
  162. package/dist/src/ws/router.js +174 -0
  163. package/dist/src/ws/scanner.d.ts +97 -0
  164. package/dist/src/ws/scanner.js +193 -0
  165. package/dist/src/ws/types.d.ts +380 -0
  166. package/dist/src/ws/types.js +213 -0
  167. package/package.json +72 -59
  168. package/dist/src/core/api-router.d.ts +0 -65
  169. package/dist/src/core/api-router.js +0 -264
  170. package/dist/src/core/swagger-ui.d.ts +0 -1
  171. package/dist/src/core/swagger-ui.js +0 -33
  172. package/dist/src/middleware/validator.d.ts +0 -14
  173. package/dist/src/middleware/validator.js +0 -133
  174. package/dist/src/utils/error.d.ts +0 -17
  175. package/dist/src/utils/error.js +0 -63
package/dist/src/index.js CHANGED
@@ -1,421 +1,1008 @@
1
- // Import stuff from core
2
- import { Server } from './core/server';
3
- import { ApiRouter } from './core/api-router';
4
- import { PageRouter } from './core/page-router';
5
- import { generateOpenAPIDocument } from './core/openapi';
6
- import { swaggerHtml } from './core/swagger-ui';
1
+ // Import stuff from core
2
+ import { Server } from './core/server.js';
3
+ import { timingSafeEqual } from './utils/timing-safe.js';
4
+ // Import router
5
+ import { Router } from './router/index.js';
6
+ import { compilePatternSegments, extractCtxInitWithSegments, } from './router/param-extract.js';
7
+ import { BurgerContext } from './context/context.js';
7
8
  // Import utils
8
- import { collectRoutes, compareRoutes } from './utils/index';
9
- import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
10
- import { extractPathnameFromUrl, extractWildcardParams, } from './utils/wildcard';
11
- // Import middleware
12
- import { createValidationMiddleware } from './middleware/validator';
9
+ import { collectRoutes, compareRoutes, setDir } from './utils/index.js';
10
+ import { applySet, methodNotAllowed, notFound, openApiError, } from './utils/response.js';
11
+ import { extractPathnameFromUrl } from './utils/wildcard.js';
12
+ import { lowercaseMethodKeys } from './utils/routing.js';
13
+ import { requireDefaultFunctionExport, warnUnknownHookExports, } from './compiler/conventions.js';
14
+ // Import plugin system
15
+ import { PluginRegistry } from './plugin/registry.js';
16
+ import { assertTransformKeys } from './lifecycle/transform.js';
17
+ // Import WebSocket router/adapter (scanner/compiler load lazily on the dev
18
+ // filesystem path only).
19
+ import { WebSocketRouter } from './ws/router.js';
20
+ import { WebSocketAdapter } from './ws/adapter.js';
13
21
  export class Burger {
14
22
  options;
15
23
  /**
16
24
  * The server instance
17
25
  */
18
26
  server;
27
+ /** The resolved API directory (dev path). */
28
+ apiDir;
19
29
  /**
20
- * The API router instance
30
+ * The API path prefix (dev path).
21
31
  */
22
- apiRouter;
32
+ apiPrefix = 'api';
33
+ /** Page router (dev path only, created lazily). */
34
+ pageRouter;
35
+ /** The page directory (dev path). */
36
+ pageDir;
23
37
  /**
24
- * The page router instance
38
+ * The page path prefix (dev path).
25
39
  */
26
- pageRouter;
40
+ pagePrefix = '';
41
+ /**
42
+ * The compiled API router: static dispatch (Bun map) plus dynamic and
43
+ * wildcard dispatch (trie).
44
+ */
45
+ dynamicRouter;
46
+ /** Structural route tree for introspection/ordering; not on the hot path. */
47
+ routeTree;
48
+ /** Plugin registry, populated via `.usePlugin()` before `serve()`. */
49
+ pluginRegistry = new PluginRegistry();
50
+ /**
51
+ * Pre-routing onRequest hooks (Framework → Plugin → Global) resolved at
52
+ * compile time; shared with the WebSocket upgrade chain so both paths run
53
+ * the same hooks.
54
+ */
55
+ onRequestHooks = [];
27
56
  /**
28
- * The global middleware
57
+ * App-level (`src/hooks.ts`) route hooks, retained so WebSocket upgrades
58
+ * run the same transform/beforeRoute chain as HTTP.
29
59
  */
30
- globalMiddleware = [];
60
+ globalRouteHooks;
61
+ /** Services from `burger.provide()`, injected into `ctx.services`. */
62
+ providers = new Map();
31
63
  /**
32
64
  * The OpenAPI document
33
65
  */
34
66
  openApiDoc = null;
35
67
  /**
36
- * The routes object
68
+ * The loaded OpenAPI configuration from openapi.config.ts.
69
+ */
70
+ openAPIConfig;
71
+ /**
72
+ * The routes object. API routes are per-method objects (`{ GET, … }`);
73
+ * page/asset/docs routes are plain request handlers.
37
74
  */
38
75
  routes = {};
76
+ /** Origin of every registered route path, for collision errors. */
77
+ routeSources = new Map();
78
+ /**
79
+ * Every compiled API path (static + dynamic). Used by `fetchHandler()`
80
+ * to tell API routes apart from Bun-only page entries in `routes`.
81
+ */
82
+ apiRoutePaths;
39
83
  /**
40
- * Pre-computed responses for reuse
84
+ * WebSocket directory (dev path)
41
85
  */
42
- METHOD_NOT_ALLOWED = METHOD_NOT_ALLOWED;
86
+ wsDir;
87
+ /**
88
+ * WebSocket router
89
+ */
90
+ wsRouter;
91
+ /**
92
+ * WebSocket adapter
93
+ */
94
+ wsAdapter;
95
+ /**
96
+ * WebSocket config
97
+ */
98
+ wsConfigOptions;
99
+ /**
100
+ * Programmatic WebSocket routes
101
+ */
102
+ programmaticWsRoutes = new Map();
43
103
  /**
44
104
  * The not found response
45
105
  */
46
- NOT_FOUND = NOT_FOUND;
106
+ notFound = notFound;
47
107
  /**
48
108
  * The OpenAPI error response
49
109
  */
50
- OPENAPI_ERROR = OPENAPI_ERROR;
110
+ openApiError = openApiError;
51
111
  /**
52
- * Constructor for the Burger class.
53
- * @param options - The options for the server and router.
54
- * The options object should contain the following properties:
55
- * - port: The port number to listen on.
56
- * - apiDir: The directory path to load API routes from.
57
- * - pageDir: The directory path to load page routes from.
58
- * - middleware: An array of global middleware functions.
112
+ * Set once API routes have been compiled. Guards `processApiRoutes()` from
113
+ * re-running when both `serve()` and `fetchHandler()` are used.
114
+ */
115
+ routesProcessed = false;
116
+ /** Set once page + asset routes are registered (serve / fetchHandler). */
117
+ pagesProcessed;
118
+ /** Set when the scanned API directory contained no route files. */
119
+ emptyApiDir;
120
+ /** Set once convention directory defaults were applied. */
121
+ conventionDefaultsApplied = false;
122
+ /**
123
+ * App-level WebSocket hooks (`onOpen` / `onMessage` / `onClose`),
124
+ * applied to every WS route.
125
+ */
126
+ globalWsHooks;
127
+ /**
128
+ * @param options Server + router options (port, apiDir, pageDir, wsDir, …).
59
129
  */
60
130
  constructor(options) {
61
131
  this.options = options;
62
- // Create server instance
63
- this.server = new Server(options);
64
- // Fast initialization for routers with nullish coalescing
65
- const { apiDir, pageDir, apiPrefix, pagePrefix, globalMiddleware } = options;
66
- // Initialize API router only when using runtime scanning (no prebuilt apiRoutes)
67
- this.apiRouter =
68
- apiDir && !Array.isArray(options.apiRoutes)
69
- ? new ApiRouter(apiDir, apiPrefix || 'api')
70
- : undefined;
71
- // Initialize page router only when using runtime scanning (no prebuilt pageRoutes)
72
- this.pageRouter =
73
- pageDir && !Array.isArray(options.pageRoutes)
74
- ? new PageRouter(pageDir, pagePrefix || '')
75
- : undefined;
76
- // Add global middleware if any
77
- this.globalMiddleware = globalMiddleware?.length
78
- ? globalMiddleware.slice()
79
- : [];
132
+ // Adapter seam: injectable for tests/embed, else Bun loads lazily.
133
+ this.server = new Server(options, options.adapter);
134
+ const { apiDir, apiPrefix, wsDir } = options;
135
+ this.apiDir = apiDir;
136
+ // `??`, not `||`: an explicit `apiPrefix: ''` mounts routes at `/`.
137
+ this.apiPrefix = apiPrefix ?? 'api';
138
+ // Pages resolve lazily on the dev scan path, keeping AOT bundles small.
139
+ this.pageDir = options.pageDir;
140
+ this.pagePrefix = options.pagePrefix ?? '';
141
+ this.wsDir = wsDir;
142
+ }
143
+ /**
144
+ * Registers a plugin; its hooks compile into every route's hook chain with
145
+ * the plugin's scope. Duplicate registrations (same name + seed) are
146
+ * ignored with a warning.
147
+ *
148
+ * @param plugin The plugin object or a factory function returning one.
149
+ * @param scope Optional scope override (default: `'plugin'`).
150
+ * @param seed Optional disambiguation string (e.g. two JWT plugins).
151
+ * @returns `this` for chaining.
152
+ */
153
+ usePlugin(plugin, scope, seed) {
154
+ this.pluginRegistry.register(plugin, scope ?? 'plugin', seed);
155
+ return this;
156
+ }
157
+ /**
158
+ * Registers an application service, injected into `ctx.services` for every
159
+ * request.
160
+ *
161
+ * @param name Service name (accessed as `ctx.services[name]`).
162
+ * @param service The service instance.
163
+ * @returns `this` for chaining.
164
+ */
165
+ provide(name, service) {
166
+ this.providers.set(name, service);
167
+ return this;
168
+ }
169
+ /**
170
+ * Register a WebSocket route programmatically.
171
+ * @param path Route path (e.g., "/chat", "/notifications/:room")
172
+ * @param handlers WebSocket handler functions
173
+ * @returns `this` for chaining.
174
+ */
175
+ websocket(path, handlers) {
176
+ this.programmaticWsRoutes.set(path, { path, handlers });
177
+ return this;
178
+ }
179
+ /**
180
+ * Set global WebSocket configuration.
181
+ * @param config WebSocket configuration options
182
+ * @returns `this` for chaining.
183
+ */
184
+ wsConfig(config) {
185
+ this.wsConfigOptions = config;
186
+ return this;
187
+ }
188
+ /**
189
+ * Filesystem mode only (no prebuilt `apiRoutes`): unconfigured directories
190
+ * default to the CLI build conventions (`src/api`, `src/pages`,
191
+ * `src/websocket`) when they exist, so dev and production match. Resolved
192
+ * lazily — `node:fs` is never loaded by AOT bundles.
193
+ */
194
+ async applyConventionDefaults() {
195
+ if (this.conventionDefaultsApplied)
196
+ return;
197
+ this.conventionDefaultsApplied = true;
198
+ if (Array.isArray(this.options.apiRoutes))
199
+ return;
200
+ const needsApi = !this.apiDir;
201
+ const needsPages = !this.pageDir && !Array.isArray(this.options.pageRoutes);
202
+ const needsWs = !this.wsDir && !Array.isArray(this.options.wsRoutes);
203
+ if (!needsApi && !needsPages && !needsWs)
204
+ return;
205
+ const { resolveConventionDir } = await import('./utils/fs.js');
206
+ if (needsApi)
207
+ this.apiDir = resolveConventionDir('api');
208
+ if (needsPages)
209
+ this.pageDir = resolveConventionDir('pages');
210
+ if (needsWs)
211
+ this.wsDir = resolveConventionDir('websocket');
212
+ }
213
+ /**
214
+ * Wraps a non-API handler (page, asset, OpenAPI spec, docs UI) so
215
+ * global/plugin `onRequest` hooks run for it like for API routes.
216
+ * Registered on the native routes map → invoked with the raw `Request`.
217
+ */
218
+ withOnRequest(handler) {
219
+ // Non-function values (Bun HTML-import bundles) are served natively,
220
+ // not wrapped.
221
+ const wrapped = this.dynamicRouter && typeof handler === 'function'
222
+ ? this.dynamicRouter.wrapWithOnRequest(handler)
223
+ : handler;
224
+ return wrapped;
80
225
  }
81
226
  /**
82
- * Process the page routes and add them to the routes object
83
- * @returns A promise that resolves to a boolean
227
+ * Registers one route path, failing loud when two sources (API route,
228
+ * page, asset, docs UI, spec) resolve to the same path. Silent overwrites
229
+ * would make one of them unreachable.
84
230
  */
231
+ registerRoute(key, handler, source) {
232
+ const existing = this.routeSources.get(key);
233
+ if (existing !== undefined) {
234
+ throw new Error(`[burger-api] Route collision: "${key}" is registered by both ` +
235
+ `${existing} and ${source}. Rename one of them.`);
236
+ }
237
+ this.routeSources.set(key, source);
238
+ this.routes[key] = handler;
239
+ }
240
+ /** Registers page + asset routes once (shared by serve and fetchHandler). */
241
+ processPageRoutesOnce() {
242
+ return (this.pagesProcessed ??= this.processPageRoutes());
243
+ }
244
+ /** Loads prebuilt or filesystem page routes. */
85
245
  async processPageRoutes() {
86
246
  // Production path: use pre-built page routes (no filesystem scan)
87
247
  const prebuiltPages = this.options.pageRoutes;
248
+ let hasPages = false;
88
249
  if (Array.isArray(prebuiltPages)) {
89
- // Sort the prebuilt pages
90
250
  const sorted = [...prebuiltPages].sort((a, b) => compareRoutes(a, b));
91
251
  for (let i = 0; i < sorted.length; i++) {
92
252
  const page = sorted[i];
93
- this.routes[page.path] = page.handler;
253
+ this.registerRoute(page.path, this.withOnRequest(this.restrictToGetHead(this.wrapPageHandler(page.handler, page.path))), page.source ? `page "${page.source}"` : `page route`);
94
254
  }
95
- return sorted.length > 0;
255
+ hasPages = sorted.length > 0;
96
256
  }
97
- // Dev path: load from filesystem via PageRouter
98
- if (!this.pageRouter)
99
- return false;
100
- // Load pages routes
101
- await this.pageRouter.loadPages();
102
- // If there are any page routes, add them to the routes object
103
- const pages = this.pageRouter.pages;
104
- // Get the length of the pages routes
105
- const pageCount = pages.length;
106
- // If no pages, return false
107
- if (pageCount === 0)
108
- return false;
109
- // Loop through the pages
110
- for (let i = 0; i < pageCount; i++) {
111
- // Get the current page
112
- const page = pages[i];
113
- // Add the page to the routes
114
- this.routes[page.path] = page.handler;
257
+ else if (this.pageDir) {
258
+ // Dev path: lazy-load the page router (AOT bundles ship prebuilt
259
+ // pageRoutes, so this module is never evaluated).
260
+ const { PageRouter } = await import('./core/page-router.js');
261
+ const pageRouter = new PageRouter(this.pageDir, this.pagePrefix);
262
+ this.pageRouter = pageRouter;
263
+ await pageRouter.loadPages();
264
+ const pages = pageRouter.pages;
265
+ for (let i = 0; i < pages.length; i++) {
266
+ const page = pages[i];
267
+ this.registerRoute(page.path, this.withOnRequest(this.restrictToGetHead(this.wrapPageHandler(page.handler, page.path))), page.source ? `page "${page.source}"` : `page route`);
268
+ }
269
+ hasPages = pages.length > 0;
115
270
  }
116
- // Return true if there are any pages
117
- return true;
271
+ // Static assets under `<pageDir>/assets/` — embedded table from the
272
+ // AOT build, or read-from-disk when running with `pageDir`.
273
+ await this.processAssetRoutes();
274
+ return hasPages;
118
275
  }
119
276
  /**
120
- * Process the API routes and add them to the routes object
121
- * @returns A promise that resolves to a boolean
277
+ * Wraps every page handler with a real per-request `BurgerContext` — the
278
+ * same object API routes get — so `ctx.services`, `ctx.query`, `ctx.set`
279
+ * and the delegated `Request` surface work on static pages too. Dynamic
280
+ * pages (`:param`) also get `ctx.params`; static pages seed only the
281
+ * route pattern (`ctx.route.path` derives lazily).
282
+ *
283
+ * Cost per page request: one `BurgerContext` allocation (no parsing).
284
+ * When an onRequest/global-hook wrapper already created the context, the
285
+ * existing instance is re-bound instead of allocated.
286
+ */
287
+ wrapPageHandler(handler, path) {
288
+ // Compile the pattern's segments once per route, not per request.
289
+ const compiledPattern = path.includes(':')
290
+ ? compilePatternSegments(path)
291
+ : undefined;
292
+ // Invoked with the raw `Request`, like `fetchHandler`'s static dispatch.
293
+ const wrapped = async (request, _ctxInit, prebuilt, env, executionCtx) => {
294
+ const ctxInit = compiledPattern
295
+ ? extractCtxInitWithSegments(request, path, compiledPattern)
296
+ : { pattern: path };
297
+ const ctx = prebuilt
298
+ ? prebuilt.bind(request, ctxInit)
299
+ : BurgerContext.create(request, ctxInit, undefined, this.dynamicRouter?.getAppServices(), undefined, env, executionCtx, this.dynamicRouter?.getRequestIPHolder());
300
+ const response = await handler(ctx);
301
+ // With no outer onRequest/global-hook wrapper there is nobody
302
+ // else to apply `ctx.set`; do it here.
303
+ return prebuilt
304
+ ? response
305
+ : ctx.hasSet()
306
+ ? applySet(response, ctx.set)
307
+ : response;
308
+ };
309
+ return wrapped;
310
+ }
311
+ /**
312
+ * Pages, assets, the docs UI and the OpenAPI spec answer GET and HEAD
313
+ * only. Every other method gets a 405 with `Allow: GET, HEAD` and the
314
+ * same RFC 9457 body route 405s use. Global/plugin response hooks and
315
+ * onRequest mappers still apply (this runs inside `withOnRequest`).
316
+ */
317
+ restrictToGetHead(handler) {
318
+ const restricted = (arg, ...rest) => {
319
+ if (arg.method !== 'GET' && arg.method !== 'HEAD') {
320
+ return methodNotAllowed('GET, HEAD');
321
+ }
322
+ return handler(arg, ...rest);
323
+ };
324
+ return restricted;
325
+ }
326
+ /**
327
+ * Registers static asset routes under `{pagePrefix}/assets/*`.
328
+ *
329
+ * Production AOT embeds base64 contents (`assetRoutes` from the CLI
330
+ * build); dev reads files from disk per request so edits show.
331
+ */
332
+ async processAssetRoutes() {
333
+ const prebuiltAssets = this.options.assetRoutes;
334
+ if (Array.isArray(prebuiltAssets)) {
335
+ const { embeddedAssetHandler } = await import('./core/embedded-assets.js');
336
+ for (const asset of prebuiltAssets) {
337
+ this.registerRoute(asset.path, this.withOnRequest(this.restrictToGetHead(embeddedAssetHandler(asset))), `asset "${asset.path}"`);
338
+ }
339
+ return;
340
+ }
341
+ if (!this.pageDir)
342
+ return;
343
+ const { collectDiskAssetRoutes, diskAssetHandler } = await import('./core/assets.js');
344
+ const routes = await collectDiskAssetRoutes(this.pageDir, this.pagePrefix);
345
+ for (const route of routes) {
346
+ this.registerRoute(route.routePath, this.withOnRequest(this.restrictToGetHead(diskAssetHandler(route))), `asset "${route.file}"`);
347
+ }
348
+ }
349
+ /**
350
+ * Compiles the API routes and merges them into the routes map. Static and
351
+ * dynamic (`:param` / `*`) routes both go on Bun's native map; unmatched or
352
+ * loose-trailing-slash requests fall through to `Router.fetch` (the trie).
353
+ * Both paths run the same compiled handler, so dispatch behavior is
354
+ * identical.
122
355
  */
123
356
  async processApiRoutes() {
357
+ if (this.routesProcessed)
358
+ return true;
124
359
  // Production path: use pre-built API routes (no filesystem scan)
125
360
  let apiRoutes;
361
+ let globalOnRequest;
362
+ // Global hooks other than onRequest — compiled into every route with
363
+ // scope 'global' (identical ordering in dev and AOT).
364
+ let globalRouteHooks;
126
365
  if (Array.isArray(this.options.apiRoutes)) {
127
- apiRoutes = [...this.options.apiRoutes].sort((a, b) => compareRoutes(a, b));
366
+ // AOT routes may carry uppercase method keys (GET/POST) in
367
+ // `schema` / `openapi`; normalize once for the compiler and
368
+ // OpenAPI generator. `config` keeps its uppercase method keys.
369
+ apiRoutes = this.options.apiRoutes
370
+ .map((def) => ({
371
+ ...def,
372
+ schema: def.schema
373
+ ? lowercaseMethodKeys(def.schema)
374
+ : def.schema,
375
+ openapi: def.openapi
376
+ ? lowercaseMethodKeys(def.openapi)
377
+ : def.openapi,
378
+ }))
379
+ .sort((a, b) => compareRoutes(a, b));
380
+ // Production: accept config from ServerOptions if provided
381
+ this.openAPIConfig = this.options.openapi;
382
+ // Production: resolve global hooks from options (a module
383
+ // namespace or its default-export object, like the dev loader).
384
+ const rawGlobal = this.options.globalHooks;
385
+ const globalHooks = rawGlobal &&
386
+ typeof rawGlobal.default === 'object' &&
387
+ rawGlobal.default !== null
388
+ ? rawGlobal.default
389
+ : rawGlobal;
390
+ if (globalHooks) {
391
+ warnUnknownHookExports(globalHooks, 'src/hooks', 'global');
392
+ const { onRequest, ...rest } = globalHooks;
393
+ if (onRequest) {
394
+ globalOnRequest = Array.isArray(onRequest)
395
+ ? onRequest
396
+ : [onRequest];
397
+ }
398
+ globalRouteHooks = rest;
399
+ this.globalWsHooks = pickWsHooks(globalHooks);
400
+ }
401
+ for (const def of apiRoutes) {
402
+ warnUnknownHookExports(def.hooks, `${def.path} hooks`, 'route');
403
+ }
128
404
  }
129
405
  else {
130
- // Dev path: load from filesystem via ApiRouter
131
- if (!this.apiRouter)
132
- return false;
133
- await this.apiRouter.loadRoutes();
134
- apiRoutes = collectRoutes(this.apiRouter.routes);
135
- }
136
- // Get the length of the API routes
137
- const routeCount = apiRoutes.length;
138
- // If there are no API routes, return false
139
- if (routeCount === 0)
140
- return false;
141
- // Generate OpenAPI document and cache it
142
- this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options);
143
- // Cache frequently accessed properties
144
- const routes = this.routes;
145
- // Get the global middleware
146
- const globalMiddleware = this.globalMiddleware;
147
- // Get the length of the global middleware
148
- const globalMiddlewareLen = globalMiddleware.length;
149
- // Process each route with optimized handler creation
150
- for (let i = 0; i < routeCount; i++) {
151
- /**
152
- * ================================================
153
- * Pre-compute the required functionality start
154
- * ================================================
155
- */
156
- // Get the current route object
157
- const route = apiRoutes[i];
158
- // Destructure the route object
159
- const { path, schema, middleware: routeMiddleware, handlers, } = route;
160
- // Get length of route specific middleware
161
- const routeMiddlewareLen = routeMiddleware?.length || 0;
162
- // Check if schema exists
163
- const hasSchema = !!schema;
164
- // Optimize middleware array initialization by pre-allocating size
165
- const totalMiddlewareCount = globalMiddlewareLen + (hasSchema ? 1 : 0) + routeMiddlewareLen;
166
- // Pre-compute wildcard info once (used in all paths)
167
- const isWildcard = route.isWildcard;
168
- const baseSegmentCount = isWildcard
169
- ? path.split('/').filter(Boolean).length - 1
170
- : 0;
171
- // Create optimized route handler based on middleware count
172
- if (totalMiddlewareCount === 0) {
173
- // Ultra-fast path: no middleware at all
174
- // Inline everything for maximum speed
175
- if (isWildcard) {
176
- // Wildcard route with no middleware
177
- routes[path] = (request) => {
178
- const pathname = extractPathnameFromUrl(request.url);
179
- extractWildcardParams(request, pathname, baseSegmentCount);
180
- const handler = handlers[request.method];
181
- return handler
182
- ? handler(request)
183
- : this.METHOD_NOT_ALLOWED;
184
- };
185
- }
186
- else {
187
- // Regular route with no middleware (most common case)
188
- routes[path] = (request) => {
189
- const handler = handlers[request.method];
190
- return handler
191
- ? handler(request)
192
- : this.METHOD_NOT_ALLOWED;
193
- };
194
- }
406
+ // Dev path: Scanner → Module Loader → RouteModule → Compiler,
407
+ // loaded lazily (AOT builds ship prebuilt apiRoutes). App-level
408
+ // convention files load even for pages-only apps (no apiDir).
409
+ await this.applyConventionDefaults();
410
+ let scanned;
411
+ if (this.apiDir) {
412
+ const { DirectoryScanner } = await import('./compiler/scanner.js');
413
+ scanned = await new DirectoryScanner(this.apiDir, this.apiPrefix).scan();
195
414
  }
196
415
  else {
197
- // Pre-compute middleware array with exact size (AOT optimization)
198
- const middlewares = new Array(totalMiddlewareCount);
199
- let idx = 0;
200
- // Copy global middleware (manual loop is faster than spread/concat)
201
- for (let j = 0; j < globalMiddlewareLen; j++) {
202
- middlewares[idx++] = globalMiddleware[j];
203
- }
204
- // Add validation middleware if needed
205
- if (hasSchema) {
206
- middlewares[idx++] = createValidationMiddleware(schema);
207
- }
208
- // Add route-specific middlewares
209
- if (routeMiddleware) {
210
- for (let j = 0; j < routeMiddlewareLen; j++) {
211
- middlewares[idx++] = routeMiddleware[j];
212
- }
416
+ const { scanAppRootConventions } = await import('./compiler/scanner.js');
417
+ const { resolveAppRootDir } = await import('./utils/fs.js');
418
+ const appRoot = resolveAppRootDir();
419
+ if (appRoot)
420
+ scanned = await scanAppRootConventions(appRoot);
421
+ }
422
+ if (scanned) {
423
+ const { ModuleLoader } = await import('./compiler/module-loader.js');
424
+ const loader = new ModuleLoader();
425
+ const modules = await loader.load(scanned);
426
+ globalOnRequest = scanned.globalOnRequest;
427
+ globalRouteHooks = scanned.globalRouteHooks;
428
+ this.globalWsHooks = pickWsHooks(scanned.globalRouteHooks);
429
+ if (this.apiDir && modules.length === 0) {
430
+ this.emptyApiDir = this.apiDir;
213
431
  }
214
- // Create specialized handler based on middleware count
215
- if (totalMiddlewareCount === 1) {
216
- // Single middleware fast path (common: just CORS or just auth)
217
- const singleMiddleware = middlewares[0];
218
- if (isWildcard) {
219
- routes[path] = (request) => {
220
- const pathname = extractPathnameFromUrl(request.url);
221
- extractWildcardParams(request, pathname, baseSegmentCount);
222
- const handler = handlers[request.method];
223
- if (!handler)
224
- return this.METHOD_NOT_ALLOWED;
225
- return this.processSingleMiddleware(request, singleMiddleware, handler);
226
- };
227
- }
228
- else {
229
- routes[path] = (request) => {
230
- const handler = handlers[request.method];
231
- if (!handler)
232
- return this.METHOD_NOT_ALLOWED;
233
- return this.processSingleMiddleware(request, singleMiddleware, handler);
234
- };
235
- }
432
+ // Load openapi.config.ts if discovered
433
+ this.openAPIConfig = await loader.loadOpenAPIConfig(scanned);
434
+ // Load and execute plugins.ts / providers.ts (app root). A
435
+ // present file with no default function export fails loud.
436
+ const pluginsMod = await loader.loadPlugins(scanned);
437
+ if (pluginsMod) {
438
+ await pluginsMod.default(this);
236
439
  }
237
- else {
238
- // Multiple middlewares (general case)
239
- if (isWildcard) {
240
- routes[path] = (request) => {
241
- const pathname = extractPathnameFromUrl(request.url);
242
- extractWildcardParams(request, pathname, baseSegmentCount);
243
- const handler = handlers[request.method];
244
- if (!handler)
245
- return this.METHOD_NOT_ALLOWED;
246
- return this.processMiddleware(request, middlewares, handler);
247
- };
248
- }
249
- else {
250
- routes[path] = (request) => {
251
- const handler = handlers[request.method];
252
- if (!handler)
253
- return this.METHOD_NOT_ALLOWED;
254
- return this.processMiddleware(request, middlewares, handler);
255
- };
256
- }
440
+ const providersMod = await loader.loadProviders(scanned);
441
+ if (providersMod) {
442
+ await providersMod.default(this);
257
443
  }
444
+ // Retained for introspection (deterministic ordering, no dispatch).
445
+ const { RouteTree } = await import('./compiler/route-tree.js');
446
+ this.routeTree = new RouteTree(modules);
447
+ apiRoutes = modules.map((m) => ({
448
+ path: m.path,
449
+ handlers: m.handlers,
450
+ schema: m.schema,
451
+ openapi: m.openapi,
452
+ hooks: m.hooks,
453
+ config: m.config,
454
+ isWildcard: m.isWildcard,
455
+ }));
258
456
  }
259
- // For wildcard routes, also register the base path
260
- // Bun's /* wildcard may not match the base path itself, so we register both
261
- if (route.isWildcard && path.endsWith('/*')) {
262
- const basePath = path.slice(0, -2); // Remove "/*" to get base path
263
- // Only register base path if no static route exists (preserve priority)
264
- // Static routes have highest priority: Static > Dynamic > Wildcard
265
- if (!routes[basePath]) {
266
- // No static route found, register wildcard for base path
267
- routes[basePath] = routes[path];
268
- }
269
- // If static route exists, it takes priority (correct behavior)
457
+ else {
458
+ apiRoutes = [];
270
459
  }
271
460
  }
272
- // Add special routes for OpenAPI
273
- routes['/openapi.json'] = () => this.openApiDoc
274
- ? Response.json(this.openApiDoc)
275
- : this.OPENAPI_ERROR;
276
- // Add special route for Swagger UI
277
- routes['/docs'] = () => new Response(swaggerHtml, {
278
- headers: { 'Content-Type': 'text/html' },
461
+ // Production: execute the pre-resolved plugins/providers modules.
462
+ // Runs for pages-only AOT apps too (no apiRoutes array). A module
463
+ // present without a default function export fails loud.
464
+ if (this.options.pluginsModule) {
465
+ const fn = requireDefaultFunctionExport(this.options.pluginsModule, 'plugins.ts');
466
+ await fn(this);
467
+ }
468
+ if (this.options.providersModule) {
469
+ const fn = requireDefaultFunctionExport(this.options.providersModule, 'providers.ts');
470
+ await fn(this);
471
+ }
472
+ // API routes are optional: the router is still built so hooks, the `ip`
473
+ // holder and app services reach pages, assets and docs.
474
+ const hasApiRoutes = apiRoutes.length > 0;
475
+ const config = this.openAPIConfig;
476
+ const openapiEnabled = config?.enabled !== false;
477
+ // Generate the OpenAPI document lazily and only when docs are enabled.
478
+ if (hasApiRoutes && openapiEnabled) {
479
+ const { generateOpenAPIDocument } = await import('./core/openapi.js');
480
+ this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options, this.openAPIConfig);
481
+ }
482
+ // Compile routes into the Hybrid Router.
483
+ const router = new Router({
484
+ debug: this.options.debug,
485
+ validation: this.options.validation ?? {},
486
+ jit: this.options.jit !== false,
487
+ engine: this.options.engine,
279
488
  });
489
+ // Resolve plugins into a single list for the compiler.
490
+ const allHooks = await this.pluginRegistry.resolveAll();
491
+ // onRequest hooks run before routing, not as per-route HookPlan
492
+ // entries. Order: Framework → Plugin → Global (src/hooks.ts) → Route.
493
+ const onRequestHooks = [];
494
+ for (const plugin of allHooks) {
495
+ const h = plugin.hooks.onRequest;
496
+ if (h) {
497
+ if (Array.isArray(h))
498
+ onRequestHooks.push(...h);
499
+ else
500
+ onRequestHooks.push(h);
501
+ }
502
+ }
503
+ onRequestHooks.push(...(globalOnRequest ?? []));
504
+ this.onRequestHooks = onRequestHooks;
505
+ this.globalRouteHooks = globalRouteHooks;
506
+ router.compile(apiRoutes, allHooks, this.providers, onRequestHooks, globalRouteHooks);
507
+ this.dynamicRouter = router;
508
+ // Only the onRequest machinery was needed (pages/assets/docs); there
509
+ // is no route table to merge and no OpenAPI document to serve.
510
+ if (!hasApiRoutes) {
511
+ this.routesProcessed = true;
512
+ return false;
513
+ }
514
+ // Merge static and dynamic routes onto Bun's native routes map (Bun
515
+ // matches `:param` / `*` directly); unmatched requests fall through to
516
+ // `Router.fetch` (the trie). Collisions with pages/assets/docs throw.
517
+ for (const [key, handlers] of Object.entries(router.staticRoutes())) {
518
+ this.registerRoute(key, handlers, `API route "${key}"`);
519
+ }
520
+ for (const [key, handlers] of Object.entries(router.nativeRoutes())) {
521
+ this.registerRoute(key, handlers, `API route "${key}"`);
522
+ }
523
+ this.apiRoutePaths = new Set([
524
+ ...Object.keys(router.staticRoutes()),
525
+ ...Object.keys(router.nativeRoutes()),
526
+ ]);
527
+ // Register OpenAPI and docs routes based on config
528
+ if (openapiEnabled) {
529
+ const specPath = config?.path ?? '/openapi.json';
530
+ const docsPath = config?.docsPath ?? '/docs';
531
+ const expectedAuth = config?.docsAuth
532
+ ? 'Basic ' +
533
+ base64Utf8(`${config.docsAuth.username}:${config.docsAuth.password}`)
534
+ : null;
535
+ // docsAuth guards the spec as well as the UI: protecting only the
536
+ // HTML page would leave the API description public.
537
+ const unauthorized = (ctx) => {
538
+ if (expectedAuth === null)
539
+ return null;
540
+ const authHeader = ctx?.headers?.get?.('authorization') ?? '';
541
+ if (timingSafeEqual(authHeader, expectedAuth))
542
+ return null;
543
+ return new Response('Unauthorized', {
544
+ status: 401,
545
+ headers: {
546
+ 'WWW-Authenticate': 'Basic realm="Documentation"',
547
+ },
548
+ });
549
+ };
550
+ // Invoked with the raw `Request` (native routes map); wrapped so
551
+ // global/plugin onRequest hooks (CORS, auth, …) apply here too.
552
+ this.registerRoute(specPath, this.withOnRequest(this.restrictToGetHead((request) => unauthorized(request) ??
553
+ (this.openApiDoc
554
+ ? Response.json(this.openApiDoc)
555
+ : this.openApiError()))), 'openapi.json route');
556
+ // Docs UI: configured provider, or Swagger UI by default (loaded
557
+ // lazily).
558
+ const { swaggerDocs } = await import('./core/docs-providers.js');
559
+ const provider = config?.provider ?? swaggerDocs();
560
+ this.registerRoute(docsPath, this.withOnRequest(this.restrictToGetHead((request) => {
561
+ const denied = unauthorized(request);
562
+ if (denied)
563
+ return denied;
564
+ const result = provider(this.openApiDoc, {
565
+ specUrl: specPath,
566
+ });
567
+ if (result instanceof Response)
568
+ return result;
569
+ return new Response(result, {
570
+ headers: { 'Content-Type': 'text/html' },
571
+ });
572
+ })), 'docs UI');
573
+ }
574
+ this.routesProcessed = true;
280
575
  return true;
281
576
  }
282
- /**
283
- * Process single middleware
284
- * @param request - The request object
285
- * @param middleware - The middleware function
286
- * @param handler - The handler function
287
- * @returns A promise that resolves to a response
288
- */
289
- async processSingleMiddleware(request, middleware, handler) {
290
- const result = await middleware(request);
291
- // Short-circuit with Response
292
- if (result instanceof Response) {
293
- return result;
577
+ /** Loads WebSocket routes (programmatic, prebuilt or file-based). */
578
+ async processWebSocketRoutes() {
579
+ this.wsRouter = new WebSocketRouter();
580
+ // Extract auth hooks from resolved plugins for WebSocket upgrade.
581
+ // beforeRoute follows the HTTP order: Framework → Plugin → Global.
582
+ const resolvedPlugins = await this.pluginRegistry.resolveAll();
583
+ let pluginTransform;
584
+ const pluginBeforeRoute = [];
585
+ const frameworkBeforeRoute = [];
586
+ const toHookArray = (value) => Array.isArray(value) ? value : [value];
587
+ for (const plugin of resolvedPlugins) {
588
+ // Collect transform hooks
589
+ if (plugin.hooks.transform) {
590
+ if (!pluginTransform)
591
+ pluginTransform = {};
592
+ Object.assign(pluginTransform, plugin.hooks.transform);
593
+ }
594
+ // Collect beforeRoute hooks, bucketed by scope.
595
+ if (plugin.hooks.beforeRoute) {
596
+ const hooks = toHookArray(plugin.hooks.beforeRoute);
597
+ if (plugin.scope === 'framework') {
598
+ frameworkBeforeRoute.push(...hooks);
599
+ }
600
+ else {
601
+ pluginBeforeRoute.push(...hooks);
602
+ }
603
+ }
604
+ }
605
+ // Same startup guard as HTTP: a reserved transform key fails loud.
606
+ assertTransformKeys(pluginTransform, 'plugin transform (WebSocket)');
607
+ assertTransformKeys(this.globalRouteHooks?.transform, 'global transform (WebSocket)');
608
+ const globalBeforeRoute = this.globalRouteHooks?.beforeRoute
609
+ ? toHookArray(this.globalRouteHooks.beforeRoute)
610
+ : undefined;
611
+ this.wsAdapter = new WebSocketAdapter({
612
+ router: this.wsRouter,
613
+ config: this.wsConfigOptions,
614
+ debug: this.options.debug,
615
+ providers: this.providers,
616
+ pluginTransform,
617
+ pluginBeforeRoute: pluginBeforeRoute.length > 0 ? pluginBeforeRoute : undefined,
618
+ frameworkBeforeRoute: frameworkBeforeRoute.length > 0
619
+ ? frameworkBeforeRoute
620
+ : undefined,
621
+ onRequestHooks: this.onRequestHooks,
622
+ globalTransform: this.globalRouteHooks?.transform,
623
+ globalBeforeRoute,
624
+ ipHolder: this.dynamicRouter?.getRequestIPHolder(),
625
+ runtimeTarget: this.options.runtimeTarget,
626
+ });
627
+ // App-level WS hooks apply to every WS route (programmatic,
628
+ // prebuilt and file-based alike).
629
+ const globalWs = this.globalWsHooks;
630
+ const mergeWsHooks = globalWs
631
+ ? (await import('./ws/compiler.js')).mergeWsHooks
632
+ : undefined;
633
+ const withGlobalWs = (hooks) => (mergeWsHooks ? mergeWsHooks(globalWs, hooks) : hooks);
634
+ // Add programmatic routes
635
+ for (const [path, route] of this.programmaticWsRoutes) {
636
+ this.wsRouter.addRoute({
637
+ path,
638
+ handlers: route.handlers,
639
+ hooks: withGlobalWs(undefined),
640
+ config: this.wsConfigOptions ?? {},
641
+ });
642
+ }
643
+ // Production path: use pre-built WebSocket routes (no filesystem scan)
644
+ const prebuiltWsRoutes = this.options.wsRoutes;
645
+ if (Array.isArray(prebuiltWsRoutes)) {
646
+ for (const route of prebuiltWsRoutes) {
647
+ warnTransportLevelWsConfig(route.path, route.config);
648
+ this.wsRouter.addRoute({
649
+ path: route.path,
650
+ handlers: route.handlers,
651
+ hooks: withGlobalWs(route.hooks),
652
+ // Deep-merge `auth`, keeping the global `auth.required`.
653
+ config: mergeWsConfig(this.wsConfigOptions, route.config),
654
+ });
655
+ }
656
+ return this.wsRouter.getRouteCount() > 0;
294
657
  }
295
- // Transform response after handler
296
- if (typeof result === 'function') {
297
- return result(await handler(request));
658
+ // Scan file-based routes if wsDir is provided
659
+ if (this.wsDir) {
660
+ // Dev path — the scanner/compiler are loaded lazily so production
661
+ // AOT builds (prebuilt wsRoutes) never evaluate them.
662
+ const { WebSocketScanner } = await import('./ws/scanner.js');
663
+ const scanner = new WebSocketScanner(this.wsDir);
664
+ const scanResult = await scanner.scan();
665
+ if (scanResult.routes.length > 0) {
666
+ const { WebSocketCompiler } = await import('./ws/compiler.js');
667
+ const compiler = new WebSocketCompiler();
668
+ // Set global hooks if found (the hooks.ts beside wsDir, else
669
+ // the app-level hooks already loaded for API routes).
670
+ if (!scanResult.globalHooks && globalWs) {
671
+ compiler.setGlobalHooks(globalWs);
672
+ }
673
+ if (scanResult.globalHooks) {
674
+ try {
675
+ const hooksModule = await import(scanResult.globalHooks);
676
+ compiler.setGlobalHooks({
677
+ onOpen: hooksModule.onOpen,
678
+ onMessage: hooksModule.onMessage,
679
+ onClose: hooksModule.onClose,
680
+ });
681
+ }
682
+ catch (error) {
683
+ console.error('[WebSocket] Failed to load global hooks:', error);
684
+ }
685
+ }
686
+ if (this.wsConfigOptions) {
687
+ compiler.setGlobalConfig(this.wsConfigOptions);
688
+ }
689
+ const compiledRoutes = await compiler.compileAll(scanResult.routes);
690
+ this.wsRouter.addRoutes(compiledRoutes);
691
+ }
298
692
  }
299
- // Continue to handler
300
- return handler(request);
693
+ return this.wsRouter.getRouteCount() > 0;
301
694
  }
302
695
  /**
303
- * Process middleware and handler
696
+ * Builds the Web-Standard fetch handler for this app.
304
697
  *
305
- * How it works:
306
- * 1. Run each middleware in order
307
- * 2. If middleware returns Response → stop and send that response (but still apply "after" functions)
308
- * 3. If middleware returns undefined → continue to next middleware
309
- * 4. If middleware returns function → save it to transform the final response later
310
- * 5. After all middlewares, run the handler
311
- * 6. Apply all saved "after" functions to the response (in reverse order)
698
+ * Dispatches the raw `Request` through the compiled routes (static map
699
+ * first, then the trie fallback for dynamic/wildcard and loose
700
+ * trailing-slash variants). API routes must be provided AOT (`apiRoutes`)
701
+ * or discovered from the filesystem on first call — never per request.
312
702
  *
313
- * Performance optimizations:
314
- * - Pre-allocated array for "after" functions (avoids dynamic resizing)
315
- * - Fast paths for 0, 1, and 2 middlewares (most common cases)
316
- * - Manual loop unrolling for small counts
317
- * - Minimal branching in hot path
318
- */
319
- async processMiddleware(request, middlewares, handler) {
320
- const len = middlewares.length;
321
- // Fast path: two middlewares (common: CORS + logger, or auth + logger)
322
- if (len === 2) {
323
- // First middleware
324
- const result1 = await middlewares[0](request);
325
- if (result1 instanceof Response) {
326
- return result1;
327
- }
328
- // Second middleware
329
- const result2 = await middlewares[1](request);
330
- if (result2 instanceof Response) {
331
- // Apply first middleware's after function if exists
332
- if (typeof result1 === 'function') {
333
- return result1(result2);
334
- }
335
- return result2;
336
- }
337
- // Run handler
338
- let response = await handler(request);
339
- // Apply after functions in reverse order (manual unroll)
340
- if (typeof result2 === 'function') {
341
- response = await result2(response);
703
+ * Runtime-agnostic: Bun.serve, Deno.serve, Vercel, Cloudflare Workers and
704
+ * Node 24+. WinterCG bindings (`env`, `executionCtx`) are bound onto the
705
+ * per-request `BurgerContext`. Pages (Bun-only) are not served here.
706
+ *
707
+ * ```ts
708
+ * import { Burger, toFetchHandler } from 'burger-api';
709
+ * const burger = new Burger({ apiRoutes });
710
+ * export default { fetch: toFetchHandler(burger) };
711
+ * ```
712
+ */
713
+ async fetchHandler() {
714
+ await this.processApiRoutes();
715
+ await this.processPageRoutesOnce();
716
+ // Prepare WebSocket handling for WinterCG runtimes (Cloudflare /
717
+ // Deno consume upgrades right here). Bun's `serve()` path wires the
718
+ // same adapter itself; plain Node needs createNodeWsBridge instead.
719
+ const hasWsSources = Array.isArray(this.options.wsRoutes) ||
720
+ this.programmaticWsRoutes.size > 0 ||
721
+ !!this.wsDir;
722
+ if (!this.wsAdapter && hasWsSources) {
723
+ await this.processWebSocketRoutes();
724
+ }
725
+ const wsAdapter = this.wsAdapter;
726
+ // Direct lookups are exact static paths: page/asset/docs handlers and
727
+ // static API routes. Native pattern keys (`:param`, `*`) must never
728
+ // match literally. Bun-only page values and dynamic pages are not
729
+ // portable: warn instead of silently 404ing.
730
+ const routes = new Map();
731
+ const bunOnlyPages = [];
732
+ const apiPaths = this.apiRoutePaths;
733
+ for (const [key, handler] of Object.entries(this.routes)) {
734
+ if (typeof handler === 'function' &&
735
+ !key.includes(':') &&
736
+ !key.includes('*')) {
737
+ // Exact static path (page / asset / docs route).
738
+ routes.set(key, handler);
739
+ continue;
342
740
  }
343
- if (typeof result1 === 'function') {
344
- response = await result1(response);
741
+ // API routes are per-method objects and dispatch through
742
+ // `router.fetch`; anything else non-callable is Bun-only.
743
+ if (apiPaths?.has(key) !== true)
744
+ bunOnlyPages.push(key);
745
+ }
746
+ if (bunOnlyPages.length > 0) {
747
+ console.warn(`[burger-api] ${bunOnlyPages.length} page route(s) are only served by serve() on Bun ` +
748
+ `(HTML-import bundles / dynamic pages) and will 404 through fetchHandler()/toFetchHandler(): ` +
749
+ bunOnlyPages.join(', '));
750
+ }
751
+ const router = this.dynamicRouter;
752
+ // Static API routes join the same table: one Map.get resolves any
753
+ // exact static path (page, asset, docs, or API), no second lookup.
754
+ if (router) {
755
+ for (const [path, dispatch] of router.staticDispatchMap()) {
756
+ routes.set(path, dispatch);
345
757
  }
346
- return response;
347
758
  }
348
- // General path: 3+ middlewares (less common)
349
- // Pre-allocate array with exact size to avoid dynamic resizing
350
- const afterStack = new Array(len);
351
- let afterCount = 0;
352
- // Run each middleware
353
- for (let i = 0; i < len; i++) {
354
- const result = await middlewares[i](request);
355
- // Short-circuit with Response (check first - most common early exit)
356
- if (result instanceof Response) {
357
- // Apply collected "after" functions in reverse
358
- if (afterCount === 0)
359
- return result;
360
- if (afterCount === 1)
361
- return afterStack[0](result);
362
- // Multiple after functions
363
- let response = result;
364
- for (let j = afterCount - 1; j >= 0; j--) {
365
- response = await afterStack[j](response);
759
+ // No direct entries: skip the lookup entirely and let the router parse
760
+ // the pathname once in `fetch` (dynamic-only apps, 404s).
761
+ const hasPageRoutes = routes.size > 0;
762
+ /**
763
+ * Shared HTTP dispatch: the direct static table (pages, assets, docs,
764
+ * static API routes) first, then the API router for dynamic /
765
+ * loose-trailing-slash / `/`+`//` requests and 404s. The pathname is
766
+ * extracted once and reused for both lookups.
767
+ */
768
+ const dispatchHttp = (request, env, executionCtx) => {
769
+ if (hasPageRoutes) {
770
+ const pathname = extractPathnameFromUrl(request.url);
771
+ const handler = routes.get(pathname);
772
+ if (handler) {
773
+ return handler(request, undefined, undefined, env, executionCtx);
774
+ }
775
+ if (router) {
776
+ return router.fetchWithPath(request, pathname, env, executionCtx);
366
777
  }
367
- return response;
778
+ return this.notFound();
368
779
  }
369
- // Save function for later (check once, no double typeof check)
370
- if (typeof result === 'function') {
371
- afterStack[afterCount++] = result;
780
+ if (router)
781
+ return router.fetch(request, env, executionCtx);
782
+ return this.notFound();
783
+ };
784
+ /** Async-only path: a WebSocket upgrade must be awaited. */
785
+ const handleWsUpgrade = async (request, env, executionCtx) => {
786
+ const outcome = await wsAdapter.handleUpgrade(request, undefined, env, executionCtx);
787
+ if (outcome.handled) {
788
+ return (outcome.response ??
789
+ new Response(null, { status: 101 }));
372
790
  }
373
- // undefined - continue (implicit, no check needed)
374
- }
375
- // All middlewares passed - run handler
376
- let response = await handler(request);
377
- // Apply "after" functions in reverse order
378
- // Fast paths for common cases
379
- if (afterCount === 0)
380
- return response;
381
- if (afterCount === 1)
382
- return afterStack[0](response);
383
- if (afterCount === 2) {
384
- response = await afterStack[1](response);
385
- return afterStack[0](response);
386
- }
387
- // General case: 3+ after functions
388
- for (let i = afterCount - 1; i >= 0; i--) {
389
- response = await afterStack[i](response);
791
+ // Not consumed: fall through to the normal HTTP dispatch.
792
+ return dispatchHttp(request, env, executionCtx);
793
+ };
794
+ // No WebSocket adapter: no upgrade probe is needed at all.
795
+ if (!wsAdapter) {
796
+ // API-only app: the router's `fetch` is the entry point (the
797
+ // public contract still returns a Promise).
798
+ if (!hasPageRoutes && router) {
799
+ return (request, env, executionCtx) => Promise.resolve(router.fetch(request, env, executionCtx));
800
+ }
801
+ return (request, env, executionCtx) => Promise.resolve(dispatchHttp(request, env, executionCtx));
390
802
  }
391
- return response;
803
+ return (request, env, executionCtx) => {
804
+ // WebSocket upgrades are consumed before HTTP dispatch.
805
+ if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
806
+ return handleWsUpgrade(request, env, executionCtx);
807
+ }
808
+ return Promise.resolve(dispatchHttp(request, env, executionCtx));
809
+ };
392
810
  }
393
811
  /**
394
- * Starts the server and begins listening for incoming requests.
395
- * @param port - The port number to listen on. Defaults to `4000`.
396
- * @param cb - An optional cb function to be executed when the server is listening.
397
- * @returns A Promise that resolves when the server has started listening.
812
+ * Starts the server and listens for requests.
813
+ * @param port Port to listen on (default `4000`).
814
+ * @param cb Called when the server is listening.
398
815
  */
399
816
  async serve(port = 4000, cb) {
400
- // Process routes in parallel if possible
401
- const [pagesConfigured, apiConfigured] = await Promise.all([
402
- this.processPageRoutes(),
403
- this.processApiRoutes(),
817
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
818
+ throw new Error(`[burger-api] Invalid port ${JSON.stringify(port)} — expected an integer from 0 to 65535.`);
819
+ }
820
+ // Process API routes first so convention files (plugins.ts, providers.ts)
821
+ // are loaded before WebSocket reads the registries (avoids race).
822
+ const apiConfigured = await this.processApiRoutes();
823
+ const [pagesConfigured, wsConfigured] = await Promise.all([
824
+ this.processPageRoutesOnce(),
825
+ this.processWebSocketRoutes(),
404
826
  ]);
405
- // Flag to track if any routes were loaded
406
- const routesConfigured = pagesConfigured || apiConfigured;
407
- // If routes were configured, start the server
827
+ const routesConfigured = pagesConfigured || apiConfigured || wsConfigured;
408
828
  if (routesConfigured) {
409
- // Start the server
410
- this.server.start(this.routes, async () => {
411
- return this.NOT_FOUND;
412
- }, port, cb);
829
+ // The adapter records its server handle as the lazy `ctx.ip`
830
+ // source (see the `onServer` hook below) — no per-request work.
831
+ const fetchHandler = this.dynamicRouter
832
+ ? (request) => this.dynamicRouter.fetch(request)
833
+ : () => this.notFound();
834
+ const wsOptions = this.wsAdapter?.createWebSocketOption();
835
+ const wsAdapter = this.wsAdapter;
836
+ // Combined fetch handler: try the WebSocket upgrade first, then
837
+ // fall through to HTTP only when the request was not consumed.
838
+ const combinedFetch = wsAdapter
839
+ ? async (request, server) => {
840
+ // Cheap header probe first: plain HTTP requests (no
841
+ // `upgrade: websocket`) skip the async upgrade path.
842
+ if (request.headers.get('upgrade')?.toLowerCase() !==
843
+ 'websocket') {
844
+ return fetchHandler(request, server);
845
+ }
846
+ const outcome = await wsAdapter.handleUpgrade(request, server);
847
+ if (outcome.handled) {
848
+ // Socket taken over (Bun returns 101 itself) or a
849
+ // protocol response (404 / auth rejection) — the
850
+ // HTTP pipeline must NOT run.
851
+ return outcome.response;
852
+ }
853
+ return fetchHandler(request, server);
854
+ }
855
+ : fetchHandler;
856
+ // A WS route on the same path as a static HTTP route is
857
+ // unreachable: Bun's static routes answer before the upgrade.
858
+ for (const wsRoute of this.wsRouter?.getRoutes() ?? []) {
859
+ if (this.routes[wsRoute.path]) {
860
+ console.warn(`[burger-api] WebSocket route "${wsRoute.path}" is shadowed by an HTTP route on the same path — upgrades never reach it. Move one of them.`);
861
+ }
862
+ }
863
+ await this.server.start({
864
+ staticRoutes: this.routes,
865
+ fetch: combinedFetch,
866
+ websocket: wsOptions,
867
+ port,
868
+ onListen: cb,
869
+ onServer: (server) => this.dynamicRouter?.setRequestIPSource(server),
870
+ });
413
871
  }
414
872
  else {
415
- // If no routes were configured, log an error
416
- console.error('Error: No routes configured! Please provide apiDir/pageDir (for dev) or apiRoutes/pageRoutes (for production builds) when initializing the Burger class.');
873
+ // Nothing to serve is a startup error, never a silent no-op.
874
+ throw new Error(this.emptyApiDir
875
+ ? `[burger-api] No routes configured — the API directory "${this.emptyApiDir}" has no route files. ` +
876
+ 'Each endpoint is a folder with a route.ts, e.g. src/api/hello/route.ts: ' +
877
+ 'export async function GET(ctx) { return Response.json({ hello: "world" }); }'
878
+ : '[burger-api] No routes configured! Please provide apiDir/pageDir (for dev) or apiRoutes/pageRoutes (for production builds) when initializing the Burger class.');
879
+ }
880
+ }
881
+ /**
882
+ * The underlying `Server` instance, exposed so callers can stop the
883
+ * server cleanly.
884
+ */
885
+ getServer() {
886
+ return this.server;
887
+ }
888
+ /**
889
+ * Node WebSocket integration: returns a bridge that plugs the framework
890
+ * pipeline into node:http's `'upgrade'` event using a framing library's
891
+ * `WebSocketServer` (e.g. the `ws` package). Call `fetchHandler()` (or
892
+ * `serve()`) first — WebSocket routes are processed there.
893
+ *
894
+ * ```ts
895
+ * import http from 'node:http';
896
+ * import { WebSocketServer } from 'ws';
897
+ *
898
+ * const fetchHandler = await burger.fetchHandler();
899
+ * const bridge = burger.createNodeWsBridge({ WebSocketServer });
900
+ * http.createServer((req, res) => { ... })
901
+ * .on('upgrade', (req, socket, head) =>
902
+ * bridge.handleUpgrade(req, socket, head))
903
+ * .listen(3000);
904
+ * ```
905
+ */
906
+ createNodeWsBridge(options) {
907
+ if (!this.wsAdapter) {
908
+ throw new Error(this.routesProcessed
909
+ ? '[burger-api] createNodeWsBridge(): no WebSocket routes are configured — ' +
910
+ 'add wsDir / wsRoutes / burger.websocket() first.'
911
+ : '[burger-api] createNodeWsBridge() was called too early. Call it after ' +
912
+ '`const fetch = await burger.fetchHandler();` (or `await burger.serve()`) — ' +
913
+ 'WebSocket routes are processed there.');
417
914
  }
915
+ return this.wsAdapter.createNodeWsBridge(options);
916
+ }
917
+ }
918
+ /**
919
+ * Connection-level WebSocket options (`maxPayloadLength`, `idleTimeout`,
920
+ * `compression`, …) are Bun.serve-wide: a route-level value cannot override
921
+ * what Bun enforces for the whole server, so warn loud instead of ignoring it.
922
+ */
923
+ const WS_TRANSPORT_KEYS = [
924
+ 'maxPayloadLength',
925
+ 'idleTimeout',
926
+ 'backpressureLimit',
927
+ 'closeOnBackpressureLimit',
928
+ 'compression',
929
+ ];
930
+ /**
931
+ * Base64 of the UTF-8 bytes. `btoa` alone throws on non-Latin1 input, so a
932
+ * password with accents/emoji would break startup.
933
+ */
934
+ function base64Utf8(value) {
935
+ const bytes = new TextEncoder().encode(value);
936
+ let binary = '';
937
+ for (let i = 0; i < bytes.length; i++) {
938
+ binary += String.fromCharCode(bytes[i]);
939
+ }
940
+ return btoa(binary);
941
+ }
942
+ /** Picks the WebSocket hooks out of an app-level hooks object. */
943
+ function pickWsHooks(hooks) {
944
+ if (!hooks)
945
+ return undefined;
946
+ const { onOpen, onMessage, onClose } = hooks;
947
+ if (!onOpen && !onMessage && !onClose)
948
+ return undefined;
949
+ return { onOpen, onMessage, onClose };
950
+ }
951
+ function warnTransportLevelWsConfig(path, config) {
952
+ if (!config)
953
+ return;
954
+ for (const key of WS_TRANSPORT_KEYS) {
955
+ if (config[key] !== undefined) {
956
+ console.warn(`[burger-api] WebSocket route "${path}": config.${key} is ` +
957
+ 'connection-level and can only be set globally via ' +
958
+ 'burger.wsConfig() — the per-route value is ignored.');
959
+ }
960
+ }
961
+ }
962
+ /**
963
+ * Merges global and per-route config. `auth` is merged deeply so a route-level
964
+ * `auth.roles` keeps a global `auth.required`; either side `false` disables it.
965
+ */
966
+ function mergeWsConfig(globalConfig, routeConfig) {
967
+ const merged = {
968
+ ...globalConfig,
969
+ ...routeConfig,
970
+ };
971
+ const globalAuth = globalConfig?.auth;
972
+ const routeAuth = routeConfig?.auth;
973
+ if (globalAuth !== undefined || routeAuth !== undefined) {
974
+ merged.auth =
975
+ globalAuth === false || routeAuth === false
976
+ ? false
977
+ : {
978
+ ...(typeof globalAuth === 'object' ? globalAuth : {}),
979
+ ...(typeof routeAuth === 'object' ? routeAuth : {}),
980
+ };
418
981
  }
982
+ return merged;
419
983
  }
420
- // Export utils
421
- export { setDir } from './utils/index';
984
+ // Export BurgerContext (the public request context type)
985
+ export { BurgerContext, setRequestIP } from './context/context.js';
986
+ // Export the schema-typed route/hooks helpers
987
+ export { defineRoute, defineHooks } from './router/define.js';
988
+ // Export the runtime-capability model (used by the CLI build and docs).
989
+ export { RUNTIME_CAPABILITIES } from './runtime/capabilities.js';
990
+ // Export utils used by examples and CLI build pipeline
991
+ export { setDir } from './utils/index.js';
992
+ export { cleanPrefix, normalizePath } from './utils/index.js';
993
+ // Export constant-time comparison (used by ecosystem auth plugins)
994
+ export { timingSafeEqual } from './utils/timing-safe.js';
995
+ // Export error classes
996
+ export { HTTPError, renderHTTPError } from './errors/http-error.js';
997
+ export { ASSET_MIME, contentTypeFor } from './core/asset-mime.js';
998
+ export { ValidationError } from './validation/error.js';
999
+ export { NotFoundError } from './errors/not-found.js';
1000
+ export { UnauthorizedError } from './errors/unauthorized.js';
1001
+ export { ForbiddenError } from './errors/forbidden.js';
1002
+ export { MethodNotAllowedError } from './errors/method-not-allowed.js';
1003
+ // Export docs providers
1004
+ export { scalarDocs, swaggerDocs, redocDocs } from './core/docs-providers.js';
1005
+ // Export the Web-Standard (WinterCG) fetch entry
1006
+ export { toFetchHandler } from './adapter/web-standard/index.js';
1007
+ export { WebSocketReadyState, WebSocketCloseCode, BurgerWSContext, } from './ws/types.js';
1008
+ export { WebSocketAdapter } from './ws/adapter.js';