ovr 4.6.0 → 6.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 (90) hide show
  1. package/dist/LICENSE.md +26 -0
  2. package/dist/app/index.d.ts +55 -103
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +67 -145
  5. package/dist/context/index.d.ts +138 -0
  6. package/dist/context/index.d.ts.map +1 -0
  7. package/dist/context/index.js +218 -0
  8. package/dist/cookie/index.d.ts +121 -0
  9. package/dist/cookie/index.d.ts.map +1 -0
  10. package/dist/cookie/index.js +56 -0
  11. package/dist/index.d.ts +6 -8
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +4 -7
  14. package/dist/jsx/{intrinsic-elements.d.ts → elements.d.ts} +14 -7
  15. package/dist/jsx/elements.d.ts.map +1 -0
  16. package/dist/jsx/index.d.ts +37 -52
  17. package/dist/jsx/index.d.ts.map +1 -1
  18. package/dist/jsx/index.js +71 -197
  19. package/dist/middleware/index.d.ts +22 -0
  20. package/dist/middleware/index.d.ts.map +1 -0
  21. package/dist/multipart/index.d.ts +122 -0
  22. package/dist/multipart/index.d.ts.map +1 -0
  23. package/dist/multipart/index.js +341 -0
  24. package/dist/render/index.d.ts +78 -0
  25. package/dist/render/index.d.ts.map +1 -0
  26. package/dist/render/index.js +248 -0
  27. package/dist/route/index.d.ts +147 -0
  28. package/dist/route/index.d.ts.map +1 -0
  29. package/dist/route/index.js +126 -0
  30. package/dist/trie/index.d.ts +31 -26
  31. package/dist/trie/index.d.ts.map +1 -1
  32. package/dist/trie/index.js +71 -80
  33. package/dist/util/index.d.ts +38 -0
  34. package/dist/util/index.d.ts.map +1 -0
  35. package/dist/util/index.js +88 -0
  36. package/package.json +4 -4
  37. package/src/app/index.ts +128 -265
  38. package/src/context/index.ts +262 -0
  39. package/src/cookie/index.ts +189 -0
  40. package/src/index.ts +6 -8
  41. package/src/jsx/{intrinsic-elements.ts → elements.ts} +14 -7
  42. package/src/jsx/index.ts +81 -222
  43. package/src/middleware/index.ts +29 -0
  44. package/src/multipart/index.ts +486 -0
  45. package/src/render/index.ts +300 -0
  46. package/src/route/index.ts +332 -0
  47. package/src/trie/index.ts +90 -107
  48. package/src/util/index.ts +112 -0
  49. package/dist/app/context.d.ts +0 -147
  50. package/dist/app/context.d.ts.map +0 -1
  51. package/dist/app/context.js +0 -283
  52. package/dist/app/helper/get.d.ts +0 -30
  53. package/dist/app/helper/get.d.ts.map +0 -1
  54. package/dist/app/helper/get.js +0 -33
  55. package/dist/app/helper/index.d.ts +0 -55
  56. package/dist/app/helper/index.d.ts.map +0 -1
  57. package/dist/app/helper/index.js +0 -96
  58. package/dist/app/helper/post.d.ts +0 -35
  59. package/dist/app/helper/post.d.ts.map +0 -1
  60. package/dist/app/helper/post.js +0 -15
  61. package/dist/app/memo/index.d.ts +0 -12
  62. package/dist/app/memo/index.d.ts.map +0 -1
  63. package/dist/app/memo/index.js +0 -34
  64. package/dist/app/mw/csrf.d.ts +0 -23
  65. package/dist/app/mw/csrf.d.ts.map +0 -1
  66. package/dist/app/mw/csrf.js +0 -30
  67. package/dist/jsx/chunk/index.d.ts +0 -38
  68. package/dist/jsx/chunk/index.d.ts.map +0 -1
  69. package/dist/jsx/chunk/index.js +0 -69
  70. package/dist/jsx/intrinsic-elements.d.ts.map +0 -1
  71. package/dist/jsx/merge-async-generators.d.ts +0 -14
  72. package/dist/jsx/merge-async-generators.d.ts.map +0 -1
  73. package/dist/jsx/merge-async-generators.js +0 -42
  74. package/dist/types/index.d.ts +0 -17
  75. package/dist/types/index.d.ts.map +0 -1
  76. package/dist/util/hash.d.ts +0 -11
  77. package/dist/util/hash.d.ts.map +0 -1
  78. package/dist/util/hash.js +0 -16
  79. package/src/app/context.ts +0 -365
  80. package/src/app/helper/get.ts +0 -46
  81. package/src/app/helper/index.ts +0 -174
  82. package/src/app/helper/post.ts +0 -54
  83. package/src/app/memo/index.ts +0 -40
  84. package/src/app/mw/csrf.ts +0 -32
  85. package/src/jsx/chunk/index.ts +0 -79
  86. package/src/jsx/merge-async-generators.ts +0 -47
  87. package/src/types/index.ts +0 -42
  88. package/src/util/hash.ts +0 -17
  89. /package/dist/jsx/{intrinsic-elements.js → elements.js} +0 -0
  90. /package/dist/{types → middleware}/index.js +0 -0
package/src/app/index.ts CHANGED
@@ -1,179 +1,99 @@
1
- import { type Params, Route, Trie } from "../trie/index.js";
2
- import type {
3
- DeepArray,
4
- ExtractMultiParams,
5
- ExtractParams,
6
- } from "../types/index.js";
7
- import { Context } from "./context.js";
8
- import { Get } from "./helper/get.js";
9
- import { Post } from "./helper/post.js";
10
- import { AsyncLocalStorage } from "node:async_hooks";
11
-
12
- export type Middleware<P extends Params = Params> = (
13
- context: Context<P>,
14
- next: () => Promise<void>,
15
- ) => any;
16
-
17
- export type TrailingSlash = "always" | "never" | "ignore";
18
-
19
- type Method =
20
- | "GET"
21
- | "HEAD"
22
- | "POST"
23
- | "PUT"
24
- | "DELETE"
25
- | "CONNECT"
26
- | "OPTIONS"
27
- | "TRACE"
28
- | "PATCH"
29
- | (string & {});
30
-
31
- type UnmatchedContext<P extends Params = Params> = Omit<Context<P>, "route"> &
32
- // route might be defined
33
- Partial<Pick<Context<P>, "route">>;
34
-
35
- export type ErrorHandler<P extends Params = Params> =
36
- | ((context: UnmatchedContext<P>, error: unknown) => any)
37
- | null;
1
+ import { Context } from "../context/index.js";
2
+ import type { Middleware } from "../middleware/index.js";
3
+ import type { Multipart } from "../multipart/index.js";
4
+ import { Route } from "../route/index.js";
5
+ import { Trie } from "../trie/index.js";
6
+ import type { Util } from "../util/index.js";
7
+
8
+ export namespace App {
9
+ export namespace Options {
10
+ /** Trailing slash preference */
11
+ export type TrailingSlash = "always" | "never" | "ignore";
12
+ }
38
13
 
39
- export type NotFoundHandler<P extends Params = Params> = (
40
- context: UnmatchedContext<P>,
41
- ) => any;
14
+ /** Configuration options */
15
+ export type Options = {
16
+ /**
17
+ * Basic
18
+ * [cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)
19
+ * protection that checks the request's `method`, and its
20
+ * [`Sec-Fetch-Site`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)
21
+ * and [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin)
22
+ * headers.
23
+ *
24
+ * More robust protection requires a stateful server or a database to store
25
+ * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
26
+ *
27
+ * @default true
28
+ */
29
+ readonly csrf?: boolean;
30
+
31
+ /**
32
+ * - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
33
+ * - `"always"` - Not found requests without a trailing slash will be redirected to the same path with a trailing slash
34
+ * - `"ignore"` - no redirects (not recommended, bad for SEO)
35
+ *
36
+ * [Trailing Slash for Frameworks by Bjorn Lu](https://bjornlu.com/blog/trailing-slash-for-frameworks)
37
+ *
38
+ * @default "never"
39
+ */
40
+ readonly trailingSlash?: Options.TrailingSlash;
41
+
42
+ /**
43
+ * Multipart form data options
44
+ * (overridden by options passed into `Context.form(options)`)
45
+ */
46
+ readonly form?: Multipart.Options;
47
+ };
48
+ }
42
49
 
50
+ /** Web server application */
43
51
  export class App {
44
- // allows for users to put other properties on the app
45
- [key: string | symbol | number]: any;
46
-
47
- /** Built tries per HTTP method. */
48
- #trieMap = new Map<Method, Trie<Middleware[]>>();
49
-
50
- /** Added routes per HTTP method. */
51
- #routesMap = new Map<Method, Route<Middleware[]>[]>();
52
+ /** Route trie */
53
+ readonly #trie = new Trie();
52
54
 
53
- /** Global middleware. */
54
- #use: Middleware[] = [];
55
-
56
- /**
57
- * - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
58
- * - `"always"` - Not found requests without a trailing slash will be redirected to the same path with a trailing slash
59
- * - `"ignore"` - no redirects (not recommended, bad for SEO)
60
- *
61
- * [Trailing Slash for Frameworks by Bjorn Lu](https://bjornlu.com/blog/trailing-slash-for-frameworks)
62
- *
63
- * @default "never"
64
- */
65
- trailingSlash: TrailingSlash = "never";
66
-
67
- /**
68
- * Base HTML to inject the `head` and `page` elements into.
69
- *
70
- * @default
71
- *
72
- * ```html
73
- * <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>
74
- * ```
75
- */
76
- base =
77
- '<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>';
55
+ /** Global middleware */
56
+ readonly #global: Middleware[] = [];
78
57
 
79
- /**
80
- * Assign a handler to run when an `Error` is thrown.
81
- *
82
- * If not set, `Error` will be thrown. This might be desired
83
- * if your server already includes error handling. Set in `config.start`
84
- * to handle errors globally.
85
- *
86
- * @default null
87
- */
88
- error: ErrorHandler = null;
58
+ /** App options */
59
+ readonly #options;
89
60
 
90
61
  /**
91
- * Middleware to run when no `body` or `status` has been set on the `context`.
92
- * Set to a new function to override the default.
62
+ * Create a new application.
93
63
  *
94
- * @default
95
- *
96
- * ```ts
97
- * (c) => c.html("Not found", 404)
98
- * ```
64
+ * @param options configuration options
99
65
  */
100
- notFound: NotFoundHandler = (c) => c.html("Not found", 404);
66
+ constructor(options?: App.Options) {
67
+ this.#options = Object.assign(
68
+ { csrf: true, trailingSlash: "never" },
69
+ options,
70
+ );
101
71
 
102
- /** Stores context per request. */
103
- static storage = new AsyncLocalStorage<Context>();
72
+ if (this.#options.csrf === true) this.#global.push(App.#csrf);
104
73
 
105
- /**
106
- * @param helpers `Helper` to add to `App`
107
- * @returns `App` instance
108
- */
109
- add(...helpers: DeepArray<Get | Post | Record<string, Get | Post>>[]) {
110
- for (const helper of helpers) {
111
- if (helper instanceof Array) {
112
- this.add(...helper);
113
- } else if (helper instanceof Get) {
114
- this.get(helper.pattern, ...helper.middleware);
115
- } else if (helper instanceof Post) {
116
- this.post(helper.pattern, ...helper.middleware);
117
- } else {
118
- this.add(...Object.values(helper));
119
- }
74
+ if (this.#options.trailingSlash !== "ignore") {
75
+ this.#global.push(App.#createTrailingSlash(this.#options.trailingSlash));
120
76
  }
121
-
122
- return this;
123
77
  }
124
78
 
125
79
  /**
126
- * Add global middleware.
127
- *
128
- * @param middleware
80
+ * @param routes Route or middleware to use
129
81
  * @returns `App` instance
130
82
  */
131
- use(...middleware: Middleware[]) {
132
- this.#use.push(...middleware);
133
- return this;
134
- }
135
-
136
- /**
137
- * @param method HTTP method
138
- * @param pattern Route pattern
139
- * @param middleware
140
- * @returns `App` instance
141
- */
142
- on<Pattern extends string>(
143
- method: Method | Method[],
144
- pattern: Pattern,
145
- ...middleware: Middleware<ExtractParams<Pattern>>[]
146
- ): this;
147
- /**
148
- * @param method HTTP method
149
- * @param patterns Array of route patterns
150
- * @param middleware
151
- * @returns `App` instance
152
- */
153
- on<Patterns extends string[]>(
154
- method: Method | Method[],
155
- patterns: [...Patterns],
156
- ...middleware: Middleware<ExtractMultiParams<Patterns>>[]
157
- ): this;
158
- on<PatternOrPatterns extends string | string[]>(
159
- method: Method | Method[],
160
- pattern: PatternOrPatterns,
161
- ...middleware: Middleware[]
83
+ use(
84
+ ...routes: Util.DeepArray<
85
+ Route | Middleware | Record<string, Route | Middleware>
86
+ >[]
162
87
  ) {
163
- if (!Array.isArray(method)) method = [method];
164
-
165
- let patterns: string[];
166
- if (!Array.isArray(pattern)) patterns = [pattern];
167
- else patterns = pattern;
168
-
169
- for (const p of patterns) {
170
- const route = new Route(p, middleware);
171
-
172
- for (const m of method) {
173
- const routes = this.#routesMap.get(m);
174
-
175
- if (routes) routes.push(route);
176
- else this.#routesMap.set(m, [route]);
88
+ for (const route of routes) {
89
+ if (route instanceof Route) {
90
+ this.#trie.add(route);
91
+ } else if (route instanceof Array) {
92
+ this.use(...route);
93
+ } else if (typeof route === "function") {
94
+ this.#global.push(route);
95
+ } else {
96
+ this.use(...Object.values(route));
177
97
  }
178
98
  }
179
99
 
@@ -181,120 +101,63 @@ export class App {
181
101
  }
182
102
 
183
103
  /**
184
- * @param pattern Route pattern
185
- * @param middleware
186
- * @returns `App` instance
187
- */
188
- get<Pattern extends string>(
189
- pattern: Pattern,
190
- ...middleware: Middleware<ExtractParams<Pattern>>[]
191
- ): this;
192
- /**
193
- * @param patterns Array of route patterns
194
- * @param middleware
195
- * @returns `App` instance
196
- */
197
- get<Patterns extends string[]>(
198
- patterns: [...Patterns],
199
- ...middleware: Middleware<ExtractMultiParams<Patterns>>[]
200
- ): this;
201
- get<PatternOrPatterns extends string | string[]>(
202
- patternOrPatterns: PatternOrPatterns,
203
- ...middleware: Middleware[]
204
- ) {
205
- return this.on("GET", patternOrPatterns as string, ...middleware);
206
- }
207
-
208
- /**
209
- * @param pattern Route pattern
210
- * @param middleware
211
- * @returns the router instance
212
- */
213
- post<Pattern extends string>(
214
- pattern: Pattern,
215
- ...middleware: Middleware<ExtractParams<Pattern>>[]
216
- ): this;
217
- /**
218
- * @param patterns Array of route patterns
219
- * @param middleware
220
- * @returns the router instance
221
- */
222
- post<Patterns extends string[]>(
223
- patterns: [...Patterns],
224
- ...middleware: Middleware<ExtractMultiParams<Patterns>>[]
225
- ): this;
226
- post<PatternOrPatterns extends string | string[]>(
227
- patternOrPatterns: PatternOrPatterns,
228
- ...middleware: Middleware[]
229
- ): this {
230
- return this.on("POST", patternOrPatterns as string, ...middleware);
231
- }
232
-
233
- /**
234
- * @param req [`Request` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
235
- * @returns [`Response` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response)
104
+ * Request a resource from the application.
105
+ *
106
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)
107
+ *
108
+ * @param resource [Resource](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#resource) to fetch
109
+ * @param options [Options](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#options) to apply to the request
110
+ * @returns Promise that resolves to the [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to the request
236
111
  */
237
- fetch = (req: Request): Promise<Response> => {
238
- const c = new Context(
239
- req,
240
- new URL(req.url),
241
- this.trailingSlash,
242
- this.base,
243
- this.error,
244
- this.notFound,
112
+ readonly fetch = async (
113
+ resource: RequestInfo | URL,
114
+ options?: RequestInit,
115
+ ) => {
116
+ const c = new Context(new Request(resource, options), this.#options);
117
+
118
+ return Context.compose(
119
+ Object.assign(
120
+ c,
121
+ // match
122
+ this.#trie.find(
123
+ // use GET for HEAD requests to find the correct route
124
+ (c.req.method === "HEAD" ? "GET" : c.req.method) + c.url.pathname,
125
+ ),
126
+ ),
127
+ this.#global.concat(c.route?.middleware ?? []),
245
128
  );
129
+ };
246
130
 
247
- return App.storage.run(c, async () => {
248
- try {
249
- // check to see if the method is already built
250
- let trie = this.#trieMap.get(req.method);
251
-
252
- if (!trie) {
253
- // check if there are any routes with the method
254
- const routes = this.#routesMap.get(req.method);
255
-
256
- if (routes) {
257
- // build trie
258
- trie = new Trie<Middleware[]>();
259
- for (const route of routes) trie.add(route);
260
- this.#trieMap.set(req.method, trie);
261
- }
262
- }
263
-
264
- if (trie) {
265
- const match = trie.find(c.url.pathname);
266
-
267
- if (match) {
268
- Object.assign(c, match);
131
+ /** Basic CSRF middleware */
132
+ static #csrf(c: Middleware.Context, next: Middleware.Next) {
133
+ if (
134
+ c.req.method === "GET" ||
135
+ c.req.method === "HEAD" ||
136
+ c.req.headers.get("sec-fetch-site") === "same-origin" ||
137
+ c.req.headers.get("origin") === c.url.origin
138
+ ) {
139
+ return next();
140
+ }
269
141
 
270
- const middleware = [...this.#use, ...match.route.store];
142
+ c.text("Forbidden", 403);
143
+ }
271
144
 
272
- // compose
273
- let i = -1;
274
- const dispatch = async (current: number): Promise<void> => {
275
- if (current <= i) throw new Error("next() called multiple times");
276
- i = current;
145
+ /** @returns Trailing slash middleware */
146
+ static #createTrailingSlash(mode: App.Options.TrailingSlash) {
147
+ return async (c: Context, next: Middleware.Next) => {
148
+ await next();
277
149
 
278
- if (middleware[current]) {
279
- const result: unknown = await middleware[current](c, () =>
280
- dispatch(current + 1),
281
- );
150
+ if (c.res.status && c.res.status !== 404) return;
282
151
 
283
- if (result instanceof Response) c.res(result.body, result);
284
- else if (result instanceof ReadableStream) c.body = result;
285
- else if (result != null) c.page(result);
286
- }
287
- };
152
+ const last = c.url.pathname.at(-1);
288
153
 
289
- await dispatch(0);
290
- }
291
- }
292
- } catch (error) {
293
- if (c.error) c.error(c, error);
294
- else throw error;
154
+ if (mode === "always" && last !== "/") {
155
+ c.url.pathname += "/";
156
+ c.redirect(c.url, 308);
157
+ } else if (mode === "never" && c.url.pathname !== "/" && last === "/") {
158
+ c.url.pathname = c.url.pathname.slice(0, -1);
159
+ c.redirect(c.url, 308);
295
160
  }
296
-
297
- return c.build();
298
- });
299
- };
161
+ };
162
+ }
300
163
  }
@@ -0,0 +1,262 @@
1
+ import type { App } from "../app/index.js";
2
+ import { Cookie } from "../cookie/index.js";
3
+ import { type Middleware } from "../middleware/index.js";
4
+ import { Multipart } from "../multipart/index.js";
5
+ import { Render } from "../render/index.js";
6
+ import { Route } from "../route/index.js";
7
+ import { type Trie } from "../trie/index.js";
8
+ import { Hash, Header } from "../util/index.js";
9
+
10
+ /** Properties to build the final `Response` with once middleware has run. */
11
+ class PreparedResponse {
12
+ /**
13
+ * `body` used to create the `Response`.
14
+ *
15
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body)
16
+ */
17
+ body?: BodyInit | null;
18
+
19
+ /**
20
+ * `status` used to create the `Response`.
21
+ *
22
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
23
+ */
24
+ status?: number;
25
+
26
+ /**
27
+ * `Headers` used to create the `Response`.
28
+ *
29
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Headers)
30
+ */
31
+ headers = new Headers();
32
+ }
33
+
34
+ export namespace Context {
35
+ // gives users access to Middleware.Context.Cookie.Options
36
+ export type Cookie = InstanceType<typeof Cookie>;
37
+ }
38
+
39
+ /**
40
+ * Request context.
41
+ *
42
+ * @template Params Parameters created from a route match
43
+ */
44
+ export class Context<Params extends Trie.Params = Trie.Params> {
45
+ /**
46
+ * Incoming `Request` to the server.
47
+ *
48
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
49
+ */
50
+ readonly req: Request;
51
+
52
+ /**
53
+ * Parsed `URL` created from `req.url`.
54
+ *
55
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL)
56
+ */
57
+ readonly url: URL;
58
+
59
+ /** Route pattern parameters */
60
+ readonly params: Params = {} as Params; // set after match
61
+
62
+ /** Matched `Route` instance */
63
+ readonly route?: Route;
64
+
65
+ /** Contains the arguments to used create the final `Response` */
66
+ readonly res = new PreparedResponse();
67
+
68
+ /** Get, set, and delete cookies. */
69
+ readonly cookie = new Cookie(this);
70
+
71
+ /** Forwarded app options */
72
+ readonly #options: App.Options;
73
+
74
+ // for reuse across methods
75
+ static readonly #textHtml = "text/html";
76
+ static readonly #utf8 = "charset=utf-8";
77
+ static readonly #htmlType = `${Context.#textHtml}; ${Context.#utf8}`;
78
+
79
+ /**
80
+ * Creates a new `Context` with the current `Request`.
81
+ *
82
+ * @param req Request
83
+ */
84
+ constructor(req: Request, options: App.Options = {}) {
85
+ this.req = req;
86
+ this.url = new URL(req.url);
87
+ this.#options = options;
88
+ }
89
+
90
+ /**
91
+ * Creates an HTML response.
92
+ *
93
+ * @param body HTML body
94
+ * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
95
+ */
96
+ html(body: BodyInit | null, status?: number) {
97
+ this.res.body = body;
98
+ this.res.status = status;
99
+ this.res.headers.set(Header.contentType, Context.#htmlType);
100
+ }
101
+
102
+ /**
103
+ * Creates a JSON response.
104
+ *
105
+ * @param data passed into JSON.stringify to create the body
106
+ * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
107
+ */
108
+ json(data: unknown, status?: number) {
109
+ this.res.body = JSON.stringify(data);
110
+ this.res.status = status;
111
+ this.res.headers.set(Header.contentType, "application/json");
112
+ }
113
+
114
+ /**
115
+ * Creates a plain text response.
116
+ *
117
+ * @param body response body
118
+ * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
119
+ */
120
+ text(body: BodyInit, status?: number) {
121
+ this.res.body = body;
122
+ this.res.status = status;
123
+ this.res.headers.set(Header.contentType, `text/plain; ${Context.#utf8}`);
124
+ }
125
+
126
+ /**
127
+ * Creates a redirect response.
128
+ *
129
+ * @param location redirect `Location` header
130
+ * @param status HTTP status code
131
+ *
132
+ * - [301 Moved Permanently](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301)
133
+ * - [302 Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) (default)
134
+ * - [303 See Other](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303)
135
+ * - [307 Temporary Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307)
136
+ * - [308 Permanent Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308)
137
+ */
138
+ redirect(location: string | URL, status: 301 | 302 | 303 | 307 | 308 = 302) {
139
+ this.res.body = null;
140
+ this.res.status = status;
141
+ this.res.headers.set("location", String(location));
142
+ }
143
+
144
+ /**
145
+ * Generates an etag from a hash of the string provided.
146
+ * If the etag matches, sets the response to not modified.
147
+ *
148
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag)
149
+ *
150
+ * @param string string to hash
151
+ * @returns `true` if the etag matches, `false` otherwise
152
+ */
153
+ etag(string: string) {
154
+ const etag = `"${Hash.djb2(string)}"`;
155
+
156
+ this.res.headers.set("etag", etag);
157
+
158
+ if (this.req.headers.get("if-none-match") === etag) {
159
+ this.res.body = null;
160
+ this.res.status = 304;
161
+
162
+ return true;
163
+ }
164
+
165
+ return false;
166
+ }
167
+
168
+ /**
169
+ * Parse multipart requests.
170
+ *
171
+ * @yields Multipart request `Part`(s)
172
+ *
173
+ * @example
174
+ *
175
+ * ```ts
176
+ * import { Route } from "ovr";
177
+ *
178
+ * const post = Route.post(async (c) => {
179
+ * for await (const part of c.form()) {
180
+ * if (part.name === "email") {
181
+ * // ...
182
+ * }
183
+ * }
184
+ * })
185
+ * ```
186
+ */
187
+ form(options?: Multipart.Options) {
188
+ return new Multipart(
189
+ this.req,
190
+ Object.assign({}, this.#options.form, options),
191
+ );
192
+ }
193
+
194
+ /**
195
+ * Dispatches the stack of `middleware` provided.
196
+ *
197
+ * @param middleware stack to run
198
+ * @param i current middleware index (default `0`)
199
+ * @returns return value of `middleware[i]`
200
+ */
201
+ async #run(middleware: Middleware<Params>[], i = 0) {
202
+ const mw = middleware[i];
203
+
204
+ if (!mw) return; // end of stack
205
+
206
+ const r = await mw(
207
+ this, // c
208
+ () => this.#run(middleware, i + 1), // next
209
+ );
210
+
211
+ // resolve the return value
212
+ if (r instanceof Response) {
213
+ // overwrite
214
+ this.res.body = r.body;
215
+ this.res.status = r.status;
216
+
217
+ // merge
218
+ for (const [name, header] of r.headers) {
219
+ this.res.headers.set(name, header);
220
+ }
221
+ } else if (r !== undefined) {
222
+ // something to stream
223
+ const type = this.res.headers.get(Header.contentType);
224
+
225
+ this.res.body = Render.stream(r, {
226
+ // other defined types are safe
227
+ safe: Boolean(type && !type.startsWith(Context.#textHtml)),
228
+ });
229
+
230
+ if (!type) {
231
+ // default to HTML
232
+ this.res.headers.set(Header.contentType, Context.#htmlType);
233
+ }
234
+
235
+ // do not overwrite/remove status - that way user can set it before returning
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Composes a stack of `middleware` into a `Response`.
241
+ *
242
+ * @param c Context
243
+ * @param middleware stack to compose
244
+ * @returns constructed `Response`
245
+ */
246
+ static async compose(c: Context, middleware: Middleware[]) {
247
+ await c.#run(middleware);
248
+
249
+ if (c.req.method === "HEAD") {
250
+ if (c.res.body instanceof ReadableStream) {
251
+ // cancel unused stream to prevent leaks
252
+ await c.res.body.cancel("HEAD");
253
+ }
254
+
255
+ c.res.body = null;
256
+ }
257
+
258
+ Object.freeze(c.res);
259
+
260
+ return new Response(c.res.body, c.res);
261
+ }
262
+ }