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,441 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The validation coordinator — builds the framework's validation hook from
|
|
3
|
+
* precompiled route validators.
|
|
4
|
+
*
|
|
5
|
+
* Runs `cv.validate(value)` once per slot — no walk over the raw schema, no
|
|
6
|
+
* adapter selection, no preparing at request time. Skips work when
|
|
7
|
+
* `ctx.validated` is already set and validates
|
|
8
|
+
* params/query/headers/cookies/body with the same checks.
|
|
9
|
+
*
|
|
10
|
+
* Throws `ValidationError` (422, RFC 9457 problem details) on failure, or
|
|
11
|
+
* `HTTPError(415)` when a body schema is declared but the request body is not
|
|
12
|
+
* JSON (never skips validation).
|
|
13
|
+
*/
|
|
14
|
+
import { apply as applyCoercion } from './coerce.js';
|
|
15
|
+
import { ValidationError } from './error.js';
|
|
16
|
+
import { HTTPError } from '../errors/http-error.js';
|
|
17
|
+
/**
|
|
18
|
+
* Splits a `Cookie` header into `name=value` pairs, following RFC 6265 quoted
|
|
19
|
+
* cookie-values. A quoted value may contain `;` or `=` without terminating the
|
|
20
|
+
* pair (e.g. `session="a;b=c"`). The surrounding DQUOTES are stripped from the
|
|
21
|
+
* value; the inner content is preserved verbatim.
|
|
22
|
+
*/
|
|
23
|
+
function splitCookiePairs(header) {
|
|
24
|
+
const pairs = [];
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (i < header.length) {
|
|
27
|
+
// Skip leading whitespace/separators between pairs.
|
|
28
|
+
while (i < header.length && (header[i] === ' ' || header[i] === ';'))
|
|
29
|
+
i++;
|
|
30
|
+
if (i >= header.length)
|
|
31
|
+
break;
|
|
32
|
+
const eq = header.indexOf('=', i);
|
|
33
|
+
if (eq === -1)
|
|
34
|
+
break; // Malformed trailing token; stop.
|
|
35
|
+
const key = header.slice(i, eq).trim();
|
|
36
|
+
i = eq + 1;
|
|
37
|
+
let value;
|
|
38
|
+
if (header[i] === '"') {
|
|
39
|
+
// Quoted value: consume until the closing unescaped DQUOTE.
|
|
40
|
+
i++; // past opening quote
|
|
41
|
+
let end = i;
|
|
42
|
+
while (end < header.length && header[end] !== '"')
|
|
43
|
+
end++;
|
|
44
|
+
value = header.slice(i, end);
|
|
45
|
+
i = end + 1; // past closing quote
|
|
46
|
+
// Advance to the next ';' (or end) so the loop skips the rest.
|
|
47
|
+
const semi = header.indexOf(';', i);
|
|
48
|
+
i = semi === -1 ? header.length : semi + 1;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const semi = header.indexOf(';', i);
|
|
52
|
+
if (semi === -1) {
|
|
53
|
+
value = header.slice(i);
|
|
54
|
+
i = header.length;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
value = header.slice(i, semi);
|
|
58
|
+
i = semi + 1;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (key)
|
|
62
|
+
pairs.push([key, value.trim()]);
|
|
63
|
+
}
|
|
64
|
+
return pairs;
|
|
65
|
+
}
|
|
66
|
+
/** Parses a `Cookie` header value into a flat record (cookie slot). */
|
|
67
|
+
export function parseCookies(header) {
|
|
68
|
+
// Null prototype: cookie names are attacker-controlled and must never
|
|
69
|
+
// touch the object prototype (`__proto__` / `constructor`).
|
|
70
|
+
const out = Object.create(null);
|
|
71
|
+
if (!header)
|
|
72
|
+
return out;
|
|
73
|
+
for (const [key, rawValue] of splitCookiePairs(header)) {
|
|
74
|
+
try {
|
|
75
|
+
out[key] = decodeURIComponent(rawValue);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// Malformed percent-encoding (e.g. "%ZZ") — keep the raw value
|
|
79
|
+
// rather than throwing inside the validator.
|
|
80
|
+
out[key] = rawValue;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Resolves the validators for a lowercase method, reusing GET's validators
|
|
87
|
+
* for HEAD (auto-HEAD: a GET route implies HEAD is allowed; the body slot is
|
|
88
|
+
* skipped by the caller).
|
|
89
|
+
*/
|
|
90
|
+
function resolveMethodValidators(validators, method) {
|
|
91
|
+
// Runtime method strings are lowercased before lookup; only methods in
|
|
92
|
+
// the union can be keys of the compiled map, so widening is safe.
|
|
93
|
+
let methodValidators = validators.methods[method];
|
|
94
|
+
if (!methodValidators && method === 'head') {
|
|
95
|
+
methodValidators = validators.methods['get'];
|
|
96
|
+
}
|
|
97
|
+
return methodValidators;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Lowercases an HTTP method without allocating when it is already lowercase
|
|
101
|
+
* (Bun hands the uppercase form in). Returns an empty string for anything
|
|
102
|
+
* that cannot be a compiled method key, so the caller takes the "no
|
|
103
|
+
* validators" path.
|
|
104
|
+
*/
|
|
105
|
+
function toLowerMethod(method) {
|
|
106
|
+
const len = method.length;
|
|
107
|
+
if (len < 3 || len > 7)
|
|
108
|
+
return '';
|
|
109
|
+
for (let i = 0; i < len; i++) {
|
|
110
|
+
const code = method.charCodeAt(i);
|
|
111
|
+
if (code >= 65 && code <= 90)
|
|
112
|
+
return method.toLowerCase();
|
|
113
|
+
}
|
|
114
|
+
return method;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Extracts the media type from a raw `Content-Type` header value without
|
|
118
|
+
* `split`/`trim`/`toLowerCase` when the value is already a plain lowercase
|
|
119
|
+
* token (the common case).
|
|
120
|
+
*/
|
|
121
|
+
function mediaTypeOf(raw) {
|
|
122
|
+
const semi = raw.indexOf(';');
|
|
123
|
+
let start = 0;
|
|
124
|
+
let end = semi === -1 ? raw.length : semi;
|
|
125
|
+
while (start < end) {
|
|
126
|
+
const c = raw.charCodeAt(start);
|
|
127
|
+
if (c !== 32 && c !== 9)
|
|
128
|
+
break;
|
|
129
|
+
start++;
|
|
130
|
+
}
|
|
131
|
+
while (end > start) {
|
|
132
|
+
const c = raw.charCodeAt(end - 1);
|
|
133
|
+
if (c !== 32 && c !== 9)
|
|
134
|
+
break;
|
|
135
|
+
end--;
|
|
136
|
+
}
|
|
137
|
+
const slice = start === 0 && end === raw.length ? raw : raw.slice(start, end);
|
|
138
|
+
// Lowercase only when the value actually carries uppercase characters
|
|
139
|
+
// (the already-lowercase common case allocates nothing).
|
|
140
|
+
for (let i = 0; i < slice.length; i++) {
|
|
141
|
+
const c = slice.charCodeAt(i);
|
|
142
|
+
if (c >= 65 && c <= 90)
|
|
143
|
+
return slice.toLowerCase();
|
|
144
|
+
}
|
|
145
|
+
return slice;
|
|
146
|
+
}
|
|
147
|
+
/** True when the media type (lowercased) is JSON (`application/json`/`+json`). */
|
|
148
|
+
function isJsonMediaType(mediaType) {
|
|
149
|
+
if (mediaType === 'application/json')
|
|
150
|
+
return true;
|
|
151
|
+
// `application/…+json` (e.g. `application/vnd.api+json`). Shortest form
|
|
152
|
+
// `application/+json` is 17 chars.
|
|
153
|
+
const len = mediaType.length;
|
|
154
|
+
if (len < 17)
|
|
155
|
+
return false;
|
|
156
|
+
if (mediaType.charCodeAt(0) !== 97 /* a */)
|
|
157
|
+
return false;
|
|
158
|
+
return mediaType.startsWith('application/') && mediaType.endsWith('+json');
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* True when a raw `Content-Type` header value is JSON (`application/json` or
|
|
162
|
+
* `application/…+json`). Shared by request-body and response validation.
|
|
163
|
+
*/
|
|
164
|
+
export function isJsonContentType(raw) {
|
|
165
|
+
return isJsonMediaType(mediaTypeOf(raw));
|
|
166
|
+
}
|
|
167
|
+
/** True when the value is empty or whitespace only (no `trim()` allocation). */
|
|
168
|
+
function isBlank(value) {
|
|
169
|
+
for (let i = 0; i < value.length; i++) {
|
|
170
|
+
const c = value.charCodeAt(i);
|
|
171
|
+
if (c !== 32 && c !== 9 && c !== 10 && c !== 13)
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Runs every declared slot for one method. Params/query/headers/cookies are
|
|
178
|
+
* synchronous; only a declared body slot returns a promise.
|
|
179
|
+
*/
|
|
180
|
+
function validateMethodSlots(ctx, methodValidators, isHead, config) {
|
|
181
|
+
// The validated bag matches the `BurgerValidated` slots, so it is
|
|
182
|
+
// assignable to `ctx.validated` without an assertion.
|
|
183
|
+
const validated = {};
|
|
184
|
+
// Track errors per slot — only populated on failure.
|
|
185
|
+
let errorsBySlot = null;
|
|
186
|
+
const coercion = methodValidators.coercion;
|
|
187
|
+
// Params
|
|
188
|
+
const paramsValidator = methodValidators.params;
|
|
189
|
+
if (paramsValidator) {
|
|
190
|
+
const input = coercion?.params
|
|
191
|
+
? applyCoercion(coercion.params, ctx.params)
|
|
192
|
+
: ctx.params;
|
|
193
|
+
const result = paramsValidator.validate(input);
|
|
194
|
+
if (result.success) {
|
|
195
|
+
validated.params = result.data;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
if (!errorsBySlot)
|
|
199
|
+
errorsBySlot = {};
|
|
200
|
+
errorsBySlot.params = result.issues;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
// Query
|
|
204
|
+
const queryValidator = methodValidators.query;
|
|
205
|
+
if (queryValidator) {
|
|
206
|
+
const queryParams = (ctx.query ?? {});
|
|
207
|
+
const input = coercion?.query
|
|
208
|
+
? applyCoercion(coercion.query, queryParams)
|
|
209
|
+
: queryParams;
|
|
210
|
+
const result = queryValidator.validate(input);
|
|
211
|
+
if (result.success) {
|
|
212
|
+
validated.query = result.data;
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
if (!errorsBySlot)
|
|
216
|
+
errorsBySlot = {};
|
|
217
|
+
errorsBySlot.query = result.issues;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// Headers
|
|
221
|
+
const headersValidator = methodValidators.headers;
|
|
222
|
+
if (headersValidator) {
|
|
223
|
+
// Null prototype: header names are attacker-controlled.
|
|
224
|
+
const headerRecord = Object.create(null);
|
|
225
|
+
const headers = ctx.headers;
|
|
226
|
+
// Bun exposes `Headers.toJSON()` (a plain record) — much cheaper than
|
|
227
|
+
// iterating the Headers object. WinterCG runtimes fall back to a
|
|
228
|
+
// manual key/value walk.
|
|
229
|
+
const toJSON = headers.toJSON;
|
|
230
|
+
if (typeof toJSON === 'function') {
|
|
231
|
+
const flat = toJSON.call(headers);
|
|
232
|
+
for (const key in flat) {
|
|
233
|
+
headerRecord[key.toLowerCase()] = flat[key];
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
for (const entry of headers) {
|
|
238
|
+
headerRecord[entry[0].toLowerCase()] = entry[1];
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const input = coercion?.headers
|
|
242
|
+
? applyCoercion(coercion.headers, headerRecord)
|
|
243
|
+
: headerRecord;
|
|
244
|
+
const result = headersValidator.validate(input);
|
|
245
|
+
if (result.success) {
|
|
246
|
+
validated.headers = result.data;
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
if (!errorsBySlot)
|
|
250
|
+
errorsBySlot = {};
|
|
251
|
+
errorsBySlot.headers = result.issues;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
// Cookies — reuse the context's cached parse (`ctx.cookies`) when the
|
|
255
|
+
// caller passed a real BurgerContext; duck-typed contexts (tests, embedded
|
|
256
|
+
// callers) fall back to parsing the header directly.
|
|
257
|
+
const cookiesValidator = methodValidators.cookies;
|
|
258
|
+
if (cookiesValidator) {
|
|
259
|
+
const cached = ctx.cookies;
|
|
260
|
+
const cookieRecord = cached !== undefined && cached !== null
|
|
261
|
+
? cached
|
|
262
|
+
: parseCookies(ctx.headers.get('cookie'));
|
|
263
|
+
const input = coercion?.cookies
|
|
264
|
+
? applyCoercion(coercion.cookies, cookieRecord)
|
|
265
|
+
: cookieRecord;
|
|
266
|
+
const result = cookiesValidator.validate(input);
|
|
267
|
+
if (result.success) {
|
|
268
|
+
validated.cookies = result.data;
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
if (!errorsBySlot)
|
|
272
|
+
errorsBySlot = {};
|
|
273
|
+
errorsBySlot.cookies = result.issues;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** Throws a `ValidationError` on failure, else stores `validated`. */
|
|
277
|
+
const finish = () => {
|
|
278
|
+
if (errorsBySlot) {
|
|
279
|
+
// Throw into the onError pipeline — the framework renders the
|
|
280
|
+
// RFC 9457 response via the default onError fallback.
|
|
281
|
+
const allIssues = [];
|
|
282
|
+
let firstSlot;
|
|
283
|
+
for (const slot in errorsBySlot) {
|
|
284
|
+
if (firstSlot === undefined) {
|
|
285
|
+
firstSlot = slot;
|
|
286
|
+
}
|
|
287
|
+
const issues = errorsBySlot[slot];
|
|
288
|
+
for (let i = 0; i < issues.length; i++) {
|
|
289
|
+
allIssues.push(issues[i]);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
throw new ValidationError(firstSlot, allIssues, {
|
|
293
|
+
errorsBySlot,
|
|
294
|
+
status: config.status,
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
ctx.validated = validated;
|
|
298
|
+
};
|
|
299
|
+
// Body (gated on the JSON media type; skipped for HEAD, which carries
|
|
300
|
+
// no body). The gate reads the raw header, so casing
|
|
301
|
+
// (`Application/JSON`) and parameters (`; charset=utf-8`) cannot bypass
|
|
302
|
+
// it.
|
|
303
|
+
const bodyValidator = methodValidators.body;
|
|
304
|
+
if (bodyValidator && !isHead) {
|
|
305
|
+
const rawContentType = ctx.headers.get('content-type') ?? '';
|
|
306
|
+
const mediaType = mediaTypeOf(rawContentType);
|
|
307
|
+
/** Validates one body value; failures land in `errorsBySlot.body`. */
|
|
308
|
+
const validateBodyValue = (bodyData) => {
|
|
309
|
+
try {
|
|
310
|
+
const result = bodyValidator.validate(bodyData);
|
|
311
|
+
if (result.success) {
|
|
312
|
+
validated.body = result.data;
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
if (!errorsBySlot)
|
|
316
|
+
errorsBySlot = {};
|
|
317
|
+
errorsBySlot.body = result.issues;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
322
|
+
if (!errorsBySlot)
|
|
323
|
+
errorsBySlot = {};
|
|
324
|
+
errorsBySlot.body = [{ path: [], message: msg }];
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
if (isJsonMediaType(mediaType)) {
|
|
328
|
+
// Read once through `ctx.text()` (bytes are cached), so
|
|
329
|
+
// `ctx.text()` / `ctx.arrayBuffer()` still work in the handler.
|
|
330
|
+
// An empty body validates as `undefined`; malformed JSON is a
|
|
331
|
+
// client error (400) and passes through onError, never 422.
|
|
332
|
+
return ctx.text().then((raw) => {
|
|
333
|
+
if (isBlank(raw)) {
|
|
334
|
+
validateBodyValue(undefined);
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
let bodyData;
|
|
338
|
+
try {
|
|
339
|
+
bodyData = JSON.parse(raw);
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
throw new HTTPError(400, `Malformed JSON body: ${error.message}`, { cause: error });
|
|
343
|
+
}
|
|
344
|
+
validateBodyValue(bodyData);
|
|
345
|
+
}
|
|
346
|
+
finish();
|
|
347
|
+
}, (error) => {
|
|
348
|
+
// Body read failure — surface as a body validation issue.
|
|
349
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
350
|
+
if (!errorsBySlot)
|
|
351
|
+
errorsBySlot = {};
|
|
352
|
+
errorsBySlot.body = [{ path: [], message: msg }];
|
|
353
|
+
finish();
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
else if (isBlank(rawContentType)) {
|
|
357
|
+
// No media type: an empty body validates as `undefined` (optional
|
|
358
|
+
// schemas work); a non-empty body is rejected rather than
|
|
359
|
+
// silently skipping validation.
|
|
360
|
+
return ctx.text().then((raw) => {
|
|
361
|
+
if (isBlank(raw)) {
|
|
362
|
+
validateBodyValue(undefined);
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
if (!errorsBySlot)
|
|
366
|
+
errorsBySlot = {};
|
|
367
|
+
errorsBySlot.body = [
|
|
368
|
+
{
|
|
369
|
+
path: [],
|
|
370
|
+
message: 'Content-Type header required for body validation',
|
|
371
|
+
},
|
|
372
|
+
];
|
|
373
|
+
}
|
|
374
|
+
finish();
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
else {
|
|
378
|
+
// A body schema is declared but the body is not JSON (form,
|
|
379
|
+
// text, …). Never let unvalidated data reach the handler:
|
|
380
|
+
// 415 Unsupported Media Type (RFC 9457 via onError).
|
|
381
|
+
throw new HTTPError(415, `Unsupported Media Type "${mediaType}" — this endpoint expects application/json`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
finish();
|
|
385
|
+
return undefined;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Builds the validation hook from precompiled route validators.
|
|
389
|
+
*
|
|
390
|
+
* On failure, throws a `ValidationError` (status 422, or
|
|
391
|
+
* `ValidatorConfig.status` when set) into the `onError` pipeline. The
|
|
392
|
+
* framework's default onError handler renders the RFC 9457 response.
|
|
393
|
+
*
|
|
394
|
+
* @param validators - the compiled validators for this route (may be empty).
|
|
395
|
+
* @param config - validation configuration (custom status, error format).
|
|
396
|
+
* @param isDev - reserved for future use (dev diagnostics).
|
|
397
|
+
* @param method - when given, the hook is specialized for that lowercase
|
|
398
|
+
* method at compile time (no per-request method lookup).
|
|
399
|
+
* @param skipValidatedBag - when true, a method without validators does not
|
|
400
|
+
* allocate the empty `{}` bag (only legal with `method` given).
|
|
401
|
+
*/
|
|
402
|
+
export function createValidationHook(validators, config = {}, isDev = false, method, skipValidatedBag = false) {
|
|
403
|
+
void isDev;
|
|
404
|
+
if (method !== undefined) {
|
|
405
|
+
const methodValidators = resolveMethodValidators(validators, method);
|
|
406
|
+
const isHead = method === 'head';
|
|
407
|
+
if (!methodValidators) {
|
|
408
|
+
if (skipValidatedBag)
|
|
409
|
+
return () => undefined;
|
|
410
|
+
// Methods without a schema still get an (empty) validated bag, so
|
|
411
|
+
// route hooks typed via `defineHooks` can read slots safely.
|
|
412
|
+
return (ctx) => {
|
|
413
|
+
if (!ctx.validated)
|
|
414
|
+
ctx.validated = {};
|
|
415
|
+
return undefined;
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
// NOT an `async` function: body-less schemas validate synchronously,
|
|
419
|
+
// and the pipeline awaits the result only when a Promise is returned.
|
|
420
|
+
return (ctx) => {
|
|
421
|
+
if (ctx.validated)
|
|
422
|
+
return undefined;
|
|
423
|
+
return validateMethodSlots(ctx, methodValidators, isHead, config);
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
// General path: resolve the method at request time (kept for callers
|
|
427
|
+
// that build a route-agnostic hook).
|
|
428
|
+
return (ctx) => {
|
|
429
|
+
// If the request has already been validated, continue.
|
|
430
|
+
if (ctx.validated) {
|
|
431
|
+
return undefined;
|
|
432
|
+
}
|
|
433
|
+
const methodLower = toLowerMethod(ctx.method || 'get');
|
|
434
|
+
const methodValidators = resolveMethodValidators(validators, methodLower);
|
|
435
|
+
if (!methodValidators) {
|
|
436
|
+
ctx.validated = {};
|
|
437
|
+
return undefined;
|
|
438
|
+
}
|
|
439
|
+
return validateMethodSlots(ctx, methodValidators, methodLower === 'head', config);
|
|
440
|
+
};
|
|
441
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matches upgrade requests to routes and wires sockets to their handlers.
|
|
3
|
+
*/
|
|
4
|
+
import type { WebSocketRouter } from './router.js';
|
|
5
|
+
import type { WebSocketConfig } from './types.js';
|
|
6
|
+
import { BurgerContext } from '../context/context.js';
|
|
7
|
+
import type { BurgerEnv, BurgerExecutionContext, RequestIPHolder } from '../context/context.js';
|
|
8
|
+
import type { Hook, TransformMap } from '../lifecycle/types.js';
|
|
9
|
+
import { type NodeWsBridge, type NodeWsBridgeOptions, type WsUpgradeOutcome } from './platform.js';
|
|
10
|
+
import { type RuntimeTarget } from '../runtime/capabilities.js';
|
|
11
|
+
/**
|
|
12
|
+
* The runtime's server-side socket (Bun, Cloudflare/Deno, or `ws` on Node).
|
|
13
|
+
* The adapter only keys per-socket state on it and reads the `data` set at
|
|
14
|
+
* upgrade; `BurgerWSContext` probes the rest.
|
|
15
|
+
*/
|
|
16
|
+
export type RawWebSocket = {
|
|
17
|
+
data?: unknown;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* WebSocket adapter options
|
|
21
|
+
*/
|
|
22
|
+
export interface WebSocketAdapterOptions {
|
|
23
|
+
/**
|
|
24
|
+
* WebSocket router
|
|
25
|
+
*/
|
|
26
|
+
router: WebSocketRouter;
|
|
27
|
+
/**
|
|
28
|
+
* Global WebSocket config
|
|
29
|
+
*/
|
|
30
|
+
config?: WebSocketConfig;
|
|
31
|
+
/**
|
|
32
|
+
* Debug mode
|
|
33
|
+
*/
|
|
34
|
+
debug?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Application services (providers) to inject into WebSocket handlers
|
|
37
|
+
*/
|
|
38
|
+
providers?: Map<string, unknown>;
|
|
39
|
+
/**
|
|
40
|
+
* Resolved plugin hooks for auth execution during upgrade
|
|
41
|
+
*/
|
|
42
|
+
pluginTransform?: TransformMap;
|
|
43
|
+
/**
|
|
44
|
+
* Resolved plugin beforeRoute hooks for auth execution during upgrade
|
|
45
|
+
*/
|
|
46
|
+
pluginBeforeRoute?: ((ctx: BurgerContext) => unknown | Promise<unknown>)[];
|
|
47
|
+
/**
|
|
48
|
+
* Resolved framework-scope beforeRoute hooks (run before plugin hooks).
|
|
49
|
+
*/
|
|
50
|
+
frameworkBeforeRoute?: Hook[];
|
|
51
|
+
/**
|
|
52
|
+
* Pre-routing onRequest hooks, in the same Framework → Plugin → Global
|
|
53
|
+
* order the HTTP path uses. Always run on upgrade — auth must not fail open.
|
|
54
|
+
*/
|
|
55
|
+
onRequestHooks?: Hook[];
|
|
56
|
+
/**
|
|
57
|
+
* App-level (`src/hooks.ts`) transform factories, applied after plugin ones.
|
|
58
|
+
*/
|
|
59
|
+
globalTransform?: TransformMap;
|
|
60
|
+
/**
|
|
61
|
+
* App-level (`src/hooks.ts`) beforeRoute hooks — run after plugin hooks.
|
|
62
|
+
*/
|
|
63
|
+
globalBeforeRoute?: Hook[];
|
|
64
|
+
/**
|
|
65
|
+
* Per-app `ctx.ip` holder, so upgrade hooks resolve the socket peer like
|
|
66
|
+
* HTTP hooks do.
|
|
67
|
+
*/
|
|
68
|
+
ipHolder?: RequestIPHolder;
|
|
69
|
+
/**
|
|
70
|
+
* The deployment target declared by `burger-api build --target`, if any.
|
|
71
|
+
* When present, resolves the handoff via `RUNTIME_CAPABILITIES` instead of
|
|
72
|
+
* live probing (Node and Vercel look identical to `globalThis` detection).
|
|
73
|
+
*/
|
|
74
|
+
runtimeTarget?: RuntimeTarget;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The WebSocket option object handed to `Bun.serve`'s `websocket` key.
|
|
78
|
+
* Framework handlers plus forwarded connection limits from `WebSocketConfig`.
|
|
79
|
+
*/
|
|
80
|
+
export interface WebSocketServeOption {
|
|
81
|
+
open: (ws: RawWebSocket) => void | Promise<void>;
|
|
82
|
+
message: (ws: RawWebSocket, message: string | Buffer) => void | Promise<void>;
|
|
83
|
+
close: (ws: RawWebSocket, code: number, reason: string) => void | Promise<void>;
|
|
84
|
+
drain: (ws: RawWebSocket) => void | Promise<void>;
|
|
85
|
+
ping: (ws: RawWebSocket) => void | Promise<void>;
|
|
86
|
+
pong: (ws: RawWebSocket) => void | Promise<void>;
|
|
87
|
+
maxPayloadLength?: number;
|
|
88
|
+
idleTimeout?: number;
|
|
89
|
+
backpressureLimit?: number;
|
|
90
|
+
closeOnBackpressureLimit?: boolean;
|
|
91
|
+
compression?: boolean;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* WebSocket adapter: upgrade handoff, auth gate and per-connection contexts.
|
|
95
|
+
*/
|
|
96
|
+
export declare class WebSocketAdapter {
|
|
97
|
+
private router;
|
|
98
|
+
private config;
|
|
99
|
+
private debug;
|
|
100
|
+
private providers?;
|
|
101
|
+
private pluginTransform?;
|
|
102
|
+
private pluginBeforeRoute?;
|
|
103
|
+
private frameworkBeforeRoute;
|
|
104
|
+
private onRequestHooks;
|
|
105
|
+
private globalTransform?;
|
|
106
|
+
private globalBeforeRoute;
|
|
107
|
+
private ipHolder?;
|
|
108
|
+
private runtimeTarget?;
|
|
109
|
+
/** One context per connection, so `ws.data` mutations persist. */
|
|
110
|
+
private wsContexts;
|
|
111
|
+
/** Matched route per connection (see `getMatch`). */
|
|
112
|
+
private wsMatches;
|
|
113
|
+
/**
|
|
114
|
+
* Per-socket event chain: messages (and close/drain/ping/pong) are
|
|
115
|
+
* delivered in order and only after `open` finished. The first event runs
|
|
116
|
+
* synchronously; only queued events wait on the chain.
|
|
117
|
+
*/
|
|
118
|
+
private wsChains;
|
|
119
|
+
constructor(options: WebSocketAdapterOptions);
|
|
120
|
+
/**
|
|
121
|
+
* Create the websocket option for Bun.serve()
|
|
122
|
+
*/
|
|
123
|
+
createWebSocketOption(): WebSocketServeOption;
|
|
124
|
+
/**
|
|
125
|
+
* Serializes events per socket. The first event starts synchronously (a
|
|
126
|
+
* sync handler keeps its immediate behavior); queued events run in order
|
|
127
|
+
* after it. Handlers catch their own errors, so the chain never rejects.
|
|
128
|
+
*/
|
|
129
|
+
private enqueue;
|
|
130
|
+
private handleOpen;
|
|
131
|
+
private runOpen;
|
|
132
|
+
private handleMessage;
|
|
133
|
+
private runMessage;
|
|
134
|
+
private handleClose;
|
|
135
|
+
private runClose;
|
|
136
|
+
private handleDrain;
|
|
137
|
+
private runDrain;
|
|
138
|
+
private handlePing;
|
|
139
|
+
private runPing;
|
|
140
|
+
private handlePong;
|
|
141
|
+
private runPong;
|
|
142
|
+
/**
|
|
143
|
+
* Entry point for WebSocket handling on every runtime: detects the
|
|
144
|
+
* platform, matches the route, runs the auth gate and performs the
|
|
145
|
+
* protocol handoff. Returns an explicit outcome so callers can never
|
|
146
|
+
* confuse "not an upgrade" with "socket taken over".
|
|
147
|
+
*
|
|
148
|
+
* @param request incoming request (upgrade or normal)
|
|
149
|
+
* @param server Bun serve handle when running under `Bun.serve`
|
|
150
|
+
* @param env platform bindings (bound onto the temporary auth context)
|
|
151
|
+
*/
|
|
152
|
+
handleUpgrade(request: Request, server?: unknown, env?: BurgerEnv, executionCtx?: BurgerExecutionContext): Promise<WsUpgradeOutcome>;
|
|
153
|
+
/**
|
|
154
|
+
* Route-match + auth, shared by every platform's upgrade handoff. The Node
|
|
155
|
+
* bridge cannot reuse {@link handleUpgrade} because that always routes
|
|
156
|
+
* through {@link detectWsPlatform}, which falls back to `'node'` there.
|
|
157
|
+
*/
|
|
158
|
+
private matchAndAuthorize;
|
|
159
|
+
/**
|
|
160
|
+
* Node cannot complete a WebSocket handshake inside a fetch handler —
|
|
161
|
+
* surface an explicit 501 with remediation instead of a thrown error.
|
|
162
|
+
*/
|
|
163
|
+
private nodeFetchUpgradeUnsupported;
|
|
164
|
+
/**
|
|
165
|
+
* Declared-target counterpart to {@link nodeFetchUpgradeUnsupported}: a
|
|
166
|
+
* target with `websocket: false` (only `vercel` today) gets a "not
|
|
167
|
+
* supported here" response — the Node bridge would be wrong advice, since
|
|
168
|
+
* that target has no persistent process.
|
|
169
|
+
*/
|
|
170
|
+
private capabilityUnsupportedResponse;
|
|
171
|
+
/**
|
|
172
|
+
* Shared event sink pushed into by non-Bun platforms. Their sockets get
|
|
173
|
+
* `data` attached before any event fires (see `wirePushListeners`).
|
|
174
|
+
*/
|
|
175
|
+
private eventSink;
|
|
176
|
+
/**
|
|
177
|
+
* Fetch-shaped wrapper around {@link handleUpgrade}, kept for backward
|
|
178
|
+
* compatibility. Returns `undefined` for BOTH "not an upgrade" and "socket
|
|
179
|
+
* taken over" — prefer {@link handleUpgrade} when the distinction matters.
|
|
180
|
+
*/
|
|
181
|
+
createFetchHandler(): (request: Request, server?: unknown) => Promise<Response | undefined>;
|
|
182
|
+
/**
|
|
183
|
+
* Node integration: bridges node:http's `'upgrade'` event into the framework
|
|
184
|
+
* pipeline using a framing library's `WebSocketServer` (e.g. the `ws`
|
|
185
|
+
* package). `fetchHandler()` must run at least once first — WS routes are
|
|
186
|
+
* processed there.
|
|
187
|
+
*
|
|
188
|
+
* ```ts
|
|
189
|
+
* import http from 'node:http';
|
|
190
|
+
* import { WebSocketServer } from 'ws';
|
|
191
|
+
*
|
|
192
|
+
* const fetchHandler = await burger.fetchHandler();
|
|
193
|
+
* const bridge = burger.createNodeWsBridge({ WebSocketServer });
|
|
194
|
+
* http.createServer((req, res) => { ... }) // bridge req/res <-> Request/Response
|
|
195
|
+
* .on('upgrade', (req, socket, head) => bridge.handleUpgrade(req, socket, head))
|
|
196
|
+
* .listen(3000);
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
createNodeWsBridge(options: NodeWsBridgeOptions): NodeWsBridge;
|
|
200
|
+
/**
|
|
201
|
+
* Get route from WebSocket data
|
|
202
|
+
*/
|
|
203
|
+
private getRouteFromWs;
|
|
204
|
+
/**
|
|
205
|
+
* The route + params matched at upgrade, cached per socket so a handler
|
|
206
|
+
* replacing `ws.data` cannot orphan the connection from its route.
|
|
207
|
+
*/
|
|
208
|
+
private getMatch;
|
|
209
|
+
/**
|
|
210
|
+
* Creates (or reuses) the BurgerWS context for a connection: one per
|
|
211
|
+
* connection, so `ws.data` mutations in one handler persist into the next.
|
|
212
|
+
*/
|
|
213
|
+
private createBurgerWS;
|
|
214
|
+
/**
|
|
215
|
+
* Runs the upgrade request through the same pre-handler chain HTTP uses —
|
|
216
|
+
* onRequest → transform → beforeRoute (Framework → Plugin → Global) —
|
|
217
|
+
* then enforces `config.auth.required` / `roles`. Always runs: auth
|
|
218
|
+
* check must never depend on a plugin being registered. `env` /
|
|
219
|
+
* `executionCtx` are bound onto the context so hooks can read bindings.
|
|
220
|
+
*/
|
|
221
|
+
private runAuthHooks;
|
|
222
|
+
/**
|
|
223
|
+
* Renders a throw from the upgrade auth chain. Only framework
|
|
224
|
+
* `HTTPError`s keep their status; anything else is a server bug and
|
|
225
|
+
* renders a generic 500 (never a fake 401 echoing the thrown message).
|
|
226
|
+
*/
|
|
227
|
+
private renderAuthError;
|
|
228
|
+
/** Applies collected mappers onion-style (last registered runs first). */
|
|
229
|
+
private applyMappers;
|
|
230
|
+
}
|