burger-api 0.9.7 → 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.
- 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 +201 -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 +47 -0
- package/dist/src/errors/http-error.js +146 -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 +263 -50
- package/dist/src/index.js +919 -332
- 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 +817 -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 +201 -0
- package/dist/src/router/router.js +600 -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 +172 -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 +2 -9
- package/dist/src/utils/wildcard.js +20 -58
- 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 +79 -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 +219 -0
- package/dist/src/ws/adapter.js +623 -0
- package/dist/src/ws/compiler.d.ts +37 -0
- package/dist/src/ws/compiler.js +156 -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 +81 -0
- package/dist/src/ws/platform.js +113 -0
- package/dist/src/ws/router.d.ts +48 -0
- package/dist/src/ws/router.js +174 -0
- package/dist/src/ws/scanner.d.ts +97 -0
- package/dist/src/ws/scanner.js +193 -0
- package/dist/src/ws/types.d.ts +380 -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,64 @@
|
|
|
1
|
+
import type { BurgerContext } from '../context/context.js';
|
|
2
|
+
import type { RequestHandler } from '../types/index.js';
|
|
3
|
+
import type { HookPlan, ResponseHook, ErrorHook } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* The global/plugin response hooks that run for every response the app
|
|
6
|
+
* produces — matched routes carry them in their plans; non-route responses
|
|
7
|
+
* (404/405/auto-OPTIONS, pages/assets/docs, onError renders) run them
|
|
8
|
+
* directly. Compiled once at startup.
|
|
9
|
+
*/
|
|
10
|
+
export interface GlobalResponsePlan {
|
|
11
|
+
afterRoute: ResponseHook[];
|
|
12
|
+
mapResponse: ResponseHook[];
|
|
13
|
+
}
|
|
14
|
+
/** True when the plan carries at least one hook. */
|
|
15
|
+
export declare function hasGlobalResponseHooks(plan: GlobalResponsePlan): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Runs the global response plan (afterRoute then mapResponse) for one
|
|
18
|
+
* response.
|
|
19
|
+
*/
|
|
20
|
+
export declare function runGlobalResponseHooks(plan: GlobalResponsePlan, ctx: BurgerContext, response: Response): Promise<Response>;
|
|
21
|
+
/**
|
|
22
|
+
* Wraps an onError-rendered response so the global response hooks still run.
|
|
23
|
+
* A throwing hook must not mask the original error response, so it is logged
|
|
24
|
+
* and skipped.
|
|
25
|
+
*/
|
|
26
|
+
export declare function globalErrorFinisher(plan: GlobalResponsePlan | undefined): (response: Promise<Response>, ctx: BurgerContext) => Promise<Response>;
|
|
27
|
+
/**
|
|
28
|
+
* Runs the frozen {@link HookPlan} inside the single request pipeline.
|
|
29
|
+
*
|
|
30
|
+
* Forward order: transform → validation → beforeRoute → handler → afterRoute
|
|
31
|
+
* → mapResponse. On throw the {@link HookPlan#onError} chain is dispatched
|
|
32
|
+
* nearest-first (route → global). `applySet` is applied by the caller (the
|
|
33
|
+
* compiled route+method executor in `router/compiler.ts`).
|
|
34
|
+
*/
|
|
35
|
+
export declare function executeHookPlan(ctx: BurgerContext, plan: HookPlan, handlers: {
|
|
36
|
+
[method: string]: RequestHandler;
|
|
37
|
+
}, request: Request): Promise<Response>;
|
|
38
|
+
/**
|
|
39
|
+
* Runs the frozen {@link HookPlan} for an already-resolved handler. The
|
|
40
|
+
* compiled route+method path resolves the handler at compile time, so the
|
|
41
|
+
* interpreter must not repeat the method lookup.
|
|
42
|
+
*/
|
|
43
|
+
export declare function executeHookPlanForHandler(ctx: BurgerContext, plan: HookPlan, handler: RequestHandler, request: Request): Promise<Response>;
|
|
44
|
+
/**
|
|
45
|
+
* Dispatches an error through the `onError` hook chain (nearest-first).
|
|
46
|
+
*
|
|
47
|
+
* Each hook may return a `Response` to handle the error; a hook that throws
|
|
48
|
+
* is skipped (no recursion). The thrown value is passed through unchanged —
|
|
49
|
+
* objects carrying a `status` stay intact.
|
|
50
|
+
*
|
|
51
|
+
* Fallback: `HTTPError` renders an RFC 9457 Problem Details response,
|
|
52
|
+
* `ValidationError` keeps its structured format, unknown errors are wrapped
|
|
53
|
+
* in `HTTPError(500)`.
|
|
54
|
+
*/
|
|
55
|
+
export declare function dispatchOnError(error: unknown, onErrorHooks: ErrorHook[], ctx: BurgerContext, debug?: boolean, validatorConfig?: import('../validation/types.js').ValidatorConfig): Promise<Response>;
|
|
56
|
+
/**
|
|
57
|
+
* Runs one response hook point (`afterRoute` / `mapResponse`). Each hook may
|
|
58
|
+
* return a `Response` (replace), a transform function `(res) => Response`
|
|
59
|
+
* (transform), or `undefined` / `void` (continue).
|
|
60
|
+
*
|
|
61
|
+
* Exported so the global/plugin response plan (used for 404/405/OPTIONS and
|
|
62
|
+
* non-route responses) runs hooks with the exact same semantics.
|
|
63
|
+
*/
|
|
64
|
+
export declare function runResponseHookList(hooks: ResponseHook[], ctx: BurgerContext, response: Response): Promise<Response>;
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { runHooks } from './hook-runner.js';
|
|
2
|
+
import { methodNotAllowed } from '../utils/response.js';
|
|
3
|
+
import { applyTransform } from './transform.js';
|
|
4
|
+
import { renderHTTPError, logUnhandledError } from '../errors/http-error.js';
|
|
5
|
+
import { ValidationError } from '../validation/error.js';
|
|
6
|
+
import { validateResponse } from '../validation/response.js';
|
|
7
|
+
import { isJsonContentType } from '../validation/validator.js';
|
|
8
|
+
import { resolveDebug } from '../utils/env.js';
|
|
9
|
+
import { isThenable } from '../utils/thenable.js';
|
|
10
|
+
/** True when the plan carries at least one hook. */
|
|
11
|
+
export function hasGlobalResponseHooks(plan) {
|
|
12
|
+
return plan.afterRoute.length > 0 || plan.mapResponse.length > 0;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Runs the global response plan (afterRoute then mapResponse) for one
|
|
16
|
+
* response.
|
|
17
|
+
*/
|
|
18
|
+
export async function runGlobalResponseHooks(plan, ctx, response) {
|
|
19
|
+
let res = response;
|
|
20
|
+
if (plan.afterRoute.length > 0) {
|
|
21
|
+
res = await runResponseHookList(plan.afterRoute, ctx, res);
|
|
22
|
+
}
|
|
23
|
+
if (plan.mapResponse.length > 0) {
|
|
24
|
+
res = await runResponseHookList(plan.mapResponse, ctx, res);
|
|
25
|
+
}
|
|
26
|
+
return res;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Wraps an onError-rendered response so the global response hooks still run.
|
|
30
|
+
* A throwing hook must not mask the original error response, so it is logged
|
|
31
|
+
* and skipped.
|
|
32
|
+
*/
|
|
33
|
+
export function globalErrorFinisher(plan) {
|
|
34
|
+
if (!plan || !hasGlobalResponseHooks(plan)) {
|
|
35
|
+
return (response) => response;
|
|
36
|
+
}
|
|
37
|
+
return async (response, ctx) => {
|
|
38
|
+
let res = await response;
|
|
39
|
+
try {
|
|
40
|
+
res = await runGlobalResponseHooks(plan, ctx, res);
|
|
41
|
+
}
|
|
42
|
+
catch (hookError) {
|
|
43
|
+
console.error('[burger-api] global response hook threw while rendering an error:', hookError);
|
|
44
|
+
}
|
|
45
|
+
return res;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Runs the frozen {@link HookPlan} inside the single request pipeline.
|
|
50
|
+
*
|
|
51
|
+
* Forward order: transform → validation → beforeRoute → handler → afterRoute
|
|
52
|
+
* → mapResponse. On throw the {@link HookPlan#onError} chain is dispatched
|
|
53
|
+
* nearest-first (route → global). `applySet` is applied by the caller (the
|
|
54
|
+
* compiled route+method executor in `router/compiler.ts`).
|
|
55
|
+
*/
|
|
56
|
+
export async function executeHookPlan(ctx, plan, handlers, request) {
|
|
57
|
+
const method = request.method;
|
|
58
|
+
let handler = handlers[method];
|
|
59
|
+
const headFallback = !handler && method === 'HEAD' && !!handlers.GET;
|
|
60
|
+
if (headFallback)
|
|
61
|
+
handler = handlers.GET;
|
|
62
|
+
if (!handler) {
|
|
63
|
+
return methodNotAllowed('');
|
|
64
|
+
}
|
|
65
|
+
return executeHookPlanForHandler(ctx, plan, handler, request);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Runs the frozen {@link HookPlan} for an already-resolved handler. The
|
|
69
|
+
* compiled route+method path resolves the handler at compile time, so the
|
|
70
|
+
* interpreter must not repeat the method lookup.
|
|
71
|
+
*/
|
|
72
|
+
export async function executeHookPlanForHandler(ctx, plan, handler, request) {
|
|
73
|
+
const method = request.method;
|
|
74
|
+
// Empty plan: the handler runs directly.
|
|
75
|
+
if (plan.transform === undefined &&
|
|
76
|
+
plan.validation === undefined &&
|
|
77
|
+
plan.validators?.response === undefined &&
|
|
78
|
+
plan.beforeRoute.length === 0 &&
|
|
79
|
+
plan.afterRoute.length === 0 &&
|
|
80
|
+
plan.mapResponse.length === 0) {
|
|
81
|
+
try {
|
|
82
|
+
return await handler(ctx);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
return globalErrorFinisher(plan.globalResponse)(dispatchOnError(error, plan.onError, ctx, plan.debug, plan.validatorConfig), ctx);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
// 1. Transform — inject derived values onto the context. Sync
|
|
90
|
+
// factories resolve without yielding.
|
|
91
|
+
if (plan.transform) {
|
|
92
|
+
const transformed = applyTransform(ctx, plan.transform);
|
|
93
|
+
if (isThenable(transformed))
|
|
94
|
+
await transformed;
|
|
95
|
+
}
|
|
96
|
+
// 2. Validation — framework-owned; throws ValidationError on failure.
|
|
97
|
+
if (plan.validation) {
|
|
98
|
+
const validated = plan.validation(ctx);
|
|
99
|
+
if (isThenable(validated))
|
|
100
|
+
await validated;
|
|
101
|
+
}
|
|
102
|
+
// 3. beforeRoute → handler.
|
|
103
|
+
let response = await runHooks(ctx, plan.beforeRoute, handler);
|
|
104
|
+
// 4. Response validation — post-handler, pre-afterRoute; validates the
|
|
105
|
+
// handler's return against declared response schemas (JSON only).
|
|
106
|
+
if (plan.validators?.response) {
|
|
107
|
+
try {
|
|
108
|
+
const ct = response.headers.get('content-type') ?? '';
|
|
109
|
+
if (isJsonContentType(ct)) {
|
|
110
|
+
// Clone to avoid consuming the body stream.
|
|
111
|
+
const clone = response.clone();
|
|
112
|
+
const body = await clone.json();
|
|
113
|
+
const outcome = validateResponse(plan.validators, method.toLowerCase(), response.status, body, plan.validatorConfig ?? {}, resolveDebug(plan.debug));
|
|
114
|
+
// A failure replaces the response; afterRoute /
|
|
115
|
+
// mapResponse still run on it (e.g. CORS headers).
|
|
116
|
+
if (!outcome.ok && outcome.errorResponse) {
|
|
117
|
+
response = outcome.errorResponse;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// Response body not JSON or unparseable — skip validation.
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
response = await runResponseHookList(plan.afterRoute, ctx, response);
|
|
126
|
+
response = await runResponseHookList(plan.mapResponse, ctx, response);
|
|
127
|
+
return response;
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
// The error render also gets the global/plugin response hooks
|
|
131
|
+
// (route-level response hooks stay off the error path).
|
|
132
|
+
return globalErrorFinisher(plan.globalResponse)(dispatchOnError(error, plan.onError, ctx, plan.debug, plan.validatorConfig), ctx);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Dispatches an error through the `onError` hook chain (nearest-first).
|
|
137
|
+
*
|
|
138
|
+
* Each hook may return a `Response` to handle the error; a hook that throws
|
|
139
|
+
* is skipped (no recursion). The thrown value is passed through unchanged —
|
|
140
|
+
* objects carrying a `status` stay intact.
|
|
141
|
+
*
|
|
142
|
+
* Fallback: `HTTPError` renders an RFC 9457 Problem Details response,
|
|
143
|
+
* `ValidationError` keeps its structured format, unknown errors are wrapped
|
|
144
|
+
* in `HTTPError(500)`.
|
|
145
|
+
*/
|
|
146
|
+
export async function dispatchOnError(error, onErrorHooks, ctx, debug, validatorConfig) {
|
|
147
|
+
for (const hook of onErrorHooks) {
|
|
148
|
+
try {
|
|
149
|
+
// Hooks may receive any thrown value; `Error` is the documented
|
|
150
|
+
// contract.
|
|
151
|
+
const result = await hook(error, ctx);
|
|
152
|
+
if (result instanceof Response) {
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
catch (hookError) {
|
|
157
|
+
// onError threw — log it, skip to the next hook, never re-enter
|
|
158
|
+
// onError. The original error still renders if none handles it.
|
|
159
|
+
console.error('[burger-api] onError hook threw; rendering the original error:', hookError);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Fallback for unhandled errors: RFC 9457. Debug mode includes stack and
|
|
163
|
+
// cause; otherwise no internals.
|
|
164
|
+
const isDev = resolveDebug(debug);
|
|
165
|
+
// ValidationError retains its structured format (errorsBySlot grouping).
|
|
166
|
+
if (error instanceof ValidationError) {
|
|
167
|
+
return error.toResponse(isDev, validatorConfig);
|
|
168
|
+
}
|
|
169
|
+
// All other HTTPError subclasses and unknown errors → RFC 9457.
|
|
170
|
+
const response = renderHTTPError(error, isDev);
|
|
171
|
+
// No onError handled a server-side failure: log it, or it would vanish
|
|
172
|
+
// (the client only sees a generic 500 in production).
|
|
173
|
+
if (response.status >= 500) {
|
|
174
|
+
logUnhandledError(ctx.method, ctx.url, error);
|
|
175
|
+
}
|
|
176
|
+
return response;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Runs one response hook point (`afterRoute` / `mapResponse`). Each hook may
|
|
180
|
+
* return a `Response` (replace), a transform function `(res) => Response`
|
|
181
|
+
* (transform), or `undefined` / `void` (continue).
|
|
182
|
+
*
|
|
183
|
+
* Exported so the global/plugin response plan (used for 404/405/OPTIONS and
|
|
184
|
+
* non-route responses) runs hooks with the exact same semantics.
|
|
185
|
+
*/
|
|
186
|
+
export async function runResponseHookList(hooks, ctx, response) {
|
|
187
|
+
let res = response;
|
|
188
|
+
for (let i = 0; i < hooks.length; i++) {
|
|
189
|
+
const result = await hooks[i](ctx);
|
|
190
|
+
if (result instanceof Response) {
|
|
191
|
+
res = result;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (typeof result === 'function') {
|
|
195
|
+
res = await result(res);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
// undefined / void → continue
|
|
199
|
+
}
|
|
200
|
+
return res;
|
|
201
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { BurgerContext } from '../context/context.js';
|
|
2
|
+
import type { RequestHandler } from '../types/index.js';
|
|
3
|
+
import type { ForwardHook, ResponseHook } from './types.js';
|
|
4
|
+
/** Either hook kind — both share the same runtime 3-way return contract. */
|
|
5
|
+
type RunnerHook = ForwardHook | ResponseHook;
|
|
6
|
+
/**
|
|
7
|
+
* Runs the hook chain (if any) for a compiled handler.
|
|
8
|
+
* Preserves the 0/1/2/3+ fast paths.
|
|
9
|
+
*/
|
|
10
|
+
export declare function runHooks(ctx: BurgerContext, hooks: RunnerHook[], handler: RequestHandler): Promise<Response>;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { isThenable } from '../utils/thenable.js';
|
|
2
|
+
/**
|
|
3
|
+
* Runs a single hook followed by the handler. Reused by the router compiler
|
|
4
|
+
* so compiled handlers share the same hook semantics.
|
|
5
|
+
*/
|
|
6
|
+
async function runSingleHook(ctx, hook, handler) {
|
|
7
|
+
// Sync-first: a plain hook result continues without a microtask.
|
|
8
|
+
let result = hook(ctx);
|
|
9
|
+
if (isThenable(result))
|
|
10
|
+
result = await result;
|
|
11
|
+
// Response short-circuits the handler.
|
|
12
|
+
if (result instanceof Response) {
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
15
|
+
// A function result maps the handler's response.
|
|
16
|
+
if (typeof result === 'function') {
|
|
17
|
+
let response = handler(ctx);
|
|
18
|
+
if (isThenable(response))
|
|
19
|
+
response = await response;
|
|
20
|
+
let mapped = result(response);
|
|
21
|
+
if (isThenable(mapped))
|
|
22
|
+
mapped = await mapped;
|
|
23
|
+
return mapped;
|
|
24
|
+
}
|
|
25
|
+
return handler(ctx);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Runs an ordered hook chain followed by the handler.
|
|
29
|
+
*
|
|
30
|
+
* Each hook may return a `Response` (stop and send it), a function (saved to
|
|
31
|
+
* transform the eventual response, applied in reverse order after the
|
|
32
|
+
* handler), or `undefined` (continue).
|
|
33
|
+
*/
|
|
34
|
+
async function runHookChain(ctx, hooks, handler) {
|
|
35
|
+
const len = hooks.length;
|
|
36
|
+
// Fast path: two hooks (common: CORS + logger, or auth + logger)
|
|
37
|
+
if (len === 2) {
|
|
38
|
+
// Length guards guarantee the elements; the `!` is safe.
|
|
39
|
+
const first = hooks[0];
|
|
40
|
+
const second = hooks[1];
|
|
41
|
+
// First hook (sync-first: no microtask when it returned a plain value)
|
|
42
|
+
let result1 = first(ctx);
|
|
43
|
+
if (isThenable(result1))
|
|
44
|
+
result1 = await result1;
|
|
45
|
+
if (result1 instanceof Response) {
|
|
46
|
+
return result1;
|
|
47
|
+
}
|
|
48
|
+
// Second hook
|
|
49
|
+
let result2 = second(ctx);
|
|
50
|
+
if (isThenable(result2))
|
|
51
|
+
result2 = await result2;
|
|
52
|
+
if (result2 instanceof Response) {
|
|
53
|
+
// Apply first hook's after function if exists
|
|
54
|
+
if (typeof result1 === 'function') {
|
|
55
|
+
let mapped = result1(result2);
|
|
56
|
+
if (isThenable(mapped))
|
|
57
|
+
mapped = await mapped;
|
|
58
|
+
return mapped;
|
|
59
|
+
}
|
|
60
|
+
return result2;
|
|
61
|
+
}
|
|
62
|
+
// Run handler
|
|
63
|
+
let response = handler(ctx);
|
|
64
|
+
if (isThenable(response))
|
|
65
|
+
response = await response;
|
|
66
|
+
// Apply after functions in reverse order (manual unroll)
|
|
67
|
+
if (typeof result2 === 'function') {
|
|
68
|
+
let mapped = result2(response);
|
|
69
|
+
if (isThenable(mapped))
|
|
70
|
+
mapped = await mapped;
|
|
71
|
+
response = mapped;
|
|
72
|
+
}
|
|
73
|
+
if (typeof result1 === 'function') {
|
|
74
|
+
let mapped = result1(response);
|
|
75
|
+
if (isThenable(mapped))
|
|
76
|
+
mapped = await mapped;
|
|
77
|
+
response = mapped;
|
|
78
|
+
}
|
|
79
|
+
return response;
|
|
80
|
+
}
|
|
81
|
+
// General path: 3+ hooks (less common)
|
|
82
|
+
// Pre-allocate array with exact size to avoid dynamic resizing
|
|
83
|
+
const afterStack = new Array(len);
|
|
84
|
+
let afterCount = 0;
|
|
85
|
+
// Run each hook (sync-first: a plain hook result never yields)
|
|
86
|
+
for (let i = 0; i < len; i++) {
|
|
87
|
+
let result = hooks[i](ctx);
|
|
88
|
+
if (isThenable(result))
|
|
89
|
+
result = await result;
|
|
90
|
+
// Short-circuit with Response (check first - most common early exit)
|
|
91
|
+
if (result instanceof Response) {
|
|
92
|
+
// Apply collected "after" functions in reverse
|
|
93
|
+
if (afterCount === 0)
|
|
94
|
+
return result;
|
|
95
|
+
if (afterCount === 1)
|
|
96
|
+
return afterStack[0](result);
|
|
97
|
+
// Multiple after functions
|
|
98
|
+
let response = result;
|
|
99
|
+
for (let j = afterCount - 1; j >= 0; j--) {
|
|
100
|
+
let mapped = afterStack[j](response);
|
|
101
|
+
if (isThenable(mapped))
|
|
102
|
+
mapped = await mapped;
|
|
103
|
+
response = mapped;
|
|
104
|
+
}
|
|
105
|
+
return response;
|
|
106
|
+
}
|
|
107
|
+
// Save function for later (check once, no double typeof check)
|
|
108
|
+
if (typeof result === 'function') {
|
|
109
|
+
afterStack[afterCount++] = result;
|
|
110
|
+
}
|
|
111
|
+
// undefined - continue (implicit, no check needed)
|
|
112
|
+
}
|
|
113
|
+
// All hooks passed - run handler
|
|
114
|
+
let response = handler(ctx);
|
|
115
|
+
if (isThenable(response))
|
|
116
|
+
response = await response;
|
|
117
|
+
// Apply "after" functions in reverse order
|
|
118
|
+
// Fast paths for common cases
|
|
119
|
+
if (afterCount === 0)
|
|
120
|
+
return response;
|
|
121
|
+
if (afterCount === 1) {
|
|
122
|
+
let mapped = afterStack[0](response);
|
|
123
|
+
if (isThenable(mapped))
|
|
124
|
+
mapped = await mapped;
|
|
125
|
+
return mapped;
|
|
126
|
+
}
|
|
127
|
+
if (afterCount === 2) {
|
|
128
|
+
let mapped = afterStack[1](response);
|
|
129
|
+
if (isThenable(mapped))
|
|
130
|
+
mapped = await mapped;
|
|
131
|
+
response = mapped;
|
|
132
|
+
mapped = afterStack[0](response);
|
|
133
|
+
if (isThenable(mapped))
|
|
134
|
+
mapped = await mapped;
|
|
135
|
+
return mapped;
|
|
136
|
+
}
|
|
137
|
+
// General case: 3+ after functions
|
|
138
|
+
for (let i = afterCount - 1; i >= 0; i--) {
|
|
139
|
+
let mapped = afterStack[i](response);
|
|
140
|
+
if (isThenable(mapped))
|
|
141
|
+
mapped = await mapped;
|
|
142
|
+
response = mapped;
|
|
143
|
+
}
|
|
144
|
+
return response;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Runs the hook chain (if any) for a compiled handler.
|
|
148
|
+
* Preserves the 0/1/2/3+ fast paths.
|
|
149
|
+
*/
|
|
150
|
+
export function runHooks(ctx, hooks, handler) {
|
|
151
|
+
if (hooks.length === 0)
|
|
152
|
+
return Promise.resolve(handler(ctx));
|
|
153
|
+
if (hooks.length === 1)
|
|
154
|
+
return runSingleHook(ctx, hooks[0], handler);
|
|
155
|
+
return runHookChain(ctx, hooks, handler);
|
|
156
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { BurgerContext } from '../context/context.js';
|
|
2
|
+
import type { RequestHandler } from '../types/index.js';
|
|
3
|
+
import type { HookPlan } from './types.js';
|
|
4
|
+
export declare function canUseJit(): boolean;
|
|
5
|
+
/** Test seam: forget the cached probe result. */
|
|
6
|
+
export declare function resetJitProbe(): void;
|
|
7
|
+
/**
|
|
8
|
+
* True when `fn` is declared `async` (or is an async generator). An
|
|
9
|
+
* async-declared function always returns a promise, so its call site must
|
|
10
|
+
* await unconditionally.
|
|
11
|
+
*/
|
|
12
|
+
export declare function isAsyncFunction(fn: unknown): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Conservative source-level proof that `fn` can NEVER return a promise,
|
|
15
|
+
* cached per function. Only two shapes are proven safe: a block body with no
|
|
16
|
+
* `return` token (the call yields `undefined`) and an arrow with a literal
|
|
17
|
+
* expression body. Everything else (a `return`, native code, unparseable
|
|
18
|
+
* source) reports `true`, so the generated code keeps its thenable check and
|
|
19
|
+
* behavior cannot drift.
|
|
20
|
+
*/
|
|
21
|
+
export declare function mayReturnPromise(fn: unknown): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Compiles a frozen {@link HookPlan} into a single function via
|
|
24
|
+
* `new Function`, unrolling the chains `executeHookPlan` walks per request.
|
|
25
|
+
*
|
|
26
|
+
* Semantics contract (same as lifecycle/executor.ts):
|
|
27
|
+
*
|
|
28
|
+
* transform → validation → beforeRoute* → handler → response-validation?
|
|
29
|
+
* → afterRoute* → mapResponse*
|
|
30
|
+
* any throw → dispatchOnError (nearest-first onError chain)
|
|
31
|
+
*
|
|
32
|
+
* - Sync-first: a step proven not to return a promise is called without
|
|
33
|
+
* `await`; otherwise a conditional thenable guard is emitted. The generated
|
|
34
|
+
* function becomes `async` only when a call actually needs `await`; the
|
|
35
|
+
* error path always returns `dispatchOnError`'s promise.
|
|
36
|
+
* - Forward hooks: `Response` short-circuits the remaining hooks and the
|
|
37
|
+
* handler (the response still flows through collected mappers, response
|
|
38
|
+
* validation, afterRoute and mapResponse); a function return is an
|
|
39
|
+
* after-mapper applied in reverse collection order.
|
|
40
|
+
* - Response hooks: `Response` replaces; `(res)=>Response` transforms.
|
|
41
|
+
* - Cold stages (transform, validation, response validation, error dispatch)
|
|
42
|
+
* delegate to the same shared functions the interpreter uses, so behavior
|
|
43
|
+
* cannot drift; only hot chains are unrolled.
|
|
44
|
+
* - Dependencies ride in one captured object `D`; no user function source is
|
|
45
|
+
* ever interpolated into the generated code.
|
|
46
|
+
*
|
|
47
|
+
* @returns the compiled dispatcher, or `null` when there is nothing worth
|
|
48
|
+
* compiling or dynamic code generation is unavailable.
|
|
49
|
+
*/
|
|
50
|
+
export declare function compileJitHookPlan(plan: HookPlan, debug?: boolean, handler?: RequestHandler): ((ctx: BurgerContext, handler: RequestHandler, method: string) => Response | Promise<Response>) | null;
|