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
@@ -0,0 +1,817 @@
1
+ import { HTTP_METHODS } from '../utils/routing.js';
2
+ import { compileRouteSchema } from '../validation/compiler.js';
3
+ import { createValidationHook } from '../validation/validator.js';
4
+ import { methodNotAllowed, applySet, createAutoOptionsHandler, } from '../utils/response.js';
5
+ import { HTTPError } from '../errors/http-error.js';
6
+ import { dispatchOnError, executeHookPlanForHandler, globalErrorFinisher, hasGlobalResponseHooks, runGlobalResponseHooks, } from '../lifecycle/executor.js';
7
+ import { compileJitHookPlan } from '../lifecycle/jit.js';
8
+ import { HookChain } from '../chain/chain.js';
9
+ import { flatten } from '../chain/flattener.js';
10
+ import { composePluginHooks } from '../plugin/composer.js';
11
+ import { BurgerContext, createServices } from '../context/context.js';
12
+ import { analyzeRouteAccess } from '../analysis/route-access-analyzer.js';
13
+ import { assertTransformKeys } from '../lifecycle/transform.js';
14
+ import { isThenable } from '../utils/thenable.js';
15
+ import { AllowCache } from './allow-cache.js';
16
+ import { StaticMap } from './static-map.js';
17
+ import { Trie } from './trie.js';
18
+ import { ROUTE_CONSTANTS } from '../utils/routing.js';
19
+ import { compilePatternSegments, extractCtxInitWithSegments, } from './param-extract.js';
20
+ /**
21
+ * Builds the global + plugin (+ framework) response plan, in the same
22
+ * nearest-first order route plans use (global → plugin → framework; route
23
+ * scope is excluded because it only runs for matched routes).
24
+ */
25
+ export function buildGlobalResponsePlan(plugins, globalHooks) {
26
+ const after = {
27
+ local: [],
28
+ global: [],
29
+ plugin: [],
30
+ framework: [],
31
+ };
32
+ const map = {
33
+ local: [],
34
+ global: [],
35
+ plugin: [],
36
+ framework: [],
37
+ };
38
+ const push = (value, bucket) => {
39
+ if (value === undefined)
40
+ return;
41
+ if (Array.isArray(value)) {
42
+ for (const hook of value)
43
+ bucket.push(hook);
44
+ }
45
+ else {
46
+ bucket.push(value);
47
+ }
48
+ };
49
+ push(globalHooks?.afterRoute, after.global);
50
+ push(globalHooks?.mapResponse, map.global);
51
+ for (const plugin of plugins ?? []) {
52
+ push(plugin.hooks.afterRoute, after[plugin.scope]);
53
+ push(plugin.hooks.mapResponse, map[plugin.scope]);
54
+ }
55
+ return {
56
+ afterRoute: [...after.global, ...after.plugin, ...after.framework],
57
+ mapResponse: [...map.global, ...map.plugin, ...map.framework],
58
+ };
59
+ }
60
+ /**
61
+ * Compiles a `RouteDefinition[]` into the dispatch structures used by `Router`:
62
+ * builds one `CompiledHandler` per route (method dispatch + 405/Allow +
63
+ * auto-HEAD + hook pipeline), classifies routes as static (`StaticMap`) or
64
+ * dynamic/wildcard (`Trie`), populates the `AllowCache`, optionally runs the
65
+ * `RouteAccessAnalyzer` (compile-time only; its output is never read at
66
+ * runtime), and fails fast on duplicate or ambiguous routes.
67
+ */
68
+ export class RouterCompiler {
69
+ debug;
70
+ config;
71
+ /** JIT HookPlan compilation (capability-gated; on unless `jit: false`). */
72
+ jit;
73
+ constructor(debug, config = {}, jit = false) {
74
+ this.debug = debug;
75
+ this.config = config;
76
+ this.jit = jit;
77
+ }
78
+ compile(defs, plugins, providers, onRequestHooksCount = 0, globalHooks, ipHolder) {
79
+ const staticMap = new StaticMap();
80
+ const trie = new Trie();
81
+ const allowCache = new AllowCache();
82
+ // Native dispatch table: `:param` / `*` routes keyed by their Bun
83
+ // pattern (e.g. `/users/:id`). Handed to Bun's `routes` map so dynamic
84
+ // routes skip the `fetch` fallback hop; the compiled handler
85
+ // self-extracts params (see param-extract.ts). The trie is retained
86
+ // for the `fetch` fallback (unmatched / loose-slash / empty param).
87
+ const nativeRoutes = new Map();
88
+ // Per-route per-method specialized executors (fed to Bun method
89
+ // objects by the Router).
90
+ const methodCores = new Map();
91
+ const registeredPaths = new Set();
92
+ // Retained metadata per route (RouteAccessInfo + RouteMeta). Build-time
93
+ // only; never read on the request hot path.
94
+ const compiledRoutes = new Map();
95
+ // App services resolved ONCE — shared (frozen) by every request.
96
+ const services = createServices(providers);
97
+ // Plugin / app-level hook functions every route runs; the route-access
98
+ // analyzer scans them alongside the route's own source (once per
99
+ // compile pass).
100
+ const accessSources = collectAccessSources(plugins, globalHooks);
101
+ // Reserved transform keys fail startup, even for apps without routes.
102
+ assertTransformKeys(globalHooks?.transform, 'global hooks');
103
+ if (plugins) {
104
+ for (const plugin of plugins) {
105
+ assertTransformKeys(plugin.hooks.transform, `plugin "${plugin.name}"`);
106
+ }
107
+ }
108
+ // Global/plugin response hooks for non-route responses (404/405/
109
+ // auto-OPTIONS/errors); matched routes already carry them in `plan`.
110
+ const globalResponse = buildGlobalResponsePlan(plugins, globalHooks);
111
+ for (const def of defs) {
112
+ const path = def.path;
113
+ // Allow header: every method the route answers. HEAD is advertised
114
+ // when GET exists (auto-HEAD) or was defined explicitly; OPTIONS is
115
+ // always answered (auto OPTIONS), so it is always listed.
116
+ const userMethods = Object.keys(def.handlers);
117
+ const allowMethods = userMethods.filter((m) => m !== 'HEAD');
118
+ const allowList = [];
119
+ for (const m of allowMethods) {
120
+ allowList.push(m);
121
+ if (m === 'GET' && !userMethods.includes('HEAD')) {
122
+ allowList.push('HEAD');
123
+ }
124
+ }
125
+ if (userMethods.includes('HEAD'))
126
+ allowList.push('HEAD');
127
+ if (!allowList.includes('OPTIONS'))
128
+ allowList.push('OPTIONS');
129
+ const allow = allowCache.compute(allowList);
130
+ allowCache.set(path, allow);
131
+ // Every handler is checked to return a `Response`. Every route
132
+ // also answers OPTIONS: when none is declared the framework adds
133
+ // one (204 + Allow) that skips beforeRoute, so auth hooks never
134
+ // reject CORS preflights (onRequest still runs).
135
+ //
136
+ // `rawHandlers` keeps the user function; `handlers` wraps it with
137
+ // the Response check for the hook pipeline.
138
+ const rawHandlers = {};
139
+ const handlers = {};
140
+ for (const m of Object.keys(def.handlers)) {
141
+ const h = def.handlers[m];
142
+ if (typeof h !== 'function')
143
+ continue;
144
+ rawHandlers[m] = h;
145
+ handlers[m] = h.isAutoOptions
146
+ ? h
147
+ : requireResponse(h, m, path);
148
+ }
149
+ if (!handlers.OPTIONS) {
150
+ // The auto-OPTIONS `Allow` must equal the 405 `Allow`, so
151
+ // reuse the exact list: HEAD (when GET exists) and OPTIONS
152
+ // included.
153
+ const autoOptions = createAutoOptionsHandler(allowList);
154
+ rawHandlers.OPTIONS = autoOptions;
155
+ handlers.OPTIONS = autoOptions;
156
+ }
157
+ const hasSchema = !!def.schema;
158
+ let routeValidators;
159
+ // Compose the frozen `HookPlan` once at compile time. The chain
160
+ // collects nodes tagged with scope + owner; the flattener orders
161
+ // the per-hook-point arrays (global → local for forward hooks,
162
+ // local → global for onError). Validation is global scope, so it
163
+ // pins at index 0.
164
+ const routeHooks = def.hooks;
165
+ const chain = new HookChain();
166
+ if (hasSchema) {
167
+ const validators = compileRouteSchema(def.schema, this.config, undefined, path);
168
+ chain.add({
169
+ stage: 'validation',
170
+ fn: createValidationHook(validators, this.config, this.debug === true),
171
+ scope: 'global',
172
+ owner: 'framework',
173
+ });
174
+ routeValidators = validators;
175
+ }
176
+ // App-level hooks (`src/hooks.ts` / `globalHooks`) stage with scope
177
+ // 'global', route hooks with scope 'local'; the flattener owns the
178
+ // ordering: request hooks run Plugin → Global → Route, response +
179
+ // error hooks Route → Global → Plugin (nearest-first). Declared
180
+ // order is kept within a scope; user arrays are never mutated.
181
+ addHookStages(chain, globalHooks, 'global', 'app');
182
+ addHookStages(chain, routeHooks, 'local', path);
183
+ // Plugin hooks are scoped (plugin by default); the flattener orders
184
+ // them between global (validation) and local (route).
185
+ if (plugins) {
186
+ composePluginHooks(chain, plugins, path);
187
+ }
188
+ const plan = flatten(chain, path);
189
+ // Merge transform from plugins, global hooks and route hooks (in
190
+ // that precedence order — route wins on key collision).
191
+ plan.transform = mergeTransformRecords(routeHooks?.transform, plugins, globalHooks?.transform);
192
+ assertTransformKeys(plan.transform, `${path} transform`);
193
+ // The error path needs the global hooks too; the plan already
194
+ // carries them in afterRoute/mapResponse for the success path.
195
+ if (hasGlobalResponseHooks(globalResponse)) {
196
+ plan.globalResponse = globalResponse;
197
+ }
198
+ // Attach compiled validators for response validation post-handler.
199
+ if (routeValidators) {
200
+ plan.validators = routeValidators;
201
+ }
202
+ // Thread debug flag for error rendering.
203
+ plan.debug = this.debug;
204
+ // Split `config.ts` into route-wide options + per-method overrides
205
+ // once; each method resolves its own merged config below. A
206
+ // default-only config passes through with its identity intact.
207
+ const { base: baseConfig, methods: methodConfigs } = splitConfig(def.config);
208
+ // Thread global validation config for response validation. A
209
+ // route's `config.ts` may override `responseValidation`; a
210
+ // per-method override replaces it for that method only.
211
+ plan.validatorConfig = resolveValidatorConfig(this.config, baseConfig);
212
+ // Compile-time-only field analysis. A `known` result (every reader
213
+ // provably accesses fields only through direct member reads) lets
214
+ // the executor skip work for fields nothing reads; any doubt keeps
215
+ // the conservative "all fields used" fallback, and `debug: true`
216
+ // disables analysis entirely.
217
+ const meta = analyzeRouteAccess(def, this.debug, accessSources);
218
+ const isWildcard = def.isWildcard === true;
219
+ const isStatic = isStaticPath(path);
220
+ const cores = buildRouteCores(rawHandlers, handlers, plan, meta, path, isWildcard, isStatic, baseConfig, methodConfigs, this.config, this.jit, services, ipHolder, globalResponse);
221
+ methodCores.set(path, cores);
222
+ // The `fetch` fallback (trie / loose-slash / undefined method)
223
+ // dispatches through the same specialized per-method functions.
224
+ const compiled = buildFallbackHandler(cores, allow);
225
+ // Retain compiled-route metadata (RouteAccessInfo + RouteMeta).
226
+ // When a schema exists, also retain the precompiled validators so
227
+ // the validation orchestrator runs them at request time.
228
+ compiledRoutes.set(path, {
229
+ def: { ...def, handlers },
230
+ handler: compiled,
231
+ methods: allowMethods,
232
+ allow,
233
+ route: { path, pattern: path },
234
+ meta,
235
+ validators: routeValidators,
236
+ });
237
+ if (isStatic) {
238
+ if (registeredPaths.has(path)) {
239
+ throw new Error(`Duplicate static route registered: "${path}". ` +
240
+ `Each path may be defined by exactly one route.ts.`);
241
+ }
242
+ registeredPaths.add(path);
243
+ staticMap.set(path, compiled, cores);
244
+ // Optional: cache provably-constant OPTIONS responses natively.
245
+ // (Loose trailing-slash equivalence is resolved at lookup time in
246
+ // Router.fetch, so it never shadows a `:param` empty-value match.)
247
+ registerNativeOptions(path, { ...def, handlers }, hasSchema, onRequestHooksCount);
248
+ }
249
+ else {
250
+ if (registeredPaths.has(path)) {
251
+ throw new Error(`Duplicate route registered: "${path}". ` +
252
+ `Each path may be defined by exactly one route.ts.`);
253
+ }
254
+ registeredPaths.add(path);
255
+ const methods = new Set(Object.keys(handlers).map((m) => m.toUpperCase()));
256
+ trie.insert(path, compiled, methods, isWildcard);
257
+ // Register on Bun's native router (no `fetch` hop): the
258
+ // specialized method handlers derive `params` from Bun's
259
+ // `request.params` (or the URL when invoked directly).
260
+ nativeRoutes.set(path, compiled);
261
+ }
262
+ }
263
+ return {
264
+ staticMap,
265
+ trie,
266
+ allowCache,
267
+ nativeRoutes,
268
+ methodCores,
269
+ routes: compiledRoutes,
270
+ };
271
+ }
272
+ /**
273
+ * Compiles a `RouteModule[]` (the Module Loader's output) into the
274
+ * dispatch structures — the compiler entry point for the file-based
275
+ * pipeline (Scanner → Module Loader → `RouteModule` → Compiler).
276
+ *
277
+ * Each module is normalized to the `RouteDefinition` shape, then compiled
278
+ * through {@link compile}.
279
+ */
280
+ compileModules(modules) {
281
+ return this.compile(modules.map(toRouteDefinition));
282
+ }
283
+ }
284
+ /**
285
+ * Normalizes a `RouteModule` (the compiler's intermediate) into the
286
+ * `RouteDefinition` shape consumed by the runtime. Convention data
287
+ * (`hooks`) is carried for downstream compilation; `config` is kept for
288
+ * runtime use.
289
+ */
290
+ function toRouteDefinition(mod) {
291
+ return {
292
+ path: mod.path,
293
+ handlers: mod.handlers,
294
+ schema: mod.schema,
295
+ openapi: mod.openapi,
296
+ hooks: mod.hooks,
297
+ isWildcard: mod.isWildcard,
298
+ config: mod.config,
299
+ };
300
+ }
301
+ /**
302
+ * Normalizes a single hook value (function or array) into an array.
303
+ * Generic so it works for both `Hook` and `ErrorHook`.
304
+ */
305
+ function toHookArray(h) {
306
+ if (h === undefined)
307
+ return [];
308
+ return Array.isArray(h) ? h : [h];
309
+ }
310
+ /** Stages one hook object's beforeRoute/afterRoute/mapResponse/onError. */
311
+ function addHookStages(chain, hooks, scope, owner) {
312
+ if (!hooks)
313
+ return;
314
+ chain.addStage('beforeRoute', toHookArray(hooks.beforeRoute), scope, owner);
315
+ chain.addStage('afterRoute', toHookArray(hooks.afterRoute), scope, owner);
316
+ chain.addStage('mapResponse', toHookArray(hooks.mapResponse), scope, owner);
317
+ chain.addStage('onError', toHookArray(hooks.onError), scope, owner);
318
+ }
319
+ /**
320
+ * Wraps a route handler so a non-`Response` return value fails loud with a
321
+ * clear 500 (message visible in dev, generic in production, always logged)
322
+ * instead of leaking to the runtime.
323
+ */
324
+ function requireResponse(handler, method, path) {
325
+ const check = (result) => {
326
+ if (result instanceof Response)
327
+ return result;
328
+ const kind = result === null
329
+ ? 'null'
330
+ : Array.isArray(result)
331
+ ? 'array'
332
+ : typeof result;
333
+ throw new HTTPError(500, `${method} ${path} returned ${kind}; route handlers must return a Response`);
334
+ };
335
+ return (ctx) => {
336
+ const result = handler(ctx);
337
+ return result instanceof Promise ? result.then(check) : check(result);
338
+ };
339
+ }
340
+ /** Describes a non-Response handler return for the fail-loud 500 message. */
341
+ function describeReturn(result) {
342
+ return result === null
343
+ ? 'null'
344
+ : Array.isArray(result)
345
+ ? 'array'
346
+ : typeof result;
347
+ }
348
+ /**
349
+ * Builds one specialized executor per route+method. Each creates (or binds)
350
+ * the request context, runs the hook plan (or calls the handler directly for
351
+ * an empty plan), and merges `ctx.set` into the response. Auto-HEAD and the
352
+ * framework's auto OPTIONS are baked in here.
353
+ *
354
+ * `config` is the route-wide config; `methodConfigs` holds the per-method
355
+ * overrides. Both are resolved to one merged object per method at compile
356
+ * time — no per-request merging or allocation.
357
+ */
358
+ function buildRouteCores(rawHandlers, planHandlers, plan, meta, pattern, isWildcard, isStatic, config, methodConfigs, validatorBase, jit, services, ipHolder, globalResponse) {
359
+ const cores = {};
360
+ // Static routes share one frozen route identity object; dynamic routes
361
+ // carry only the pattern and derive `route.path` lazily on first access.
362
+ const staticRouteMeta = isStatic
363
+ ? Object.freeze({ path: pattern, pattern })
364
+ : undefined;
365
+ // When the analyzer proved nothing reads `ctx.validated` and a method
366
+ // declares no validators, the empty `{}` bag is not allocated.
367
+ const skipValidatedBag = meta.unknown === false && !meta.has('validated');
368
+ for (const m of Object.keys(planHandlers)) {
369
+ const methodConfig = mergeMethodConfig(config, methodConfigs?.[m.toLowerCase()]);
370
+ cores[m] = buildMethodCore(m, m, rawHandlers[m], planHandlers[m], specializePlan(plan, m, skipValidatedBag, methodValidatorConfig(plan, validatorBase, methodConfig)), meta, pattern, isWildcard, staticRouteMeta, methodConfig, jit, services, ipHolder, globalResponse);
371
+ }
372
+ // Auto-HEAD: derive from GET when no explicit HEAD handler exists. The
373
+ // GET handler runs through the normal plan and its response is returned as-is:
374
+ // the server drops the body (and cancels a stream) for HEAD, so a body is
375
+ // never read here. Config follows GET, mirroring the handler derivation.
376
+ if (!cores.HEAD && rawHandlers.GET) {
377
+ const headConfig = mergeMethodConfig(config, methodConfigs?.head ?? methodConfigs?.get);
378
+ const headCore = buildMethodCore('HEAD', 'GET', rawHandlers.GET, planHandlers.GET, specializePlan(plan, 'HEAD', skipValidatedBag, methodValidatorConfig(plan, validatorBase, headConfig)), meta, pattern, isWildcard, staticRouteMeta, headConfig, jit, services, ipHolder, globalResponse);
379
+ cores.HEAD = (request, ctxInit, prebuilt, env, executionCtx) => {
380
+ const result = headCore(request, ctxInit, prebuilt, env, executionCtx);
381
+ return isThenable(result)
382
+ ? result.then(finishHead)
383
+ : finishHead(result);
384
+ };
385
+ }
386
+ return cores;
387
+ }
388
+ /**
389
+ * Auto-HEAD exit. The body is never read: the server drops it for HEAD (and
390
+ * reports a buffered body's size). A handler-set Content-Length is kept by
391
+ * sending headers only, since some servers drop it when the body is a stream.
392
+ */
393
+ function finishHead(response) {
394
+ if (!response.body || !response.headers.has('content-length')) {
395
+ return response;
396
+ }
397
+ void response.body.cancel().catch(() => { });
398
+ return new Response(null, {
399
+ status: response.status,
400
+ statusText: response.statusText,
401
+ headers: response.headers,
402
+ });
403
+ }
404
+ /**
405
+ * Shallow-merges a method's config over the route-wide config (method keys
406
+ * win). Returns the route-wide object unchanged when the method has no
407
+ * override — preserving its identity for `ctx.config`.
408
+ */
409
+ function mergeMethodConfig(base, override) {
410
+ if (!override)
411
+ return base;
412
+ return { ...base, ...override };
413
+ }
414
+ /**
415
+ * Resolves a method's effective `responseValidation` mode. Returns the base
416
+ * plan's config object unchanged when the method does not change the mode, so
417
+ * every core without an override shares the same ValidatorConfig.
418
+ */
419
+ function methodValidatorConfig(plan, validatorBase, methodConfig) {
420
+ const baseResolved = plan.validatorConfig ??
421
+ resolveValidatorConfig(validatorBase, undefined);
422
+ if (methodConfig === undefined)
423
+ return baseResolved;
424
+ const mode = methodConfig.responseValidation;
425
+ if (mode !== 'off' && mode !== 'dev' && mode !== 'enforce') {
426
+ return baseResolved;
427
+ }
428
+ return mode === baseResolved.responseValidation
429
+ ? baseResolved
430
+ : { ...validatorBase, responseValidation: mode };
431
+ }
432
+ /**
433
+ * Applies a route config's `responseValidation` mode to the app validation
434
+ * config; unknown/absent modes leave the base object untouched.
435
+ */
436
+ function resolveValidatorConfig(base, config) {
437
+ const mode = config?.responseValidation;
438
+ return mode === 'off' || mode === 'dev' || mode === 'enforce'
439
+ ? { ...base, responseValidation: mode }
440
+ : base;
441
+ }
442
+ /**
443
+ * Splits a route's `config.ts` object into route-wide options and per-method
444
+ * overrides (uppercase method keys only, lowercased here), so plain options
445
+ * such as `options` or `delete` stay route-wide. A config without method
446
+ * keys passes through untouched, preserving object identity.
447
+ */
448
+ function splitConfig(config) {
449
+ if (!config)
450
+ return { base: undefined, methods: undefined };
451
+ let methods;
452
+ for (const [key, value] of Object.entries(config)) {
453
+ if (!isMethodKey(key))
454
+ continue;
455
+ if (value === null || typeof value !== 'object')
456
+ continue;
457
+ (methods ??= {})[key.toLowerCase()] = value;
458
+ }
459
+ if (!methods)
460
+ return { base: config, methods: undefined };
461
+ const base = {};
462
+ for (const [key, value] of Object.entries(config)) {
463
+ if (isMethodKey(key))
464
+ continue;
465
+ base[key] = value;
466
+ }
467
+ return { base, methods };
468
+ }
469
+ /** True when `key` is an uppercase HTTP method (`GET`, `POST`, …). */
470
+ function isMethodKey(key) {
471
+ return HTTP_METHODS.includes(key);
472
+ }
473
+ /**
474
+ * Clones a route plan with the validation hook specialized for one method:
475
+ * the method lookup and `toLowerCase()` are resolved at compile time, so the
476
+ * request path runs only the declared slots. Plans without validators are
477
+ * returned as-is (no allocation) unless the method's `responseValidation`
478
+ * override changed the validator config.
479
+ */
480
+ function specializePlan(plan, method, skipValidatedBag, validatorConfig) {
481
+ const validators = plan.validators;
482
+ const configChanged = validatorConfig !== plan.validatorConfig;
483
+ if (!validators || !plan.validation) {
484
+ return configChanged ? { ...plan, validatorConfig } : plan;
485
+ }
486
+ // Response validation is resolved at compile time. 'off', and 'dev'
487
+ // without debug output, do no observable work — dropping the validator
488
+ // removes the per-request clone/parse entirely.
489
+ const responseMode = validatorConfig.responseValidation ?? 'dev';
490
+ const dropResponse = validators.response !== undefined &&
491
+ (responseMode === 'off' ||
492
+ (responseMode === 'dev' && plan.debug !== true));
493
+ const planValidators = dropResponse
494
+ ? omitResponseValidators(validators)
495
+ : validators;
496
+ return {
497
+ ...plan,
498
+ validation: createValidationHook(validators, plan.validatorConfig ?? {}, plan.debug === true, method.toLowerCase(), skipValidatedBag),
499
+ validators: planValidators,
500
+ validatorConfig,
501
+ };
502
+ }
503
+ /** Shallow copy of the validators without the `response` map. */
504
+ function omitResponseValidators(validators) {
505
+ const { response: _response, ...rest } = validators;
506
+ return rest;
507
+ }
508
+ /**
509
+ * Per-function access readers that are not part of the route definition but
510
+ * still run for it: plugin hooks and app-level (`src/hooks.ts`) hooks plus
511
+ * their transform factories. Used by the route-access analyzer so a "known"
512
+ * result accounts for every framework-known reader.
513
+ */
514
+ function collectAccessSources(plugins, globalHooks) {
515
+ const out = [];
516
+ const pushStage = (value) => {
517
+ if (value === undefined)
518
+ return;
519
+ if (Array.isArray(value)) {
520
+ for (let i = 0; i < value.length; i++)
521
+ out.push(value[i]);
522
+ }
523
+ else {
524
+ out.push(value);
525
+ }
526
+ };
527
+ const pushHooks = (hooks) => {
528
+ pushStage(hooks.beforeRoute);
529
+ pushStage(hooks.afterRoute);
530
+ pushStage(hooks.mapResponse);
531
+ pushStage(hooks.onError);
532
+ if (hooks.transform !== undefined)
533
+ out.push(hooks.transform);
534
+ };
535
+ if (globalHooks)
536
+ pushHooks(globalHooks);
537
+ if (plugins) {
538
+ for (let i = 0; i < plugins.length; i++)
539
+ pushHooks(plugins[i].hooks);
540
+ }
541
+ return out;
542
+ }
543
+ /**
544
+ * Builds one method's executor. The empty-plan path calls the handler
545
+ * directly with a synchronous try/catch; the Response check and `ctx.set`
546
+ * merge happen in `settle`, and failures render through the same
547
+ * `dispatchOnError` path the hook pipeline uses.
548
+ */
549
+ function buildMethodCore(method, errorMethod, rawHandler, planHandler, plan, meta, pattern, isWildcard, staticRouteMeta, config, jit, services, ipHolder, globalResponse) {
550
+ // The framework's auto OPTIONS answers directly: no beforeRoute (auth
551
+ // hooks must not reject CORS preflights) and no route hooks. Global and
552
+ // plugin response hooks still run (headers on preflight), as does
553
+ // `ctx.set` seeded by onRequest.
554
+ if (rawHandler.isAutoOptions) {
555
+ if (!hasGlobalResponseHooks(globalResponse)) {
556
+ return () => rawHandler();
557
+ }
558
+ return (request, _ctxInit, prebuilt, env, executionCtx) => {
559
+ const ctx = prebuilt ??
560
+ BurgerContext.create(request, undefined, undefined, services, undefined, env, executionCtx, ipHolder);
561
+ const response = rawHandler();
562
+ return runGlobalResponseHooks(globalResponse, ctx, response).then((res) => (ctx.hasSet() ? applySet(res, ctx.set) : res));
563
+ };
564
+ }
565
+ // `isWildcard` may be unset on hand-built AOT definitions; the pattern is
566
+ // authoritative (extractCtxInit always keyed off it too).
567
+ const hasWildcard = isWildcard || pattern.includes('*');
568
+ // When the analyzer proved (`unknown === false`) that neither the handler
569
+ // nor any framework-known hook reads params/wildcardParams, and the method
570
+ // declares no params validator, per-request extraction (Bun record copy /
571
+ // URL split + decode) is skipped. `ctx.params` still materializes lazily
572
+ // as `{}` if unforeseen code reads it, matching the documented
573
+ // empty-record default.
574
+ const needsParams = meta.unknown !== false ||
575
+ meta.has('params') ||
576
+ meta.has('wildcardParams') ||
577
+ methodHasSlot(plan.validators, method, 'params');
578
+ // The pattern's segment layout is compiled ONCE here; request handling
579
+ // does a single URL scan and decodes only `%`-bearing segments.
580
+ const compiledPattern = needsParams && !staticRouteMeta
581
+ ? compilePatternSegments(pattern)
582
+ : undefined;
583
+ const resolveCtxInit = (request) => {
584
+ if (staticRouteMeta)
585
+ return { route: staticRouteMeta };
586
+ if (!needsParams) {
587
+ // Only the pattern is carried so `ctx.route` can still derive its
588
+ // concrete path lazily.
589
+ return { pattern };
590
+ }
591
+ // Wildcards are not exposed by Bun's `request.params`; the URL is
592
+ // needed to split the captured segments.
593
+ if (hasWildcard) {
594
+ return extractCtxInitWithSegments(request, pattern, compiledPattern);
595
+ }
596
+ // Bun decodes `:param` values already; use its record directly (a
597
+ // plain object with `Record<string,string>` semantics) and keep the
598
+ // route identity lazy. Direct (non-Bun) invocations fall back to URL
599
+ // extraction.
600
+ const bunParams = request
601
+ .params;
602
+ return bunParams !== undefined
603
+ ? { params: bunParams, pattern }
604
+ : extractCtxInitWithSegments(request, pattern, compiledPattern);
605
+ };
606
+ const makeCtx = (request, ctxInit, prebuilt, env, executionCtx) => {
607
+ const init = ctxInit ?? resolveCtxInit(request);
608
+ // One context per request: bind the pre-routing instance (onRequest)
609
+ // when present, otherwise allocate it here. `meta` is accepted but
610
+ // ignored at runtime.
611
+ return prebuilt
612
+ ? prebuilt.bind(request, init, meta, undefined, config, env, executionCtx, ipHolder)
613
+ : BurgerContext.create(request, init, meta, services, config, env, executionCtx, ipHolder);
614
+ };
615
+ const finish = (ctx, response) => ctx.hasSet() ? applySet(response, ctx.set) : response;
616
+ /**
617
+ * Error exit: dispatch through `onError`, run the global/plugin response
618
+ * hooks (route-level response hooks stay off the error path, as before),
619
+ * then apply `ctx.set` like every other path. `applySet` keeps the error
620
+ * status; only headers/other mutations are merged.
621
+ */
622
+ const finishError = globalErrorFinisher(globalResponse);
623
+ const fail = (ctx, error) => finishError(dispatchOnError(error, plan.onError, ctx, plan.debug, plan.validatorConfig), ctx).then((response) => {
624
+ const mutated = finish(ctx, response);
625
+ return mutated;
626
+ });
627
+ const settle = (ctx, result) => {
628
+ if (!(result instanceof Response)) {
629
+ return fail(ctx, new HTTPError(500, `${errorMethod} ${pattern} returned ${describeReturn(result)}; route handlers must return a Response`));
630
+ }
631
+ const mutated = finish(ctx, result);
632
+ return mutated;
633
+ };
634
+ const runDirect = (ctx) => {
635
+ try {
636
+ const result = rawHandler(ctx);
637
+ return result instanceof Promise
638
+ ? result.then((value) => settle(ctx, value), (error) => fail(ctx, error))
639
+ : settle(ctx, result);
640
+ }
641
+ catch (error) {
642
+ return fail(ctx, error);
643
+ }
644
+ };
645
+ // JIT state: undefined = not yet attempted, null = unavailable, otherwise
646
+ // the compiled dispatcher (lazily built on first hit so unused routes pay
647
+ // no startup cost).
648
+ let jitFn;
649
+ const runPlan = (ctx, handler, request) => {
650
+ if (jit) {
651
+ if (jitFn === undefined) {
652
+ // The handler is passed for compile-time async analysis only;
653
+ // the generated function still receives it per request.
654
+ jitFn = compileJitHookPlan(plan, plan.debug, planHandler);
655
+ }
656
+ const compiled = jitFn;
657
+ if (compiled) {
658
+ // The compiled function stays synchronous when every step was
659
+ // provably sync — no `Promise.resolve` wrapper on that path.
660
+ return compiled(ctx, handler, request.method);
661
+ }
662
+ }
663
+ return executeHookPlanForHandler(ctx, plan, handler, request);
664
+ };
665
+ const hasPlanStages = plan.transform !== undefined ||
666
+ plan.validation !== undefined ||
667
+ plan.validators?.response !== undefined ||
668
+ plan.beforeRoute.length > 0 ||
669
+ plan.afterRoute.length > 0 ||
670
+ plan.mapResponse.length > 0;
671
+ // Empty plan: handler → finish/fail with no async wrapper when the
672
+ // handler returns synchronously.
673
+ if (!hasPlanStages) {
674
+ return (request, ctxInit, prebuilt, env, executionCtx) => runDirect(makeCtx(request, ctxInit, prebuilt, env, executionCtx));
675
+ }
676
+ // Validation-only plans: call the validator, await only if it returned a
677
+ // promise (schemas without a body slot validate synchronously).
678
+ if (plan.transform === undefined &&
679
+ plan.validation !== undefined &&
680
+ plan.validators?.response === undefined &&
681
+ plan.beforeRoute.length === 0 &&
682
+ plan.afterRoute.length === 0 &&
683
+ plan.mapResponse.length === 0) {
684
+ const validation = plan.validation;
685
+ return (request, ctxInit, prebuilt, env, executionCtx) => {
686
+ const ctx = makeCtx(request, ctxInit, prebuilt, env, executionCtx);
687
+ let outcome;
688
+ try {
689
+ outcome = validation(ctx);
690
+ }
691
+ catch (error) {
692
+ return fail(ctx, error);
693
+ }
694
+ return outcome instanceof Promise
695
+ ? outcome.then(() => runDirect(ctx), (error) => fail(ctx, error))
696
+ : runDirect(ctx);
697
+ };
698
+ }
699
+ return (request, ctxInit, prebuilt, env, executionCtx) => {
700
+ const ctx = makeCtx(request, ctxInit, prebuilt, env, executionCtx);
701
+ const result = runPlan(ctx, planHandler, request);
702
+ // Sync-first exit: a synchronously resolved plan finishes without an
703
+ // extra `.then` microtask.
704
+ if (isThenable(result)) {
705
+ return result.then((response) => {
706
+ const mutated = finish(ctx, response);
707
+ return mutated;
708
+ });
709
+ }
710
+ const mutated = finish(ctx, result);
711
+ return mutated;
712
+ };
713
+ }
714
+ /**
715
+ * The `fetch`-facing dispatcher for one route: method lookup against the
716
+ * precomputed specialized executors (auto-HEAD and auto-OPTIONS included),
717
+ * otherwise 405 + Allow. The hook plan already ran inside the executor.
718
+ *
719
+ * Sync-first: a synchronously resolved executor returns its `Response`
720
+ * directly; only async plans produce a Promise.
721
+ */
722
+ function buildFallbackHandler(cores, allow) {
723
+ return (request, ctxInit, prebuilt, env, executionCtx) => {
724
+ const core = cores[request.method];
725
+ if (!core)
726
+ return methodNotAllowed(allow);
727
+ return core(request, ctxInit, prebuilt, env, executionCtx);
728
+ };
729
+ }
730
+ /**
731
+ * Merges transform records from route hooks and plugins. Plugin transform records
732
+ * are applied first, then route-level transform overrides on key collision.
733
+ */
734
+ function mergeTransformRecords(routeTransform, plugins, globalTransform) {
735
+ const merged = {};
736
+ if (plugins) {
737
+ for (const p of plugins) {
738
+ if (p.hooks.transform) {
739
+ for (const k of Object.keys(p.hooks.transform)) {
740
+ merged[k] = p.hooks.transform[k];
741
+ }
742
+ }
743
+ }
744
+ }
745
+ if (globalTransform) {
746
+ for (const k of Object.keys(globalTransform)) {
747
+ merged[k] = globalTransform[k];
748
+ }
749
+ }
750
+ if (routeTransform) {
751
+ for (const k of Object.keys(routeTransform)) {
752
+ merged[k] = routeTransform[k];
753
+ }
754
+ }
755
+ return Object.keys(merged).length > 0 ? merged : undefined;
756
+ }
757
+ /**
758
+ * True when the method's compiled validators declare `slot`. HEAD reuses
759
+ * GET's validators (auto-HEAD derives from GET), so a params validator never
760
+ * loses its input.
761
+ */
762
+ function methodHasSlot(validators, method, slot) {
763
+ if (!validators)
764
+ return false;
765
+ const lower = method.toLowerCase();
766
+ let methodValidators = validators.methods[lower];
767
+ if (!methodValidators && lower === 'head') {
768
+ methodValidators = validators.methods['get'];
769
+ }
770
+ return methodValidators?.[slot] !== undefined;
771
+ }
772
+ /**
773
+ * A path is static when it contains no `:param` or `*` segment.
774
+ */
775
+ function isStaticPath(path) {
776
+ return (!path.includes(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX) &&
777
+ !path.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX));
778
+ }
779
+ /**
780
+ * Optionally registers a provably-constant `OPTIONS` (204) response via
781
+ * `Bun.nativeStaticResponse`. Only safe when the route has no hooks, no
782
+ * schema, and uses the auto OPTIONS handler, so the response is identical
783
+ * for every request. Pure performance optimization; the pipeline works
784
+ * without it.
785
+ */
786
+ function registerNativeOptions(path, def, hasSchema, onRequestHooksCount = 0) {
787
+ // Skip native OPTIONS when onRequest hooks exist — they may need to
788
+ // intercept OPTIONS preflight (e.g. CORS hook).
789
+ if (onRequestHooksCount > 0) {
790
+ return;
791
+ }
792
+ const nativeStaticResponse = typeof Bun === 'undefined'
793
+ ? undefined
794
+ : Bun
795
+ .nativeStaticResponse;
796
+ if (typeof nativeStaticResponse !== 'function') {
797
+ return;
798
+ }
799
+ if (hasSchema) {
800
+ return;
801
+ }
802
+ const opt = def.handlers['OPTIONS'];
803
+ if (opt && opt.isAutoOptions === true) {
804
+ try {
805
+ nativeStaticResponse('OPTIONS', path, new Response(null, {
806
+ status: 204,
807
+ headers: {
808
+ Allow: opt.allowHeader ?? '',
809
+ },
810
+ }));
811
+ }
812
+ catch {
813
+ // Native static response not available for this path; the compiled
814
+ // handler still serves OPTIONS correctly, so ignore.
815
+ }
816
+ }
817
+ }