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,600 @@
1
+ import { renderUncaught } from '../errors/http-error.js';
2
+ import { dispatchOnError } from '../lifecycle/executor.js';
3
+ import { applySet, notFound, methodNotAllowed, } from '../utils/response.js';
4
+ import { extractPathnameFromUrl } from '../utils/wildcard.js';
5
+ import { isThenable } from '../utils/thenable.js';
6
+ import { RouterCompiler, buildGlobalResponsePlan } from './compiler.js';
7
+ import { hasGlobalResponseHooks, runGlobalResponseHooks, } from '../lifecycle/executor.js';
8
+ import { resolveDebug } from '../utils/env.js';
9
+ import { AllowCache } from './allow-cache.js';
10
+ import { StaticMap } from './static-map.js';
11
+ import { Trie } from './trie.js';
12
+ import { buildRegexMatcher, } from './regex-matcher.js';
13
+ import { BurgerContext, EMPTY_SERVICES, createServices, isRequestIPSource, } from '../context/context.js';
14
+ /**
15
+ * Public router: owns the compiled dispatch state and orchestrates lookup
16
+ * and execution.
17
+ *
18
+ * Static, dynamic (`:param`), and wildcard (`*`) routes are all registered
19
+ * on Bun's native `routes` map; compiled handlers self-extract `params` /
20
+ * `wildcardParams`. The `fetch` fallback still runs for unmatched and
21
+ * trailing-slash requests (`/foo/` ≡ `/foo`), consulting the internal trie.
22
+ *
23
+ * Both paths execute the same compiled handler, so method dispatch,
24
+ * 405+Allow, auto-HEAD, and lifecycle behavior are identical. Non-Bun
25
+ * (WinterCG) adapters dispatch every route through `fetch` + trie.
26
+ */
27
+ export class Router {
28
+ staticMap = new StaticMap();
29
+ trie = new Trie();
30
+ allowCache = new AllowCache();
31
+ compiler;
32
+ /** Dev mode: controls error-rendering detail (stack/cause in problem bodies). */
33
+ debug;
34
+ /** Dynamic-dispatch engine preference ('auto' default). */
35
+ engine;
36
+ /** Native dispatch table for `:param` / `*` routes (Bun `routes` map keys). */
37
+ nativeRoutesMap = new Map();
38
+ /** Per-path per-method specialized executors (fed to Bun method objects). */
39
+ methodCores = new Map();
40
+ /** Retained compiled-route metadata (RouteAccessInfo + RouteMeta). */
41
+ compiledRoutes;
42
+ /** Memoized `staticRoutes()` result; rebuilt on `compile()`. */
43
+ cachedStaticRoutes;
44
+ /** Memoized `nativeRoutes()` result; rebuilt on `compile()`. */
45
+ cachedNativeRoutes;
46
+ /** Pre-routing hooks (Plugin + Global scope). Run before routing in `fetch()`. */
47
+ onRequestHooks = [];
48
+ /** True when pre-routing `onRequest` hooks exist (hot-path flag). */
49
+ hasOnRequest = false;
50
+ /**
51
+ * Error hooks available before a route is matched (Global → Plugin →
52
+ * Framework, nearest-first). Let pre-routing `onRequest` throws go
53
+ * through the same `onError` pipeline as request errors.
54
+ */
55
+ onErrorHooks = [];
56
+ /**
57
+ * Global/plugin response hooks (afterRoute + mapResponse) for responses
58
+ * with no matched route plan: 404/405/auto-OPTIONS, pages/assets/docs,
59
+ * and onError-rendered errors. Compiled once at startup.
60
+ */
61
+ globalResponsePlan = {
62
+ afterRoute: [],
63
+ mapResponse: [],
64
+ };
65
+ /** Hot-path flag: true when the global response plan has hooks. */
66
+ globalResponseActive = false;
67
+ /** App services resolved ONCE; shared (frozen) by every request context. */
68
+ appServices = EMPTY_SERVICES;
69
+ /** Per-app server reference for lazy `ctx.ip` (written once at startup). */
70
+ ipHolder = {};
71
+ /**
72
+ * RegExp matcher for dynamic/wildcard routes (WinterCG fast path).
73
+ * Built when the engine setting allows and compilation succeeds;
74
+ * `null` means dispatch stays on the trie.
75
+ */
76
+ regexMatcher = null;
77
+ constructor(config = {}) {
78
+ // Resolve once: `debug: true` or NODE_ENV=development. The compiler
79
+ // (hook plans) and renderUnhandled share this exact value, so
80
+ // onRequest errors and handler errors render the same.
81
+ this.debug = resolveDebug(config.debug);
82
+ this.engine = config.engine;
83
+ this.compiler = new RouterCompiler(this.debug, config.validation ?? {}, config.jit !== false);
84
+ }
85
+ /**
86
+ * Compiles a `RouteDefinition[]` into the dispatch structures.
87
+ * Replaces all tables wholesale (no incremental merge) so hot reload
88
+ * cannot leak stale routes.
89
+ */
90
+ compile(defs, plugins, providers, onRequestHooks, globalHooks) {
91
+ // Services are resolved once here (shared with the compiled handlers,
92
+ // which receive the already-built object).
93
+ this.appServices = createServices(providers);
94
+ const result = this.compiler.compile(defs, plugins, this.appServices, onRequestHooks?.length ?? 0, globalHooks, this.ipHolder);
95
+ this.staticMap = result.staticMap;
96
+ this.trie = result.trie;
97
+ this.allowCache = result.allowCache;
98
+ this.nativeRoutesMap = result.nativeRoutes;
99
+ this.methodCores = result.methodCores;
100
+ this.compiledRoutes = result.routes;
101
+ this.cachedStaticRoutes = undefined;
102
+ this.cachedNativeRoutes = undefined;
103
+ this.onRequestHooks = onRequestHooks ?? [];
104
+ this.hasOnRequest = this.onRequestHooks.length > 0;
105
+ this.onErrorHooks = buildPreRoutingErrorChain(plugins, globalHooks);
106
+ this.globalResponsePlan = buildGlobalResponsePlan(plugins, globalHooks);
107
+ this.globalResponseActive = hasGlobalResponseHooks(this.globalResponsePlan);
108
+ this.regexMatcher = this.buildMatcher(result);
109
+ }
110
+ /**
111
+ * Records the serving runtime's handle (Bun's `Server`) once so `ctx.ip`
112
+ * can resolve the socket peer lazily — no per-request WeakMap write.
113
+ * Adapter-facing; called at startup by the Bun serve path.
114
+ */
115
+ setRequestIPSource(server) {
116
+ if (isRequestIPSource(server)) {
117
+ this.ipHolder.server = server;
118
+ }
119
+ }
120
+ /**
121
+ * The per-app `ctx.ip` holder. Non-API contexts (dynamic pages) receive it
122
+ * so their `ctx.ip` resolves exactly like API routes.
123
+ */
124
+ getRequestIPHolder() {
125
+ return this.ipHolder;
126
+ }
127
+ /**
128
+ * The app services resolved ONCE at compile time. Non-API contexts
129
+ * (dynamic pages) receive the same shared object so `ctx.services` is
130
+ * populated there too.
131
+ */
132
+ getAppServices() {
133
+ return this.appServices;
134
+ }
135
+ /**
136
+ * Builds the RegExp dispatch matcher for dynamic/wildcard routes when
137
+ * the configured engine asks for it ('regex'). 'auto' stays on the trie,
138
+ * so the matcher is an explicit opt-in.
139
+ */
140
+ buildMatcher(result) {
141
+ if (this.engine !== 'regex')
142
+ return null;
143
+ if (!result.routes || result.routes.size === 0)
144
+ return null;
145
+ const entries = [];
146
+ for (const [path, compiled] of result.routes) {
147
+ if (!isDynamicPath(path))
148
+ continue;
149
+ entries.push({
150
+ path,
151
+ handler: compiled.handler,
152
+ methods: new Set(Object.keys(compiled.def.handlers).map((m) => m.toUpperCase())),
153
+ isWildcard: compiled.def.isWildcard === true || path.includes('*'),
154
+ });
155
+ }
156
+ // The trie is compiled in the same pass — its DFS order is the
157
+ // authoritative alternative order.
158
+ const built = buildRegexMatcher(entries, result.trie.orderedPatterns());
159
+ if (!built)
160
+ return null; // trie fallback applies
161
+ return built;
162
+ }
163
+ /**
164
+ * Read-only access to the retained compiled-route metadata
165
+ * (`RouteAccessInfo` + `RouteMeta`). Populated by `compile()`; not used on
166
+ * the request hot path, so it has no runtime performance impact.
167
+ */
168
+ getCompiledRoutes() {
169
+ return this.compiledRoutes;
170
+ }
171
+ /**
172
+ * Returns the static routes as a `Bun.serve` `routes` map: one **method
173
+ * object** per path (`{ GET: fnGet, POST: fnPost, HEAD: fnHead, ... }`).
174
+ * Each method is specialized at compile time; methods not present fall
175
+ * through to `fetch`, which answers 405 + Allow for known paths.
176
+ */
177
+ staticRoutes() {
178
+ if (this.cachedStaticRoutes)
179
+ return this.cachedStaticRoutes;
180
+ const out = {};
181
+ for (const [path] of this.staticMap.entries()) {
182
+ out[path] = this.buildMethods(path);
183
+ }
184
+ this.cachedStaticRoutes = out;
185
+ return out;
186
+ }
187
+ /**
188
+ * Same method-object shape for `:param` / `*` routes: Bun matches the
189
+ * pattern natively and passes decoded `request.params`, so no URL
190
+ * re-parsing happens on the hot path.
191
+ */
192
+ nativeRoutes() {
193
+ if (this.cachedNativeRoutes)
194
+ return this.cachedNativeRoutes;
195
+ const out = {};
196
+ for (const pattern of this.nativeRoutesMap.keys()) {
197
+ out[pattern] = this.buildMethods(pattern);
198
+ }
199
+ this.cachedNativeRoutes = out;
200
+ return out;
201
+ }
202
+ /**
203
+ * Exact static API paths as direct dispatchers, keyed by path.
204
+ * `fetchHandler()` merges these into its page/asset lookup so a static
205
+ * API request resolves in one `Map.get` instead of a page-map miss plus
206
+ * a `StaticMap` hit. Each dispatcher mirrors the `fetch` fallback for its
207
+ * own path: known method → specialized core, otherwise the compiled
208
+ * method-dispatch handler (405 + Allow), with global response hooks and
209
+ * the `onRequest` pipeline applied exactly as `fetchWithPath` does.
210
+ */
211
+ staticDispatchMap() {
212
+ const out = new Map();
213
+ for (const path of this.staticMap.keys()) {
214
+ out.set(path, this.buildStaticDispatch(path));
215
+ }
216
+ return out;
217
+ }
218
+ buildStaticDispatch(path) {
219
+ // Hook path: reuse the router's own pre-routing pipeline. The path is
220
+ // exact, so no slash handling is skipped.
221
+ if (this.hasOnRequest) {
222
+ return (request, _ctxInit, _prebuilt, env, executionCtx) => this.dispatchWithOnRequest(request, env, executionCtx, path);
223
+ }
224
+ const entry = this.staticMap.getEntry(path);
225
+ // A known method runs its core — the core already carries the global
226
+ // response plan. Only the method-dispatch fallback (405 + Allow) is a
227
+ // non-route response, so only it gets `finishNonRouteResponse` —
228
+ // exactly the split `dispatchMatched` uses.
229
+ const finishFallback = this.globalResponseActive;
230
+ return (request, _ctxInit, _prebuilt, env, executionCtx) => {
231
+ const core = entry.cores?.[request.method];
232
+ if (core) {
233
+ return core(request, undefined, undefined, env, executionCtx);
234
+ }
235
+ const response = entry.handler(request, undefined, undefined, env, executionCtx);
236
+ return finishFallback
237
+ ? this.finishNonRouteResponse(response, request, undefined, env, executionCtx)
238
+ : response;
239
+ };
240
+ }
241
+ /**
242
+ * Builds the Bun method object for one compiled path. Without hooks each
243
+ * method forwards straight to the compiled core; with hooks each method
244
+ * runs onRequest once before the core and binds the resulting context
245
+ * onto the route.
246
+ */
247
+ buildMethods(path) {
248
+ const cores = this.methodCores.get(path);
249
+ const out = {};
250
+ if (!this.hasOnRequest) {
251
+ for (const key of Object.keys(cores)) {
252
+ const core = cores[key];
253
+ out[key] = (request) => core(request);
254
+ }
255
+ return out;
256
+ }
257
+ for (const key of Object.keys(cores)) {
258
+ const core = cores[key];
259
+ const wrapped = async (request) => {
260
+ const outcome = await this.runOnRequest(request);
261
+ if (outcome.shortCircuit)
262
+ return outcome.shortCircuit;
263
+ try {
264
+ // The onRequest context is bound by the route, so state
265
+ // seeded pre-routing survives (one context per request).
266
+ const result = await core(request, undefined, outcome.ctx);
267
+ return outcome.mappers.length > 0
268
+ ? this.applyMappers(result, outcome.mappers)
269
+ : result;
270
+ }
271
+ catch (error) {
272
+ return this.renderUnhandled(request, error);
273
+ }
274
+ };
275
+ out[key] = wrapped;
276
+ }
277
+ return out;
278
+ }
279
+ /**
280
+ * Wraps a non-API handler registered on the native routes map (pages,
281
+ * static assets, `/openapi.json`, `/docs`) so global/plugin `onRequest`
282
+ * hooks (CORS, logging, auth, rate limiting) apply to it exactly like
283
+ * API routes. Returned unchanged when no `onRequest` hooks exist.
284
+ */
285
+ wrapWithOnRequest(handler) {
286
+ if (this.onRequestHooks.length === 0 && !this.globalResponseActive) {
287
+ return handler;
288
+ }
289
+ const inner = handler;
290
+ const wrapped = async (request, _serverOrCtxInit, prebuilt, env, executionCtx) => {
291
+ const outcome = await this.runOnRequest(request, env, executionCtx);
292
+ if (outcome.shortCircuit)
293
+ return outcome.shortCircuit;
294
+ // The onRequest context is handed to the handler so pages bind
295
+ // it (one context per request) and ctx.set survives.
296
+ const ctx = prebuilt ?? outcome.ctx;
297
+ try {
298
+ const result = (await inner(request, undefined, ctx, env, executionCtx));
299
+ const finished = await this.finishNonRouteResponse(result, request, ctx, env, executionCtx);
300
+ return outcome.mappers.length > 0
301
+ ? this.applyMappers(finished, outcome.mappers)
302
+ : finished;
303
+ }
304
+ catch (error) {
305
+ const rendered = this.renderUnhandled(request, error);
306
+ const finished = await this.finishNonRouteResponse(rendered, request, ctx, env, executionCtx);
307
+ return outcome.mappers.length > 0
308
+ ? this.applyMappers(finished, outcome.mappers)
309
+ : finished;
310
+ }
311
+ };
312
+ return wrapped;
313
+ }
314
+ /** Renders an error that escaped the pipeline; logs it when 5xx. */
315
+ renderUnhandled(request, error) {
316
+ return renderUncaught(error, request, this.debug);
317
+ }
318
+ /**
319
+ * Applies the global/plugin response plan and `ctx.set` to a response
320
+ * that did not run a route plan (404/405/OPTIONS, pages/assets/docs,
321
+ * onError renders). Returns the response unchanged — zero cost — when
322
+ * neither applies.
323
+ */
324
+ finishNonRouteResponse(response, request, prebuilt, env, executionCtx) {
325
+ if (!this.globalResponseActive && prebuilt?.hasSet() !== true) {
326
+ return response;
327
+ }
328
+ return isThenable(response)
329
+ ? response.then((res) => this.applyGlobalResponseHooks(res, request, prebuilt, env, executionCtx))
330
+ : this.applyGlobalResponseHooks(response, request, prebuilt, env, executionCtx);
331
+ }
332
+ /** Runs the global response plan, then `ctx.set`, for one response. */
333
+ async applyGlobalResponseHooks(response, request, prebuilt, env, executionCtx) {
334
+ const ctx = prebuilt ??
335
+ BurgerContext.create(request, undefined, undefined, this.appServices, undefined, env, executionCtx, this.ipHolder);
336
+ let res = response;
337
+ if (this.globalResponseActive) {
338
+ try {
339
+ res = await runGlobalResponseHooks(this.globalResponsePlan, ctx, res);
340
+ }
341
+ catch (error) {
342
+ // A failing response hook renders through the same onError
343
+ // chain as request errors instead of rejecting.
344
+ res = await dispatchOnError(error, this.onErrorHooks, ctx, this.debug);
345
+ }
346
+ }
347
+ return ctx.hasSet() ? applySet(res, ctx.set) : res;
348
+ }
349
+ /**
350
+ * Compatibility alias for `staticRoutes()`.
351
+ */
352
+ get routes() {
353
+ return this.staticRoutes();
354
+ }
355
+ /**
356
+ * Executes pre-routing `onRequest` hooks on a minimal BurgerContext.
357
+ * Returns a Response if any hook short-circuits, or undefined to continue.
358
+ * Platform `env` / `executionCtx` are bound onto the context here so they
359
+ * survive into the dispatched handler via re-binding.
360
+ */
361
+ async runOnRequest(request, env, executionCtx) {
362
+ // ONE context per request: created here (before routing) so
363
+ // onRequest hooks can seed state that survives into the handler.
364
+ // The dispatched route binds this instance to its matched route.
365
+ const ctx = BurgerContext.create(request, undefined, undefined, this.appServices, undefined, env, executionCtx, this.ipHolder);
366
+ const outcome = {
367
+ shortCircuit: undefined,
368
+ mappers: [],
369
+ ctx,
370
+ };
371
+ if (this.onRequestHooks.length === 0)
372
+ return outcome;
373
+ for (const hook of this.onRequestHooks) {
374
+ try {
375
+ const result = await hook(ctx);
376
+ if (result instanceof Response) {
377
+ // Global/plugin response hooks and ctx.set apply to the
378
+ // short-circuit too; mappers from earlier hooks still
379
+ // wrap it (e.g. cors() then rateLimit(): the 429 keeps
380
+ // CORS headers) — same contract as beforeRoute.
381
+ outcome.shortCircuit = await this.applyMappers(await this.finishNonRouteResponse(result, request, ctx, env, executionCtx), outcome.mappers);
382
+ return outcome;
383
+ }
384
+ if (typeof result === 'function') {
385
+ outcome.mappers.push(result);
386
+ }
387
+ }
388
+ catch (error) {
389
+ // Same onError chain as request errors (nearest-first:
390
+ // Global → Plugin → Framework) — never a bare render. The
391
+ // rendered error also gets the global response hooks.
392
+ outcome.shortCircuit = await this.applyMappers(await this.finishNonRouteResponse(await dispatchOnError(error, this.onErrorHooks, ctx, this.debug), request, ctx, env, executionCtx), outcome.mappers);
393
+ return outcome;
394
+ }
395
+ }
396
+ return outcome;
397
+ }
398
+ /**
399
+ * Dynamic / wildcard lookup: the RegExp matcher first (when compiled),
400
+ * then the radix trie. Both produce identical match shapes. A match that
401
+ * binds a `:param` to an empty segment is rejected. Apps with no dynamic
402
+ * routes skip both matchers.
403
+ */
404
+ matchDynamic(path) {
405
+ if (!this.regexMatcher && this.nativeRoutesMap.size === 0)
406
+ return null;
407
+ let match = null;
408
+ if (this.regexMatcher)
409
+ match = this.regexMatcher(path);
410
+ if (!match)
411
+ match = this.trie.match(path);
412
+ if (match && hasEmptyParam(match.params))
413
+ return null;
414
+ return match;
415
+ }
416
+ /**
417
+ * Applies collected after-mappers in onion order (last registered runs
418
+ * first, the first hook's mapper wraps outermost) — identical to
419
+ * `runHooks` and the JIT for beforeRoute.
420
+ */
421
+ async applyMappers(response, mappers) {
422
+ let res = response;
423
+ for (let i = mappers.length - 1; i >= 0; i--) {
424
+ res = await mappers[i](res);
425
+ }
426
+ return res;
427
+ }
428
+ /**
429
+ * The `fetch` fallback handed to `Bun.serve`: dynamic/wildcard routes
430
+ * via the trie, plus loose-trailing-slash static variants Bun did not
431
+ * match directly.
432
+ *
433
+ * `env` / `executionCtx` are optional platform bindings (WinterCG
434
+ * `fetch(request, env, ctx)`). The signature is its own shape — NOT the
435
+ * server-oriented `FetchHandler` — so the platform slots stay unambiguous.
436
+ * Sync-first: a synchronously resolved executor returns a `Response`
437
+ * directly; only hook plans and async handlers produce a Promise.
438
+ */
439
+ fetch = (request, env, executionCtx) => this.hasOnRequest
440
+ ? this.dispatchWithOnRequest(request, env, executionCtx, undefined)
441
+ : this.dispatchMatched(request, extractPathnameFromUrl(request.url), undefined, undefined, env, executionCtx);
442
+ /**
443
+ * `fetch` with a pathname the caller already extracted (e.g.
444
+ * `fetchHandler()` resolved page/asset routes first), avoiding a second
445
+ * URL parse per request. The pathname must come from
446
+ * `extractPathnameFromUrl`.
447
+ */
448
+ fetchWithPath = (request, pathname, env, executionCtx) => this.hasOnRequest
449
+ ? this.dispatchWithOnRequest(request, env, executionCtx, pathname)
450
+ : this.dispatchMatched(request, pathname, undefined, undefined, env, executionCtx);
451
+ /** Pre-routing hook path: context + mappers wrap the matched dispatch. */
452
+ async dispatchWithOnRequest(request, env, executionCtx, precomputedPath) {
453
+ // Pre-routing: create the one context and run onRequest hooks. A hook
454
+ // returning a Response short-circuits the pipeline; mapper functions
455
+ // are collected and applied to the eventual response.
456
+ const outcome = await this.runOnRequest(request, env, executionCtx);
457
+ if (outcome.shortCircuit)
458
+ return outcome.shortCircuit;
459
+ const mappers = outcome.mappers;
460
+ const apply = mappers.length > 0
461
+ ? (res) => this.applyMappers(res, mappers)
462
+ : undefined;
463
+ const path = precomputedPath ?? extractPathnameFromUrl(request.url);
464
+ return this.dispatchMatched(request, path, outcome.ctx, apply, env, executionCtx);
465
+ }
466
+ /**
467
+ * Routing + execution against the compiled tables. `prebuilt` is the
468
+ * pre-routing context (onRequest path) or `undefined`; `apply` wraps the
469
+ * response in collected onRequest mappers when any exist.
470
+ */
471
+ dispatchMatched(request, raw, prebuilt, apply, env, executionCtx) {
472
+ // Collapse repeated slashes but PRESERVE a single trailing slash (the
473
+ // exact form is tried first; the slash-less form is the fallback).
474
+ // The regex runs only when the path actually carries `//`.
475
+ const path = raw.indexOf('//') === -1 ? raw : raw.replace(/\/+/g, '/');
476
+ // 1. Exact static route (slash-preserving — Bun already serves the exact
477
+ // form natively; this catches the trailing-slash variants it missed).
478
+ const staticEntry = this.staticMap.getEntry(path);
479
+ if (staticEntry) {
480
+ // No ctxInit: the compiled executor seeds the route identity from
481
+ // its own frozen static route meta (no per-request allocation).
482
+ // A known method dispatches straight to its specialized core
483
+ // (skips the method-dispatch wrapper); an unknown method falls
484
+ // through to the wrapper's 405 + Allow.
485
+ const core = staticEntry.cores?.[request.method];
486
+ const response = core
487
+ ? core(request, undefined, prebuilt, env, executionCtx)
488
+ : this.finishNonRouteResponse(staticEntry.handler(request, undefined, prebuilt, env, executionCtx), request, prebuilt, env, executionCtx);
489
+ return apply === undefined
490
+ ? response
491
+ : applyToResponse(response, apply);
492
+ }
493
+ // 2. Dynamic / wildcard routes (see matchDynamic). A `:param` never
494
+ // matches an empty segment (`/users/` is not `/users/:id` with id "");
495
+ // a trailing slash is retried without it, so `/users/1/` ≡ `/users/1`.
496
+ let routePath = path;
497
+ let match = this.matchDynamic(path);
498
+ if (!match && path.length > 1 && path.endsWith('/')) {
499
+ // 3. Loose trailing-slash fallback: `/foo/` ≡ `/foo`.
500
+ // `path` is already slash-collapsed, so stripping the trailing
501
+ // slash is exactly `normalizePath(raw)`.
502
+ const normalized = path.slice(0, -1);
503
+ const loose = this.staticMap.getEntry(normalized) ??
504
+ this.staticMap.getEntry(normalized + '/');
505
+ if (loose) {
506
+ const ctxInit = {
507
+ route: { path: normalized, pattern: normalized },
508
+ };
509
+ const core = loose.cores?.[request.method];
510
+ const response = core
511
+ ? core(request, ctxInit, prebuilt, env, executionCtx)
512
+ : this.finishNonRouteResponse(loose.handler(request, ctxInit, prebuilt, env, executionCtx), request, prebuilt, env, executionCtx);
513
+ return apply === undefined
514
+ ? response
515
+ : applyToResponse(response, apply);
516
+ }
517
+ match = this.matchDynamic(normalized);
518
+ routePath = normalized;
519
+ }
520
+ if (match) {
521
+ // Auto-HEAD: a GET route implies HEAD is allowed.
522
+ const method = request.method;
523
+ const headAllowed = method === 'HEAD' && match.methods.has('GET');
524
+ if (!match.methods.has(method) && !headAllowed) {
525
+ const allow = this.allowCache.get(match.pattern) ??
526
+ [...match.methods].join(', ');
527
+ const notAllowed = this.finishNonRouteResponse(methodNotAllowed(allow), request, prebuilt, env, executionCtx);
528
+ return apply === undefined
529
+ ? notAllowed
530
+ : applyToResponse(notAllowed, apply);
531
+ }
532
+ // Seed `ctxInit`: `route` is always present; `params` /
533
+ // `wildcardParams` are added only when the route has them.
534
+ const ctxInit = {
535
+ route: { path: routePath, pattern: match.pattern },
536
+ params: match.params,
537
+ wildcardParams: match.wildcardParams,
538
+ };
539
+ const response = match.handler(request, ctxInit, prebuilt, env, executionCtx);
540
+ return apply === undefined
541
+ ? response
542
+ : applyToResponse(response, apply);
543
+ }
544
+ const notFoundResponse = this.finishNonRouteResponse(notFound(), request, prebuilt, env, executionCtx);
545
+ return apply === undefined
546
+ ? notFoundResponse
547
+ : applyToResponse(notFoundResponse, apply);
548
+ }
549
+ }
550
+ /** Applies collected onRequest mappers to a sync or async response. */
551
+ function applyToResponse(response, apply) {
552
+ return isThenable(response) ? response.then(apply) : apply(response);
553
+ }
554
+ /**
555
+ * Builds the pre-routing `onError` chain: the hooks available before a route
556
+ * is matched, in the same nearest-first order a route plan uses (Global →
557
+ * Plugin → Framework).
558
+ */
559
+ function buildPreRoutingErrorChain(plugins, globalHooks) {
560
+ const buckets = {
561
+ local: [],
562
+ global: [],
563
+ plugin: [],
564
+ framework: [],
565
+ };
566
+ const push = (value, to) => {
567
+ if (value === undefined)
568
+ return;
569
+ if (Array.isArray(value))
570
+ for (const h of value)
571
+ to.push(h);
572
+ else
573
+ to.push(value);
574
+ };
575
+ push(globalHooks?.onError, buckets.global);
576
+ for (const plugin of plugins ?? []) {
577
+ push(plugin.hooks.onError, buckets[plugin.scope]);
578
+ }
579
+ return [
580
+ ...buckets.global,
581
+ ...buckets.plugin,
582
+ ...buckets.framework,
583
+ ];
584
+ }
585
+ /** True when any matched `:param` captured an empty segment. */
586
+ function hasEmptyParam(params) {
587
+ if (!params)
588
+ return false;
589
+ for (const k in params)
590
+ if (params[k] === '')
591
+ return true;
592
+ return false;
593
+ }
594
+ /**
595
+ * A route path is dynamic when it carries a `:param` or `*` segment —
596
+ * the set dispatched through the trie / RegExp matcher.
597
+ */
598
+ function isDynamicPath(path) {
599
+ return path.includes(':') || path.includes('*');
600
+ }
@@ -0,0 +1,39 @@
1
+ import type { CompiledHandler, NativeMethodCores } from './types.js';
2
+ /**
3
+ * One static route's framework-side entry: the method-dispatching compiled
4
+ * handler plus the per-method specialized cores (used by the `fetch` fallback
5
+ * to dispatch a known method without re-entering the dispatching wrapper).
6
+ */
7
+ export interface StaticEntry {
8
+ handler: CompiledHandler;
9
+ cores: NativeMethodCores | undefined;
10
+ }
11
+ /**
12
+ * Static dispatch table.
13
+ *
14
+ * Static API routes are served by Bun's native `routes` map (the fast path);
15
+ * this holds the framework-side copy so the Router can enumerate them into
16
+ * Bun's map and resolve loose-trailing-slash variants Bun did not match.
17
+ * Keyed by path; one compiled handler serves all methods, with dispatch and
18
+ * 405+Allow inside it.
19
+ */
20
+ export declare class StaticMap {
21
+ private map;
22
+ /**
23
+ * Registers a compiled handler for a static path.
24
+ * @throws if a *different* handler is already registered at the same path
25
+ * (duplicate static route). Re-setting the same handler reference
26
+ * (used for loose trailing-slash variants) is allowed.
27
+ */
28
+ set(path: string, handler: CompiledHandler, cores?: NativeMethodCores): void;
29
+ get(path: string): CompiledHandler | undefined;
30
+ /** The full entry (handler + method cores) for a static path. */
31
+ getEntry(path: string): StaticEntry | undefined;
32
+ has(path: string): boolean;
33
+ /** Registered static paths, in insertion order. */
34
+ keys(): IterableIterator<string>;
35
+ /**
36
+ * Yields `[path, handler]` pairs for feeding Bun's `routes` map.
37
+ */
38
+ entries(): IterableIterator<[string, CompiledHandler]>;
39
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Static dispatch table.
3
+ *
4
+ * Static API routes are served by Bun's native `routes` map (the fast path);
5
+ * this holds the framework-side copy so the Router can enumerate them into
6
+ * Bun's map and resolve loose-trailing-slash variants Bun did not match.
7
+ * Keyed by path; one compiled handler serves all methods, with dispatch and
8
+ * 405+Allow inside it.
9
+ */
10
+ export class StaticMap {
11
+ map = new Map();
12
+ /**
13
+ * Registers a compiled handler for a static path.
14
+ * @throws if a *different* handler is already registered at the same path
15
+ * (duplicate static route). Re-setting the same handler reference
16
+ * (used for loose trailing-slash variants) is allowed.
17
+ */
18
+ set(path, handler, cores) {
19
+ const existing = this.map.get(path);
20
+ if (existing !== undefined && existing.handler !== handler) {
21
+ throw new Error(`Duplicate static route registered: ${path}`);
22
+ }
23
+ this.map.set(path, { handler, cores });
24
+ }
25
+ get(path) {
26
+ return this.map.get(path)?.handler;
27
+ }
28
+ /** The full entry (handler + method cores) for a static path. */
29
+ getEntry(path) {
30
+ return this.map.get(path);
31
+ }
32
+ has(path) {
33
+ return this.map.has(path);
34
+ }
35
+ /** Registered static paths, in insertion order. */
36
+ keys() {
37
+ return this.map.keys();
38
+ }
39
+ /**
40
+ * Yields `[path, handler]` pairs for feeding Bun's `routes` map.
41
+ */
42
+ entries() {
43
+ const out = [];
44
+ for (const [path, entry] of this.map)
45
+ out.push([path, entry.handler]);
46
+ return out[Symbol.iterator]();
47
+ }
48
+ }