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