ovr 4.6.0 → 5.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/src/app/index.ts CHANGED
@@ -7,11 +7,12 @@ import type {
7
7
  import { Context } from "./context.js";
8
8
  import { Get } from "./helper/get.js";
9
9
  import { Post } from "./helper/post.js";
10
- import { AsyncLocalStorage } from "node:async_hooks";
10
+
11
+ export type Next = () => Promise<void>;
11
12
 
12
13
  export type Middleware<P extends Params = Params> = (
13
14
  context: Context<P>,
14
- next: () => Promise<void>,
15
+ next: Next,
15
16
  ) => any;
16
17
 
17
18
  export type TrailingSlash = "always" | "never" | "ignore";
@@ -28,30 +29,22 @@ type Method =
28
29
  | "PATCH"
29
30
  | (string & {});
30
31
 
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;
38
-
39
- export type NotFoundHandler<P extends Params = Params> = (
40
- context: UnmatchedContext<P>,
41
- ) => any;
42
-
43
- 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
-
53
- /** Global middleware. */
54
- #use: Middleware[] = [];
32
+ /** `App` configuration options */
33
+ type AppOptions = {
34
+ /**
35
+ * Basic
36
+ * [cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)
37
+ * protection that checks the request's `method`, and its
38
+ * [`Sec-Fetch-Site`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)
39
+ * and [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin)
40
+ * headers.
41
+ *
42
+ * More robust protection requires a stateful server or a database to store
43
+ * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
44
+ *
45
+ * @default true
46
+ */
47
+ csrf?: boolean;
55
48
 
56
49
  /**
57
50
  * - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
@@ -62,45 +55,32 @@ export class App {
62
55
  *
63
56
  * @default "never"
64
57
  */
65
- trailingSlash: TrailingSlash = "never";
58
+ trailingSlash?: TrailingSlash;
59
+ };
66
60
 
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>';
61
+ export class App {
62
+ constructor(options?: AppOptions) {
63
+ const resolved: Required<AppOptions> = {
64
+ csrf: true,
65
+ trailingSlash: "never",
66
+ };
67
+ Object.assign(resolved, options);
78
68
 
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;
69
+ if (resolved.csrf === true) this.#use.push(App.#csrf);
89
70
 
90
- /**
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.
93
- *
94
- * @default
95
- *
96
- * ```ts
97
- * (c) => c.html("Not found", 404)
98
- * ```
99
- */
100
- notFound: NotFoundHandler = (c) => c.html("Not found", 404);
71
+ if (resolved.trailingSlash !== "ignore") {
72
+ this.#use.push(App.#trailingSlash(resolved.trailingSlash));
73
+ }
74
+ }
101
75
 
102
- /** Stores context per request. */
103
- static storage = new AsyncLocalStorage<Context>();
76
+ /** Built tries per HTTP method. */
77
+ #trieMap = new Map<Method, Trie<Middleware[]>>();
78
+
79
+ /** Added routes per HTTP method. */
80
+ #routesMap = new Map<Method, Route<Middleware[]>[]>();
81
+
82
+ /** Global middleware. */
83
+ #use: Middleware[] = [];
104
84
 
105
85
  /**
106
86
  * @param helpers `Helper` to add to `App`
@@ -231,70 +211,78 @@ export class App {
231
211
  }
232
212
 
233
213
  /**
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)
214
+ * Request a resource from the application.
215
+ *
216
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)
217
+ *
218
+ * @param resource [Resource](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#resource) to fetch
219
+ * @param options [Options](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#options) to apply to the request
220
+ * @returns Promise that resolves to the [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to the request
236
221
  */
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,
245
- );
246
-
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);
269
-
270
- const middleware = [...this.#use, ...match.route.store];
271
-
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;
277
-
278
- if (middleware[current]) {
279
- const result: unknown = await middleware[current](c, () =>
280
- dispatch(current + 1),
281
- );
282
-
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
- };
288
-
289
- await dispatch(0);
290
- }
291
- }
292
- } catch (error) {
293
- if (c.error) c.error(c, error);
294
- else throw error;
222
+ fetch = async (
223
+ resource: RequestInfo | URL,
224
+ options?: RequestInit,
225
+ ): Promise<Response> => {
226
+ const c = new Context(new Request(resource, options));
227
+
228
+ // see if the method is already built
229
+ let trie = this.#trieMap.get(c.req.method);
230
+
231
+ if (!trie) {
232
+ // check if there are any routes with the method
233
+ const routes = this.#routesMap.get(c.req.method);
234
+
235
+ if (routes) {
236
+ // build trie
237
+ trie = new Trie<Middleware[]>();
238
+ for (const route of routes) trie.add(route);
239
+ this.#trieMap.set(c.req.method, trie);
295
240
  }
241
+ }
296
242
 
297
- return c.build();
298
- });
243
+ if (trie) {
244
+ const match = trie.find(c.url.pathname);
245
+
246
+ if (match) {
247
+ Object.assign(c, match);
248
+ return c.build(this.#use.concat(match.route.store));
249
+ }
250
+ }
251
+
252
+ // no match, just run global middleware
253
+ return c.build(this.#use);
299
254
  };
255
+
256
+ /** Basic CSRF middleware. */
257
+ static async #csrf(c: Context, next: Next) {
258
+ if (
259
+ c.req.method === "GET" ||
260
+ c.req.method === "HEAD" ||
261
+ c.req.headers.get("sec-fetch-site") === "same-origin" ||
262
+ c.req.headers.get("origin") === c.url.origin
263
+ ) {
264
+ return next();
265
+ }
266
+
267
+ c.text("Forbidden", 403);
268
+ }
269
+
270
+ /** @returns Trailing slash middleware */
271
+ static #trailingSlash(mode: TrailingSlash) {
272
+ return async (c: Context, next: Next) => {
273
+ await next();
274
+
275
+ if (c.status && c.status !== 404) return;
276
+
277
+ const last = c.url.pathname.at(-1);
278
+
279
+ if (mode === "always" && last !== "/") {
280
+ c.url.pathname += "/";
281
+ c.redirect(c.url, 308);
282
+ } else if (mode === "never" && c.url.pathname !== "/" && last === "/") {
283
+ c.url.pathname = c.url.pathname.slice(0, -1);
284
+ c.redirect(c.url, 308);
285
+ }
286
+ };
287
+ }
300
288
  }
@@ -12,7 +12,7 @@ export class Memo {
12
12
  * @param fn Function to memoize.
13
13
  * @returns The memoized function.
14
14
  */
15
- use = <A extends any[], R>(fn: (...args: A) => R) => {
15
+ use<A extends any[], R>(fn: (...args: A) => R) {
16
16
  if (this.#memoized.has(fn)) return this.#memoized.get(fn) as typeof fn;
17
17
 
18
18
  // closure will GC automatically
@@ -36,5 +36,5 @@ export class Memo {
36
36
  this.#memoized.set(fn, memo);
37
37
 
38
38
  return memo;
39
- };
39
+ }
40
40
  }
package/src/index.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  export { jsx, toGenerator, toStream, toString, type JSX } from "./jsx/index.js";
2
2
  export { Chunk } from "./jsx/chunk/index.js";
3
3
  export { Trie, Route } from "./trie/index.js";
4
- export { App, type Middleware } from "./app/index.js";
4
+ export { App, type Middleware, type Next } from "./app/index.js";
5
5
  export { Context } from "./app/context.js";
6
6
  export { Get } from "./app/helper/get.js";
7
7
  export { Post } from "./app/helper/post.js";
8
- export { csrf } from "./app/mw/csrf.js";
package/src/jsx/index.ts CHANGED
@@ -2,9 +2,6 @@ import type { MaybeFunction, MaybePromise } from "../types/index.js";
2
2
  import { Chunk } from "./chunk/index.js";
3
3
  import type { IntrinsicElements as IE } from "./intrinsic-elements.js";
4
4
  import { merge } from "./merge-async-generators.js";
5
- import { performance } from "node:perf_hooks";
6
- import { setImmediate } from "node:timers/promises";
7
- import { types } from "node:util";
8
5
 
9
6
  /** ovr JSX namespace */
10
7
  export namespace JSX {
@@ -92,6 +89,8 @@ export async function* jsx<P extends Props = Props>(
92
89
  // otherwise, don't include the attribute
93
90
  }
94
91
 
92
+ if (tag === "html") yield Chunk.safe("<!doctype html>");
93
+
95
94
  yield Chunk.safe(`<${tag}${attributes}>`);
96
95
 
97
96
  if (voidElements.has(tag)) return;
@@ -143,22 +142,9 @@ export async function* toGenerator(
143
142
 
144
143
  if (Symbol.iterator in element) {
145
144
  // sync iterable
146
- if (types.isGeneratorObject(element)) {
145
+ if ("next" in element) {
147
146
  // sync generator - lazily resolve, avoids loading all in memory
148
- const ms = 8;
149
- let deadline = performance.now() + ms;
150
-
151
- for (const children of element) {
152
- yield* toGenerator(children);
153
-
154
- if (performance.now() > deadline) {
155
- // yields back to the event loop if deadline is reached
156
- // to send chunks or check if the request has been cancelled
157
- await setImmediate();
158
- deadline = performance.now() + ms;
159
- }
160
- }
161
-
147
+ for (const children of element) yield* toGenerator(children);
162
148
  return;
163
149
  }
164
150
 
@@ -232,26 +218,41 @@ const encoder = new TextEncoder();
232
218
  export const toStream = (element: JSX.Element) => {
233
219
  const gen = toGenerator(element);
234
220
 
235
- return new ReadableStream<Uint8Array>({
236
- async pull(c) {
237
- const result = await gen.next();
221
+ return new ReadableStream<Uint8Array>(
222
+ {
223
+ // enables zero-copy transfer from underlying source when queue is empty
224
+ // https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#overview
225
+ type: "bytes",
226
+ // `pull` ensures backpressure and cancelled requests stop the generator
227
+ async pull(c) {
228
+ const result = await gen.next();
229
+
230
+ if (result.done) {
231
+ c.close();
232
+ gen.return();
233
+ return;
234
+ }
238
235
 
239
- if (result.done) {
240
- c.close();
236
+ c.enqueue(
237
+ // need to encode for Node (ex: during prerendering) or it will error
238
+ // doesn't seem to be needed for browsers
239
+ // faster than piping through a `TextEncoderStream`
240
+ encoder.encode(result.value.value),
241
+ );
242
+ },
243
+ cancel() {
241
244
  gen.return();
242
- return;
243
- }
244
-
245
- c.enqueue(
246
- // need to encode for Node JS (ex: during prerendering) or it will error
247
- // doesn't seem to be needed for browsers
248
- // faster than piping through a `TextEncoderStream`
249
- encoder.encode(result.value.value),
250
- );
245
+ },
251
246
  },
252
-
253
- cancel() {
254
- gen.return();
247
+ {
248
+ // `highWaterMark` defaults to 1
249
+ // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#highwatermark
250
+ // setting this ensures at least a small buffer is maintained if the
251
+ // underlying server does not have its own high water mark set
252
+ // https://blog.cloudflare.com/unpacking-cloudflare-workers-cpu-performance-benchmarks/#inefficient-streams-adapters
253
+ // in Node, the default is 16kb, so this stacks another 2kb in front
254
+ // https://nodejs.org/api/http.html#outgoingmessagewritablehighwatermark
255
+ highWaterMark: 2048,
255
256
  },
256
- });
257
+ );
257
258
  };
package/src/trie/index.ts CHANGED
@@ -7,6 +7,10 @@ export class Route<Store> {
7
7
  /** Store returned when route is found */
8
8
  store: Store;
9
9
 
10
+ /**
11
+ * @param pattern route pattern
12
+ * @param store value to store in the patterns final node
13
+ */
10
14
  constructor(pattern: string, store: Store) {
11
15
  if (pattern[0] !== "/") {
12
16
  throw new Error(
@@ -50,6 +54,9 @@ export class Trie<Store> {
50
54
  /** Matched wildcard route */
51
55
  wildcardRoute: Route<Store> | null = null;
52
56
 
57
+ static #paramMatch = /:.+?(?=\/|$)/g;
58
+ static #paramSplit = /:.+?(?=\/|$)/;
59
+
53
60
  /**
54
61
  * @param segment pattern segment
55
62
  * @param staticChildren static children nodes to add to staticMap
@@ -142,8 +149,8 @@ export class Trie<Store> {
142
149
  const endsWithWildcard = pattern.endsWith("*");
143
150
  if (endsWithWildcard) pattern = pattern.slice(0, -1);
144
151
 
145
- const paramSegments = pattern.match(/:.+?(?=\/|$)/g) ?? []; // match the params
146
- const staticSegments = pattern.split(/:.+?(?=\/|$)/); // split on the params
152
+ const paramSegments = pattern.match(Trie.#paramMatch) ?? [];
153
+ const staticSegments = pattern.split(Trie.#paramSplit);
147
154
 
148
155
  // if the last segment is a param without a trailing slash
149
156
  // then there will be an empty string, remove
package/src/util/hash.ts CHANGED
@@ -9,8 +9,8 @@
9
9
  */
10
10
  export const hash = (s: string) => {
11
11
  let hash = 5381;
12
-
13
12
  let i = s.length;
13
+
14
14
  while (i) hash = (hash * 33) ^ s.charCodeAt(--i);
15
15
 
16
16
  return (hash >>> 0).toString(36);
@@ -1,23 +0,0 @@
1
- import type { Middleware } from "../index.js";
2
- /**
3
- * Basic
4
- * [cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)
5
- * protection that checks the request's `method` and `Origin` header.
6
- * For more robust protection you'll need a stateful server or a database to store
7
- * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
8
- *
9
- * @param options
10
- * @returns CSRF middleware
11
- *
12
- * @example
13
- *
14
- * ```ts
15
- * import { csrf } from "ovr";
16
- *
17
- * app.use(csrf({ origin: "https://example.com" }));
18
- * ```
19
- */
20
- export declare const csrf: (options: {
21
- origin: string | string[];
22
- }) => Middleware;
23
- //# sourceMappingURL=csrf.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"csrf.d.ts","sourceRoot":"","sources":["../../../src/app/mw/csrf.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,IAAI,GAAI,SAAS;IAAE,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;CAAE,KAAG,UAW7D,CAAC"}
@@ -1,30 +0,0 @@
1
- /**
2
- * Basic
3
- * [cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)
4
- * protection that checks the request's `method` and `Origin` header.
5
- * For more robust protection you'll need a stateful server or a database to store
6
- * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
7
- *
8
- * @param options
9
- * @returns CSRF middleware
10
- *
11
- * @example
12
- *
13
- * ```ts
14
- * import { csrf } from "ovr";
15
- *
16
- * app.use(csrf({ origin: "https://example.com" }));
17
- * ```
18
- */
19
- export const csrf = (options) => {
20
- if (typeof options.origin === "string")
21
- options.origin = [options.origin];
22
- return (c, next) => {
23
- if (["GET", "HEAD"].includes(c.req.method))
24
- return next();
25
- const origin = c.req.headers.get("Origin");
26
- if (origin && options.origin.includes(origin))
27
- return next();
28
- return c.text("Forbidden", 403);
29
- };
30
- };
@@ -1,32 +0,0 @@
1
- import type { Middleware } from "../index.js";
2
-
3
- /**
4
- * Basic
5
- * [cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)
6
- * protection that checks the request's `method` and `Origin` header.
7
- * For more robust protection you'll need a stateful server or a database to store
8
- * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
9
- *
10
- * @param options
11
- * @returns CSRF middleware
12
- *
13
- * @example
14
- *
15
- * ```ts
16
- * import { csrf } from "ovr";
17
- *
18
- * app.use(csrf({ origin: "https://example.com" }));
19
- * ```
20
- */
21
- export const csrf = (options: { origin: string | string[] }): Middleware => {
22
- if (typeof options.origin === "string") options.origin = [options.origin];
23
-
24
- return (c, next) => {
25
- if (["GET", "HEAD"].includes(c.req.method)) return next();
26
-
27
- const origin = c.req.headers.get("Origin");
28
- if (origin && options.origin.includes(origin)) return next();
29
-
30
- return c.text("Forbidden", 403);
31
- };
32
- };