burger-api 0.9.7 → 1.0.0-beta.1

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