@tessellation/http 0.0.0-stage → 2.0.0
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/LICENSE +21 -0
- package/README.md +412 -2
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/lib/auth/api-key.d.ts +17 -0
- package/dist/lib/auth/api-key.d.ts.map +1 -0
- package/dist/lib/auth/api-key.js +48 -0
- package/dist/lib/auth/jwt.d.ts +33 -0
- package/dist/lib/auth/jwt.d.ts.map +1 -0
- package/dist/lib/auth/jwt.js +227 -0
- package/dist/lib/auth/provide-auth.d.ts +30 -0
- package/dist/lib/auth/provide-auth.d.ts.map +1 -0
- package/dist/lib/auth/provide-auth.js +69 -0
- package/dist/lib/auth/strategy.d.ts +47 -0
- package/dist/lib/auth/strategy.d.ts.map +1 -0
- package/dist/lib/auth/strategy.js +18 -0
- package/dist/lib/compile.d.ts +46 -0
- package/dist/lib/compile.d.ts.map +1 -0
- package/dist/lib/compile.js +126 -0
- package/dist/lib/compression.d.ts +23 -0
- package/dist/lib/compression.d.ts.map +1 -0
- package/dist/lib/compression.js +86 -0
- package/dist/lib/config.d.ts +173 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +93 -0
- package/dist/lib/cors.d.ts +41 -0
- package/dist/lib/cors.d.ts.map +1 -0
- package/dist/lib/cors.js +101 -0
- package/dist/lib/docs.d.ts +15 -0
- package/dist/lib/docs.d.ts.map +1 -0
- package/dist/lib/docs.js +93 -0
- package/dist/lib/engine.d.ts +83 -0
- package/dist/lib/engine.d.ts.map +1 -0
- package/dist/lib/engine.js +562 -0
- package/dist/lib/errors.d.ts +31 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +55 -0
- package/dist/lib/etag.d.ts +5 -0
- package/dist/lib/etag.d.ts.map +1 -0
- package/dist/lib/etag.js +30 -0
- package/dist/lib/headers.d.ts +3 -0
- package/dist/lib/headers.d.ts.map +1 -0
- package/dist/lib/headers.js +14 -0
- package/dist/lib/json-schema.d.ts +11 -0
- package/dist/lib/json-schema.d.ts.map +1 -0
- package/dist/lib/json-schema.js +23 -0
- package/dist/lib/openapi.d.ts +18 -0
- package/dist/lib/openapi.d.ts.map +1 -0
- package/dist/lib/openapi.js +218 -0
- package/dist/lib/rate-limit.d.ts +52 -0
- package/dist/lib/rate-limit.d.ts.map +1 -0
- package/dist/lib/rate-limit.js +87 -0
- package/dist/lib/reply.d.ts +27 -0
- package/dist/lib/reply.d.ts.map +1 -0
- package/dist/lib/reply.js +52 -0
- package/dist/lib/request.d.ts +55 -0
- package/dist/lib/request.d.ts.map +1 -0
- package/dist/lib/request.js +36 -0
- package/dist/lib/router.d.ts +35 -0
- package/dist/lib/router.d.ts.map +1 -0
- package/dist/lib/router.js +173 -0
- package/dist/lib/routes.d.ts +196 -0
- package/dist/lib/routes.d.ts.map +1 -0
- package/dist/lib/routes.js +98 -0
- package/dist/lib/security-headers.d.ts +19 -0
- package/dist/lib/security-headers.d.ts.map +1 -0
- package/dist/lib/security-headers.js +22 -0
- package/dist/lib/serializer.d.ts +35 -0
- package/dist/lib/serializer.d.ts.map +1 -0
- package/dist/lib/serializer.js +147 -0
- package/dist/lib/server.d.ts +86 -0
- package/dist/lib/server.d.ts.map +1 -0
- package/dist/lib/server.js +255 -0
- package/dist/lib/testing.d.ts +21 -0
- package/dist/lib/testing.d.ts.map +1 -0
- package/dist/lib/testing.js +62 -0
- package/dist/lib/transports/node.d.ts +4 -0
- package/dist/lib/transports/node.d.ts.map +1 -0
- package/dist/lib/transports/node.js +249 -0
- package/dist/lib/transports/transport.d.ts +32 -0
- package/dist/lib/transports/transport.d.ts.map +1 -0
- package/dist/lib/transports/transport.js +1 -0
- package/dist/lib/transports/uws.d.ts +8 -0
- package/dist/lib/transports/uws.d.ts.map +1 -0
- package/dist/lib/transports/uws.js +246 -0
- package/dist/lib/websocket.d.ts +71 -0
- package/dist/lib/websocket.d.ts.map +1 -0
- package/dist/lib/websocket.js +125 -0
- package/package.json +67 -3
- package/src/index.ts +103 -0
- package/src/lib/auth/api-key.ts +73 -0
- package/src/lib/auth/jwt.ts +339 -0
- package/src/lib/auth/provide-auth.ts +99 -0
- package/src/lib/auth/strategy.ts +66 -0
- package/src/lib/compile.ts +207 -0
- package/src/lib/compression.ts +121 -0
- package/src/lib/config.ts +107 -0
- package/src/lib/cors.ts +146 -0
- package/src/lib/docs.ts +115 -0
- package/src/lib/engine.ts +770 -0
- package/src/lib/errors.ts +84 -0
- package/src/lib/etag.ts +37 -0
- package/src/lib/headers.ts +18 -0
- package/src/lib/json-schema.ts +36 -0
- package/src/lib/openapi.ts +299 -0
- package/src/lib/rate-limit.ts +142 -0
- package/src/lib/reply.ts +70 -0
- package/src/lib/request.ts +83 -0
- package/src/lib/router.ts +217 -0
- package/src/lib/routes.ts +414 -0
- package/src/lib/security-headers.ts +38 -0
- package/src/lib/serializer.ts +203 -0
- package/src/lib/server.ts +352 -0
- package/src/lib/testing.ts +88 -0
- package/src/lib/transports/node.ts +315 -0
- package/src/lib/transports/transport.ts +39 -0
- package/src/lib/transports/uws.ts +310 -0
- package/src/lib/websocket.ts +184 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { ProvidedIn } from '@tessellation/core';
|
|
2
|
+
|
|
3
|
+
import type { WebSocketSession } from './websocket.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* An incoming request, independent of the transport serving it. Inject it in
|
|
7
|
+
* request-scoped providers; handlers and middleware receive it in their
|
|
8
|
+
* context.
|
|
9
|
+
*/
|
|
10
|
+
export abstract class HttpRequest {
|
|
11
|
+
static readonly providedIn: ProvidedIn = null;
|
|
12
|
+
|
|
13
|
+
/** Upper-case method, such as `GET`. */
|
|
14
|
+
abstract readonly method: string;
|
|
15
|
+
/** Path without the query string, as sent (not decoded). */
|
|
16
|
+
abstract readonly path: string;
|
|
17
|
+
/** Query string without the leading `?`; empty if there is none. */
|
|
18
|
+
abstract readonly query: string;
|
|
19
|
+
/** Headers with lower-case names. */
|
|
20
|
+
abstract readonly headers: Readonly<Record<string, string | undefined>>;
|
|
21
|
+
/** The client's IP address. */
|
|
22
|
+
abstract readonly remoteAddress: string;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The request id (from the `x-request-id` header when valid, otherwise
|
|
26
|
+
* generated). Undefined when request ids are disabled.
|
|
27
|
+
*/
|
|
28
|
+
id: string | undefined;
|
|
29
|
+
|
|
30
|
+
/** Proxies in front of the server whose `x-forwarded-for` entries are trusted. Set by the server. */
|
|
31
|
+
trustedProxies = 0;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The client's address. With `http.trustProxy` set to the number of proxies
|
|
35
|
+
* in front of the server, it is read from `x-forwarded-for`; otherwise it
|
|
36
|
+
* is the connection's address.
|
|
37
|
+
*/
|
|
38
|
+
get clientIp(): string {
|
|
39
|
+
if (this.trustedProxies === 0) {
|
|
40
|
+
return this.remoteAddress;
|
|
41
|
+
}
|
|
42
|
+
const chain = (this.headers['x-forwarded-for'] ?? '')
|
|
43
|
+
.split(',')
|
|
44
|
+
.map((entry) => entry.trim())
|
|
45
|
+
.filter((entry) => entry !== '');
|
|
46
|
+
chain.push(this.remoteAddress);
|
|
47
|
+
return (
|
|
48
|
+
chain[Math.max(0, chain.length - 1 - this.trustedProxies)] ??
|
|
49
|
+
this.remoteAddress
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The request body. Rejects with a 413 `HttpError` when it exceeds the
|
|
55
|
+
* configured body limit. Can be called more than once.
|
|
56
|
+
*/
|
|
57
|
+
abstract body(): Promise<Uint8Array>;
|
|
58
|
+
|
|
59
|
+
/** A header by case-insensitive name. */
|
|
60
|
+
header(name: string): string | undefined {
|
|
61
|
+
return this.headers[name.toLowerCase()];
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Where a transport writes the response for one request. */
|
|
66
|
+
export interface ResponseSink {
|
|
67
|
+
/** True once the client has disconnected; sending is then a no-op. */
|
|
68
|
+
readonly aborted: boolean;
|
|
69
|
+
/** Calls `handler` if the client disconnects before the response is sent. */
|
|
70
|
+
onAbort(handler: () => void): void;
|
|
71
|
+
/** Completes a WebSocket handshake; present only for upgrade requests. */
|
|
72
|
+
upgrade?(session: WebSocketSession): void;
|
|
73
|
+
/**
|
|
74
|
+
* Sends the whole response. For HEAD requests (`head`), headers are sent
|
|
75
|
+
* with the body's length but without the body.
|
|
76
|
+
*/
|
|
77
|
+
send(
|
|
78
|
+
status: number,
|
|
79
|
+
headers: Readonly<Record<string, string>>,
|
|
80
|
+
body: string | Uint8Array | undefined,
|
|
81
|
+
head: boolean,
|
|
82
|
+
): void;
|
|
83
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A segment trie router. Patterns are made of static segments, `:name`
|
|
3
|
+
* parameters (one segment) and a final `*` or `*name` wildcard (the rest of
|
|
4
|
+
* the path). Matching prefers static segments, then parameters, then
|
|
5
|
+
* wildcards, and backtracks so a more specific route never hides another.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const PARAM_NAME = /^[A-Za-z_]\w*$/;
|
|
9
|
+
|
|
10
|
+
class Node<T> {
|
|
11
|
+
statics: Map<string, Node<T>> | undefined;
|
|
12
|
+
param: Node<T> | undefined;
|
|
13
|
+
paramName: string | undefined;
|
|
14
|
+
wildcard: Map<string, T> | undefined;
|
|
15
|
+
wildcardName: string | undefined;
|
|
16
|
+
handlers: Map<string, T> | undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type RouteMatch<T> =
|
|
20
|
+
| { kind: 'found'; value: T; params: string[] }
|
|
21
|
+
| { kind: 'method-not-allowed'; allowed: string[] }
|
|
22
|
+
| { kind: 'not-found' };
|
|
23
|
+
|
|
24
|
+
export interface PatternSegment {
|
|
25
|
+
kind: 'static' | 'param' | 'wildcard';
|
|
26
|
+
value: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Splits a pattern such as `/users/:id/*rest` into segments. */
|
|
30
|
+
export function parsePattern(pattern: string): PatternSegment[] {
|
|
31
|
+
if (!pattern.startsWith('/')) {
|
|
32
|
+
throw new Error(`Route path "${pattern}" must start with "/".`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const parts = pattern === '/' ? [] : pattern.slice(1).split('/');
|
|
36
|
+
return parts.map((part, index) => {
|
|
37
|
+
if (part.startsWith(':')) {
|
|
38
|
+
const name = part.slice(1);
|
|
39
|
+
if (!PARAM_NAME.test(name)) {
|
|
40
|
+
throw new Error(`Invalid parameter name "${name}" in "${pattern}".`);
|
|
41
|
+
}
|
|
42
|
+
return { kind: 'param', value: name };
|
|
43
|
+
}
|
|
44
|
+
if (part.startsWith('*')) {
|
|
45
|
+
if (index !== parts.length - 1) {
|
|
46
|
+
throw new Error(`A wildcard must be the last segment of "${pattern}".`);
|
|
47
|
+
}
|
|
48
|
+
const name = part.slice(1) || '*';
|
|
49
|
+
if (name !== '*' && !PARAM_NAME.test(name)) {
|
|
50
|
+
throw new Error(`Invalid wildcard name "${name}" in "${pattern}".`);
|
|
51
|
+
}
|
|
52
|
+
return { kind: 'wildcard', value: name };
|
|
53
|
+
}
|
|
54
|
+
if (part === '') {
|
|
55
|
+
throw new Error(`Route path "${pattern}" has an empty segment.`);
|
|
56
|
+
}
|
|
57
|
+
return { kind: 'static', value: part };
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class Router<T> {
|
|
62
|
+
private readonly root = new Node<T>();
|
|
63
|
+
|
|
64
|
+
/** Registers a route. Returns its parameter names in match order. */
|
|
65
|
+
add(method: string, pattern: string, value: T): string[] {
|
|
66
|
+
const names: string[] = [];
|
|
67
|
+
let node = this.root;
|
|
68
|
+
|
|
69
|
+
for (const segment of parsePattern(pattern)) {
|
|
70
|
+
if (segment.kind === 'static') {
|
|
71
|
+
node.statics ??= new Map();
|
|
72
|
+
let next = node.statics.get(segment.value);
|
|
73
|
+
if (next === undefined) {
|
|
74
|
+
next = new Node();
|
|
75
|
+
node.statics.set(segment.value, next);
|
|
76
|
+
}
|
|
77
|
+
node = next;
|
|
78
|
+
} else if (segment.kind === 'param') {
|
|
79
|
+
if (node.param !== undefined && node.paramName !== segment.value) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
`Route "${pattern}" names a parameter ":${segment.value}" where another route uses ":${node.paramName}".`,
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
node.param ??= new Node();
|
|
85
|
+
node.paramName = segment.value;
|
|
86
|
+
names.push(segment.value);
|
|
87
|
+
node = node.param;
|
|
88
|
+
} else {
|
|
89
|
+
if (
|
|
90
|
+
node.wildcard !== undefined &&
|
|
91
|
+
node.wildcardName !== segment.value
|
|
92
|
+
) {
|
|
93
|
+
throw new Error(
|
|
94
|
+
`Route "${pattern}" names a wildcard "*${segment.value}" where another route uses "*${node.wildcardName}".`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
node.wildcard ??= new Map();
|
|
98
|
+
node.wildcardName = segment.value;
|
|
99
|
+
names.push(segment.value);
|
|
100
|
+
if (node.wildcard.has(method)) {
|
|
101
|
+
throw new Error(`Duplicate route ${method} ${pattern}.`);
|
|
102
|
+
}
|
|
103
|
+
node.wildcard.set(method, value);
|
|
104
|
+
return names;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
node.handlers ??= new Map();
|
|
109
|
+
if (node.handlers.has(method)) {
|
|
110
|
+
throw new Error(`Duplicate route ${method} ${pattern}.`);
|
|
111
|
+
}
|
|
112
|
+
node.handlers.set(method, value);
|
|
113
|
+
return names;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Finds the route for a method and path. HEAD falls back to GET. A trailing
|
|
118
|
+
* slash is ignored. Parameter values are returned undecoded.
|
|
119
|
+
*/
|
|
120
|
+
find(method: string, path: string): RouteMatch<T> {
|
|
121
|
+
if (path.length > 1 && path.endsWith('/')) {
|
|
122
|
+
path = path.slice(0, -1);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const params: string[] = [];
|
|
126
|
+
const allowed = new Set<string>();
|
|
127
|
+
const value = this.walk(this.root, path, 1, method, params, allowed);
|
|
128
|
+
|
|
129
|
+
if (value !== undefined) {
|
|
130
|
+
return { kind: 'found', value, params };
|
|
131
|
+
}
|
|
132
|
+
if (allowed.size > 0) {
|
|
133
|
+
if (allowed.has('GET')) {
|
|
134
|
+
allowed.add('HEAD');
|
|
135
|
+
}
|
|
136
|
+
return { kind: 'method-not-allowed', allowed: [...allowed].sort() };
|
|
137
|
+
}
|
|
138
|
+
return { kind: 'not-found' };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private walk(
|
|
142
|
+
node: Node<T>,
|
|
143
|
+
path: string,
|
|
144
|
+
start: number,
|
|
145
|
+
method: string,
|
|
146
|
+
params: string[],
|
|
147
|
+
allowed: Set<string>,
|
|
148
|
+
): T | undefined {
|
|
149
|
+
if (start >= path.length) {
|
|
150
|
+
const found = this.pick(node.handlers, method, allowed);
|
|
151
|
+
if (found !== undefined) {
|
|
152
|
+
return found;
|
|
153
|
+
}
|
|
154
|
+
// "/docs/*" also matches "/docs" with an empty wildcard.
|
|
155
|
+
if (node.wildcard !== undefined) {
|
|
156
|
+
const wildcard = this.pick(node.wildcard, method, allowed);
|
|
157
|
+
if (wildcard !== undefined) {
|
|
158
|
+
params.push('');
|
|
159
|
+
return wildcard;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const slash = path.indexOf('/', start);
|
|
166
|
+
const end = slash === -1 ? path.length : slash;
|
|
167
|
+
const next = end + 1;
|
|
168
|
+
|
|
169
|
+
if (node.statics !== undefined) {
|
|
170
|
+
const child = node.statics.get(path.slice(start, end));
|
|
171
|
+
if (child !== undefined) {
|
|
172
|
+
const found = this.walk(child, path, next, method, params, allowed);
|
|
173
|
+
if (found !== undefined) {
|
|
174
|
+
return found;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (node.param !== undefined && end > start) {
|
|
180
|
+
params.push(path.slice(start, end));
|
|
181
|
+
const found = this.walk(node.param, path, next, method, params, allowed);
|
|
182
|
+
if (found !== undefined) {
|
|
183
|
+
return found;
|
|
184
|
+
}
|
|
185
|
+
params.pop();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (node.wildcard !== undefined) {
|
|
189
|
+
const found = this.pick(node.wildcard, method, allowed);
|
|
190
|
+
if (found !== undefined) {
|
|
191
|
+
params.push(path.slice(start));
|
|
192
|
+
return found;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private pick(
|
|
200
|
+
handlers: Map<string, T> | undefined,
|
|
201
|
+
method: string,
|
|
202
|
+
allowed: Set<string>,
|
|
203
|
+
): T | undefined {
|
|
204
|
+
if (handlers === undefined) {
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
const found =
|
|
208
|
+
handlers.get(method) ??
|
|
209
|
+
(method === 'HEAD' ? handlers.get('GET') : undefined);
|
|
210
|
+
if (found === undefined) {
|
|
211
|
+
for (const key of handlers.keys()) {
|
|
212
|
+
allowed.add(key);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return found;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
InferSchemaOutput,
|
|
3
|
+
Provider,
|
|
4
|
+
StandardSchemaV1,
|
|
5
|
+
} from '@tessellation/core';
|
|
6
|
+
|
|
7
|
+
import type { Reply } from './reply.js';
|
|
8
|
+
import type { HttpRequest } from './request.js';
|
|
9
|
+
import {
|
|
10
|
+
captureContext,
|
|
11
|
+
UpgradeReply,
|
|
12
|
+
type WebSocketHandlers,
|
|
13
|
+
} from './websocket.js';
|
|
14
|
+
|
|
15
|
+
type Schema = StandardSchemaV1;
|
|
16
|
+
type Output<S> = S extends Schema ? InferSchemaOutput<S> : never;
|
|
17
|
+
type Simplify<T> = { [K in keyof T]: T[K] } & {};
|
|
18
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
19
|
+
/** An object type with no keys. */
|
|
20
|
+
type Empty = Record<never, never>;
|
|
21
|
+
|
|
22
|
+
/** Parameter names in a path, typed as strings: `/:id/*rest` → `{ id; rest }`. */
|
|
23
|
+
export type PathParams<Path extends string> =
|
|
24
|
+
Path extends `${string}:${infer Param}/${infer Rest}`
|
|
25
|
+
? { [K in Param]: string } & PathParams<`/${Rest}`>
|
|
26
|
+
: Path extends `${string}:${infer Param}`
|
|
27
|
+
? { [K in Param]: string }
|
|
28
|
+
: Path extends `${string}*${infer Name}`
|
|
29
|
+
? { [K in Name extends '' ? '*' : Name]: string }
|
|
30
|
+
: Empty;
|
|
31
|
+
|
|
32
|
+
/** Params introduced by a path segment, with a schema's output replacing strings. */
|
|
33
|
+
type OwnParams<Path extends string, ParamsSchema> = ParamsSchema extends Schema
|
|
34
|
+
? Omit<PathParams<Path>, keyof Output<ParamsSchema>> & Output<ParamsSchema>
|
|
35
|
+
: PathParams<Path>;
|
|
36
|
+
|
|
37
|
+
/** One schema for 200, or schemas per status code. */
|
|
38
|
+
export type ResponseSchemas = Schema | { readonly [status: number]: Schema };
|
|
39
|
+
|
|
40
|
+
type ResponseBody<R> = R extends Schema
|
|
41
|
+
? Output<R>
|
|
42
|
+
: R extends { readonly [status: number]: Schema }
|
|
43
|
+
? Output<R[keyof R]>
|
|
44
|
+
: unknown;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* What a handler may return: a body (sent as 200), a `Reply` for another
|
|
48
|
+
* status or headers, or `undefined` for 204.
|
|
49
|
+
*/
|
|
50
|
+
export type HandlerResult<R> =
|
|
51
|
+
ResponseBody<R> | Reply<ResponseBody<R>> | Reply<undefined> | undefined;
|
|
52
|
+
|
|
53
|
+
/** Query parameters without a schema: repeated keys become arrays. */
|
|
54
|
+
export type RawQuery = Record<string, string | string[]>;
|
|
55
|
+
|
|
56
|
+
export interface RequestContext<Params, Query, Body> {
|
|
57
|
+
readonly params: Params;
|
|
58
|
+
readonly query: Query;
|
|
59
|
+
readonly body: Body;
|
|
60
|
+
readonly request: HttpRequest;
|
|
61
|
+
/**
|
|
62
|
+
* Aborted when the client disconnects or the request times out. Pass it
|
|
63
|
+
* to database calls and `fetch` so abandoned work stops.
|
|
64
|
+
*/
|
|
65
|
+
readonly signal: AbortSignal;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface MiddlewareContext {
|
|
69
|
+
readonly request: HttpRequest;
|
|
70
|
+
/** Aborted when the client disconnects or the request times out. */
|
|
71
|
+
readonly signal: AbortSignal;
|
|
72
|
+
/** The matched route's method and full path pattern. */
|
|
73
|
+
readonly route: { readonly method: string; readonly path: string };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Runs around the handler. Call `next()` to continue; it resolves to the
|
|
78
|
+
* reply (errors thrown later in the chain are already turned into error
|
|
79
|
+
* replies). Return a reply without calling `next()` to answer early, or throw
|
|
80
|
+
* an `HttpError`. Middleware runs in the request's injection context.
|
|
81
|
+
*/
|
|
82
|
+
export type Middleware = (
|
|
83
|
+
context: MiddlewareContext,
|
|
84
|
+
next: () => Promise<Reply>,
|
|
85
|
+
) => MaybePromise<Reply>;
|
|
86
|
+
|
|
87
|
+
/** OpenAPI documentation for a route. */
|
|
88
|
+
export interface RouteDocs {
|
|
89
|
+
summary?: string;
|
|
90
|
+
description?: string;
|
|
91
|
+
/** Added to the tags of enclosing groups. */
|
|
92
|
+
tags?: readonly string[];
|
|
93
|
+
operationId?: string;
|
|
94
|
+
deprecated?: boolean;
|
|
95
|
+
/** Leave the route out of the OpenAPI document. */
|
|
96
|
+
hidden?: boolean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface RouteOptions<
|
|
100
|
+
Parent,
|
|
101
|
+
Path extends string,
|
|
102
|
+
ParamsSchema,
|
|
103
|
+
QuerySchema,
|
|
104
|
+
BodySchema,
|
|
105
|
+
Response,
|
|
106
|
+
> extends RouteDocs {
|
|
107
|
+
/** Validates (and may convert) this route's own path parameters. */
|
|
108
|
+
params?: ParamsSchema;
|
|
109
|
+
query?: QuerySchema;
|
|
110
|
+
/** Validates a JSON body; requests with another content type get 415. */
|
|
111
|
+
body?: BodySchema;
|
|
112
|
+
/**
|
|
113
|
+
* Response schemas. They document the route and drive fast, compiled JSON
|
|
114
|
+
* serialization that only writes declared properties.
|
|
115
|
+
*/
|
|
116
|
+
response?: Response;
|
|
117
|
+
middleware?: readonly Middleware[];
|
|
118
|
+
/** Providers created once per request, in a child of the app injector. */
|
|
119
|
+
providers?: readonly Provider[];
|
|
120
|
+
handler: (
|
|
121
|
+
context: RequestContext<
|
|
122
|
+
Simplify<Parent & OwnParams<Path, ParamsSchema>>,
|
|
123
|
+
QuerySchema extends Schema ? Output<QuerySchema> : RawQuery,
|
|
124
|
+
BodySchema extends Schema ? Output<BodySchema> : undefined
|
|
125
|
+
>,
|
|
126
|
+
) => MaybePromise<HandlerResult<Response>>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface GroupOptions<ParamsSchema> {
|
|
130
|
+
/** Validates the group's own path parameters, for every route inside. */
|
|
131
|
+
params?: ParamsSchema;
|
|
132
|
+
middleware?: readonly Middleware[];
|
|
133
|
+
/** Request-scoped providers for every route inside. */
|
|
134
|
+
providers?: readonly Provider[];
|
|
135
|
+
/** OpenAPI tags for every route inside. */
|
|
136
|
+
tags?: readonly string[];
|
|
137
|
+
/** Leave every route inside out of the OpenAPI document. */
|
|
138
|
+
hidden?: boolean;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export type HttpMethod =
|
|
142
|
+
'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
|
143
|
+
|
|
144
|
+
export interface WebSocketRouteOptions<
|
|
145
|
+
Parent,
|
|
146
|
+
Path extends string,
|
|
147
|
+
ParamsSchema,
|
|
148
|
+
QuerySchema,
|
|
149
|
+
Data,
|
|
150
|
+
> extends WebSocketHandlers<Data> {
|
|
151
|
+
params?: ParamsSchema;
|
|
152
|
+
query?: QuerySchema;
|
|
153
|
+
/** Runs before the upgrade, like route middleware (authentication, rate limits). */
|
|
154
|
+
middleware?: readonly Middleware[];
|
|
155
|
+
providers?: readonly Provider[];
|
|
156
|
+
/**
|
|
157
|
+
* Accepts the connection and returns its `data`, or throws (such as
|
|
158
|
+
* `unauthorized()`) to refuse it with that response.
|
|
159
|
+
*/
|
|
160
|
+
upgrade?: (
|
|
161
|
+
context: RequestContext<
|
|
162
|
+
Simplify<Parent & OwnParams<Path, ParamsSchema>>,
|
|
163
|
+
QuerySchema extends Schema ? Output<QuerySchema> : RawQuery,
|
|
164
|
+
undefined
|
|
165
|
+
>,
|
|
166
|
+
) => Data | Promise<Data>;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/* eslint-disable @typescript-eslint/no-explicit-any -- erased route types */
|
|
170
|
+
export interface RouteDefinition {
|
|
171
|
+
readonly kind: 'route';
|
|
172
|
+
readonly method: HttpMethod;
|
|
173
|
+
readonly path: string;
|
|
174
|
+
readonly options: RouteOptions<any, string, any, any, any, any> & {
|
|
175
|
+
websocket?: WebSocketHandlers<any>;
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/* eslint-enable @typescript-eslint/no-explicit-any */
|
|
179
|
+
|
|
180
|
+
export interface GroupDefinition {
|
|
181
|
+
readonly kind: 'group';
|
|
182
|
+
readonly path: string;
|
|
183
|
+
readonly options: GroupOptions<Schema | undefined>;
|
|
184
|
+
readonly children: readonly RouteNode[];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export type RouteNode = RouteDefinition | GroupDefinition;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* A group of routes. `Expects` is the params it needs from where it is
|
|
191
|
+
* included; `include()` checks that the enclosing groups provide them.
|
|
192
|
+
*/
|
|
193
|
+
export interface RouteTree<
|
|
194
|
+
Expects extends object = Empty,
|
|
195
|
+
> extends GroupDefinition {
|
|
196
|
+
/** Type-only marker, contravariant in `Expects`. */
|
|
197
|
+
readonly __expects?: (params: Expects) => void;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
type Build<Params> = (r: RouteBuilder<Params>) => readonly RouteNode[];
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Defines routes. Its type parameter is the params already available from
|
|
204
|
+
* enclosing groups; the builder for a group's children carries the group's
|
|
205
|
+
* params too, so handlers see every param on their path, typed.
|
|
206
|
+
*/
|
|
207
|
+
export class RouteBuilder<Params> {
|
|
208
|
+
get<
|
|
209
|
+
const Path extends string,
|
|
210
|
+
P extends Schema | undefined = undefined,
|
|
211
|
+
Q extends Schema | undefined = undefined,
|
|
212
|
+
R extends ResponseSchemas | undefined = undefined,
|
|
213
|
+
>(
|
|
214
|
+
path: Path,
|
|
215
|
+
options: RouteOptions<Params, Path, P, Q, undefined, R>,
|
|
216
|
+
): RouteDefinition {
|
|
217
|
+
return route('GET', path, options);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
post<
|
|
221
|
+
const Path extends string,
|
|
222
|
+
P extends Schema | undefined = undefined,
|
|
223
|
+
Q extends Schema | undefined = undefined,
|
|
224
|
+
B extends Schema | undefined = undefined,
|
|
225
|
+
R extends ResponseSchemas | undefined = undefined,
|
|
226
|
+
>(
|
|
227
|
+
path: Path,
|
|
228
|
+
options: RouteOptions<Params, Path, P, Q, B, R>,
|
|
229
|
+
): RouteDefinition {
|
|
230
|
+
return route('POST', path, options);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
put<
|
|
234
|
+
const Path extends string,
|
|
235
|
+
P extends Schema | undefined = undefined,
|
|
236
|
+
Q extends Schema | undefined = undefined,
|
|
237
|
+
B extends Schema | undefined = undefined,
|
|
238
|
+
R extends ResponseSchemas | undefined = undefined,
|
|
239
|
+
>(
|
|
240
|
+
path: Path,
|
|
241
|
+
options: RouteOptions<Params, Path, P, Q, B, R>,
|
|
242
|
+
): RouteDefinition {
|
|
243
|
+
return route('PUT', path, options);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
patch<
|
|
247
|
+
const Path extends string,
|
|
248
|
+
P extends Schema | undefined = undefined,
|
|
249
|
+
Q extends Schema | undefined = undefined,
|
|
250
|
+
B extends Schema | undefined = undefined,
|
|
251
|
+
R extends ResponseSchemas | undefined = undefined,
|
|
252
|
+
>(
|
|
253
|
+
path: Path,
|
|
254
|
+
options: RouteOptions<Params, Path, P, Q, B, R>,
|
|
255
|
+
): RouteDefinition {
|
|
256
|
+
return route('PATCH', path, options);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
delete<
|
|
260
|
+
const Path extends string,
|
|
261
|
+
P extends Schema | undefined = undefined,
|
|
262
|
+
Q extends Schema | undefined = undefined,
|
|
263
|
+
B extends Schema | undefined = undefined,
|
|
264
|
+
R extends ResponseSchemas | undefined = undefined,
|
|
265
|
+
>(
|
|
266
|
+
path: Path,
|
|
267
|
+
options: RouteOptions<Params, Path, P, Q, B, R>,
|
|
268
|
+
): RouteDefinition {
|
|
269
|
+
return route('DELETE', path, options);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
options<
|
|
273
|
+
const Path extends string,
|
|
274
|
+
P extends Schema | undefined = undefined,
|
|
275
|
+
Q extends Schema | undefined = undefined,
|
|
276
|
+
R extends ResponseSchemas | undefined = undefined,
|
|
277
|
+
>(
|
|
278
|
+
path: Path,
|
|
279
|
+
options: RouteOptions<Params, Path, P, Q, undefined, R>,
|
|
280
|
+
): RouteDefinition {
|
|
281
|
+
return route('OPTIONS', path, options);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* A WebSocket endpoint. The upgrade request goes through middleware and
|
|
286
|
+
* validation like any route; handlers then run in its async context, so
|
|
287
|
+
* `requirePrincipal()` and request log fields keep working.
|
|
288
|
+
*
|
|
289
|
+
* ```ts
|
|
290
|
+
* r.websocket('/rooms/:room', {
|
|
291
|
+
* middleware: [authenticated()],
|
|
292
|
+
* upgrade: ({ params }) => ({ room: params.room, user: requirePrincipal().id }),
|
|
293
|
+
* open: (socket) => socket.subscribe(socket.data.room),
|
|
294
|
+
* message: (socket, text) => socket.publish(socket.data.room, text),
|
|
295
|
+
* })
|
|
296
|
+
* ```
|
|
297
|
+
*/
|
|
298
|
+
websocket<
|
|
299
|
+
const Path extends string,
|
|
300
|
+
P extends Schema | undefined = undefined,
|
|
301
|
+
Q extends Schema | undefined = undefined,
|
|
302
|
+
D = undefined,
|
|
303
|
+
>(
|
|
304
|
+
path: Path,
|
|
305
|
+
options: WebSocketRouteOptions<Params, Path, P, Q, D>,
|
|
306
|
+
): RouteDefinition {
|
|
307
|
+
const { upgrade, open, message, close, ...rest } = options;
|
|
308
|
+
return route('GET', path, {
|
|
309
|
+
...rest,
|
|
310
|
+
hidden: true,
|
|
311
|
+
websocket: { open, message, close } as WebSocketHandlers<unknown>,
|
|
312
|
+
handler: async (context: never) => {
|
|
313
|
+
const data = upgrade === undefined ? undefined : await upgrade(context);
|
|
314
|
+
// Captured here, inside middleware, so handlers see what it set up.
|
|
315
|
+
return new UpgradeReply(data, captureContext());
|
|
316
|
+
},
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** A nested group: its path, params, middleware and providers apply to its children. */
|
|
321
|
+
group<const Path extends string>(
|
|
322
|
+
path: Path,
|
|
323
|
+
build: Build<Simplify<Params & PathParams<Path>>>,
|
|
324
|
+
): GroupDefinition;
|
|
325
|
+
group<const Path extends string, P extends Schema | undefined = undefined>(
|
|
326
|
+
path: Path,
|
|
327
|
+
options: GroupOptions<P>,
|
|
328
|
+
build: Build<Simplify<Params & OwnParams<Path, P>>>,
|
|
329
|
+
): GroupDefinition;
|
|
330
|
+
group(
|
|
331
|
+
path: string,
|
|
332
|
+
optionsOrBuild: GroupOptions<Schema | undefined> | Build<never>,
|
|
333
|
+
build?: Build<never>,
|
|
334
|
+
): GroupDefinition {
|
|
335
|
+
return group(path, optionsOrBuild, build);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Includes routes defined elsewhere, such as in another file. */
|
|
339
|
+
include(tree: RouteTree<Params & object>): GroupDefinition {
|
|
340
|
+
return tree;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const builder = new RouteBuilder<never>();
|
|
345
|
+
|
|
346
|
+
/** Builds a definition; typed options are erased here, once. */
|
|
347
|
+
function route(
|
|
348
|
+
method: HttpMethod,
|
|
349
|
+
path: string,
|
|
350
|
+
options: object,
|
|
351
|
+
): RouteDefinition {
|
|
352
|
+
const erased = options as RouteDefinition['options'];
|
|
353
|
+
if (typeof erased.handler !== 'function') {
|
|
354
|
+
throw new Error(`Route ${method} ${path} needs a handler function.`);
|
|
355
|
+
}
|
|
356
|
+
return { kind: 'route', method, path, options: erased };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function group(
|
|
360
|
+
path: string,
|
|
361
|
+
optionsOrBuild: GroupOptions<Schema | undefined> | Build<never>,
|
|
362
|
+
build?: Build<never>,
|
|
363
|
+
): GroupDefinition {
|
|
364
|
+
const options = typeof optionsOrBuild === 'function' ? {} : optionsOrBuild;
|
|
365
|
+
const buildChildren =
|
|
366
|
+
typeof optionsOrBuild === 'function' ? optionsOrBuild : build;
|
|
367
|
+
if (buildChildren === undefined) {
|
|
368
|
+
throw new Error(
|
|
369
|
+
`Group "${path}" needs a function that returns its routes.`,
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
return { kind: 'group', path, options, children: buildChildren(builder) };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
interface RoutesFunction<Expects extends object> {
|
|
376
|
+
<const Path extends string>(
|
|
377
|
+
path: Path,
|
|
378
|
+
build: Build<Simplify<Expects & PathParams<Path>>>,
|
|
379
|
+
): RouteTree<Expects>;
|
|
380
|
+
<const Path extends string, P extends Schema | undefined = undefined>(
|
|
381
|
+
path: Path,
|
|
382
|
+
options: GroupOptions<P>,
|
|
383
|
+
build: Build<Simplify<Expects & OwnParams<Path, P>>>,
|
|
384
|
+
): RouteTree<Expects>;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function createRoutes<Expects extends object>(): RoutesFunction<Expects> {
|
|
388
|
+
return ((
|
|
389
|
+
path: string,
|
|
390
|
+
optionsOrBuild: GroupOptions<Schema | undefined> | Build<never>,
|
|
391
|
+
build?: Build<never>,
|
|
392
|
+
) => group(path, optionsOrBuild, build)) as RoutesFunction<Expects>;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Defines a tree of routes under a path.
|
|
397
|
+
*
|
|
398
|
+
* ```ts
|
|
399
|
+
* export const userRoutes = routes('/users', (r) => [
|
|
400
|
+
* r.get('/', { handler: () => inject(UserService).list() }),
|
|
401
|
+
* r.group('/:userId', { params: z.object({ userId: z.uuid() }) }, (r) => [
|
|
402
|
+
* r.get('/', { handler: ({ params }) => inject(UserService).get(params.userId) }),
|
|
403
|
+
* ]),
|
|
404
|
+
* ]);
|
|
405
|
+
* ```
|
|
406
|
+
*
|
|
407
|
+
* Use `routes.withParams<{ userId: string }>()` for routes that are included
|
|
408
|
+
* under a group providing those params.
|
|
409
|
+
*/
|
|
410
|
+
export const routes: RoutesFunction<Empty> & {
|
|
411
|
+
withParams<Expects extends object>(): RoutesFunction<Expects>;
|
|
412
|
+
} = Object.assign(createRoutes<Empty>(), {
|
|
413
|
+
withParams: <Expects extends object>() => createRoutes<Expects>(),
|
|
414
|
+
});
|