ovr 1.4.0 → 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.
- package/dist/app/action.d.ts +49 -0
- package/dist/app/action.js +31 -0
- package/dist/{router → app}/context.d.ts +42 -41
- package/dist/{router → app}/context.js +62 -54
- package/dist/app/index.d.ts +115 -0
- package/dist/app/index.js +168 -0
- package/dist/app/page.d.ts +41 -0
- package/dist/app/page.js +42 -0
- package/dist/escape/index.d.ts +4 -4
- package/dist/escape/index.js +6 -6
- package/dist/hash/index.d.ts +1 -0
- package/dist/hash/index.js +9 -0
- package/dist/index.d.ts +7 -6
- package/dist/index.js +6 -6
- package/dist/jsx/elements.d.ts +2 -2
- package/dist/jsx/index.d.ts +6 -7
- package/dist/jsx/index.js +8 -5
- package/dist/jsx-dev-runtime.d.ts +1 -1
- package/dist/jsx-dev-runtime.js +1 -1
- package/dist/jsx-runtime.d.ts +1 -1
- package/dist/jsx-runtime.js +1 -1
- package/dist/memo/index.d.ts +11 -0
- package/dist/memo/index.js +34 -0
- package/dist/trie/index.d.ts +2 -1
- package/dist/trie/insert-params.d.ts +7 -0
- package/dist/trie/insert-params.js +22 -0
- package/dist/types/index.d.ts +14 -0
- package/dist/types/index.js +1 -0
- package/package.json +5 -2
- package/dist/components/index.d.ts +0 -2
- package/dist/components/index.js +0 -3
- package/dist/components/suspense.d.ts +0 -33
- package/dist/components/suspense.js +0 -31
- package/dist/router/get-context.d.ts +0 -6
- package/dist/router/get-context.js +0 -9
- package/dist/router/index.d.ts +0 -99
- package/dist/router/index.js +0 -134
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type JSX } from "../jsx/index.js";
|
|
2
|
+
import type { ExtractParams } from "../types/index.js";
|
|
3
|
+
import type { Middleware, Params } from "./index.js";
|
|
4
|
+
type FormProps<P extends Params> = Omit<JSX.IntrinsicElements["form"], "action" | "method"> & (keyof P extends never ? {
|
|
5
|
+
params?: never;
|
|
6
|
+
} : {
|
|
7
|
+
params: P;
|
|
8
|
+
});
|
|
9
|
+
export declare class Action<Pattern extends string = string> {
|
|
10
|
+
#private;
|
|
11
|
+
/** Route pattern */
|
|
12
|
+
pattern: Pattern;
|
|
13
|
+
/** POST middleware */
|
|
14
|
+
middleware: Middleware<any>[];
|
|
15
|
+
/** `<form>` component with preset `method` and `action` attributes. */
|
|
16
|
+
Form: (props: FormProps<ExtractParams<Pattern>>) => AsyncGenerator<string, void, unknown>;
|
|
17
|
+
/**
|
|
18
|
+
* @param middleware POST middleware
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
*
|
|
22
|
+
* ```tsx
|
|
23
|
+
* // action.tsx
|
|
24
|
+
* import { Action } from "ovr";
|
|
25
|
+
*
|
|
26
|
+
* export const action = new Action((c) => {
|
|
27
|
+
* console.log("posted");
|
|
28
|
+
* c.redirect("/", 303);
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* export const page = new Page("/", () => (
|
|
32
|
+
* <action.Form>
|
|
33
|
+
* <input />
|
|
34
|
+
* <button>Submit</button>
|
|
35
|
+
* </action.Form>
|
|
36
|
+
* ));
|
|
37
|
+
*
|
|
38
|
+
* // app.tsx
|
|
39
|
+
* app.add(page, action); registers the action
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
constructor(...middleware: Middleware<{}>[]);
|
|
43
|
+
/**
|
|
44
|
+
* @param pattern Route pattern
|
|
45
|
+
* @param middleware POST middleware
|
|
46
|
+
*/
|
|
47
|
+
constructor(pattern: Pattern, ...middleware: Middleware<ExtractParams<Pattern>>[]);
|
|
48
|
+
}
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { hash } from "../hash/index.js";
|
|
2
|
+
import { jsx } from "../jsx/index.js";
|
|
3
|
+
import { insertParams } from "../trie/insert-params.js";
|
|
4
|
+
export class Action {
|
|
5
|
+
/** Route pattern */
|
|
6
|
+
pattern;
|
|
7
|
+
/** POST middleware */
|
|
8
|
+
middleware;
|
|
9
|
+
/** `<form>` component with preset `method` and `action` attributes. */
|
|
10
|
+
Form;
|
|
11
|
+
#parts = [];
|
|
12
|
+
constructor(patternOrMiddleware, ...middleware) {
|
|
13
|
+
this.middleware = middleware;
|
|
14
|
+
if (typeof patternOrMiddleware === "string") {
|
|
15
|
+
this.pattern = patternOrMiddleware;
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
this.middleware.unshift(patternOrMiddleware);
|
|
19
|
+
this.pattern = `/_action/${hash(this.middleware.join())}`;
|
|
20
|
+
}
|
|
21
|
+
this.#parts = this.pattern.split("/");
|
|
22
|
+
this.Form = (props) => {
|
|
23
|
+
const { params = {}, ...rest } = props;
|
|
24
|
+
return jsx("form", {
|
|
25
|
+
action: insertParams(this.#parts, params),
|
|
26
|
+
method: "post",
|
|
27
|
+
...rest,
|
|
28
|
+
});
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -1,21 +1,15 @@
|
|
|
1
1
|
import { type JSX } from "../jsx/index.js";
|
|
2
2
|
import type { Route } from "../trie/index.js";
|
|
3
|
-
import type
|
|
3
|
+
import { type ErrorHandler, type Middleware, type NotFoundHandler, type Params, type TrailingSlash } from "./index.js";
|
|
4
4
|
type Layout = (props: {
|
|
5
5
|
children: JSX.Element;
|
|
6
6
|
}) => JSX.Element;
|
|
7
|
-
export declare class Context<
|
|
7
|
+
export declare class Context<P extends Params = Params> {
|
|
8
8
|
#private;
|
|
9
9
|
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request) */
|
|
10
10
|
req: Request;
|
|
11
11
|
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL) */
|
|
12
12
|
url: URL;
|
|
13
|
-
/**
|
|
14
|
-
* `state` returned from `config.start`, possibly modified by previous middleware.
|
|
15
|
-
*
|
|
16
|
-
* @default null
|
|
17
|
-
*/
|
|
18
|
-
state: State;
|
|
19
13
|
/**
|
|
20
14
|
* Route pattern parameters
|
|
21
15
|
*
|
|
@@ -26,45 +20,21 @@ export declare class Context<State, P extends Params> {
|
|
|
26
20
|
*/
|
|
27
21
|
params: P;
|
|
28
22
|
/** The matched `Route` instance. */
|
|
29
|
-
route: Route<Middleware<
|
|
23
|
+
route: Route<Middleware<P>[]>;
|
|
30
24
|
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body) */
|
|
31
25
|
body: BodyInit | null;
|
|
32
26
|
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) */
|
|
33
27
|
status?: number;
|
|
34
28
|
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Headers) */
|
|
35
29
|
headers: Headers;
|
|
36
|
-
/**
|
|
37
|
-
* Base HTML to inject the `head` and `page` elements into.
|
|
38
|
-
*
|
|
39
|
-
* @default
|
|
40
|
-
*
|
|
41
|
-
* ```html
|
|
42
|
-
* <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>
|
|
43
|
-
* ```
|
|
44
|
-
*/
|
|
30
|
+
/** Passed from `app.base` */
|
|
45
31
|
base: string;
|
|
46
|
-
/**
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
*
|
|
53
|
-
* @default null
|
|
54
|
-
*/
|
|
55
|
-
error: ((context: UnmatchedContext<State, Params>, error: unknown) => any) | null;
|
|
56
|
-
constructor(req: Request, url: URL, trailingSlash: TrailingSlash);
|
|
57
|
-
/**
|
|
58
|
-
* Middleware to run when no `body` or `status` has been set on the `context`.
|
|
59
|
-
* Set to a new function to override the default.
|
|
60
|
-
*
|
|
61
|
-
* @default
|
|
62
|
-
*
|
|
63
|
-
* ```ts
|
|
64
|
-
* () => this.html("Not found", 404)
|
|
65
|
-
* ```
|
|
66
|
-
*/
|
|
67
|
-
notFound(_context: UnmatchedContext<State, P>): any;
|
|
32
|
+
/** Passed from `app.error` */
|
|
33
|
+
error: ErrorHandler<P>;
|
|
34
|
+
/** Passed from `app.notFound` */
|
|
35
|
+
notFound: NotFoundHandler<P>;
|
|
36
|
+
memo: <A extends any[], R>(fn: (...args: A) => R) => (...args: A) => R;
|
|
37
|
+
constructor(req: Request, url: URL, trailingSlash: TrailingSlash, base: string, error: ErrorHandler<P>, notFound: NotFoundHandler<P>);
|
|
68
38
|
/**
|
|
69
39
|
* Mirrors `new Response()` constructor, set values with one function.
|
|
70
40
|
*
|
|
@@ -106,7 +76,13 @@ export declare class Context<State, P extends Params> {
|
|
|
106
76
|
* Creates a redirect response.
|
|
107
77
|
*
|
|
108
78
|
* @param location redirect `Location` header
|
|
109
|
-
* @param status
|
|
79
|
+
* @param status HTTP status code
|
|
80
|
+
*
|
|
81
|
+
* - [301 Moved Permanently](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301)
|
|
82
|
+
* - [302 Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) (default)
|
|
83
|
+
* - [303 See Other](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303)
|
|
84
|
+
* - [307 Temporary Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307)
|
|
85
|
+
* - [308 Permanent Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308)
|
|
110
86
|
*/
|
|
111
87
|
redirect(location: string | URL, status?: 301 | 302 | 303 | 307 | 308): void;
|
|
112
88
|
/**
|
|
@@ -138,5 +114,30 @@ export declare class Context<State, P extends Params> {
|
|
|
138
114
|
* @returns the constructed `Response`
|
|
139
115
|
*/
|
|
140
116
|
build(): Response;
|
|
117
|
+
/**
|
|
118
|
+
* Call within the scope of a handler to get the current context.
|
|
119
|
+
*
|
|
120
|
+
* @returns Request context
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
*
|
|
124
|
+
* ```ts
|
|
125
|
+
* import { Context } from "ovr";
|
|
126
|
+
*
|
|
127
|
+
* const app = new Router();
|
|
128
|
+
*
|
|
129
|
+
* const fn = () => {
|
|
130
|
+
* const c = Context.get();
|
|
131
|
+
* // ...
|
|
132
|
+
* }
|
|
133
|
+
*
|
|
134
|
+
* app.get("/", () => {
|
|
135
|
+
* fn(); // OK
|
|
136
|
+
* });
|
|
137
|
+
*
|
|
138
|
+
* fn() // ReferenceError - outside AsyncLocalStorage scope
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
static get(): Context<Params>;
|
|
141
142
|
}
|
|
142
143
|
export {};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { hash } from "../hash/index.js";
|
|
2
2
|
import { toGenerator } from "../jsx/index.js";
|
|
3
|
+
import { Memo } from "../memo/index.js";
|
|
4
|
+
import { App, } from "./index.js";
|
|
3
5
|
class TagNotFound extends Error {
|
|
4
6
|
constructor(tag) {
|
|
5
7
|
super(`No closing ${tag} tag found`);
|
|
@@ -11,12 +13,6 @@ export class Context {
|
|
|
11
13
|
req;
|
|
12
14
|
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL) */
|
|
13
15
|
url;
|
|
14
|
-
/**
|
|
15
|
-
* `state` returned from `config.start`, possibly modified by previous middleware.
|
|
16
|
-
*
|
|
17
|
-
* @default null
|
|
18
|
-
*/
|
|
19
|
-
state = null;
|
|
20
16
|
/**
|
|
21
17
|
* Route pattern parameters
|
|
22
18
|
*
|
|
@@ -34,46 +30,24 @@ export class Context {
|
|
|
34
30
|
status;
|
|
35
31
|
/** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Headers) */
|
|
36
32
|
headers = new Headers();
|
|
37
|
-
/**
|
|
38
|
-
* Base HTML to inject the `head` and `page` elements into.
|
|
39
|
-
*
|
|
40
|
-
* @default
|
|
41
|
-
*
|
|
42
|
-
* ```html
|
|
43
|
-
* <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>
|
|
44
|
-
* ```
|
|
45
|
-
*/
|
|
46
|
-
base = '<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>';
|
|
47
|
-
/**
|
|
48
|
-
* Assign a handler to run when an `Error` is thrown.
|
|
49
|
-
*
|
|
50
|
-
* If not set, `Error` will be thrown. This might be desired
|
|
51
|
-
* if your server already includes error handling. Set in `config.start`
|
|
52
|
-
* to handle errors globally.
|
|
53
|
-
*
|
|
54
|
-
* @default null
|
|
55
|
-
*/
|
|
56
|
-
error = null;
|
|
57
33
|
#layouts = [];
|
|
58
34
|
#headElements = [];
|
|
59
35
|
#trailingSlash;
|
|
60
|
-
|
|
36
|
+
/** Passed from `app.base` */
|
|
37
|
+
base;
|
|
38
|
+
/** Passed from `app.error` */
|
|
39
|
+
error;
|
|
40
|
+
/** Passed from `app.notFound` */
|
|
41
|
+
notFound;
|
|
42
|
+
#memo = new Memo();
|
|
43
|
+
memo = this.#memo.use;
|
|
44
|
+
constructor(req, url, trailingSlash, base, error, notFound) {
|
|
61
45
|
this.req = req;
|
|
62
46
|
this.url = url;
|
|
63
47
|
this.#trailingSlash = trailingSlash;
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
* Set to a new function to override the default.
|
|
68
|
-
*
|
|
69
|
-
* @default
|
|
70
|
-
*
|
|
71
|
-
* ```ts
|
|
72
|
-
* () => this.html("Not found", 404)
|
|
73
|
-
* ```
|
|
74
|
-
*/
|
|
75
|
-
notFound(_context) {
|
|
76
|
-
this.html("Not found", 404);
|
|
48
|
+
this.base = base;
|
|
49
|
+
this.error = error;
|
|
50
|
+
this.notFound = notFound;
|
|
77
51
|
}
|
|
78
52
|
/**
|
|
79
53
|
* Mirrors `new Response()` constructor, set values with one function.
|
|
@@ -86,7 +60,7 @@ export class Context {
|
|
|
86
60
|
this.status = init?.status ?? 200;
|
|
87
61
|
if (init?.headers) {
|
|
88
62
|
for (const [name, value] of new Headers(init.headers)) {
|
|
89
|
-
this.headers.
|
|
63
|
+
this.headers.set(name, value);
|
|
90
64
|
}
|
|
91
65
|
}
|
|
92
66
|
}
|
|
@@ -130,7 +104,13 @@ export class Context {
|
|
|
130
104
|
* Creates a redirect response.
|
|
131
105
|
*
|
|
132
106
|
* @param location redirect `Location` header
|
|
133
|
-
* @param status
|
|
107
|
+
* @param status HTTP status code
|
|
108
|
+
*
|
|
109
|
+
* - [301 Moved Permanently](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301)
|
|
110
|
+
* - [302 Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) (default)
|
|
111
|
+
* - [303 See Other](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303)
|
|
112
|
+
* - [307 Temporary Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307)
|
|
113
|
+
* - [308 Permanent Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308)
|
|
134
114
|
*/
|
|
135
115
|
redirect(location, status = 302) {
|
|
136
116
|
this.headers.set("location", location.toString());
|
|
@@ -162,13 +142,17 @@ export class Context {
|
|
|
162
142
|
const elements = this.base.split(headClose);
|
|
163
143
|
if (!elements[1])
|
|
164
144
|
throw new TagNotFound(headClose);
|
|
165
|
-
elements.splice(1, 0, this.#headElements,
|
|
145
|
+
elements.splice(1, 0, this.#headElements, headClose);
|
|
166
146
|
const bodyParts = elements[3].split(bodyClose);
|
|
167
147
|
if (!bodyParts[1])
|
|
168
148
|
throw new TagNotFound(bodyClose);
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
149
|
+
const userAgent = this.req.headers.get("user-agent");
|
|
150
|
+
if (userAgent?.includes("Safari") && !userAgent.includes("Chrome")) {
|
|
151
|
+
// https://bugs.webkit.org/show_bug.cgi?id=252413
|
|
152
|
+
// https://github.com/sveltejs/kit/issues/10315
|
|
153
|
+
// https://github.com/remix-run/remix/issues/5804
|
|
154
|
+
bodyParts[0] += `<div aria-hidden=true style=position:absolute;width:0;height:0;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0>${"\u200b".repeat(200)}</div>`;
|
|
155
|
+
}
|
|
172
156
|
elements[3] = bodyParts[0];
|
|
173
157
|
elements.push(Page, bodyClose + bodyParts[1]);
|
|
174
158
|
this.html(new ReadableStream({
|
|
@@ -189,13 +173,7 @@ export class Context {
|
|
|
189
173
|
* @returns `true` if the etag matches, `false` otherwise
|
|
190
174
|
*/
|
|
191
175
|
etag(s) {
|
|
192
|
-
|
|
193
|
-
// Adapted from SvelteKit https://github.com/sveltejs/kit/blob/25d459104814b0c2dc6b4cf73b680378a29d8200/packages/kit/src/runtime/hash.js
|
|
194
|
-
let hash = 5381;
|
|
195
|
-
let i = s.length;
|
|
196
|
-
while (i)
|
|
197
|
-
hash = (hash * 33) ^ s.charCodeAt(--i);
|
|
198
|
-
const etag = `"${(hash >>> 0).toString(36)}"`;
|
|
176
|
+
const etag = `"${hash(s)}"`;
|
|
199
177
|
this.headers.set("etag", etag);
|
|
200
178
|
if (this.req.headers.get("if-none-match") === etag) {
|
|
201
179
|
this.body = null;
|
|
@@ -226,4 +204,34 @@ export class Context {
|
|
|
226
204
|
this.notFound(this);
|
|
227
205
|
return new Response(this.body, this);
|
|
228
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* Call within the scope of a handler to get the current context.
|
|
209
|
+
*
|
|
210
|
+
* @returns Request context
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
*
|
|
214
|
+
* ```ts
|
|
215
|
+
* import { Context } from "ovr";
|
|
216
|
+
*
|
|
217
|
+
* const app = new Router();
|
|
218
|
+
*
|
|
219
|
+
* const fn = () => {
|
|
220
|
+
* const c = Context.get();
|
|
221
|
+
* // ...
|
|
222
|
+
* }
|
|
223
|
+
*
|
|
224
|
+
* app.get("/", () => {
|
|
225
|
+
* fn(); // OK
|
|
226
|
+
* });
|
|
227
|
+
*
|
|
228
|
+
* fn() // ReferenceError - outside AsyncLocalStorage scope
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
static get() {
|
|
232
|
+
const c = App.storage.getStore();
|
|
233
|
+
if (!c)
|
|
234
|
+
throw new ReferenceError("Context can only be obtained within a handler.");
|
|
235
|
+
return c;
|
|
236
|
+
}
|
|
229
237
|
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { DeepArray, ExtractMultiParams, ExtractParams } from "../types/index.js";
|
|
2
|
+
import { Action } from "./action.js";
|
|
3
|
+
import { Context } from "./context.js";
|
|
4
|
+
import { Page } from "./page.js";
|
|
5
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
+
export type Params = Record<string, string>;
|
|
7
|
+
export type Middleware<P extends Params = Params> = (context: Context<P>, next: () => Promise<void>) => any;
|
|
8
|
+
export type TrailingSlash = "always" | "never" | "ignore";
|
|
9
|
+
type Method = "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "CONNECT" | "OPTIONS" | "TRACE" | "PATCH" | (string & {});
|
|
10
|
+
type UnmatchedContext<P extends Params = Params> = Omit<Context<P>, "route"> & Partial<Pick<Context<P>, "route">>;
|
|
11
|
+
export type ErrorHandler<P extends Params = Params> = ((context: UnmatchedContext<P>, error: unknown) => any) | null;
|
|
12
|
+
export type NotFoundHandler<P extends Params = Params> = (context: UnmatchedContext<P>) => any;
|
|
13
|
+
export declare class App {
|
|
14
|
+
#private;
|
|
15
|
+
[key: string | symbol | number]: any;
|
|
16
|
+
/**
|
|
17
|
+
* - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
|
|
18
|
+
* - `"always"` - Not found requests without a trailing slash will be redirected to the same path with a trailing slash
|
|
19
|
+
* - `"ignore"` - no redirects (not recommended, bad for SEO)
|
|
20
|
+
*
|
|
21
|
+
* [Trailing Slash for Frameworks by Bjorn Lu](https://bjornlu.com/blog/trailing-slash-for-frameworks)
|
|
22
|
+
*
|
|
23
|
+
* @default "never"
|
|
24
|
+
*/
|
|
25
|
+
trailingSlash: TrailingSlash;
|
|
26
|
+
/**
|
|
27
|
+
* Base HTML to inject the `head` and `page` elements into.
|
|
28
|
+
*
|
|
29
|
+
* @default
|
|
30
|
+
*
|
|
31
|
+
* ```html
|
|
32
|
+
* <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
base: string;
|
|
36
|
+
/**
|
|
37
|
+
* Assign a handler to run when an `Error` is thrown.
|
|
38
|
+
*
|
|
39
|
+
* If not set, `Error` will be thrown. This might be desired
|
|
40
|
+
* if your server already includes error handling. Set in `config.start`
|
|
41
|
+
* to handle errors globally.
|
|
42
|
+
*
|
|
43
|
+
* @default null
|
|
44
|
+
*/
|
|
45
|
+
error: ErrorHandler;
|
|
46
|
+
/**
|
|
47
|
+
* Middleware to run when no `body` or `status` has been set on the `context`.
|
|
48
|
+
* Set to a new function to override the default.
|
|
49
|
+
*
|
|
50
|
+
* @default
|
|
51
|
+
*
|
|
52
|
+
* ```ts
|
|
53
|
+
* (c) => c.html("Not found", 404)
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
notFound: NotFoundHandler;
|
|
57
|
+
/** Stores context per request. */
|
|
58
|
+
static storage: AsyncLocalStorage<Context<Params>>;
|
|
59
|
+
/**
|
|
60
|
+
* @param routes `Page`s or `Action`s to add to the `App`
|
|
61
|
+
* @returns `App` instance
|
|
62
|
+
*/
|
|
63
|
+
add(...routes: DeepArray<Page | Action | Record<string, Page | Action>>[]): this;
|
|
64
|
+
/**
|
|
65
|
+
* Add global middleware.
|
|
66
|
+
*
|
|
67
|
+
* @param middleware
|
|
68
|
+
* @returns `App` instance
|
|
69
|
+
*/
|
|
70
|
+
use(...middleware: Middleware[]): this;
|
|
71
|
+
/**
|
|
72
|
+
* @param method HTTP method
|
|
73
|
+
* @param pattern Route pattern
|
|
74
|
+
* @param middleware
|
|
75
|
+
* @returns `App` instance
|
|
76
|
+
*/
|
|
77
|
+
on<Pattern extends string>(method: Method | Method[], pattern: Pattern, ...middleware: Middleware<ExtractParams<Pattern>>[]): this;
|
|
78
|
+
/**
|
|
79
|
+
* @param method HTTP method
|
|
80
|
+
* @param patterns Array of route patterns
|
|
81
|
+
* @param middleware
|
|
82
|
+
* @returns `App` instance
|
|
83
|
+
*/
|
|
84
|
+
on<Patterns extends string[]>(method: Method | Method[], patterns: [...Patterns], ...middleware: Middleware<ExtractMultiParams<Patterns>>[]): this;
|
|
85
|
+
/**
|
|
86
|
+
* @param pattern Route pattern
|
|
87
|
+
* @param middleware
|
|
88
|
+
* @returns `App` instance
|
|
89
|
+
*/
|
|
90
|
+
get<Pattern extends string>(pattern: Pattern, ...middleware: Middleware<ExtractParams<Pattern>>[]): this;
|
|
91
|
+
/**
|
|
92
|
+
* @param patterns Array of route patterns
|
|
93
|
+
* @param middleware
|
|
94
|
+
* @returns `App` instance
|
|
95
|
+
*/
|
|
96
|
+
get<Patterns extends string[]>(patterns: [...Patterns], ...middleware: Middleware<ExtractMultiParams<Patterns>>[]): this;
|
|
97
|
+
/**
|
|
98
|
+
* @param pattern Route pattern
|
|
99
|
+
* @param middleware
|
|
100
|
+
* @returns the router instance
|
|
101
|
+
*/
|
|
102
|
+
post<Pattern extends string>(pattern: Pattern, ...middleware: Middleware<ExtractParams<Pattern>>[]): this;
|
|
103
|
+
/**
|
|
104
|
+
* @param patterns Array of route patterns
|
|
105
|
+
* @param middleware
|
|
106
|
+
* @returns the router instance
|
|
107
|
+
*/
|
|
108
|
+
post<Patterns extends string[]>(patterns: [...Patterns], ...middleware: Middleware<ExtractMultiParams<Patterns>>[]): this;
|
|
109
|
+
/**
|
|
110
|
+
* @param req [`Request` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
|
|
111
|
+
* @returns [`Response` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response)
|
|
112
|
+
*/
|
|
113
|
+
fetch: (req: Request) => Promise<Response>;
|
|
114
|
+
}
|
|
115
|
+
export {};
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { Trie, Route } from "../trie/index.js";
|
|
2
|
+
import { Action } from "./action.js";
|
|
3
|
+
import { Context } from "./context.js";
|
|
4
|
+
import { Page } from "./page.js";
|
|
5
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
+
export class App {
|
|
7
|
+
/** Built tries per HTTP method. */
|
|
8
|
+
#trieMap = new Map();
|
|
9
|
+
/** Added routes per HTTP method. */
|
|
10
|
+
#routesMap = new Map();
|
|
11
|
+
/** Global middleware. */
|
|
12
|
+
#use = [];
|
|
13
|
+
/**
|
|
14
|
+
* - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
|
|
15
|
+
* - `"always"` - Not found requests without a trailing slash will be redirected to the same path with a trailing slash
|
|
16
|
+
* - `"ignore"` - no redirects (not recommended, bad for SEO)
|
|
17
|
+
*
|
|
18
|
+
* [Trailing Slash for Frameworks by Bjorn Lu](https://bjornlu.com/blog/trailing-slash-for-frameworks)
|
|
19
|
+
*
|
|
20
|
+
* @default "never"
|
|
21
|
+
*/
|
|
22
|
+
trailingSlash = "never";
|
|
23
|
+
/**
|
|
24
|
+
* Base HTML to inject the `head` and `page` elements into.
|
|
25
|
+
*
|
|
26
|
+
* @default
|
|
27
|
+
*
|
|
28
|
+
* ```html
|
|
29
|
+
* <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
base = '<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>';
|
|
33
|
+
/**
|
|
34
|
+
* Assign a handler to run when an `Error` is thrown.
|
|
35
|
+
*
|
|
36
|
+
* If not set, `Error` will be thrown. This might be desired
|
|
37
|
+
* if your server already includes error handling. Set in `config.start`
|
|
38
|
+
* to handle errors globally.
|
|
39
|
+
*
|
|
40
|
+
* @default null
|
|
41
|
+
*/
|
|
42
|
+
error = null;
|
|
43
|
+
/**
|
|
44
|
+
* Middleware to run when no `body` or `status` has been set on the `context`.
|
|
45
|
+
* Set to a new function to override the default.
|
|
46
|
+
*
|
|
47
|
+
* @default
|
|
48
|
+
*
|
|
49
|
+
* ```ts
|
|
50
|
+
* (c) => c.html("Not found", 404)
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
notFound = (c) => c.html("Not found", 404);
|
|
54
|
+
/** Stores context per request. */
|
|
55
|
+
static storage = new AsyncLocalStorage();
|
|
56
|
+
/**
|
|
57
|
+
* @param routes `Page`s or `Action`s to add to the `App`
|
|
58
|
+
* @returns `App` instance
|
|
59
|
+
*/
|
|
60
|
+
add(...routes) {
|
|
61
|
+
for (const route of routes) {
|
|
62
|
+
if (route instanceof Array) {
|
|
63
|
+
this.add(...route);
|
|
64
|
+
}
|
|
65
|
+
else if (route instanceof Page) {
|
|
66
|
+
this.get(route.pattern, ...route.middleware);
|
|
67
|
+
}
|
|
68
|
+
else if (route instanceof Action) {
|
|
69
|
+
this.post(route.pattern, ...route.middleware);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
this.add(...Object.values(route));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Add global middleware.
|
|
79
|
+
*
|
|
80
|
+
* @param middleware
|
|
81
|
+
* @returns `App` instance
|
|
82
|
+
*/
|
|
83
|
+
use(...middleware) {
|
|
84
|
+
this.#use.push(...middleware);
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
on(method, pattern, ...middleware) {
|
|
88
|
+
if (!Array.isArray(method))
|
|
89
|
+
method = [method];
|
|
90
|
+
let patterns;
|
|
91
|
+
if (!Array.isArray(pattern))
|
|
92
|
+
patterns = [pattern];
|
|
93
|
+
else
|
|
94
|
+
patterns = pattern;
|
|
95
|
+
for (const p of patterns) {
|
|
96
|
+
const route = new Route(p, middleware);
|
|
97
|
+
for (const m of method) {
|
|
98
|
+
const routes = this.#routesMap.get(m);
|
|
99
|
+
if (routes)
|
|
100
|
+
routes.push(route);
|
|
101
|
+
else
|
|
102
|
+
this.#routesMap.set(m, [route]);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return this;
|
|
106
|
+
}
|
|
107
|
+
get(patternOrPatterns, ...middleware) {
|
|
108
|
+
return this.on("GET", patternOrPatterns, ...middleware);
|
|
109
|
+
}
|
|
110
|
+
post(patternOrPatterns, ...middleware) {
|
|
111
|
+
return this.on("POST", patternOrPatterns, ...middleware);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* @param req [`Request` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
|
|
115
|
+
* @returns [`Response` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response)
|
|
116
|
+
*/
|
|
117
|
+
fetch = (req) => {
|
|
118
|
+
const c = new Context(req, new URL(req.url), this.trailingSlash, this.base, this.error, this.notFound);
|
|
119
|
+
return App.storage.run(c, async () => {
|
|
120
|
+
try {
|
|
121
|
+
// check to see if the method is already built
|
|
122
|
+
let trie = this.#trieMap.get(req.method);
|
|
123
|
+
if (!trie) {
|
|
124
|
+
// check if there are any routes with the method
|
|
125
|
+
const routes = this.#routesMap.get(req.method);
|
|
126
|
+
if (routes) {
|
|
127
|
+
// build trie
|
|
128
|
+
trie = new Trie();
|
|
129
|
+
for (const route of routes)
|
|
130
|
+
trie.add(route);
|
|
131
|
+
this.#trieMap.set(req.method, trie);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (trie) {
|
|
135
|
+
const match = trie.find(c.url.pathname);
|
|
136
|
+
if (match) {
|
|
137
|
+
Object.assign(c, match);
|
|
138
|
+
const middleware = [...this.#use, ...match.route.store];
|
|
139
|
+
// compose
|
|
140
|
+
let i = -1;
|
|
141
|
+
const dispatch = async (current) => {
|
|
142
|
+
if (current <= i)
|
|
143
|
+
throw new Error("next() called multiple times");
|
|
144
|
+
i = current;
|
|
145
|
+
if (middleware[current]) {
|
|
146
|
+
const result = await middleware[current](c, () => dispatch(current + 1));
|
|
147
|
+
if (result instanceof Response)
|
|
148
|
+
c.res(result.body, result);
|
|
149
|
+
else if (result instanceof ReadableStream)
|
|
150
|
+
c.body = result;
|
|
151
|
+
else if (result)
|
|
152
|
+
c.page(result);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
await dispatch(0);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (c.error)
|
|
161
|
+
c.error(c, error);
|
|
162
|
+
else
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
return c.build();
|
|
166
|
+
});
|
|
167
|
+
};
|
|
168
|
+
}
|