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,401 @@
|
|
|
1
|
+
import { parseQuery } from './query-parser.js';
|
|
2
|
+
import { parseCookies } from '../validation/validator.js';
|
|
3
|
+
import { TrackedContextSet } from './context-set.js';
|
|
4
|
+
import { extractPathnameFromUrl } from '../utils/wildcard.js';
|
|
5
|
+
import { HTTPError } from '../errors/http-error.js';
|
|
6
|
+
/** Shared UTF-8 decoder; strips a leading BOM like `Request.json()` does. */
|
|
7
|
+
const utf8 = new TextDecoder();
|
|
8
|
+
/**
|
|
9
|
+
* Shared services object for apps without `burger.provide()` providers.
|
|
10
|
+
* Frozen: services are app-scoped singletons, never per-request scratch space.
|
|
11
|
+
*/
|
|
12
|
+
export const EMPTY_SERVICES = Object.freeze(Object.create(null));
|
|
13
|
+
/**
|
|
14
|
+
* Resolves the app-level services for `ctx.services` once, at compile time.
|
|
15
|
+
* Providers are app-scoped singletons, so the resulting frozen bag is shared
|
|
16
|
+
* by every request; a prebuilt object passes through unchanged.
|
|
17
|
+
*/
|
|
18
|
+
export function createServices(providers) {
|
|
19
|
+
if (providers === undefined)
|
|
20
|
+
return EMPTY_SERVICES;
|
|
21
|
+
if (providers instanceof Map) {
|
|
22
|
+
if (providers.size === 0)
|
|
23
|
+
return EMPTY_SERVICES;
|
|
24
|
+
return Object.freeze(Object.fromEntries(providers));
|
|
25
|
+
}
|
|
26
|
+
return providers;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Per-request client address sources keyed by the raw `Request`. Set by the
|
|
30
|
+
* serving layer (or a Node adapter via {@link setRequestIP}); read by `ctx.ip`.
|
|
31
|
+
*/
|
|
32
|
+
const requestIPs = new WeakMap();
|
|
33
|
+
/**
|
|
34
|
+
* Records the client (socket peer) address for a request so `ctx.ip` can
|
|
35
|
+
* report it. Pass the address string (e.g. a Node adapter's
|
|
36
|
+
* `socket.remoteAddress`) or a server with `requestIP(request)` (Bun),
|
|
37
|
+
* resolved lazily on first read. Adapter-facing; apps read `ctx.ip`.
|
|
38
|
+
*/
|
|
39
|
+
export function setRequestIP(request, source) {
|
|
40
|
+
requestIPs.set(request, source);
|
|
41
|
+
}
|
|
42
|
+
/** True when `value` looks like a server that can resolve peer addresses. */
|
|
43
|
+
export function isRequestIPSource(value) {
|
|
44
|
+
return (typeof value === 'object' &&
|
|
45
|
+
value !== null &&
|
|
46
|
+
typeof value.requestIP === 'function');
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* `BurgerContext` — the public request context type.
|
|
50
|
+
*
|
|
51
|
+
* Exactly one instance is allocated per request via `BurgerContext.create()`;
|
|
52
|
+
* it is re-bound to the matched route, never re-allocated.
|
|
53
|
+
*
|
|
54
|
+
* Generic over the route's `schema.ts` method export for `ctx.validated`
|
|
55
|
+
* inference:
|
|
56
|
+
*
|
|
57
|
+
* ```ts
|
|
58
|
+
* // schema.ts
|
|
59
|
+
* export const GET = { query: z.object({ q: z.string() }) };
|
|
60
|
+
*
|
|
61
|
+
* // route.ts
|
|
62
|
+
* import type { GET as RouteSchema } from './schema';
|
|
63
|
+
* export async function GET(ctx: BurgerContext<typeof RouteSchema>) {
|
|
64
|
+
* ctx.validated.query; // { q: string } | undefined
|
|
65
|
+
* }
|
|
66
|
+
* ```
|
|
67
|
+
*
|
|
68
|
+
* The default type parameter keeps plain `BurgerContext` working (slots fall
|
|
69
|
+
* back to `unknown`, `BurgerValidated` augmentation applies).
|
|
70
|
+
*
|
|
71
|
+
* One shared frozen prototype carries every lazy getter and delegated
|
|
72
|
+
* `Request` member; instances hold only mutable state, so every instance has
|
|
73
|
+
* the same shape. Fields are parsed lazily and at most once — a field a route
|
|
74
|
+
* never reads is never parsed.
|
|
75
|
+
*/
|
|
76
|
+
export class BurgerContext {
|
|
77
|
+
/** True once anything touched `ctx.set` (lazy allocation marker). */
|
|
78
|
+
hasSet() {
|
|
79
|
+
return this._set !== undefined;
|
|
80
|
+
}
|
|
81
|
+
get set() {
|
|
82
|
+
return (this._set ??= new TrackedContextSet());
|
|
83
|
+
}
|
|
84
|
+
set set(value) {
|
|
85
|
+
this._set = value;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The single context creation entry point.
|
|
89
|
+
*
|
|
90
|
+
* `meta` (a `RouteAccessInfo` hint) is accepted but ignored at runtime:
|
|
91
|
+
* every field is already available lazily on the stable prototype.
|
|
92
|
+
*/
|
|
93
|
+
static create(raw, ctxInit, _meta, services, config, env, executionCtx, ipHolder) {
|
|
94
|
+
const ctx = new BurgerContext();
|
|
95
|
+
// Assignments run in declaration order so every instance has an
|
|
96
|
+
// identical hidden class.
|
|
97
|
+
ctx._raw = raw;
|
|
98
|
+
ctx._ctxInit = ctxInit ?? {};
|
|
99
|
+
ctx._query = undefined;
|
|
100
|
+
ctx._cookies = undefined;
|
|
101
|
+
ctx._json = undefined;
|
|
102
|
+
ctx._bodyBuffer = undefined;
|
|
103
|
+
ctx._bodyText = undefined;
|
|
104
|
+
ctx.validated = undefined;
|
|
105
|
+
ctx._set = undefined;
|
|
106
|
+
// A Map (direct callers, e.g. the WS adapter) is copied per context;
|
|
107
|
+
// a prebuilt services object (the compiled route path) is shared.
|
|
108
|
+
ctx.services =
|
|
109
|
+
services === undefined
|
|
110
|
+
? EMPTY_SERVICES
|
|
111
|
+
: services instanceof Map
|
|
112
|
+
? Object.fromEntries(services)
|
|
113
|
+
: services;
|
|
114
|
+
// Route config is opaque user data until `RouteConfig` is augmented.
|
|
115
|
+
ctx._config = config;
|
|
116
|
+
ctx._env = env ?? undefined;
|
|
117
|
+
ctx._executionCtx = executionCtx ?? undefined;
|
|
118
|
+
ctx._ipHolder = ipHolder;
|
|
119
|
+
ctx._ip = undefined;
|
|
120
|
+
return ctx;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* @internal Re-bind route-specific state on an existing context.
|
|
124
|
+
*
|
|
125
|
+
* The router creates one context per request before routing (so
|
|
126
|
+
* `onRequest` hooks can seed request IDs, counters, …) and the dispatched
|
|
127
|
+
* handler binds that same instance to the matched route. Caches stay
|
|
128
|
+
* valid because the underlying `Request` is identical.
|
|
129
|
+
*/
|
|
130
|
+
bind(raw, ctxInit, _meta, _services, config, env, executionCtx, ipHolder) {
|
|
131
|
+
// `raw` is always the request the context was created for; reset the
|
|
132
|
+
// lazily cached peer address only if that ever stops holding.
|
|
133
|
+
if (raw !== this._raw) {
|
|
134
|
+
this._ip = undefined;
|
|
135
|
+
}
|
|
136
|
+
this._raw = raw;
|
|
137
|
+
this._ctxInit = ctxInit ?? this._ctxInit;
|
|
138
|
+
// Services were resolved at creation (shared per app); bind must not
|
|
139
|
+
// rebuild them per request.
|
|
140
|
+
if (config !== undefined) {
|
|
141
|
+
this._config = config;
|
|
142
|
+
}
|
|
143
|
+
// Platform bindings carry over from the pre-routing context unless a
|
|
144
|
+
// fresh value is supplied.
|
|
145
|
+
if (env !== undefined) {
|
|
146
|
+
this._env = env;
|
|
147
|
+
}
|
|
148
|
+
if (executionCtx !== undefined) {
|
|
149
|
+
this._executionCtx = executionCtx;
|
|
150
|
+
}
|
|
151
|
+
if (ipHolder !== undefined) {
|
|
152
|
+
this._ipHolder = ipHolder;
|
|
153
|
+
}
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
156
|
+
/** Lazily parsed query record. Parsed once on first access, then cached. */
|
|
157
|
+
get query() {
|
|
158
|
+
if (this._query === undefined) {
|
|
159
|
+
const url = this._raw.url;
|
|
160
|
+
const q = url.indexOf('?');
|
|
161
|
+
const search = q === -1 ? '' : url.slice(q + 1);
|
|
162
|
+
this._query = parseQuery(search);
|
|
163
|
+
}
|
|
164
|
+
return this._query;
|
|
165
|
+
}
|
|
166
|
+
/** Lazily parsed cookie record. Parsed once on first access, then cached. */
|
|
167
|
+
get cookies() {
|
|
168
|
+
if (this._cookies === undefined) {
|
|
169
|
+
this._cookies = parseCookies(this._raw.headers.get('Cookie'));
|
|
170
|
+
}
|
|
171
|
+
return this._cookies;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The socket peer address (never a forwarded header — `X-Forwarded-For`
|
|
175
|
+
* and friends are client-controlled unless a trusted proxy sets them).
|
|
176
|
+
* `undefined` when the runtime does not expose it (WinterCG `fetch`).
|
|
177
|
+
*/
|
|
178
|
+
get ip() {
|
|
179
|
+
if (this._ip !== undefined)
|
|
180
|
+
return this._ip ?? undefined;
|
|
181
|
+
const source = requestIPs.get(this._raw);
|
|
182
|
+
if (source !== undefined) {
|
|
183
|
+
this._ip =
|
|
184
|
+
typeof source === 'string'
|
|
185
|
+
? source
|
|
186
|
+
: (source.requestIP(this._raw)?.address ?? null);
|
|
187
|
+
return this._ip ?? undefined;
|
|
188
|
+
}
|
|
189
|
+
// Per-app server reference (set once at startup): resolve the socket
|
|
190
|
+
// peer lazily and cache it for the request.
|
|
191
|
+
const server = this._ipHolder?.server;
|
|
192
|
+
this._ip = server ? (server.requestIP(this._raw)?.address ?? null) : null;
|
|
193
|
+
return this._ip ?? undefined;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Publish a message to every WebSocket socket subscribed to `topic`
|
|
197
|
+
* (Bun only — `server.publish`). Unlike `ws.publish`, delivery is not
|
|
198
|
+
* tied to a publishing socket, so the sender is included when subscribed.
|
|
199
|
+
*
|
|
200
|
+
* @returns Bun's send status: bytes sent, `0` when the message was
|
|
201
|
+
* dropped, `-1` on backpressure.
|
|
202
|
+
* @throws when the app is not served by Bun (`app.serve()`), or before
|
|
203
|
+
* the server has started.
|
|
204
|
+
*/
|
|
205
|
+
publish(topic, message) {
|
|
206
|
+
const server = this._ipHolder?.server;
|
|
207
|
+
const publish = server?.publish;
|
|
208
|
+
if (typeof publish !== 'function') {
|
|
209
|
+
throw new Error(`[burger-api] ctx.publish("${topic}") requires a running Bun ` +
|
|
210
|
+
'server with WebSocket handlers (app.serve()); none is ' +
|
|
211
|
+
'available on this runtime or at this point in the ' +
|
|
212
|
+
'lifecycle. Use ws.publish() inside a WebSocket handler ' +
|
|
213
|
+
'when no HTTP context is available.');
|
|
214
|
+
}
|
|
215
|
+
return publish.call(server, topic, message);
|
|
216
|
+
}
|
|
217
|
+
/** The underlying raw `Request`. */
|
|
218
|
+
get request() {
|
|
219
|
+
return this._raw;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Route path params (seeded from `ctxInit`). Always an object — empty
|
|
223
|
+
* for routes without `[param]` segments — so `ctx.params.id` compiles.
|
|
224
|
+
*/
|
|
225
|
+
get params() {
|
|
226
|
+
return (this._ctxInit.params ??= {});
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Wildcard segments (seeded from `ctxInit`). Always an array — empty
|
|
230
|
+
* for non-wildcard routes.
|
|
231
|
+
*/
|
|
232
|
+
get wildcardParams() {
|
|
233
|
+
return (this._ctxInit.wildcardParams ??= []);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* The matched-route identity (seeded from `ctxInit`).
|
|
237
|
+
*
|
|
238
|
+
* Native dynamic routes seed only the `pattern`; the concrete requested
|
|
239
|
+
* `path` is derived here on first access and cached for the request.
|
|
240
|
+
*/
|
|
241
|
+
get route() {
|
|
242
|
+
const init = this._ctxInit;
|
|
243
|
+
if (init.route === undefined && init.pattern !== undefined) {
|
|
244
|
+
init.route = Object.freeze({
|
|
245
|
+
path: extractPathnameFromUrl(this._raw.url),
|
|
246
|
+
pattern: init.pattern,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return init.route;
|
|
250
|
+
}
|
|
251
|
+
/** Route-specific configuration from `config.ts`. */
|
|
252
|
+
get config() {
|
|
253
|
+
return this._config;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Deployment-platform bindings (`env.MY_KV`, secrets, …), typed via
|
|
257
|
+
* augmentation of `BurgerEnv`. `undefined` when the runtime provides none.
|
|
258
|
+
*/
|
|
259
|
+
get env() {
|
|
260
|
+
return this._env;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Platform execution context (`waitUntil`). `undefined` when the
|
|
264
|
+
* runtime does not supply one.
|
|
265
|
+
*/
|
|
266
|
+
get executionCtx() {
|
|
267
|
+
return this._executionCtx;
|
|
268
|
+
}
|
|
269
|
+
// --- Delegated standard `Request` surface (read-only accessors) ---
|
|
270
|
+
get headers() {
|
|
271
|
+
return this._raw.headers;
|
|
272
|
+
}
|
|
273
|
+
get method() {
|
|
274
|
+
return this._raw.method;
|
|
275
|
+
}
|
|
276
|
+
get url() {
|
|
277
|
+
return this._raw.url;
|
|
278
|
+
}
|
|
279
|
+
get signal() {
|
|
280
|
+
return this._raw.signal;
|
|
281
|
+
}
|
|
282
|
+
get body() {
|
|
283
|
+
return this._raw.body;
|
|
284
|
+
}
|
|
285
|
+
get bodyUsed() {
|
|
286
|
+
return this._raw.bodyUsed;
|
|
287
|
+
}
|
|
288
|
+
// --- Delegated standard `Request` methods (forward to `_raw`) ---
|
|
289
|
+
/**
|
|
290
|
+
* Parses the request body as JSON with the same semantics as the platform
|
|
291
|
+
* `Request.json()`. The default type is `any` because the shape of
|
|
292
|
+
* arbitrary JSON is unknown; callers can supply the expected shape:
|
|
293
|
+
*
|
|
294
|
+
* ```ts
|
|
295
|
+
* const body = await ctx.json<{ id: number }>();
|
|
296
|
+
* ```
|
|
297
|
+
*/
|
|
298
|
+
json() {
|
|
299
|
+
// Parsed once and cached (body validation reads it first). Malformed
|
|
300
|
+
// JSON is a client error: 400 Problem Details, not a 500.
|
|
301
|
+
if (this._json === undefined) {
|
|
302
|
+
this._json = this.text().then((raw) => {
|
|
303
|
+
try {
|
|
304
|
+
return JSON.parse(raw);
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
if (error instanceof SyntaxError) {
|
|
308
|
+
throw new HTTPError(400, `Malformed JSON body: ${error.message}`, { cause: error });
|
|
309
|
+
}
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
312
|
+
}, (error) => {
|
|
313
|
+
// A stream failure is not cached: a later read may retry.
|
|
314
|
+
this._json = undefined;
|
|
315
|
+
throw error;
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
return this._json;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* The body is read once, in the form first asked for. Text is the fast
|
|
322
|
+
* path (JSON parsing and validation use it); bytes asked for first stay
|
|
323
|
+
* byte-exact (webhook signatures over raw bytes).
|
|
324
|
+
*/
|
|
325
|
+
text() {
|
|
326
|
+
if (this._bodyText !== undefined)
|
|
327
|
+
return this._bodyText;
|
|
328
|
+
if (this._bodyBuffer !== undefined) {
|
|
329
|
+
return (this._bodyText = this._bodyBuffer.then((buffer) => utf8.decode(buffer)));
|
|
330
|
+
}
|
|
331
|
+
return (this._bodyText = this._raw.text());
|
|
332
|
+
}
|
|
333
|
+
arrayBuffer() {
|
|
334
|
+
if (this._bodyBuffer !== undefined)
|
|
335
|
+
return this._bodyBuffer;
|
|
336
|
+
if (this._bodyText !== undefined) {
|
|
337
|
+
// Read as text already: its UTF-8 bytes (identical for any
|
|
338
|
+
// valid UTF-8 body, which every JSON body is).
|
|
339
|
+
return (this._bodyBuffer = this._bodyText.then((text) => new TextEncoder().encode(text).buffer));
|
|
340
|
+
}
|
|
341
|
+
return (this._bodyBuffer = this._raw.arrayBuffer());
|
|
342
|
+
}
|
|
343
|
+
blob() {
|
|
344
|
+
return this._raw.blob();
|
|
345
|
+
}
|
|
346
|
+
formData() {
|
|
347
|
+
return this._raw.formData();
|
|
348
|
+
}
|
|
349
|
+
clone() {
|
|
350
|
+
// Delegates to the underlying `Request.clone()`.
|
|
351
|
+
return this._raw.clone();
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Delegation of the full `Request` surface: every `Request.prototype` member
|
|
356
|
+
* not already defined on `BurgerContext` is copied onto the shared prototype
|
|
357
|
+
* once at module load, so instances keep one hidden class.
|
|
358
|
+
*/
|
|
359
|
+
for (const name of Object.getOwnPropertyNames(Request.prototype)) {
|
|
360
|
+
if (name === 'constructor' || name === 'prototype')
|
|
361
|
+
continue;
|
|
362
|
+
if (Object.prototype.hasOwnProperty.call(BurgerContext.prototype, name)) {
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
const desc = Object.getOwnPropertyDescriptor(Request.prototype, name);
|
|
366
|
+
if (!desc)
|
|
367
|
+
continue;
|
|
368
|
+
if (typeof desc.value === 'function') {
|
|
369
|
+
Object.defineProperty(BurgerContext.prototype, name, {
|
|
370
|
+
value: function (...args) {
|
|
371
|
+
return this._raw[name](...args);
|
|
372
|
+
},
|
|
373
|
+
writable: true,
|
|
374
|
+
configurable: true,
|
|
375
|
+
enumerable: false,
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
else if (desc.get) {
|
|
379
|
+
Object.defineProperty(BurgerContext.prototype, name, {
|
|
380
|
+
get() {
|
|
381
|
+
return this._raw[name];
|
|
382
|
+
},
|
|
383
|
+
configurable: true,
|
|
384
|
+
enumerable: false,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Freezes the shared prototype's getters so a handler cannot replace them on
|
|
390
|
+
* the prototype and leak state across requests. Delegation methods stay
|
|
391
|
+
* writable/configurable so user hooks can attach custom properties.
|
|
392
|
+
*/
|
|
393
|
+
for (const name of Object.getOwnPropertyNames(BurgerContext.prototype)) {
|
|
394
|
+
const desc = Object.getOwnPropertyDescriptor(BurgerContext.prototype, name);
|
|
395
|
+
if (!desc || !desc.get || desc.set)
|
|
396
|
+
continue;
|
|
397
|
+
Object.defineProperty(BurgerContext.prototype, name, {
|
|
398
|
+
configurable: false,
|
|
399
|
+
enumerable: false,
|
|
400
|
+
});
|
|
401
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fast, allocation-light querystring parser.
|
|
3
|
+
*
|
|
4
|
+
* One linear `charCodeAt` scan of the raw query string; never constructs a
|
|
5
|
+
* `URL` or `URLSearchParams`, and `decodeURIComponent` runs only for segments
|
|
6
|
+
* that actually contain a `%` or `+`.
|
|
7
|
+
*
|
|
8
|
+
* Behavior matches `URLSearchParams`, including the
|
|
9
|
+
* `application/x-www-form-urlencoded` rule that `+` decodes to a space.
|
|
10
|
+
* Malformed percent-encoding (and lone surrogates) is preserved verbatim and
|
|
11
|
+
* never throws.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Parses a raw query string (after `?`, with or without the leading `?`)
|
|
15
|
+
* into a `Record<string, string | string[]>`.
|
|
16
|
+
*
|
|
17
|
+
* - Empty input → `{}`; a segment without `=` maps its key to `""`.
|
|
18
|
+
* - A repeated key becomes an array of values, in order.
|
|
19
|
+
* - Keys and values are percent-decoded when needed; `+` becomes a space.
|
|
20
|
+
* - The `[]` suffix is literal, not an array hint.
|
|
21
|
+
* - Malformed percent-escapes are preserved verbatim; never throws.
|
|
22
|
+
*/
|
|
23
|
+
export declare function parseQuery(search: string): Record<string, string | string[]>;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fast, allocation-light querystring parser.
|
|
3
|
+
*
|
|
4
|
+
* One linear `charCodeAt` scan of the raw query string; never constructs a
|
|
5
|
+
* `URL` or `URLSearchParams`, and `decodeURIComponent` runs only for segments
|
|
6
|
+
* that actually contain a `%` or `+`.
|
|
7
|
+
*
|
|
8
|
+
* Behavior matches `URLSearchParams`, including the
|
|
9
|
+
* `application/x-www-form-urlencoded` rule that `+` decodes to a space.
|
|
10
|
+
* Malformed percent-encoding (and lone surrogates) is preserved verbatim and
|
|
11
|
+
* never throws.
|
|
12
|
+
*/
|
|
13
|
+
/** Segment flags recorded while scanning one `key=value` pair. */
|
|
14
|
+
const KEY_NEEDS_DECODE = 1;
|
|
15
|
+
const KEY_HAS_PLUS = 2;
|
|
16
|
+
const VALUE_NEEDS_DECODE = 4;
|
|
17
|
+
const VALUE_HAS_PLUS = 8;
|
|
18
|
+
const CHAR_AMPERSAND = 38; // '&'
|
|
19
|
+
const CHAR_EQUALS = 61; // '='
|
|
20
|
+
const CHAR_PERCENT = 37; // '%'
|
|
21
|
+
const CHAR_PLUS = 43; // '+'
|
|
22
|
+
const CHAR_QUESTION = 63; // '?'
|
|
23
|
+
/**
|
|
24
|
+
* Replaces every `+` with a space without regex/split allocations. Called
|
|
25
|
+
* only when the scan already proved the segment contains a `+`.
|
|
26
|
+
*/
|
|
27
|
+
function replacePlus(segment) {
|
|
28
|
+
let out = '';
|
|
29
|
+
let start = 0;
|
|
30
|
+
let idx = segment.indexOf('+');
|
|
31
|
+
while (idx !== -1) {
|
|
32
|
+
out += segment.slice(start, idx) + ' ';
|
|
33
|
+
start = idx + 1;
|
|
34
|
+
idx = segment.indexOf('+', start);
|
|
35
|
+
}
|
|
36
|
+
return out + segment.slice(start);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Decodes a single key/value segment: `+` normalized to a space, then
|
|
40
|
+
* `decodeURIComponent`. Malformed escapes and lone surrogates make
|
|
41
|
+
* `decodeURIComponent` throw, so we fall back to the raw substring (never
|
|
42
|
+
* throws). The flags come from the caller's scan, so segments without
|
|
43
|
+
* `%`/`+` skip decoding entirely.
|
|
44
|
+
*/
|
|
45
|
+
function decodeSegment(segment, flags) {
|
|
46
|
+
let value = segment;
|
|
47
|
+
if (flags & (KEY_HAS_PLUS | VALUE_HAS_PLUS))
|
|
48
|
+
value = replacePlus(value);
|
|
49
|
+
if (flags & (KEY_NEEDS_DECODE | VALUE_NEEDS_DECODE)) {
|
|
50
|
+
try {
|
|
51
|
+
return decodeURIComponent(value);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Parses a raw query string (after `?`, with or without the leading `?`)
|
|
61
|
+
* into a `Record<string, string | string[]>`.
|
|
62
|
+
*
|
|
63
|
+
* - Empty input → `{}`; a segment without `=` maps its key to `""`.
|
|
64
|
+
* - A repeated key becomes an array of values, in order.
|
|
65
|
+
* - Keys and values are percent-decoded when needed; `+` becomes a space.
|
|
66
|
+
* - The `[]` suffix is literal, not an array hint.
|
|
67
|
+
* - Malformed percent-escapes are preserved verbatim; never throws.
|
|
68
|
+
*/
|
|
69
|
+
export function parseQuery(search) {
|
|
70
|
+
// Null prototype: `__proto__` / `constructor` keys are attacker-
|
|
71
|
+
// controlled and must land as plain own properties, never touch the
|
|
72
|
+
// object prototype.
|
|
73
|
+
const result = Object.create(null);
|
|
74
|
+
const len = search.length;
|
|
75
|
+
// Tolerate a leading '?'.
|
|
76
|
+
let i = len > 0 && search.charCodeAt(0) === CHAR_QUESTION ? 1 : 0;
|
|
77
|
+
if (i === len)
|
|
78
|
+
return result;
|
|
79
|
+
let pairStart = i;
|
|
80
|
+
let equalsIndex = -1;
|
|
81
|
+
let keyFlags = 0;
|
|
82
|
+
let valueFlags = 0;
|
|
83
|
+
// One pass; a virtual `&` at `len` flushes the final pair.
|
|
84
|
+
for (; i <= len; i++) {
|
|
85
|
+
const code = i === len ? CHAR_AMPERSAND : search.charCodeAt(i);
|
|
86
|
+
if (code === CHAR_AMPERSAND) {
|
|
87
|
+
// Skip empty segments (e.g. trailing '&' or '&&').
|
|
88
|
+
if (i > pairStart) {
|
|
89
|
+
const key = decodeSegment(equalsIndex === -1
|
|
90
|
+
? search.slice(pairStart, i)
|
|
91
|
+
: search.slice(pairStart, equalsIndex), keyFlags);
|
|
92
|
+
const value = equalsIndex === -1
|
|
93
|
+
? ''
|
|
94
|
+
: decodeSegment(search.slice(equalsIndex + 1, i), valueFlags);
|
|
95
|
+
const existing = result[key];
|
|
96
|
+
if (existing === undefined) {
|
|
97
|
+
result[key] = value;
|
|
98
|
+
}
|
|
99
|
+
else if (Array.isArray(existing)) {
|
|
100
|
+
existing.push(value);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
result[key] = [existing, value];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
pairStart = i + 1;
|
|
107
|
+
equalsIndex = -1;
|
|
108
|
+
keyFlags = 0;
|
|
109
|
+
valueFlags = 0;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (equalsIndex === -1) {
|
|
113
|
+
if (code === CHAR_EQUALS) {
|
|
114
|
+
equalsIndex = i;
|
|
115
|
+
}
|
|
116
|
+
else if (code === CHAR_PERCENT) {
|
|
117
|
+
keyFlags |= KEY_NEEDS_DECODE;
|
|
118
|
+
}
|
|
119
|
+
else if (code === CHAR_PLUS) {
|
|
120
|
+
keyFlags |= KEY_HAS_PLUS;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else if (code === CHAR_PERCENT) {
|
|
124
|
+
valueFlags |= VALUE_NEEDS_DECODE;
|
|
125
|
+
}
|
|
126
|
+
else if (code === CHAR_PLUS) {
|
|
127
|
+
valueFlags |= VALUE_HAS_PLUS;
|
|
128
|
+
}
|
|
129
|
+
// A second '=' belongs to the value and needs no decoding itself.
|
|
130
|
+
}
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ContextField, RouteAccessInfo } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Builds and freezes a `RouteAccessInfo` hint. Frozen so it can be shared
|
|
4
|
+
* across requests; `unknown: true` (the safe default) makes `has()` report
|
|
5
|
+
* every field as used.
|
|
6
|
+
*/
|
|
7
|
+
export declare function freezeRouteAccessInfo(fields: Iterable<ContextField>, unknown?: boolean, hooks?: Iterable<string>): RouteAccessInfo;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds and freezes a `RouteAccessInfo` hint. Frozen so it can be shared
|
|
3
|
+
* across requests; `unknown: true` (the safe default) makes `has()` report
|
|
4
|
+
* every field as used.
|
|
5
|
+
*/
|
|
6
|
+
export function freezeRouteAccessInfo(fields, unknown = false, hooks) {
|
|
7
|
+
const access = new Set(fields);
|
|
8
|
+
const hookSet = new Set(hooks ?? []);
|
|
9
|
+
const info = {
|
|
10
|
+
access,
|
|
11
|
+
unknown,
|
|
12
|
+
hooks: hookSet,
|
|
13
|
+
has(field) {
|
|
14
|
+
return unknown || access.has(field);
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
return Object.freeze(info);
|
|
18
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal types for the prototype-based request context. `BurgerContext`
|
|
3
|
+
* re-exports the public ones (`ContextSet`, `RouteMeta`).
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* The request fields `RouteAccessAnalyzer` can reason about — the lazy
|
|
7
|
+
* surface `BurgerContext` exposes.
|
|
8
|
+
*/
|
|
9
|
+
export type ContextField = 'params' | 'query' | 'cookies' | 'headers' | 'json' | 'validated' | 'set' | 'route' | 'services' | 'request' | 'wildcardParams';
|
|
10
|
+
/**
|
|
11
|
+
* Route-specific data passed from `Router.fetch` when seeding
|
|
12
|
+
* `BurgerContext`. Only fields relevant to the matched route are populated.
|
|
13
|
+
*/
|
|
14
|
+
export interface ContextInit {
|
|
15
|
+
params?: Record<string, string>;
|
|
16
|
+
wildcardParams?: string[];
|
|
17
|
+
route?: RouteMeta;
|
|
18
|
+
/**
|
|
19
|
+
* Route pattern for natively dispatched matches. When `route` is absent,
|
|
20
|
+
* the `route` getter derives `RouteMeta` from this lazily.
|
|
21
|
+
*/
|
|
22
|
+
pattern?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The response-mutation surface exposed through `ctx.set`.
|
|
26
|
+
* `cookies` is intentionally absent (reserved for a future release).
|
|
27
|
+
*/
|
|
28
|
+
export interface ContextSet {
|
|
29
|
+
status?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Response headers. A value may be an array: array values (and
|
|
32
|
+
* `Set-Cookie` values) are appended, so multiple cookies survive.
|
|
33
|
+
*/
|
|
34
|
+
headers?: Record<string, string | string[]> | Headers;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* What `RouteAccessAnalyzer` found a route to use (request fields and hook
|
|
38
|
+
* stages). Frozen; an optimization hint only — never read at runtime.
|
|
39
|
+
*/
|
|
40
|
+
export interface RouteAccessInfo {
|
|
41
|
+
/** The set of fields the analyzer determined the route reads. */
|
|
42
|
+
access: ReadonlySet<ContextField>;
|
|
43
|
+
/**
|
|
44
|
+
* When `true`, the analyzer could not prove what the route reads (ambiguous
|
|
45
|
+
* source or `debug` mode), so every field must be treated as used — the safe
|
|
46
|
+
* default.
|
|
47
|
+
*/
|
|
48
|
+
unknown: boolean;
|
|
49
|
+
/** The set of lifecycle hook stages the route uses. */
|
|
50
|
+
hooks: ReadonlySet<string>;
|
|
51
|
+
/** Reports whether `field` is considered accessed by this route. */
|
|
52
|
+
has(field: ContextField): boolean;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The matched-route identity exposed as `ctx.route`. `path` is the concrete
|
|
56
|
+
* requested pathname (never the query string); `pattern` is the route pattern
|
|
57
|
+
* (e.g. `/users/:id`).
|
|
58
|
+
*/
|
|
59
|
+
export interface RouteMeta {
|
|
60
|
+
path: string;
|
|
61
|
+
pattern: string;
|
|
62
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extension → Content-Type lookup for static assets. Kept separate from
|
|
3
|
+
* `assets.ts` so the main entry can re-export `contentTypeFor` without pulling
|
|
4
|
+
* a Node builtin into its static import graph.
|
|
5
|
+
*/
|
|
6
|
+
/** Extension → Content-Type map for supported static assets. */
|
|
7
|
+
export declare const ASSET_MIME: Record<string, string>;
|
|
8
|
+
/** Resolves the content type for an asset path (defaults to octet-stream). */
|
|
9
|
+
export declare function contentTypeFor(filePath: string): string;
|