@chidchanun/bcp 0.1.6 → 0.1.8

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.
@@ -0,0 +1,82 @@
1
+ import {
2
+ requestUrl,
3
+ } from "./request-context.js";
4
+
5
+ export type RedirectStatus =
6
+ | 301
7
+ | 302
8
+ | 303
9
+ | 307
10
+ | 308;
11
+
12
+ export function json<T>(
13
+ data: T,
14
+ init?: ResponseInit
15
+ ): Response {
16
+ return Response.json(
17
+ data,
18
+ init
19
+ );
20
+ }
21
+
22
+ export async function redirect(
23
+ destination:
24
+ string |
25
+ URL,
26
+ status:
27
+ RedirectStatus =
28
+ 307
29
+ ): Promise<Response> {
30
+ assertRedirectStatus(
31
+ status
32
+ );
33
+
34
+ const base =
35
+ await requestUrl();
36
+
37
+ const target =
38
+ destination instanceof URL
39
+ ? new URL(
40
+ destination.href
41
+ )
42
+ : new URL(
43
+ destination,
44
+ base
45
+ );
46
+
47
+ if (
48
+ target.protocol !== "http:" &&
49
+ target.protocol !== "https:"
50
+ ) {
51
+ throw new Error(
52
+ `BCP Framework: redirect only supports http and https URLs, received "${target.protocol}".`
53
+ );
54
+ }
55
+
56
+ return new Response(
57
+ null,
58
+ {
59
+ status,
60
+ headers: {
61
+ Location:
62
+ target.href,
63
+ },
64
+ }
65
+ );
66
+ }
67
+
68
+ function assertRedirectStatus(
69
+ status: number
70
+ ): asserts status is RedirectStatus {
71
+ if (
72
+ status !== 301 &&
73
+ status !== 302 &&
74
+ status !== 303 &&
75
+ status !== 307 &&
76
+ status !== 308
77
+ ) {
78
+ throw new Error(
79
+ `BCP Framework: invalid redirect status ${status}. Use 301, 302, 303, 307 or 308.`
80
+ );
81
+ }
82
+ }