-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.ts
More file actions
1328 lines (1281 loc) · 40.1 KB
/
Copy pathrouter.ts
File metadata and controls
1328 lines (1281 loc) · 40.1 KB
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
import type { Effect } from "@baetheus/fun/effect";
import type { StatusCode, StatusText } from "./status.ts";
import type { Header } from "./unstable-header.ts";
import * as E from "@baetheus/fun/effect";
import { match } from "@baetheus/fun/either";
import { map as mapRecord } from "@baetheus/fun/record";
import { identity, pipe } from "@baetheus/fun/fn";
import { HEADER } from "./unstable-header.ts";
import { STATUS_CODE, STATUS_TEXT } from "./status.ts";
/**
* HTTP header constants re-exported from Deno's standard library.
*
* Provides easy access to common HTTP header names with proper typing.
*
* @example
* ```ts
* import { HEADER } from "./router.ts";
*
* const headers = new Headers();
* headers.set(HEADER.ContentType, "application/json");
* ```
*
* @since 0.1.0
*/
export { HEADER };
/**
* HTTP status code constants re-exported from Deno's standard library.
*
* Provides numerical HTTP status codes for use in responses.
*
* @example
* ```ts
* import { STATUS_CODE, response_init } from "./router.ts";
*
* const notFoundInit = response_init(STATUS_CODE.NotFound);
* ```
*
* @since 0.1.0
*/
export { STATUS_CODE };
/**
* HTTP status text constants re-exported from Deno's standard library.
*
* Provides the standard text descriptions for HTTP status codes.
*
* @example
* ```ts
* import { STATUS_TEXT, STATUS_CODE } from "./router.ts";
*
* console.log(STATUS_TEXT[STATUS_CODE.OK]); // "OK"
* ```
*
* @since 0.1.0
*/
export { STATUS_TEXT };
/**
* Creates a ResponseInit object with the specified status, headers, and status text.
*
* This utility function simplifies the creation of ResponseInit objects by providing
* sensible defaults and ensuring proper typing for status codes and headers.
*
* @param status - The HTTP status code for the response
* @param headers - Optional headers to include in the response (defaults to empty array)
* @param statusText - Optional status text (defaults to standard text for the status code)
* @returns A ResponseInit object ready to be used with the Response constructor
*
* @example
* ```ts
* import { response_init, STATUS_CODE, HEADER } from "./router.ts";
*
* const init = response_init(STATUS_CODE.NotFound);
* const initWithHeaders = response_init(
* STATUS_CODE.OK,
* [[HEADER.ContentType, "application/json"]]
* );
* ```
*
* @since 0.1.0
*/
export function response_init(
status: StatusCode,
headers: HeadersInit = [],
statusText: StatusText = STATUS_TEXT[status],
): ResponseInit {
return { status, statusText, headers };
}
/**
* Creates a new Response with the given body and response initialization options.
*
* This is a convenience wrapper around the native Response constructor that provides
* a sensible default ResponseInit with a 200 OK status.
*
* @param body - The body content for the response
* @param res - Optional ResponseInit configuration (defaults to 200 OK status)
* @returns A new Response object
*
* @example
* ```ts
* import { response, response_init, STATUS_CODE } from "./router.ts";
*
* const okResponse = response("Hello World");
* const notFoundResponse = response(
* "Not Found",
* response_init(STATUS_CODE.NotFound)
* );
* ```
*
* @since 0.1.0
*/
export function response(
body: BodyInit,
res: ResponseInit = response_init(STATUS_CODE.OK),
): Response {
return new Response(body, res);
}
/**
* Creates an HTML response with the appropriate Content-Type header.
*
* This function automatically sets the Content-Type header to "text/html; charset=utf-8"
* and creates a Response object with the provided HTML content.
*
* @param content - The HTML content to send in the response body
* @param status - Optional HTTP status code (defaults to 200 OK)
* @returns A Response object configured for HTML content
*
* @example
* ```ts
* import { html, STATUS_CODE } from "./router.ts";
*
* const homePage = html("<h1>Welcome!</h1><p>Hello World</p>");
* const errorPage = html(
* "<h1>Not Found</h1><p>The page was not found</p>",
* STATUS_CODE.NotFound
* );
* ```
*
* @since 0.1.0
*/
export function html(
content: BodyInit,
status: StatusCode = STATUS_CODE.OK,
): Response {
return response(
content,
response_init(status, [[HEADER.ContentType, "text/html; charset=utf-8"]]),
);
}
/**
* Creates a JSON response with the appropriate Content-Type header.
*
* This function automatically sets the Content-Type header to "application/json; charset=utf-8"
* and creates a Response object with the provided JSON content.
*
* @param content - The JSON content to send in the response body
* @param status - Optional HTTP status code (defaults to 200 OK)
* @returns A Response object configured for JSON content
*
* @example
* ```ts
* import { json, STATUS_CODE } from "./router.ts";
*
* const user = { id: 1, name: "John Doe", email: "john@example.com" };
* const userResponse = json(JSON.stringify(user));
* const errorResponse = json(
* JSON.stringify({ error: "User not found" }),
* STATUS_CODE.NotFound
* );
* ```
*
* @since 0.1.0
*/
export function json(
content: BodyInit,
status: StatusCode = STATUS_CODE.OK,
): Response {
return response(
content,
response_init(status, [[
HEADER.ContentType,
"application/json; charset=utf-8",
]]),
);
}
/**
* Creates a plain text response.
*
* This function creates a Response object with plain text content. The Content-Type
* header defaults to "text/plain" as per the Response constructor's default behavior.
*
* @param content - The text content to send in the response body
* @param status - Optional HTTP status code (defaults to 200 OK)
* @returns A Response object configured for plain text content
*
* @example
* ```ts
* import { text, STATUS_CODE } from "./router.ts";
*
* const greeting = text("Hello, World!");
* const error = text("Something went wrong", STATUS_CODE.InternalServerError);
* ```
*
* @since 0.1.0
*/
export function text(
content: BodyInit,
status: StatusCode = STATUS_CODE.OK,
): Response {
// new Response() defaults to text/plain
return response(content, response_init(status));
}
/**
* Creates a function that modifies headers on a Response object.
*
* This higher-order function takes a modification function and returns a new function
* that applies the modification to the headers of any Response object passed to it.
* This enables functional composition for header manipulation.
*
* @param modify_fn - A function that receives Headers object and modifies it
* @returns A function that takes a Response and returns the same Response with modified headers
*
* @example
* ```ts
* import { modify_header, text, HEADER } from "./router.ts";
*
* const addCacheControl = modify_header((headers) => {
* headers.set(HEADER.CacheControl, "max-age=3600");
* });
*
* const response = addCacheControl(text("Cached content"));
* ```
*
* @since 0.1.0
*/
export function modify_header(
modify_fn: (h: Headers) => void,
): (res: Response) => Response {
return (res) => {
modify_fn(res.headers);
return res;
};
}
/**
* A tuple representing a single HTTP header as a key-value pair.
*
* This type defines the structure for representing an HTTP header with its name and value,
* used in functions that manipulate multiple headers.
*
* @example
* ```ts
* import { HeaderPair, HEADER } from "./router.ts";
*
* const contentTypeHeader: HeaderPair = [HEADER.ContentType, "application/json"];
* const cacheControlHeader: HeaderPair = [HEADER.CacheControl, "no-cache"];
* ```
*
* @since 0.1.0
*/
export type HeaderPair = [header: Header, value: string];
/**
* A tuple of one or more HeaderPair tuples for batch header operations.
*
* This type ensures that at least one header pair is provided when using functions
* that manipulate multiple headers at once, preventing empty header operations.
*
* @example
* ```ts
* import { HeaderPairs, HEADER } from "./router.ts";
*
* const headers: HeaderPairs = [
* [HEADER.ContentType, "application/json"],
* [HEADER.CacheControl, "max-age=3600"],
* [HEADER.AccessControlAllowOrigin, "*"]
* ];
* ```
*
* @since 0.1.0
*/
export type HeaderPairs = [HeaderPair, ...HeaderPair[]];
/**
* Creates a function that sets multiple headers on a Response object.
*
* This function uses the Headers.set() method, which replaces any existing values
* for the specified headers. It's built on top of modify_header for functional composition.
*
* @param pairs - One or more header-value pairs to set on the response
* @returns A function that takes a Response and returns it with the specified headers set
*
* @example
* ```ts
* import { set_headers, text, HEADER } from "./router.ts";
*
* const addApiHeaders = set_headers(
* [HEADER.ContentType, "application/json"],
* [HEADER.AccessControlAllowOrigin, "*"],
* [HEADER.CacheControl, "no-cache"]
* );
*
* const response = addApiHeaders(text("API Response"));
* ```
*
* @since 0.1.0
*/
export function set_headers(
...pairs: HeaderPairs
): (res: Response) => Response {
return modify_header((headers) =>
pairs.forEach(([header, value]) => headers.set(header, value))
);
}
/**
* Creates a function that appends multiple headers to a Response object.
*
* This function uses the Headers.append() method, which adds values to existing headers
* or creates new ones if they don't exist. Useful for headers that can have multiple values.
*
* @param pairs - One or more header-value pairs to append to the response
* @returns A function that takes a Response and returns it with the specified headers appended
*
* @example
* ```ts
* import { append_header, text, HEADER } from "./router.ts";
*
* const addCorsHeaders = append_header(
* [HEADER.AccessControlAllowOrigin, "https://example.com"],
* [HEADER.AccessControlAllowMethods, "GET, POST"]
* );
*
* const response = addCorsHeaders(text("CORS enabled response"));
* ```
*
* @since 0.1.0
*/
export function append_header(
...pairs: HeaderPairs
): (res: Response) => Response {
return modify_header((headers) =>
pairs.forEach(([header, value]) => headers.append(header, value))
);
}
/**
* Creates a function that deletes multiple headers from a Response object.
*
* This function uses the Headers.delete() method to remove the specified headers
* from a response. Useful for cleaning up unwanted headers before sending responses.
*
* @param keys - One or more header names to delete from the response
* @returns A function that takes a Response and returns it with the specified headers removed
*
* @example
* ```ts
* import { delete_header, text, HEADER } from "./router.ts";
*
* const removeHeaders = delete_header(
* HEADER.Server,
* HEADER.Date
* );
*
* const response = removeHeaders(text("Clean response"));
* ```
*
* @since 0.1.0
*/
export function delete_header(
...keys: [Header, ...Header[]]
): (res: Response) => Response {
return modify_header((headers) => keys.forEach((key) => headers.delete(key)));
}
type Rec<Key extends string | symbol = string, Value = string> = {
readonly [K in Key]: Value;
};
/**
* A comprehensive collection of HTTP methods supported by the router.
* This constant object provides all standard HTTP methods as defined
* in RFC specifications, including WebDAV methods and other extensions.
*
* @example
* ```ts
* import { METHODS } from "@baetheus/pick/router";
*
* console.log(METHODS.GET); // "GET"
* console.log(METHODS.POST); // "POST"
* console.log(METHODS.DELETE); // "DELETE"
* ```
*
* @since 0.1.0
*/
export const METHODS = {
"ACL": "ACL",
"BIND": "BIND",
"CHECKOUT": "CHECKOUT",
"CONNECT": "CONNECT",
"COPY": "COPY",
"DELETE": "DELETE",
"GET": "GET",
"HEAD": "HEAD",
"LINK": "LINK",
"LOCK": "LOCK",
"MERGE": "MERGE",
"MKACTIVITY": "MKACTIVITY",
"MKCALENDAR": "MKCALENDAR",
"MKCOL": "MKCOL",
"MOVE": "MOVE",
"NOTIFY": "NOTIFY",
"OPTIONS": "OPTIONS",
"PATCH": "PATCH",
"POST": "POST",
"PROPFIND": "PROPFIND",
"PROPPATCH": "PROPPATCH",
"PURGE": "PURGE",
"PUT": "PUT",
"REBIND": "REBIND",
"REPORT": "REPORT",
"SEARCH": "SEARCH",
"SOURCE": "SOURCE",
"SUBSCRIBE": "SUBSCRIBE",
"TRACE": "TRACE",
"UNBIND": "UNBIND",
"UNLINK": "UNLINK",
"UNLOCK": "UNLOCK",
"UNSUBSCRIBE": "UNSUBSCRIBE",
} as const;
/**
* A type representing all valid HTTP methods supported by the router.
* This is a union type of all keys from the METHODS constant, providing
* type safety when working with HTTP methods in route definitions.
*
* @example
* ```ts
* import type { Methods } from "./router.ts";
*
* // Type-safe method specification
* const method: Methods = "GET"; // ✓ Valid
* // const invalidMethod: Methods = "INVALID"; // ✗ TypeScript error
*
* // Use in function parameters
* function handleMethod(method: Methods) {
* // method is now type-safe
* return method;
* }
* ```
*
* @since 0.1.0
*/
export type Methods = keyof typeof METHODS;
/**
* Parses a URL path pattern into a structured type representing the path parameters.
* This recursive conditional type analyzes path strings with parameter placeholders
* and wildcards to create a type-safe object structure for accessing matched path segments.
*
* The type supports:
* - Named parameters with `:name` syntax (e.g., `:id`, `:userId`)
* - Wildcard segments with `*` syntax (captured as array of strings)
* - Static path segments (ignored in the result type)
* - HTTP method prefix (ignored in the result type)
*
* @example
* ```ts
* import type { ParsePath } from "@baetheus/pick/router";
*
* // Parses to { id: string }
* type UserParams = ParsePath<"GET /users/:id">;
*
* // Parses to { year: string; month: string; slug: string }
* type BlogParams = ParsePath<"GET /blog/:year/:month/:slug">;
*
* // Parses to { "0": readonly string[] }
* type WildcardParams = ParsePath<"GET /files/*">;
* ```
*
* @since 0.1.0
*/
export type ParsePath<
P extends string,
// deno-lint-ignore ban-types
R extends Record<string, string> = {},
> = P extends `${Methods} /${infer Part}` ? ParsePath<Part>
: P extends `:${infer Key}/${infer Part}` ? ParsePath<Part, R & Rec<Key>>
: P extends `*/${infer Part}`
? ParsePath<Part, R & Rec<"0", readonly string[]>>
: P extends `${string}/${infer Part}` ? ParsePath<Part, R>
: P extends `:${infer Key}` ? ParsePath<"", R & Rec<Key>>
: P extends `*` ? ParsePath<"", R & Rec<"0", readonly string[]>>
: { readonly [K in keyof R]: R[K] };
/**
* A template literal type representing a complete route definition string.
* This type ensures that route strings follow the correct format of
* "METHOD /path" where METHOD is one of the supported HTTP methods
* and path is a valid URL path string.
*
* The type provides compile-time validation that route strings are
* properly formatted and use valid HTTP methods.
*
* @example
* ```ts
* import type { RouteString } from "./router.ts";
*
* // Valid route strings
* const getUsers: RouteString = "GET /api/users";
* const postUser: RouteString = "POST /api/users";
* const wildcardRoute: RouteString = "GET /files/*";
*
* // Invalid - would cause TypeScript error
* // const invalid: RouteString = "GET"; // Missing path
* // const invalid2: RouteString = "INVALID /path"; // Invalid method
* ```
*
* @since 0.1.0
*/
export type RouteString = `${Methods} /${string}`;
/**
* Creates a properly typed route string from an HTTP method and path.
*
* This utility function combines an HTTP method and path string into a RouteString
* type, ensuring proper formatting with a space separator. The resulting string
* follows the "METHOD /path" format expected by the router system.
*
* @param method - The HTTP method to use in the route string
* @param path - The URL path pattern for the route
* @returns A properly formatted route string with type safety
*
* @example
* ```ts
* import { route_string } from "./router.ts";
*
* const userRoute = route_string("GET", "/users/:id");
* const postRoute = route_string("POST", "/users");
* const wildcardRoute = route_string("GET", "/files/*");
* ```
*
* @since 0.1.0
*/
export function route_string(method: Methods, path: string): RouteString {
return `${method} /${path}` as RouteString;
}
/**
* A function type for logging messages at various levels.
*
* LogFn represents a variadic function that accepts any number of arguments
* of any type and returns void. This type is used for all logging functions
* in the Logger interface, providing flexibility for different logging implementations.
*
* @example
* ```ts
* import type { LogFn } from "./router.ts";
*
* const simpleLogger: LogFn = (message: string, ...args: any[]) => {
* console.log(`[${new Date().toISOString()}] ${message}`, ...args);
* };
*
* const structuredLogger: LogFn = (...data: any[]) => {
* const entry = {
* timestamp: new Date().toISOString(),
* level: "info",
* data: data
* };
* console.log(JSON.stringify(entry));
* };
* ```
*
* @since 0.1.0
*/
// deno-lint-ignore no-explicit-any
export type LogFn = (...data: any[]) => void;
/**
* An interface defining a complete logging system with multiple severity levels.
*
* The Logger interface provides methods for logging at different levels of severity,
* from most critical (fatal) to least critical (trace). Each logging method accepts
* a LogFn function that can handle variadic arguments for flexible logging formats.
*
* This interface allows for easy mocking in tests and custom logging implementations
* while maintaining consistent logging behavior across the router system.
*
* @example
* ```ts
* import type { Logger } from "./router.ts";
* import type { LogFn } from "./router.ts";
*
* const customLogger: Logger = {
* fatal: (message: string, error?: Error) => {
* console.error(`FATAL: ${message}`, error);
* // Send to external logging service
* },
* error: (message: string, ...args: any[]) => {
* console.error(`ERROR: ${message}`, ...args);
* },
* warn: (message: string, ...args: any[]) => {
* console.warn(`WARN: ${message}`, ...args);
* },
* info: (message: string, ...args: any[]) => {
* console.info(`INFO: ${message}`, ...args);
* },
* debug: (message: string, ...args: any[]) => {
* console.debug(`DEBUG: ${message}`, ...args);
* },
* trace: (message: string, ...args: any[]) => {
* console.trace(`TRACE: ${message}`, ...args);
* }
* };
* ```
*
* @since 0.1.0
*/
export type Logger = {
readonly fatal: LogFn;
readonly error: LogFn;
readonly warn: LogFn;
readonly info: LogFn;
readonly debug: LogFn;
readonly trace: LogFn;
};
/**
* A default logger implementation that uses the browser/Deno console methods.
*
* This logger provides a standard implementation of the Logger interface using
* the global console object's methods for each logging level. It serves as a
* sensible default that can be overridden when creating contexts or routers
* that require custom logging behavior.
*
* All logging methods in this implementation map directly to their corresponding
* console methods with the same names.
*
* @example
* ```ts
* import { DEFAULT_LOGGER, context } from "./router.ts";
*
* // Use the default logger when creating contexts
* const ctx = context({ userId: "123" }, DEFAULT_LOGGER);
*
* ctx.logger.info("User logged in:", ctx.state.userId);
* ctx.logger.error("Database connection failed");
* ctx.logger.debug("Processing request", { method: "GET", path: "/api/users" });
* ```
*
* @since 0.1.0
*/
export const DEFAULT_LOGGER: Logger = {
fatal: console.error,
error: console.error,
warn: console.warn,
info: console.info,
debug: console.debug,
trace: console.trace,
};
function noop(): void {}
/**
* A logger implementation that silently discards all log messages.
*
* Useful for testing or when logging should be completely disabled.
*
* @example
* ```ts
* import { NOOP_LOGGER, context } from "@baetheus/pick/router";
*
* const ctx = context({ userId: "123" }, NOOP_LOGGER);
* ctx.logger.info("This message is discarded");
* ```
*
* @since 0.1.0
*/
export const NOOP_LOGGER: Logger = {
fatal: noop,
error: noop,
warn: noop,
info: noop,
debug: noop,
trace: noop,
};
/**
* The context object passed to route handlers, containing all the information
* needed to process a request. The context provides access to the original
* request, URL pattern matching results, and any shared state data.
*
* @example
* ```ts
* import type { Ctx } from "@baetheus/pick/router";
*
* type AppState = { db: Database };
*
* function handleRequest(ctx: Ctx<AppState>): Response {
* ctx.logger.info("Processing request");
* const db = ctx.state.db;
* return new Response("OK");
* }
* ```
*
* @since 0.1.0
*/
export type Ctx<D = unknown> = {
readonly logger: Logger;
readonly state: D;
};
/**
* Creates a context object for route handlers. The context encapsulates all
* the information needed to process a request, including the original request,
* URL pattern matching results, and shared state data.
*
* This function is typically used internally by the router when invoking
* route handlers, but can also be used directly when testing handlers or
* building custom routing logic.
*
* @param state The shared state data passed between routes.
* @param logger Optional logger instance (defaults to DEFAULT_LOGGER).
* @returns A context object that can be passed to route handlers.
*
* @example
* ```ts
* import { context, router, right } from "@baetheus/pick/router";
*
* const ctx = context({ count: 0 });
* const app = router(ctx, {
* routes: [right("GET /", () => new Response("Hello"))]
* });
* ```
*
* @since 0.1.0
*/
export function context<D = unknown>(
state: D,
logger: Logger = DEFAULT_LOGGER,
): Ctx<D> {
return { state, logger };
}
/**
* A type alias for the Effect used as route handlers in the router system.
* Route handlers are Effect functions that take a context containing the request,
* URL pattern matching results, and shared state, and return a Response wrapped
* in the Effect's error handling system.
*
* The Effect signature is:
* - Input state: [Request, URLPatternResult, Ctx<D>]
* - Error type: Response (failed responses become error values)
* - Success type: Response (successful responses become success values)
*
* @example
* ```ts
* import type { Handler } from "@baetheus/pick/router";
* import * as E from "@baetheus/fun/effect";
*
* const myHandler: Handler<{ db: Database }> = E.gets((req, result, ctx) => {
* return new Response("Hello from handler");
* });
* ```
*
* @since 0.1.0
*/
export type Handler<D = unknown> = Effect<
[Request, URLPatternResult, Ctx<D>],
Response,
Response
>;
/**
* Represents a complete route definition in the router system. A route
* consists of an HTTP method, URL pattern, compiled URLPattern for matching,
* and a handler function that processes matching requests.
*
* Routes are the core building blocks of the router, defining how different
* URL patterns and HTTP methods are handled. Each route can access shared
* state and provides type-safe parameter extraction from URLs.
*
* @example
* ```ts
* import type { Route } from "@baetheus/pick/router";
* import { right } from "@baetheus/pick/router";
*
* const userRoute: Route<{ db: Database }> = right(
* "GET /users/:id",
* (req, params, ctx) => new Response(`User: ${params.id}`)
* );
* ```
*
* @since 0.1.0
*/
export type Route<D = unknown> = {
readonly method: Methods;
readonly pathname: string;
readonly url_pattern: URLPattern;
readonly handler: Handler<D>;
// Here we will add input and output schemas at a later date.
};
/**
* A type alias for routes with untyped or unknown state. This is useful when
* working with collections of routes where the specific state type is not
* known or when building generic routing utilities that work with any route type.
*
* This type should be used sparingly in application code, as it loses the
* type safety benefits of the generic Route<D> type. It's primarily intended
* for library and utility functions that need to work with arbitrary routes.
*
* @example
* ```ts
* import type { AnyRoute } from "@baetheus/pick/router";
*
* function logRoutes(routes: AnyRoute[]): void {
* routes.forEach(r => console.log(`${r.method} ${r.pathname}`));
* }
* ```
*
* @since 0.1.0
*/
// deno-lint-ignore no-explicit-any
export type AnyRoute = Route<any>;
/**
* Creates a route definition from a route string and handler function.
* This is the low-level function for creating routes, handling the parsing
* of the route string into method and pathname components, and creating
* the URLPattern for request matching.
*
* For most use cases, the `right()` helper function is preferred as it
* provides better type safety and ergonomics for route definitions.
*
* @template D The type of shared state passed between routes.
* @param route_string A string in the format "METHOD /pathname" (e.g., "GET /users/:id").
* @param handler The route handler function that processes matching requests.
* @returns A complete route definition ready to be used in a router.
*
* @example
* ```ts
* import { route, router, right, context } from "./router.ts";
* import { right as rightEither, left as leftEither } from "@baetheus/fun/either";
* import { todo } from "@baetheus/fun/fn";
* import * as E from "@baetheus/fun/effect";
*
* type User = {
* id: string;
* name: string;
* email: string;
* }
*
* type Database = {
* findUser: (id: string) => Promise<User>;
* }
*
* // Create a route manually using the low-level API
* const userRoute = route<{ db: Database }>(
* "GET /users/:id",
* async (request, patternResult, ctx) => {
* const userId = patternResult.pathname.groups.id;
* if (!userId) {
* return [leftEither(new Response("User ID is required", { status: 400 })), ctx.state];
* }
* const user = await ctx.state.db.findUser(userId);
* return [rightEither(new Response(JSON.stringify(user))), ctx.state];
* }
* );
*
* // Use in a router
* const ctx = context({ db: { findUser: todo } });
* const appRouter = router(ctx, { routes: [userRoute] });
*
* // Alternative: use the right() helper for better ergonomics
* const betterRoute = right("GET /users/:id", (request, params) => {
* return new Response(`User ${params.id}`);
* });
* ```
*
* @since 0.1.0
*/
export function route<D>(
method: Methods,
path: string,
handler: Handler<D>,
): Route<D> {
const pathname = path.startsWith("/") ? path : `/${path}`;
return {
method,
pathname,
handler,
url_pattern: new URLPattern({ pathname }),
};
}
/**
* Creates a route with a handler that expects to return successful responses.
* This helper function provides better ergonomics than the low-level `route()`
* function by automatically handling path parameter extraction and Effect wrapping.
*
* The handler function receives both the context and parsed path parameters,
* and should return a Response directly (not wrapped in an Effect). The function
* automatically wraps the handler in the Effect system and handles path parsing.
*
* Use this function for the majority of route definitions as it provides the
* best balance of type safety and ergonomics.
*
* @template D The type of shared state passed between routes.
* @template R The route string type that determines the structure of path parameters.
* @param route_string A string in the format "METHOD /pathname" with parameter placeholders.
* @param handler A function that receives context and parsed path parameters, returns a Response.
* @returns A complete route definition ready to be used in a router.
*
* @example
* ```ts
* import { right } from "./router.ts";
*
* // Simple route without parameters
* const homeRoute = right("GET /", (ctx) => {
* return new Response("Welcome home!");
* });
*
* // Route with path parameters
* const userRoute = right("GET /users/:id", (_, params) => {
* const userId = params.id; // Type-safe access to path parameter
* return new Response(`User ID: ${userId}`);
* });
*
* // Route with multiple parameters
* const blogRoute = right("GET /:year/:month/:slug", (_, params) => {
* const { year, month, slug } = params;
* return new Response(`Blog post: ${year}/${month}/${slug}`);
* });
*
* // Route with wildcard
* const fileRoute = right("GET /files/:path/*", (_, params) => {
* const { path, 0: segments } = params;
* return new Response(`File: ${path}, segments: ${segments.join('/')}`);
* });
* ```
*
* @since 0.1.0
*/
export function right<D, R extends RouteString>(
route_string: R,
handler: (
request: Request,
path: ParsePath<R>,
ctx: Ctx<D>,
) => Response | Promise<Response>,
): Route<D> {
const [method, path_name] = route_string.split(" ") as [Methods, string];
return route(
method,
path_name,
E.gets(handler) as unknown as Handler<D>,
);
}
/**
* Creates a route with a handler that expects to return error responses.
* This helper function is similar to `right()` but wraps the handler's return
* value as an error (Left) in the Effect system instead of a success (Right).
*
* This is useful for routes that are designed to handle error conditions
* or when you want to explicitly handle failures in your routing logic.
* The handler function still receives the same context and path parameters,
* but the returned Response will be treated as an error response.
*
* @template D The type of shared state passed between routes.
* @template R The route string type that determines the structure of path parameters.
* @param route_string A string in the format "METHOD /pathname" with parameter placeholders.
* @param handler A function that receives context and parsed path parameters, returns a Response.
* @returns A complete route definition ready to be used in a router.
*
* @example
* ```ts
* import { left } from "./router.ts";
*
* // Route that always returns error responses
* const errorRoute = left("GET /error", () => {
* return new Response("Something went wrong", { status: 500 });
* });
*
* // Conditional error handling
* const conditionalErrorRoute = left("GET /admin/:action", (request, params) => {
* const user = request.headers.get("authorization");
* if (!user) {
* return new Response("Unauthorized", { status: 403 });
* }