-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrouter.ts
1646 lines (1536 loc) Β· 48 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022-2024 the oak authors. All rights reserved.
/**
* The router for acorn, which is the foundational part of the framework.
*
* @example
* ```ts
* import { Router } from "jsr:@oak/acorn/router";
*
* const router = new Router();
*
* router.get("/", () => ({ hello: "world" }));
*
* const BOOKS = {
* "1": { title: "The Hound of the Baskervilles" },
* "2": { title: "It" },
* };
*
* router.get("/books/:id", (ctx) => BOOKS[ctx.params.id]);
*
* router.listen({ port: 3000 });
* ```
*
* @module
*/
import { Context } from "./context.ts";
import {
assert,
createHttpError,
isClientErrorStatus,
isErrorStatus,
isHttpError,
isInformationalStatus,
isRedirectStatus,
isServerErrorStatus,
isSuccessfulStatus,
SecureCookieMap,
Status,
} from "./deps.ts";
import type { Deserializer, KeyRing, Serializer } from "./types.ts";
import type {
Addr,
Destroyable,
Listener,
RequestEvent,
Server as _Server,
ServerConstructor,
} from "./types_internal.ts";
import {
CONTENT_TYPE_HTML,
CONTENT_TYPE_JSON,
CONTENT_TYPE_TEXT,
createPromiseWithResolvers,
isBodyInit,
isBun,
isHtmlLike,
isJsonLike,
responseFromHttpError,
} from "./util.ts";
if (!("URLPattern" in globalThis)) {
await import("urlpattern-polyfill");
}
/** Valid return values from a route handler. */
export type RouteResponse<Type> = Response | BodyInit | Type;
type ParamsDictionary = Record<string, string>;
type RemoveTail<S extends string, Tail extends string> = S extends
`${infer P}${Tail}` ? P : S;
type GetRouteParameter<S extends string> = RemoveTail<
RemoveTail<RemoveTail<S, `/${string}`>, `-${string}`>,
`.${string}`
>;
/** The type alias to help infer what the route parameters are for a route based
* on the route string. */
export type RouteParameters<Route extends string> = string extends Route
? ParamsDictionary
: Route extends `${string}(${string}` ? ParamsDictionary
: Route extends `${string}:${infer Rest}` ?
& (
GetRouteParameter<Rest> extends never ? ParamsDictionary
: GetRouteParameter<Rest> extends `${infer ParamName}?`
? { [P in ParamName]?: string }
: { [P in GetRouteParameter<Rest>]: string }
)
& (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
? RouteParameters<Next>
: unknown)
: ParamsDictionary;
/** The interface for route handlers, which are provided via a context
* argument. The route handler is expected to return a
* {@linkcode RouteResponse} or `undefined` if it cannot handle the request,
* which will typically result in a 404 being returned to the client. */
export interface RouteHandler<
ResponseType,
BodyType = unknown,
Params extends Record<string, string> = Record<string, string>,
> {
(
context: Context<BodyType, Params>,
):
| Promise<RouteResponse<ResponseType> | undefined>
| RouteResponse<ResponseType>
| undefined;
}
/**
* The interface too status handlers, which are registered on the
* {@linkcode Router} via the `.on()` method and intended for being notified of
* certain state changes related to routing requests.
*/
export interface StatusHandler<S extends Status> {
(
context: Context<unknown, Record<string, string>>,
status: S,
response?: Response,
):
| Promise<RouteResponse<unknown> | undefined>
| RouteResponse<unknown>
| undefined;
}
/** An error handler is tied to a specific route and can implement custom logic
* to deal with an error that occurred when processing the route. */
interface ErrorHandler {
(
request: Request,
error: unknown,
): Response | undefined | Promise<Response | undefined>;
}
/** Options that can be specified when adding a route to the router. */
export interface RouteOptions<
R extends string,
BodyType,
Params extends RouteParameters<R>,
> {
/** An optional deserializer to use when decoding the body. This can be used
* to validate the body of the request or hydrate an object. */
deserializer?: Deserializer<BodyType, Params>;
/** An error handler which is specific to this route, which will be called
* when there is an error thrown when trying to process the route. */
errorHandler?: ErrorHandler;
/** The serializer is used to serialize a return value of the route handler,
* when the value is not a {@linkcode Response} or {@linkcode BodyInit}. The
* optional `.stringify()` method of the serializer is expected to return a
* JSON string representation of the body returned from the handler, where as
* the `.toResponse()` method is expected to return a full
* {@linkcode Response} object. */
serializer?: Serializer<Params>;
}
/** An interface of route options which also includes the handler, intended to
* make it easy to provide a single object to register a route. */
export interface RouteOptionsWithHandler<
R extends string,
BodyType,
Params extends RouteParameters<R>,
ResponseType,
> extends RouteOptions<R, BodyType, Params> {
handler: RouteHandler<ResponseType, BodyType, Params>;
}
const HTTP_VERBS = [
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT",
] as const;
const HANDLE_START = "handle start";
type HTTPVerbs = typeof HTTP_VERBS[number];
/** A string that represents a range of HTTP response {@linkcode Status} codes:
*
* - `"*"` - matches any status code
* - `"info"` - matches information status codes (`100`-`199`)
* - `"success"` - matches successful status codes (`200`-`299`)
* - `"redirect"` - matches redirection status codes (`300`-`399`)
* - `"client-error"` - matches client error status codes (`400`-`499`)
* - `"server-error"` - matches server error status codes (`500`-`599`)
* - `"error"` - matches any error status code (`400`-`599`)
*/
export type StatusRange =
| "*"
| "info"
| "success"
| "redirect"
| "client-error"
| "server-error"
| "error";
/** A {@linkcode Status} code or a shorthand {@linkcode StatusRange} string. */
export type StatusAndRanges = Status | StatusRange;
interface NotFoundEventListener {
(evt: NotFoundEvent): void | Promise<void>;
}
interface NotFoundListenerObject {
handleEvent(evt: NotFoundEvent): void | Promise<void>;
}
type NotFoundEventListenerOrEventListenerObject =
| NotFoundEventListener
| NotFoundListenerObject;
interface HandledEventListener {
(evt: HandledEvent): void | Promise<void>;
}
interface HandledEventListenerObject {
handleEvent(evt: HandledEvent): void | Promise<void>;
}
type HandledEventListenerOrEventListenerObject =
| HandledEventListener
| HandledEventListenerObject;
interface RouterErrorEventListener {
(evt: RouterErrorEvent): void | Promise<void>;
}
interface RouterErrorEventListenerObject {
handleEvent(evt: RouterErrorEvent): void | Promise<void>;
}
type RouterErrorEventListenerOrEventListenerObject =
| RouterErrorEventListener
| RouterErrorEventListenerObject;
interface RouterListenEventListener {
(evt: RouterListenEvent): void | Promise<void>;
}
interface RouterListenEventListenerObject {
handleEvent(evt: RouterListenEvent): void | Promise<void>;
}
type RouterListenEventListenerOrEventListenerObject =
| RouterListenEventListener
| RouterListenEventListenerObject;
interface RouterRequestEventListener {
(evt: RouterRequestEvent): void | Promise<void>;
}
interface RouterRequestEventListenerObject {
handleEvent(evt: RouterRequestEvent): void | Promise<void>;
}
type RouterRequestListenerOrEventListenerObject =
| RouterRequestEventListener
| RouterRequestEventListenerObject;
interface NotFoundEventInit extends EventInit {
request: Request;
}
/** A DOM like event that is emitted from the router when any request did not
* match any routes.
*
* Setting the `.response` property will cause the default response to be
* overridden. */
export class NotFoundEvent extends Event {
#request: Request;
/** The original {@linkcode Request} associated with the event. */
get request(): Request {
return this.#request;
}
/** If the event listener whishes to issue a specific response to the event,
* then it should set the value here to a {@linkcode Response} and the router
* will use it to respond. */
response?: Response;
constructor(eventInitDict: NotFoundEventInit) {
super("notfound", eventInitDict);
this.#request = eventInitDict.request;
}
}
interface HandledEventInit extends EventInit {
measure: PerformanceMeasure;
request: Request;
response: Response;
route?: Route;
}
/** A DOM like event emitted by the router when a request has been handled.
*
* This can be used to provide logging and reporting for the router. */
export class HandledEvent extends Event {
#measure: PerformanceMeasure;
#request: Request;
#response: Response;
#route?: Route;
/** The performance measure from the start of handling the route until it
* finished, which can provide timing information about the processing. */
get measure(): PerformanceMeasure {
return this.#measure;
}
/** The {@linkcode Request} that was handled. */
get request(): Request {
return this.#request;
}
/** The {@linkcode Response} that was handled. */
get response(): Response {
return this.#response;
}
/** The {@linkcode Route} that was matched. */
get route(): Route | undefined {
return this.#route;
}
constructor(eventInitDict: HandledEventInit) {
super("handled", eventInitDict);
this.#request = eventInitDict.request;
this.#response = eventInitDict.response;
this.#route = eventInitDict.route;
this.#measure = eventInitDict.measure;
}
}
interface RouterErrorEventInit extends ErrorEventInit {
request?: Request;
respondable?: boolean;
route?: Route;
}
/** Error events from the router will be of this type, which provides additional
* context about the error and provides a way to override the default behaviors
* of the router. */
export class RouterErrorEvent extends ErrorEvent {
#request?: Request;
#respondable: boolean;
#route?: Route;
/** The original {@linkcode Request} object. */
get request(): Request | undefined {
return this.#request;
}
/** To provide a custom response to an error event set a {@linkcode Response}
* to this property and it will be used instead of the built in default.
*
* The `.respondable` property will indicate if a response to the client is
* possible or not.
*/
response?: Response;
/** Indicates if the error can be responded to. `true` indicates that a
* `Response` has not been sent to the client yet, while `false` indicates
* that a response cannot be sent. */
get respondable(): boolean {
return this.#respondable;
}
/** If the error occurred while processing a route, the {@linkcode Route} will
* be available on this property. */
get route(): Route | undefined {
return this.#route;
}
constructor(eventInitDict: RouterErrorEventInit) {
super("error", eventInitDict);
this.#request = eventInitDict.request;
this.#respondable = eventInitDict.respondable ?? false;
this.#route = eventInitDict.route;
}
}
interface RouterListenEventInit extends EventInit {
hostname: string;
listener: Listener;
port: number;
secure: boolean;
}
/** The event class that is emitted when the router starts listening. */
export class RouterListenEvent extends Event {
#hostname: string;
#listener: Listener;
#port: number;
#secure: boolean;
/** The hostname that is being listened on. */
get hostname(): string {
return this.#hostname;
}
/** A reference to the {@linkcode Listener} being listened to. */
get listener(): Listener {
return this.#listener;
}
/** The port that is being listened on. */
get port(): number {
return this.#port;
}
/** A flag to indicate if the router believes it is running in a secure
* context (e.g. TLS/HTTPS). */
get secure(): boolean {
return this.#secure;
}
constructor(eventInitDict: RouterListenEventInit) {
super("listen", eventInitDict);
this.#hostname = eventInitDict.hostname;
this.#listener = eventInitDict.listener;
this.#port = eventInitDict.port;
this.#secure = eventInitDict.secure;
}
}
/** The init for a {@linkcode RouterRequestEvent}. */
export interface RouterRequestEventInit extends EventInit {
/** Any secure cookies associated with the request event. */
cookies: SecureCookieMap;
/** The {@linkcode Request} associated with the event. */
request: Request;
/** A link to the response headers object that should be used when
* initing a response. */
responseHeaders: Headers;
}
/** An event that is raised when the router is processing an event. If the
* event's `response` property is set after the event completes its dispatch,
* then the value will be used to send the response, otherwise the router will
* attempt to match a route. */
export class RouterRequestEvent extends Event {
#cookies: SecureCookieMap;
#request: Request;
#responseHeaders: Headers;
get cookies(): SecureCookieMap {
return this.#cookies;
}
get request(): Request {
return this.#request;
}
response?: Response;
get responseHeaders(): Headers {
return this.#responseHeaders;
}
constructor(eventInitDict: RouterRequestEventInit) {
super("request", eventInitDict);
this.#cookies = eventInitDict.cookies;
this.#request = eventInitDict.request;
this.#responseHeaders = eventInitDict.responseHeaders;
}
}
interface ListenOptionsBase {
hostname?: string;
port?: number;
secure?: boolean;
server?: ServerConstructor;
signal?: AbortSignal;
}
interface ListenOptionsSecure extends ListenOptionsBase {
/** Server private key in PEM format */
key?: string;
/** Cert chain in PEM format */
cert?: string;
/** Application-Layer Protocol Negotiation (ALPN) protocols to announce to
* the client. If not specified, no ALPN extension will be included in the
* TLS handshake. */
alpnProtocols?: string[];
secure: true;
}
type ListenOptions = ListenOptionsBase | ListenOptionsSecure;
interface InternalState {
closed: boolean;
closing: boolean;
server: ServerConstructor;
}
/** Options which can be used when creating a new router. */
export interface RouterOptions {
/** A key ring which will be used for signing and validating cookies. */
keys?: KeyRing;
/** When providing internal responses, like on unhandled errors, prefer JSON
* responses to HTML responses. When set to `false` HTML will be preferred
* when responding, but content type negotiation will still be respected.
* Defaults to `true`. */
preferJson?: boolean;
}
function appendHeaders(response: Response, headers: Headers): Response {
for (const [key, value] of headers) {
response.headers.append(key, value);
}
return response;
}
class Route<
R extends string = string,
BodyType = unknown,
Params extends RouteParameters<R> = RouteParameters<R>,
ResponseType = unknown,
> {
#handler: RouteHandler<unknown, BodyType, Params>;
#deserializer?: Deserializer<BodyType, Params>;
#destroyHandle: Destroyable;
#errorHandler?: ErrorHandler;
#params?: Params;
#route: R;
#serializer?: Serializer<Params>;
#urlPattern: URLPattern;
#verbs: HTTPVerbs[];
get route(): R {
return this.#route;
}
constructor(
verbs: HTTPVerbs[],
route: R,
handler: RouteHandler<ResponseType, BodyType, Params>,
destroyHandle: Destroyable,
{ deserializer, errorHandler, serializer }: RouteOptions<
R,
BodyType,
Params
>,
) {
this.#verbs = verbs;
this.#route = route;
this.#urlPattern = new URLPattern({ pathname: route });
this.#handler = handler;
this.#deserializer = deserializer;
this.#errorHandler = errorHandler;
this.#serializer = serializer;
this.#destroyHandle = destroyHandle;
}
destroy(): void {
this.#destroyHandle.destroy();
}
error(
request: Request,
error: unknown,
): Response | undefined | Promise<Response | undefined> {
if (this.#errorHandler) {
return this.#errorHandler(request, error);
}
}
async handle(
requestEvent: RequestEvent,
headers: Headers,
secure: boolean,
keys?: KeyRing,
): Promise<Response | undefined> {
assert(this.#params, "params should have been set in .matches()");
const context = new Context<BodyType, Params>(
{
deserializer: this.#deserializer,
headers,
keys,
params: this.#params,
requestEvent,
secure,
},
);
const result = await this.#handler(context);
if (result instanceof Response) {
return appendHeaders(result, headers);
}
if (isBodyInit(result)) {
if (typeof result === "string") {
if (isHtmlLike(result)) {
headers.set("content-type", CONTENT_TYPE_HTML);
} else if (isJsonLike(result)) {
headers.set("content-type", CONTENT_TYPE_JSON);
} else {
headers.set("content-type", CONTENT_TYPE_TEXT);
}
} else {
headers.set("content-type", CONTENT_TYPE_JSON);
}
return new Response(result, { headers });
}
if (result) {
if (this.#serializer?.toResponse) {
return appendHeaders(
await this.#serializer.toResponse(
result,
this.#params,
requestEvent.request,
),
headers,
);
} else {
headers.set("content-type", CONTENT_TYPE_JSON);
return new Response(
this.#serializer?.stringify
? await this.#serializer.stringify(result)
: JSON.stringify(result),
{ headers },
);
}
}
return undefined;
}
matches(request: Request): boolean {
if (this.#verbs.includes(request.method as HTTPVerbs)) {
const result = this.#urlPattern.exec(request.url);
if (result) {
this.#params = result.pathname.groups as Params;
}
return !!result;
}
return false;
}
}
class StatusRoute<S extends Status> {
#destroyHandle: Destroyable;
#handler: StatusHandler<S>;
#status: StatusAndRanges[];
constructor(
status: StatusAndRanges[],
handler: StatusHandler<S>,
destroyHandle: Destroyable,
) {
this.#destroyHandle = destroyHandle;
this.#handler = handler;
this.#status = status;
}
destroy(): void {
this.#destroyHandle.destroy();
}
async handle(
status: Status,
requestEvent: RequestEvent,
response: Response | undefined,
responseHeaders: Headers,
secure: boolean,
keys?: KeyRing,
): Promise<Response | undefined> {
const headers = response ? new Headers(response.headers) : responseHeaders;
const context = new Context({ requestEvent, headers, secure, keys });
const result = await this.#handler(context, status as S, response);
if (result instanceof Response) {
return appendHeaders(result, headers);
}
if (isBodyInit(result)) {
if (typeof result === "string") {
if (isHtmlLike(result)) {
headers.set("content-type", CONTENT_TYPE_HTML);
} else if (isJsonLike(result)) {
headers.set("content-type", CONTENT_TYPE_JSON);
} else {
headers.set("content-type", CONTENT_TYPE_TEXT);
}
} else {
headers.set("content-type", CONTENT_TYPE_JSON);
}
return new Response(result, { status, headers });
}
if (result) {
headers.set("content-type", CONTENT_TYPE_JSON);
return new Response(JSON.stringify(result), { status, headers });
}
return undefined;
}
matches(status: Status): boolean {
for (const item of this.#status) {
if (typeof item === "number") {
if (status === item) {
return true;
} else {
continue;
}
}
switch (item) {
case "*":
return true;
case "info":
if (isInformationalStatus(status)) {
return true;
}
break;
case "success":
if (isSuccessfulStatus(status)) {
return true;
}
break;
case "redirect":
if (isRedirectStatus(status)) {
return true;
}
break;
case "client-error":
if (isClientErrorStatus(status)) {
return true;
}
break;
case "server-error":
if (isServerErrorStatus(status)) {
return true;
}
break;
case "error":
if (isErrorStatus(status)) {
return true;
}
}
}
return false;
}
}
/** Context to be provided when invoking the `.handle()` method on the
* router. */
export interface RouterHandleInit {
addr: Addr;
/** @default {false} */
secure?: boolean;
}
let ServerCtor: ServerConstructor | undefined;
/** A router which is specifically geared for handling RESTful type of requests
* and providing a straight forward API to respond to them.
*
* A {@linkcode RouteHandler} is registered with the router, and when a request
* matches a route the handler will be invoked. The handler will be provided
* with {@linkcode Context} of the current request. The handler can return a
* web platform {@linkcode Response} instance, {@linkcode BodyInit} value, or
* any other object which will be to be serialized to a JSON string as set as
* the value of the response body.
*
* The handler context includes a property named `cookies` which is an instance
* of {@linkcode Cookies}, which provides an interface for reading request
* cookies and setting cookies in the response. `Cookies` supports cryptographic
* signing of keys using a key ring which adheres to the {@linkcode KeyRing}
* interface, which can be passed as an option when creating the router.
*
* The route is specified using the pathname part of the {@linkcode URLPattern}
* API which supports routes with wildcards (e.g. `/posts/*`) and named groups
* (e.g. `/books/:id`) which are then provided as `.params` on the context
* argument to the handler.
*
* When registering a route handler, a {@linkcode Deserializer},
* {@linkcode Serializer}, and {@linkcode ErrorHandler} can all be specified.
* When a deserializer is specified and a request has a body, the deserializer
* will be used to parse the body. This is designed to make it possible to
* validate a body or hydrate an object from a request. When a serializer is
* specified and the handler returns something other than a `Response` or
* `BodyInit`, the serializer will be used to serialize the response from the
* route handler, if present, otherwise
* [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
* will be used to convert the body used in the response.
*
* Observability of the router is designed using DOM events, where there are
* several events which can be listened for:
*
* - `"error"` - produces a {@linkcode RouterErrorEvent} when an error occurs
* when within the router. This can be used to provide a customized response
* for errors.
* - `"listen"` - produces a {@linkcode RouterListenEvent} when the router has
* successfully started listening to requests.
* - `"handled"` - produces a {@linkcode HandledEvent} when the router has
* completed handling of a request and has sent the response.
* - `"notfound"` - produces a {@linkcode NotFoundEvent} when the router was
* unable to provide a response for a given request. This can be used to
* provide a customized response for not found events.
*
* ## Example
*
* ```ts
* import { Router } from "jsr:@oak/acorn/router";
*
* const router = new Router();
*
* router.all("/:id", (ctx) => ({ id: ctx.params.id }));
*
* router.listen({ port: 8080 });
* ```
*/
export class Router extends EventTarget {
#handling: Set<Promise<Response>> = new Set();
#keys?: KeyRing;
#preferJson: boolean;
#routes = new Set<Route>();
#secure = false;
#state?: InternalState;
#statusRoutes = new Set<StatusRoute<Status>>();
#uid = 0;
#add<
R extends string,
BodyType,
Params extends RouteParameters<R>,
ResponseType,
>(
verbs: HTTPVerbs[],
route: R,
handler: RouteHandler<ResponseType, BodyType, Params>,
options: RouteOptions<R, BodyType, Params> = {},
): Route<R, BodyType, Params, ResponseType> {
const r = new Route(verbs, route, handler, {
destroy: () => {
this.#routes.delete(r as unknown as Route);
},
}, options);
this.#routes.add(r as unknown as Route);
return r;
}
#error(
request: Request,
error: unknown,
respondable: boolean,
): Response {
const message = error instanceof Error ? error.message : "Internal error";
const event = new RouterErrorEvent({
request,
error,
message,
respondable,
});
this.dispatchEvent(event);
let response = event.response;
if (!response) {
if (isHttpError(error)) {
response = responseFromHttpError(request, error, this.#preferJson);
} else {
const message = error instanceof Error
? error.message
: "Internal error";
response = responseFromHttpError(
request,
createHttpError(Status.InternalServerError, message),
this.#preferJson,
);
}
}
return response;
}
async #handleStatus(
status: Status,
requestEvent: RequestEvent,
responseHeaders: Headers,
response?: Response,
): Promise<Response | undefined> {
for (const route of this.#statusRoutes) {
if (route.matches(status)) {
try {
const result = await route.handle(
status,
requestEvent,
response,
responseHeaders,
this.#secure,
this.#keys,
);
if (result) {
response = result;
}
} catch (error) {
return this.#error(requestEvent.request, error, true);
}
}
}
return response;
}
async #handle(requestEvent: RequestEvent): Promise<void> {
const uid = this.#uid++;
performance.mark(`${HANDLE_START} ${uid}`);
const { promise, resolve } = Promise.withResolvers<Response>();
this.#handling.add(promise);
requestEvent.respond(promise);
promise.then(() => this.#handling.delete(promise)).catch(
(error) => {
this.#error(requestEvent.request, error, false);
},
);
const { request } = requestEvent;
const responseHeaders = new Headers();
let cookies: SecureCookieMap;
try {
cookies = new SecureCookieMap(request, {
keys: this.#keys,
response: responseHeaders,
secure: this.#secure,
});
} catch {
// deal with a request dropping before the headers can be read which can
// occur under heavy load
this.#handling.delete(promise);
return;
}
const routerRequestEvent = new RouterRequestEvent({
cookies,
request,
responseHeaders,
});
if (
this.dispatchEvent(routerRequestEvent) || !routerRequestEvent.response
) {
for (const route of this.#routes) {
if (route.matches(request)) {
try {
const response = await route.handle(
requestEvent,
responseHeaders,
this.#secure,
this.#keys,
);
if (response) {
const result = await this.#handleStatus(
response.status,
requestEvent,
response.headers,
response,
);
resolve(result ?? response);
const measure = performance.measure(
`handle ${uid}`,
`${HANDLE_START} ${uid}`,
);
this.dispatchEvent(
new HandledEvent({ request, route, response, measure }),
);
return;
}
} catch (error) {
let response = await route.error(request, error);
const status = isHttpError(error)
? error.status
: response?.status ?? Status.InternalServerError;
response = await this.#handleStatus(
status,
requestEvent,
responseHeaders,
response,
);
if (!response) {
response = this.#error(request, error, true);
}
resolve(response);
this.#handling.delete(promise);
const measure = performance.measure(
`handle ${uid}`,
`${HANDLE_START} ${uid}`,
);
this.dispatchEvent(
new HandledEvent({ request, route, response, measure }),
);
return;
}
}
}
} else if (routerRequestEvent.response) {
const { response } = routerRequestEvent;
const result = await this.#handleStatus(
response.status,
requestEvent,
responseHeaders,
response,
);
resolve(result ?? response);
this.#handling.delete(promise);