@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.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -2
  3. package/dist/index.d.ts +20 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +16 -0
  6. package/dist/lib/auth/api-key.d.ts +17 -0
  7. package/dist/lib/auth/api-key.d.ts.map +1 -0
  8. package/dist/lib/auth/api-key.js +48 -0
  9. package/dist/lib/auth/jwt.d.ts +33 -0
  10. package/dist/lib/auth/jwt.d.ts.map +1 -0
  11. package/dist/lib/auth/jwt.js +227 -0
  12. package/dist/lib/auth/provide-auth.d.ts +30 -0
  13. package/dist/lib/auth/provide-auth.d.ts.map +1 -0
  14. package/dist/lib/auth/provide-auth.js +69 -0
  15. package/dist/lib/auth/strategy.d.ts +47 -0
  16. package/dist/lib/auth/strategy.d.ts.map +1 -0
  17. package/dist/lib/auth/strategy.js +18 -0
  18. package/dist/lib/compile.d.ts +46 -0
  19. package/dist/lib/compile.d.ts.map +1 -0
  20. package/dist/lib/compile.js +126 -0
  21. package/dist/lib/compression.d.ts +23 -0
  22. package/dist/lib/compression.d.ts.map +1 -0
  23. package/dist/lib/compression.js +86 -0
  24. package/dist/lib/config.d.ts +173 -0
  25. package/dist/lib/config.d.ts.map +1 -0
  26. package/dist/lib/config.js +93 -0
  27. package/dist/lib/cors.d.ts +41 -0
  28. package/dist/lib/cors.d.ts.map +1 -0
  29. package/dist/lib/cors.js +101 -0
  30. package/dist/lib/docs.d.ts +15 -0
  31. package/dist/lib/docs.d.ts.map +1 -0
  32. package/dist/lib/docs.js +93 -0
  33. package/dist/lib/engine.d.ts +83 -0
  34. package/dist/lib/engine.d.ts.map +1 -0
  35. package/dist/lib/engine.js +562 -0
  36. package/dist/lib/errors.d.ts +31 -0
  37. package/dist/lib/errors.d.ts.map +1 -0
  38. package/dist/lib/errors.js +55 -0
  39. package/dist/lib/etag.d.ts +5 -0
  40. package/dist/lib/etag.d.ts.map +1 -0
  41. package/dist/lib/etag.js +30 -0
  42. package/dist/lib/headers.d.ts +3 -0
  43. package/dist/lib/headers.d.ts.map +1 -0
  44. package/dist/lib/headers.js +14 -0
  45. package/dist/lib/json-schema.d.ts +11 -0
  46. package/dist/lib/json-schema.d.ts.map +1 -0
  47. package/dist/lib/json-schema.js +23 -0
  48. package/dist/lib/openapi.d.ts +18 -0
  49. package/dist/lib/openapi.d.ts.map +1 -0
  50. package/dist/lib/openapi.js +218 -0
  51. package/dist/lib/rate-limit.d.ts +52 -0
  52. package/dist/lib/rate-limit.d.ts.map +1 -0
  53. package/dist/lib/rate-limit.js +87 -0
  54. package/dist/lib/reply.d.ts +27 -0
  55. package/dist/lib/reply.d.ts.map +1 -0
  56. package/dist/lib/reply.js +52 -0
  57. package/dist/lib/request.d.ts +55 -0
  58. package/dist/lib/request.d.ts.map +1 -0
  59. package/dist/lib/request.js +36 -0
  60. package/dist/lib/router.d.ts +35 -0
  61. package/dist/lib/router.d.ts.map +1 -0
  62. package/dist/lib/router.js +173 -0
  63. package/dist/lib/routes.d.ts +196 -0
  64. package/dist/lib/routes.d.ts.map +1 -0
  65. package/dist/lib/routes.js +98 -0
  66. package/dist/lib/security-headers.d.ts +19 -0
  67. package/dist/lib/security-headers.d.ts.map +1 -0
  68. package/dist/lib/security-headers.js +22 -0
  69. package/dist/lib/serializer.d.ts +35 -0
  70. package/dist/lib/serializer.d.ts.map +1 -0
  71. package/dist/lib/serializer.js +147 -0
  72. package/dist/lib/server.d.ts +86 -0
  73. package/dist/lib/server.d.ts.map +1 -0
  74. package/dist/lib/server.js +255 -0
  75. package/dist/lib/testing.d.ts +21 -0
  76. package/dist/lib/testing.d.ts.map +1 -0
  77. package/dist/lib/testing.js +62 -0
  78. package/dist/lib/transports/node.d.ts +4 -0
  79. package/dist/lib/transports/node.d.ts.map +1 -0
  80. package/dist/lib/transports/node.js +249 -0
  81. package/dist/lib/transports/transport.d.ts +32 -0
  82. package/dist/lib/transports/transport.d.ts.map +1 -0
  83. package/dist/lib/transports/transport.js +1 -0
  84. package/dist/lib/transports/uws.d.ts +8 -0
  85. package/dist/lib/transports/uws.d.ts.map +1 -0
  86. package/dist/lib/transports/uws.js +246 -0
  87. package/dist/lib/websocket.d.ts +71 -0
  88. package/dist/lib/websocket.d.ts.map +1 -0
  89. package/dist/lib/websocket.js +125 -0
  90. package/package.json +67 -3
  91. package/src/index.ts +103 -0
  92. package/src/lib/auth/api-key.ts +73 -0
  93. package/src/lib/auth/jwt.ts +339 -0
  94. package/src/lib/auth/provide-auth.ts +99 -0
  95. package/src/lib/auth/strategy.ts +66 -0
  96. package/src/lib/compile.ts +207 -0
  97. package/src/lib/compression.ts +121 -0
  98. package/src/lib/config.ts +107 -0
  99. package/src/lib/cors.ts +146 -0
  100. package/src/lib/docs.ts +115 -0
  101. package/src/lib/engine.ts +770 -0
  102. package/src/lib/errors.ts +84 -0
  103. package/src/lib/etag.ts +37 -0
  104. package/src/lib/headers.ts +18 -0
  105. package/src/lib/json-schema.ts +36 -0
  106. package/src/lib/openapi.ts +299 -0
  107. package/src/lib/rate-limit.ts +142 -0
  108. package/src/lib/reply.ts +70 -0
  109. package/src/lib/request.ts +83 -0
  110. package/src/lib/router.ts +217 -0
  111. package/src/lib/routes.ts +414 -0
  112. package/src/lib/security-headers.ts +38 -0
  113. package/src/lib/serializer.ts +203 -0
  114. package/src/lib/server.ts +352 -0
  115. package/src/lib/testing.ts +88 -0
  116. package/src/lib/transports/node.ts +315 -0
  117. package/src/lib/transports/transport.ts +39 -0
  118. package/src/lib/transports/uws.ts +310 -0
  119. package/src/lib/websocket.ts +184 -0
@@ -0,0 +1,83 @@
1
+ import { Injector, type Logger, type Tracer } from '@tessellation/core';
2
+ import type { CompiledRoute } from './compile.js';
3
+ import type { Compressor } from './compression.js';
4
+ import type { CorsPolicy } from './cors.js';
5
+ import { HttpRequest, type ResponseSink } from './request.js';
6
+ import type { RawQuery } from './routes.js';
7
+ export interface EngineOptions {
8
+ /** The application injector; request injectors are its children. */
9
+ injector: Injector;
10
+ logger: Logger;
11
+ accessLog: boolean;
12
+ /** Applied to every response, and answers preflight requests. */
13
+ cors?: CorsPolicy | undefined;
14
+ /** Header carrying request ids, lower-case; undefined disables request ids. */
15
+ requestIdHeader?: string | undefined;
16
+ /** Milliseconds before a request is answered with 503; 0 disables. */
17
+ requestTimeout?: number;
18
+ /** Proxies in front of the server, for `HttpRequest.clientIp`. */
19
+ trustProxy?: number;
20
+ /** Added to every response that does not set them. */
21
+ securityHeaders?: readonly (readonly [string, string])[];
22
+ /** Compresses responses the client accepts compressed. */
23
+ compressor?: Compressor | undefined;
24
+ /** Generate weak ETags for successful GET responses. */
25
+ etag?: boolean;
26
+ /** Creates a server span per request; pass only when tracing is on. */
27
+ tracer?: Tracer | undefined;
28
+ /**
29
+ * Called after every response with the route pattern (or `(unmatched)` /
30
+ * `(preflight)`), the status and the duration in seconds. Used for metrics.
31
+ */
32
+ observe?: ((method: string, route: string, status: number, seconds: number) => void) | undefined;
33
+ }
34
+ /** Handles requests for a set of compiled routes, independent of transport. */
35
+ export declare class HttpEngine {
36
+ readonly routes: readonly CompiledRoute[];
37
+ private readonly router;
38
+ private readonly injector;
39
+ private readonly logger;
40
+ private readonly accessLog;
41
+ private readonly cors;
42
+ private readonly requestIdHeader;
43
+ private readonly requestTimeout;
44
+ private readonly trustProxy;
45
+ private readonly securityHeaders;
46
+ private readonly compressor;
47
+ private readonly observe;
48
+ private readonly etag;
49
+ private readonly tracer;
50
+ private inFlight;
51
+ private readonly webSockets;
52
+ private readonly sessionLifecycle;
53
+ private idle;
54
+ /** Set while shutting down: responses ask clients to close the connection. */
55
+ closing: boolean;
56
+ constructor(routes: readonly CompiledRoute[], options: EngineOptions);
57
+ /** Number of requests being handled. */
58
+ get pending(): number;
59
+ /** The transport entry point. Never throws. */
60
+ readonly handle: (request: HttpRequest, sink: ResponseSink) => void;
61
+ /** Open WebSocket connections. */
62
+ get webSocketCount(): number;
63
+ /** Closes every open WebSocket, such as when shutting down. */
64
+ closeWebSockets(code: number, reason: string): void;
65
+ /** Resolves once no request is being handled. */
66
+ drain(): Promise<void>;
67
+ /** Handles the request in a server span when tracing is on. */
68
+ private traced;
69
+ private process;
70
+ /** Answers 503 and aborts the request's signal if it takes too long. */
71
+ private withTimeout;
72
+ /** Runs middleware around the endpoint. Errors from the endpoint are already replies. */
73
+ private run;
74
+ private endpoint;
75
+ private params;
76
+ private body;
77
+ private errorResponse;
78
+ /** Sends a reply. Returns a promise only when compression makes it asynchronous. */
79
+ private send;
80
+ }
81
+ /** Parses a query string; repeated keys become arrays. */
82
+ export declare function parseQuery(query: string): RawQuery;
83
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/lib/engine.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,QAAQ,EACR,KAAK,MAAM,EAOX,KAAK,MAAM,EAEZ,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAI5C,OAAO,EAAE,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAG9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAI5C,MAAM,WAAW,aAAa;IAC5B,oEAAoE;IACpE,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,iEAAiE;IACjE,IAAI,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;IAC9B,+EAA+E;IAC/E,eAAe,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,sEAAsE;IACtE,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Q,CAAK;IACrB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA+B;IAC1D,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAG/B;IACF,OAAO,CAAC,IAAI,CAAyC;IACrD,8EAA8E;IAC9E,OAAO,UAAS;gBAGL,MAAM,EAAE,SAAS,aAAa,EAAE,EACzC,OAAO,EAAE,aAAa;IAoBxB,wCAAwC;IACxC,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,+CAA+C;IAC/C,QAAQ,CAAC,MAAM,GAAI,SAAS,WAAW,EAAE,MAAM,YAAY,KAAG,IAAI,CA6BhE;IAEF,kCAAkC;IAClC,IAAI,cAAc,IAAI,MAAM,CAE3B;IAED,+DAA+D;IAC/D,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAMnD,iDAAiD;IACjD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQtB,+DAA+D;IAC/D,OAAO,CAAC,MAAM;YAmBA,OAAO;IAsKrB,wEAAwE;YAC1D,WAAW;IAyBzB,yFAAyF;IACzF,OAAO,CAAC,GAAG;YAyBG,QAAQ;YAwCR,MAAM;YA0BN,IAAI;IA0BlB,OAAO,CAAC,aAAa;IAwBrB,oFAAoF;IACpF,OAAO,CAAC,IAAI;CA2Eb;AA4CD,0DAA0D;AAC1D,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,QAAQ,CA2BlD"}
@@ -0,0 +1,562 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { Injector, parseTraceparent, provide, runInInjectionContext, withLogFields, } from '@tessellation/core';
3
+ import { badRequest, errorReply, HttpError, problem } from './errors.js';
4
+ import { etagMatches, weakEtag } from './etag.js';
5
+ import { Reply } from './reply.js';
6
+ import { HttpRequest } from './request.js';
7
+ import { UpgradeReply, WebSocketSession } from './websocket.js';
8
+ import { Router } from './router.js';
9
+ const KNOWN_METHODS = new Set([
10
+ 'GET',
11
+ 'HEAD',
12
+ 'POST',
13
+ 'PUT',
14
+ 'PATCH',
15
+ 'DELETE',
16
+ 'OPTIONS',
17
+ ]);
18
+ const REQUEST_ID = /^[\w.:-]{1,128}$/;
19
+ /** Classes (not object literals with getters) keep one hidden class for V8. */
20
+ class HandlerContext {
21
+ params;
22
+ query;
23
+ body;
24
+ request;
25
+ scope;
26
+ constructor(params, query, body, request, scope) {
27
+ this.params = params;
28
+ this.query = query;
29
+ this.body = body;
30
+ this.request = request;
31
+ this.scope = scope;
32
+ }
33
+ get signal() {
34
+ return this.scope.signal;
35
+ }
36
+ }
37
+ class MiddlewareContextImpl {
38
+ request;
39
+ scope;
40
+ route;
41
+ constructor(request, route, scope) {
42
+ this.request = request;
43
+ this.scope = scope;
44
+ this.route = { method: route.method, path: route.path };
45
+ }
46
+ get signal() {
47
+ return this.scope.signal;
48
+ }
49
+ }
50
+ /**
51
+ * Per-request state: the abort signal handlers see. The controller is only
52
+ * created when something reads the signal, so requests that do not use it
53
+ * pay nothing.
54
+ */
55
+ class RequestScope {
56
+ sink;
57
+ controller;
58
+ reason;
59
+ constructor(sink) {
60
+ this.sink = sink;
61
+ }
62
+ get signal() {
63
+ if (this.controller === undefined) {
64
+ this.controller = new AbortController();
65
+ if (this.reason === undefined) {
66
+ this.sink.onAbort(() => this.abort(new DOMException('The client disconnected.', 'AbortError')));
67
+ }
68
+ else {
69
+ this.controller.abort(this.reason);
70
+ }
71
+ }
72
+ return this.controller.signal;
73
+ }
74
+ abort(reason) {
75
+ if (this.reason === undefined) {
76
+ this.reason = reason;
77
+ this.controller?.abort(reason);
78
+ }
79
+ }
80
+ }
81
+ const decoder = new TextDecoder();
82
+ const JSON_TYPE = /^application\/(?:[\w.+-]*\+)?json\b/i;
83
+ /** Handles requests for a set of compiled routes, independent of transport. */
84
+ export class HttpEngine {
85
+ routes;
86
+ router = new Router();
87
+ injector;
88
+ logger;
89
+ accessLog;
90
+ cors;
91
+ requestIdHeader;
92
+ requestTimeout;
93
+ trustProxy;
94
+ securityHeaders;
95
+ compressor;
96
+ observe;
97
+ etag;
98
+ tracer;
99
+ inFlight = 0;
100
+ webSockets = new Set();
101
+ sessionLifecycle = {
102
+ opened: (session) => this.webSockets.add(session),
103
+ closed: (session) => this.webSockets.delete(session),
104
+ };
105
+ idle;
106
+ /** Set while shutting down: responses ask clients to close the connection. */
107
+ closing = false;
108
+ constructor(routes, options) {
109
+ this.routes = routes;
110
+ this.injector = options.injector;
111
+ this.logger = options.logger;
112
+ this.accessLog = options.accessLog;
113
+ this.cors = options.cors?.enabled === true ? options.cors : undefined;
114
+ this.requestIdHeader = options.requestIdHeader;
115
+ this.requestTimeout = options.requestTimeout ?? 0;
116
+ this.trustProxy = options.trustProxy ?? 0;
117
+ this.securityHeaders = options.securityHeaders ?? [];
118
+ this.compressor = options.compressor;
119
+ this.observe = options.observe;
120
+ this.etag = options.etag ?? false;
121
+ this.tracer = options.tracer;
122
+ for (const route of routes) {
123
+ this.router.add(route.method, route.path, route);
124
+ }
125
+ }
126
+ /** Number of requests being handled. */
127
+ get pending() {
128
+ return this.inFlight;
129
+ }
130
+ /** The transport entry point. Never throws. */
131
+ handle = (request, sink) => {
132
+ this.inFlight += 1;
133
+ request.trustedProxies = this.trustProxy;
134
+ let work;
135
+ if (this.requestIdHeader === undefined) {
136
+ work = this.traced(request, sink);
137
+ }
138
+ else {
139
+ const incoming = request.headers[this.requestIdHeader];
140
+ const id = incoming !== undefined && REQUEST_ID.test(incoming)
141
+ ? incoming
142
+ : randomUUID();
143
+ request.id = id;
144
+ // Everything logged while handling the request carries its id.
145
+ work = withLogFields({ requestId: id }, () => this.traced(request, sink));
146
+ }
147
+ work
148
+ .catch((error) => {
149
+ this.logger.error('Failed to send response', { err: error });
150
+ })
151
+ .finally(() => {
152
+ this.inFlight -= 1;
153
+ if (this.inFlight === 0) {
154
+ this.idle?.resolve();
155
+ this.idle = undefined;
156
+ }
157
+ });
158
+ };
159
+ /** Open WebSocket connections. */
160
+ get webSocketCount() {
161
+ return this.webSockets.size;
162
+ }
163
+ /** Closes every open WebSocket, such as when shutting down. */
164
+ closeWebSockets(code, reason) {
165
+ for (const session of [...this.webSockets]) {
166
+ session.close(code, reason);
167
+ }
168
+ }
169
+ /** Resolves once no request is being handled. */
170
+ drain() {
171
+ if (this.inFlight === 0) {
172
+ return Promise.resolve();
173
+ }
174
+ this.idle ??= Promise.withResolvers();
175
+ return this.idle.promise;
176
+ }
177
+ /** Handles the request in a server span when tracing is on. */
178
+ traced(request, sink) {
179
+ const { tracer } = this;
180
+ if (tracer === undefined) {
181
+ return this.process(request, sink, undefined);
182
+ }
183
+ return tracer.span(request.method, (span) => this.process(request, sink, span), {
184
+ kind: 'server',
185
+ parent: parseTraceparent(request.headers['traceparent']),
186
+ attributes: {
187
+ 'http.request.method': request.method,
188
+ 'url.path': request.path,
189
+ },
190
+ });
191
+ }
192
+ async process(request, sink, span) {
193
+ const timed = this.accessLog || this.observe !== undefined;
194
+ const started = timed ? performance.now() : 0;
195
+ const { cors } = this;
196
+ let route;
197
+ let requestInjector;
198
+ let response;
199
+ if (cors !== undefined && cors.isPreflight(request)) {
200
+ // No route has a NUL method, so this lists the methods the path supports.
201
+ const methods = this.router.find('\0', request.path);
202
+ response =
203
+ methods.kind === 'method-not-allowed'
204
+ ? cors.preflight(request, methods.allowed)
205
+ : problem(404);
206
+ const sending = this.send(response, undefined, request, sink);
207
+ if (sending !== undefined) {
208
+ await sending;
209
+ }
210
+ this.observe?.(methodLabel(request.method), '(preflight)', response.status, (performance.now() - started) / 1000);
211
+ return;
212
+ }
213
+ let pending;
214
+ const match = this.router.find(request.method, request.path);
215
+ if (match.kind === 'found') {
216
+ route = match.value;
217
+ if (span !== undefined) {
218
+ span.name = `${request.method} ${route.path}`;
219
+ span.setAttribute('http.route', route.path);
220
+ }
221
+ try {
222
+ if (route.websocket !== undefined &&
223
+ request.headers['upgrade']?.toLowerCase() !== 'websocket') {
224
+ throw new HttpError(426, 'This endpoint only accepts WebSocket connections.', {
225
+ headers: { upgrade: 'websocket' },
226
+ });
227
+ }
228
+ if (route.providers.length > 0) {
229
+ requestInjector = Injector.create({
230
+ name: 'request',
231
+ parent: this.injector,
232
+ providers: [
233
+ provide(HttpRequest, { useValue: request }),
234
+ ...route.providers,
235
+ ],
236
+ });
237
+ }
238
+ const scope = new RequestScope(sink);
239
+ pending = this.run(route, request, match.params, requestInjector ?? this.injector, scope);
240
+ response =
241
+ this.requestTimeout > 0
242
+ ? await this.withTimeout(pending, scope, request, route)
243
+ : await pending;
244
+ }
245
+ catch (error) {
246
+ response = this.errorResponse(error, request, route);
247
+ }
248
+ }
249
+ else if (match.kind === 'method-not-allowed') {
250
+ response = problem(405, undefined, {}, { allow: match.allowed.join(', ') });
251
+ }
252
+ else {
253
+ response = problem(404);
254
+ }
255
+ let upgraded = false;
256
+ if (response instanceof UpgradeReply) {
257
+ if (route?.websocket !== undefined && sink.upgrade !== undefined) {
258
+ sink.upgrade(new WebSocketSession(route.path, route.websocket, response, this.injector, this.logger, this.sessionLifecycle));
259
+ upgraded = true;
260
+ }
261
+ else {
262
+ response = problem(426, 'This endpoint only accepts WebSocket connections.', {}, {
263
+ upgrade: 'websocket',
264
+ });
265
+ }
266
+ }
267
+ if (span !== undefined) {
268
+ span.setAttribute('http.response.status_code', response.status);
269
+ if (response.status >= 500) {
270
+ span.status = 'error';
271
+ }
272
+ }
273
+ cors?.apply(request, response);
274
+ if (request.id !== undefined && this.requestIdHeader !== undefined) {
275
+ response.header(this.requestIdHeader, request.id);
276
+ }
277
+ if (!upgraded) {
278
+ const sent = this.send(response, route, request, sink);
279
+ if (sent !== undefined) {
280
+ await sent;
281
+ }
282
+ }
283
+ if (requestInjector !== undefined) {
284
+ const injector = requestInjector;
285
+ // After a timeout the handler may still be running: clean up once it ends.
286
+ void (pending ?? Promise.resolve())
287
+ .catch(() => undefined)
288
+ .then(() => injector.destroy())
289
+ .catch((error) => {
290
+ this.logger.error('Failed to clean up request providers', {
291
+ err: error,
292
+ });
293
+ });
294
+ }
295
+ if (this.observe !== undefined) {
296
+ this.observe(methodLabel(request.method), route?.path ?? '(unmatched)', response.status, (performance.now() - started) / 1000);
297
+ }
298
+ if (this.accessLog) {
299
+ this.logger.info('Request', {
300
+ method: request.method,
301
+ path: request.path,
302
+ route: route?.path,
303
+ status: response.status,
304
+ durationMs: Math.round((performance.now() - started) * 100) / 100,
305
+ });
306
+ }
307
+ }
308
+ /** Answers 503 and aborts the request's signal if it takes too long. */
309
+ async withTimeout(work, scope, request, route) {
310
+ let timer;
311
+ const timeout = new Promise((resolve) => {
312
+ timer = setTimeout(() => {
313
+ scope.abort(new DOMException('The request timed out.', 'TimeoutError'));
314
+ this.logger.warn('Request timed out', {
315
+ method: request.method,
316
+ route: route.path,
317
+ timeoutMs: this.requestTimeout,
318
+ });
319
+ resolve(problem(503, 'The request timed out.'));
320
+ }, this.requestTimeout);
321
+ });
322
+ try {
323
+ return await Promise.race([work, timeout]);
324
+ }
325
+ finally {
326
+ clearTimeout(timer);
327
+ }
328
+ }
329
+ /** Runs middleware around the endpoint. Errors from the endpoint are already replies. */
330
+ run(route, request, rawParams, injector, scope) {
331
+ const { middleware } = route;
332
+ if (middleware.length === 0) {
333
+ return this.endpoint(route, request, rawParams, injector, scope);
334
+ }
335
+ const context = new MiddlewareContextImpl(request, route, scope);
336
+ const dispatch = async (index) => {
337
+ const current = middleware[index];
338
+ if (current === undefined) {
339
+ return this.endpoint(route, request, rawParams, injector, scope);
340
+ }
341
+ return runInInjectionContext(injector, () => current(context, () => dispatch(index + 1)));
342
+ };
343
+ return dispatch(0);
344
+ }
345
+ async endpoint(route, request, rawParams, injector, scope) {
346
+ try {
347
+ const issues = [];
348
+ const params = await this.params(route, rawParams, issues);
349
+ const rawQuery = parseQuery(request.query);
350
+ const query = route.query
351
+ ? await validate(route.query, rawQuery, 'query', issues)
352
+ : rawQuery;
353
+ const body = route.body
354
+ ? await this.body(route.body, request, issues)
355
+ : undefined;
356
+ if (issues.length > 0) {
357
+ throw badRequest('The request is invalid.', { details: { issues } });
358
+ }
359
+ const result = runInInjectionContext(injector, () => route.handler(new HandlerContext(params, query, body, request, scope)));
360
+ const value = result instanceof Promise ? await result : result;
361
+ if (value instanceof Reply) {
362
+ return value;
363
+ }
364
+ return value === undefined
365
+ ? new Reply(204, undefined)
366
+ : new Reply(200, value);
367
+ }
368
+ catch (error) {
369
+ return this.errorResponse(error, request, route);
370
+ }
371
+ }
372
+ async params(route, values, issues) {
373
+ const params = {};
374
+ const names = route.paramNames;
375
+ for (let index = 0; index < names.length; index += 1) {
376
+ params[names[index]] = decodeComponent(values[index]);
377
+ }
378
+ for (const level of route.paramLevels) {
379
+ const input = {};
380
+ for (const name of level.names) {
381
+ input[name] = params[name];
382
+ }
383
+ const output = await validate(level.schema, input, 'params', issues);
384
+ if (output !== undefined) {
385
+ Object.assign(params, output);
386
+ }
387
+ }
388
+ return params;
389
+ }
390
+ async body(schema, request, issues) {
391
+ const bytes = await request.body();
392
+ let value;
393
+ if (bytes.byteLength > 0) {
394
+ const type = request.headers['content-type'] ?? '';
395
+ if (!JSON_TYPE.test(type)) {
396
+ throw new HttpError(415, 'The request body must be JSON (content-type: application/json).');
397
+ }
398
+ try {
399
+ value = JSON.parse(decoder.decode(bytes));
400
+ }
401
+ catch {
402
+ throw badRequest('The request body is not valid JSON.');
403
+ }
404
+ }
405
+ return validate(schema, value, 'body', issues);
406
+ }
407
+ errorResponse(error, request, route) {
408
+ if (error instanceof HttpError) {
409
+ if (error.status >= 500) {
410
+ this.logger.error('Request failed', {
411
+ method: request.method,
412
+ route: route?.path,
413
+ err: error,
414
+ });
415
+ }
416
+ return errorReply(error);
417
+ }
418
+ this.logger.error('Unhandled error', {
419
+ method: request.method,
420
+ route: route?.path,
421
+ err: error,
422
+ });
423
+ return problem(500);
424
+ }
425
+ /** Sends a reply. Returns a promise only when compression makes it asynchronous. */
426
+ send(response, route, request, sink) {
427
+ if (sink.aborted) {
428
+ return undefined;
429
+ }
430
+ const { headers, body, status } = response;
431
+ let payload;
432
+ if (body === undefined || (body === null && status === 204)) {
433
+ payload = undefined;
434
+ }
435
+ else if (typeof body === 'string') {
436
+ payload = body;
437
+ headers['content-type'] ??= 'text/plain; charset=utf-8';
438
+ }
439
+ else if (body instanceof Uint8Array) {
440
+ payload = body;
441
+ headers['content-type'] ??= 'application/octet-stream';
442
+ }
443
+ else {
444
+ const serialize = route?.serializers.get(status) ?? JSON.stringify;
445
+ payload = serialize(body);
446
+ headers['content-type'] ??= 'application/json';
447
+ }
448
+ for (const [name, value] of this.securityHeaders) {
449
+ headers[name] ??= value;
450
+ }
451
+ if (this.closing) {
452
+ headers['connection'] = 'close';
453
+ }
454
+ const head = request.method === 'HEAD';
455
+ // Conditional GET: honour ETags set by handlers, or generate them.
456
+ if (status === 200 &&
457
+ payload !== undefined &&
458
+ (head || request.method === 'GET')) {
459
+ let tag = headers['etag'];
460
+ if (tag === undefined && this.etag) {
461
+ tag = weakEtag(payload);
462
+ headers['etag'] = tag;
463
+ }
464
+ if (tag !== undefined &&
465
+ etagMatches(request.headers['if-none-match'], tag)) {
466
+ delete headers['content-type'];
467
+ sink.send(304, headers, undefined, head);
468
+ return undefined;
469
+ }
470
+ }
471
+ if (this.compressor !== undefined &&
472
+ payload !== undefined &&
473
+ !head &&
474
+ status !== 204 &&
475
+ status !== 304) {
476
+ return this.compressor
477
+ .apply(request.headers['accept-encoding'], headers, payload)
478
+ .then((compressed) => {
479
+ if (!sink.aborted) {
480
+ sink.send(status, headers, compressed, head);
481
+ }
482
+ });
483
+ }
484
+ sink.send(status, headers, payload, head);
485
+ return undefined;
486
+ }
487
+ }
488
+ async function validate(schema, value, location, issues) {
489
+ let result = schema['~standard'].validate(value);
490
+ if (result instanceof Promise) {
491
+ result = await result;
492
+ }
493
+ if (result.issues === undefined) {
494
+ return result.value;
495
+ }
496
+ for (const issue of result.issues) {
497
+ issues.push({
498
+ in: location,
499
+ path: issuePath(issue),
500
+ message: issue.message,
501
+ });
502
+ }
503
+ return undefined;
504
+ }
505
+ function issuePath(issue) {
506
+ return (issue.path ?? [])
507
+ .map((segment) => String(typeof segment === 'object' ? segment.key : segment))
508
+ .join('.');
509
+ }
510
+ function decodeComponent(value) {
511
+ if (!value.includes('%')) {
512
+ return value;
513
+ }
514
+ try {
515
+ return decodeURIComponent(value);
516
+ }
517
+ catch {
518
+ throw badRequest('The request path is not correctly URL-encoded.');
519
+ }
520
+ }
521
+ /** Parses a query string; repeated keys become arrays. */
522
+ export function parseQuery(query) {
523
+ const result = Object.create(null);
524
+ if (query === '') {
525
+ return result;
526
+ }
527
+ for (const pair of query.split('&')) {
528
+ if (pair === '') {
529
+ continue;
530
+ }
531
+ const equals = pair.indexOf('=');
532
+ const key = decodeQueryComponent(equals === -1 ? pair : pair.slice(0, equals));
533
+ const value = equals === -1 ? '' : decodeQueryComponent(pair.slice(equals + 1));
534
+ const existing = result[key];
535
+ if (existing === undefined) {
536
+ result[key] = value;
537
+ }
538
+ else if (Array.isArray(existing)) {
539
+ existing.push(value);
540
+ }
541
+ else {
542
+ result[key] = [existing, value];
543
+ }
544
+ }
545
+ return result;
546
+ }
547
+ function decodeQueryComponent(value) {
548
+ const spaced = value.includes('+') ? value.replaceAll('+', ' ') : value;
549
+ if (!spaced.includes('%')) {
550
+ return spaced;
551
+ }
552
+ try {
553
+ return decodeURIComponent(spaced);
554
+ }
555
+ catch {
556
+ throw badRequest('The query string is not correctly URL-encoded.');
557
+ }
558
+ }
559
+ /** Bounded method values for metric labels. */
560
+ function methodLabel(method) {
561
+ return KNOWN_METHODS.has(method) ? method : 'OTHER';
562
+ }
@@ -0,0 +1,31 @@
1
+ import { Reply } from './reply.js';
2
+ export interface HttpErrorOptions extends ErrorOptions {
3
+ /** Extra members for the problem details body, such as `{ field: 'email' }`. */
4
+ details?: Record<string, unknown>;
5
+ /** Response headers, such as `retry-after`. */
6
+ headers?: Record<string, string>;
7
+ }
8
+ /**
9
+ * Throw from a handler or middleware to send an error response. The body is
10
+ * an RFC 9457 problem details object (`application/problem+json`):
11
+ * `{ type, title, status, detail, ...details }`.
12
+ */
13
+ export declare class HttpError extends Error {
14
+ readonly status: number;
15
+ readonly name = "HttpError";
16
+ readonly details: Record<string, unknown> | undefined;
17
+ readonly headers: Record<string, string> | undefined;
18
+ constructor(status: number, message?: string, options?: HttpErrorOptions);
19
+ }
20
+ export declare const badRequest: (message?: string, options?: HttpErrorOptions) => HttpError;
21
+ export declare const unauthorized: (message?: string, options?: HttpErrorOptions) => HttpError;
22
+ export declare const forbidden: (message?: string, options?: HttpErrorOptions) => HttpError;
23
+ export declare const notFound: (message?: string, options?: HttpErrorOptions) => HttpError;
24
+ export declare const conflict: (message?: string, options?: HttpErrorOptions) => HttpError;
25
+ export declare const unprocessable: (message?: string, options?: HttpErrorOptions) => HttpError;
26
+ export declare const tooManyRequests: (message?: string, options?: HttpErrorOptions) => HttpError;
27
+ export declare function statusText(status: number): string;
28
+ /** The problem details reply for an error status. */
29
+ export declare function problem(status: number, detail?: string, extra?: Record<string, unknown>, headers?: Record<string, string>): Reply<Record<string, unknown>>;
30
+ export declare function errorReply(error: HttpError): Reply<Record<string, unknown>>;
31
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/lib/errors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC,MAAM,WAAW,gBAAiB,SAAQ,YAAY;IACpD,gFAAgF;IAChF,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;;;GAIG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAMhC,QAAQ,CAAC,MAAM,EAAE,MAAM;IALzB,SAAkB,IAAI,eAAe;IACrC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,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