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
@@ -1,46 +0,0 @@
1
- import { type JSX, jsx } from "../../jsx/index.js";
2
- import type { ExtractParams } from "../../types/index.js";
3
- import type { Middleware } from "../index.js";
4
- import { Helper, type UrlOptions } from "./index.js";
5
-
6
- export class Get<Pattern extends string = string> extends Helper<Pattern> {
7
- /** `<a>` component with preset `href` attribute. */
8
- Anchor: (
9
- props: JSX.IntrinsicElements["a"] & UrlOptions<ExtractParams<Pattern>>,
10
- ) => JSX.Element;
11
-
12
- /**
13
- * @param pattern Route pattern
14
- * @param middleware GET middleware
15
- *
16
- * @example
17
- *
18
- * ```tsx
19
- * import { Get } from "ovr";
20
- *
21
- * const page = new Get("/", () => {
22
- * return <p>Hello world</p>
23
- * });
24
- *
25
- * const Nav = () => {
26
- * return <page.Anchor>Home</page.Anchor>
27
- * }
28
- *
29
- * app.add(page); // register
30
- * ```
31
- */
32
- constructor(
33
- pattern: Pattern,
34
- ...middleware: Middleware<ExtractParams<Pattern>>[]
35
- ) {
36
- super("GET", pattern, ...middleware);
37
-
38
- this.Anchor = ({ params, search, hash, ...rest }) =>
39
- jsx("a", {
40
- href: this.url({ params, search, hash } as UrlOptions<
41
- ExtractParams<Pattern>
42
- >),
43
- ...rest,
44
- });
45
- }
46
- }
@@ -1,174 +0,0 @@
1
- import { type JSX, jsx } from "../../jsx/index.js";
2
- import type { Params } from "../../trie/index.js";
3
- import type { ExtractParams, InsertParams } from "../../types/index.js";
4
- import { Context } from "../context.js";
5
- import type { Middleware } from "../index.js";
6
-
7
- export type UrlOptions<P extends Params> = {
8
- /**
9
- * If `true` the current request's `url.search` is forwarded, this option
10
- * can only be used in the context of a request.
11
- *
12
- * Otherwise the value is passed into `URLSearchParams` constructor to
13
- * create new params.
14
- *
15
- * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
16
- */
17
- search?:
18
- | boolean
19
- | string
20
- // Iterable is more accurate than the built in string[][] + URLSearchParams
21
- // https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/2070
22
- | Iterable<[string, string]>
23
- | Record<string, string>;
24
-
25
- /**
26
- * Hash (fragment) of the URL. `"#"` prefix is added if not present.
27
- *
28
- * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash)
29
- */
30
- hash?: string;
31
- } & (keyof P extends never
32
- ? {
33
- /** Route pattern does not contain parameters */
34
- params?: never;
35
- }
36
- : {
37
- /** Route pattern parameters */
38
- params: P;
39
- });
40
-
41
- export class Helper<Pattern extends string> {
42
- /** Extracted parameters type for the pattern */
43
- declare readonly Params: ExtractParams<Pattern>;
44
-
45
- /** Route pattern */
46
- pattern: Pattern;
47
-
48
- /** GET middleware */
49
- middleware: Middleware<any>[]; // any so you can use other middleware
50
-
51
- /** `<button>` component with preset `formaction` and `formmethod` attributes. */
52
- Button: (
53
- props: JSX.IntrinsicElements["button"] & UrlOptions<ExtractParams<Pattern>>,
54
- ) => JSX.Element;
55
-
56
- /** `<form>` component with preset `method` and `action` attributes. */
57
- Form: (
58
- props: JSX.IntrinsicElements["form"] & UrlOptions<ExtractParams<Pattern>>,
59
- ) => JSX.Element;
60
-
61
- /** Pattern parts */
62
- #parts: string[];
63
-
64
- constructor(
65
- method: string,
66
- pattern: Pattern,
67
- ...middleware: Middleware<ExtractParams<Pattern>>[]
68
- ) {
69
- this.pattern = pattern;
70
- this.middleware = middleware;
71
- this.#parts = pattern.split("/");
72
-
73
- this.Button = ({ params, search, hash, ...rest }) =>
74
- jsx("button", {
75
- formaction: this.url({ params, search, hash } as UrlOptions<
76
- ExtractParams<Pattern>
77
- >),
78
- formmethod: method,
79
- ...rest,
80
- });
81
-
82
- this.Form = ({ params, search, hash, ...rest }) =>
83
- jsx("form", {
84
- action: this.url({ params, search, hash } as UrlOptions<
85
- ExtractParams<Pattern>
86
- >),
87
- method,
88
- ...rest,
89
- });
90
- }
91
-
92
- /**
93
- * Constructs a _relative_ URL for the route.
94
- *
95
- * @param [options] Options with type safe parameters
96
- * @returns `pathname` + `search` + `hash`
97
- */
98
- url(
99
- ...[options]: keyof ExtractParams<Pattern> extends never
100
- ? [UrlOptions<ExtractParams<Pattern>>] | []
101
- : [UrlOptions<ExtractParams<Pattern>>]
102
- ) {
103
- const pathname = this.pathname(
104
- // @ts-expect-error - do not have to pass in {} if no params
105
- options?.params,
106
- );
107
-
108
- let search: string;
109
- if (options?.search) {
110
- if (options.search === true) {
111
- // forward current request's search
112
- search = Context.get().url.search;
113
- } else {
114
- // use the value as the init
115
- search =
116
- "?" +
117
- new URLSearchParams(
118
- options.search as ConstructorParameters<typeof URLSearchParams>[0],
119
- );
120
- }
121
- } else {
122
- search = "";
123
- }
124
-
125
- let hash: string;
126
- if (options?.hash) {
127
- // adding # prefix if not present matches the URL setter:
128
- // https://developer.mozilla.org/en-US/docs/Web/API/URL/hash
129
- if (options.hash.startsWith("#")) {
130
- hash = options.hash;
131
- } else {
132
- hash = "#" + options.hash;
133
- }
134
- } else {
135
- hash = "";
136
- }
137
-
138
- return pathname + search + hash;
139
- }
140
-
141
- /**
142
- * @param [params] Parameters to insert
143
- * @returns Resolved `pathname` with params
144
- */
145
- pathname<Params extends ExtractParams<Pattern>>(
146
- ...[params]: keyof Params extends never ? [] : [Params]
147
- ): InsertParams<Pattern, Params> {
148
- if (!params) return this.pattern as InsertParams<Pattern, Params>;
149
-
150
- const wild = "*";
151
-
152
- return this.#parts
153
- .map((part) => {
154
- if (part.startsWith(":")) {
155
- const param = part.slice(1);
156
-
157
- if (!(param in params))
158
- throw new Error(`Parameter "${param}" did not match pattern.`);
159
-
160
- return params[param as keyof typeof params];
161
- }
162
-
163
- if (part === wild) {
164
- if (!(wild in params))
165
- throw new Error("No wildcard parameter found.");
166
-
167
- return params[wild];
168
- }
169
-
170
- return part;
171
- })
172
- .join("/") as InsertParams<Pattern, Params>;
173
- }
174
- }
@@ -1,54 +0,0 @@
1
- import type { ExtractParams } from "../../types/index.js";
2
- import { hash } from "../../util/hash.js";
3
- import type { Middleware } from "../index.js";
4
- import { Helper } from "./index.js";
5
-
6
- export class Post<Pattern extends string = string> extends Helper<Pattern> {
7
- /**
8
- * @param middleware POST middleware
9
- *
10
- * @example
11
- *
12
- * ```tsx
13
- * import { Post } from "ovr";
14
- *
15
- * const post = new Post((c) => {
16
- * console.log("posted");
17
- * c.redirect("/", 303);
18
- * });
19
- *
20
- * const page = new Get("/", () => (
21
- * <post.Form>
22
- * <input type="text" name="name" />
23
- * <button>Submit</button>
24
- * </post.Form>
25
- * ));
26
- *
27
- * app.add(page, post); // register
28
- * ```
29
- */
30
- constructor(...middleware: Middleware<{}>[]);
31
- /**
32
- * @param pattern Route pattern
33
- * @param middleware POST middleware
34
- */
35
- constructor(
36
- pattern: Pattern,
37
- ...middleware: Middleware<ExtractParams<Pattern>>[]
38
- );
39
- constructor(
40
- patternOrMiddleware: Pattern | Middleware<ExtractParams<Pattern>>,
41
- ...middleware: Middleware<ExtractParams<Pattern>>[]
42
- ) {
43
- let pattern: Pattern;
44
-
45
- if (typeof patternOrMiddleware === "string") {
46
- pattern = patternOrMiddleware;
47
- } else {
48
- middleware.unshift(patternOrMiddleware);
49
- pattern = `/_p/${hash(middleware.join())}` as Pattern;
50
- }
51
-
52
- super("POST", pattern, ...middleware);
53
- }
54
- }
@@ -1,40 +0,0 @@
1
- export class Memo {
2
- /** Already memoized functions. */
3
- #memoized = new WeakMap<Function, Function>();
4
-
5
- /** Symbol to store the result of each memoized function. */
6
- static #RESULT = Symbol();
7
-
8
- /**
9
- * Calls to the returned function with the same arguments will
10
- * return a cached result.
11
- *
12
- * @param fn Function to memoize.
13
- * @returns The memoized function.
14
- */
15
- use = <A extends any[], R>(fn: (...args: A) => R) => {
16
- if (this.#memoized.has(fn)) return this.#memoized.get(fn) as typeof fn;
17
-
18
- // closure will GC automatically
19
- const trie = new Map();
20
-
21
- const memo = (...args: A): R => {
22
- let node = trie;
23
-
24
- for (const arg of args) {
25
- // get/create a node for each arg
26
- if (!node.has(arg)) node.set(arg, new Map());
27
- node = node.get(arg);
28
- }
29
-
30
- // set the final result if not there
31
- if (!node.has(Memo.#RESULT)) node.set(Memo.#RESULT, fn(...args));
32
-
33
- return node.get(Memo.#RESULT);
34
- };
35
-
36
- this.#memoized.set(fn, memo);
37
-
38
- return memo;
39
- };
40
- }
@@ -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
- };
@@ -1,79 +0,0 @@
1
- export class Chunk {
2
- static #attr = /[&"<]/g;
3
- static #content = /[&<]/g;
4
-
5
- /** Safe value to render */
6
- value: string;
7
-
8
- /**
9
- * `Chunk` to send in an HTML stream.
10
- *
11
- * @param html string of HTML to escape
12
- * @param safe Set to `true` if the HTML is safe and should not be escaped
13
- */
14
- constructor(html: unknown, safe?: boolean) {
15
- const value = String(html ?? "");
16
- this.value = safe ? value : Chunk.escape(value);
17
- }
18
-
19
- /**
20
- * @returns `value`
21
- */
22
- toString() {
23
- return this.value;
24
- }
25
-
26
- /**
27
- * @param chunks Chunks to append to the end of the chunk
28
- */
29
- concat(...chunks: Chunk[]) {
30
- this.value += chunks.join("");
31
- }
32
-
33
- /**
34
- * Wraps `new Chunk("html", true)`.
35
- *
36
- * Use to create a new `Chunk` and bypass escaping.
37
- *
38
- * @param html Safe string of HTML
39
- * @returns New _safe_ `Chunk`
40
- */
41
- static safe(html: unknown) {
42
- return new Chunk(html, true);
43
- }
44
-
45
- /**
46
- * Escapes strings of HTML.
47
- *
48
- * @param html String to escape
49
- * @param attr Set to `true` if the value is an attribute, otherwise it's a string of HTML content
50
- * @returns Escaped string of HTML
51
- */
52
- static escape(html: string, attr?: boolean) {
53
- // adapted from https://github.com/sveltejs/svelte/blob/main/packages/svelte/src/escaping.js
54
- const regex = attr ? Chunk.#attr : Chunk.#content;
55
-
56
- // search starts at beginning of the string
57
- regex.lastIndex = 0;
58
- // tracks the position of the last successful match in the input string
59
- let start = 0;
60
- let result = "";
61
-
62
- // since `g` flag is used, regex maintains state with each loop,
63
- // checking from the lastIndex onward each time
64
- while (regex.test(html)) {
65
- // index of the match
66
- const i = regex.lastIndex - 1;
67
- const match = html[i];
68
-
69
- result +=
70
- // everything that didn't match during this test
71
- html.slice(start, i) +
72
- // replacement
73
- (match === "&" ? "&amp;" : match === '"' ? "&quot;" : "&lt;");
74
- start = regex.lastIndex;
75
- }
76
-
77
- return result + html.slice(start);
78
- }
79
- }
@@ -1,47 +0,0 @@
1
- const next = async <T, R>(iterator: AsyncIterator<T, R>, index: number) => ({
2
- index,
3
- result: await iterator.next(),
4
- });
5
-
6
- /**
7
- * Merges `AsyncGenerator[]` into a single `AsyncGenerator`, resolving all in parallel.
8
- * The return of each `AsyncGenerator` is yielded from the generator with `done: true`.
9
- *
10
- * Adapted from [stack overflow answers](https://stackoverflow.com/questions/50585456).
11
- *
12
- * @param generators Resolved in parallel.
13
- * @yields `IteratorResult` and `index` of the resolved generator.
14
- */
15
- export async function* merge<T>(generators: AsyncGenerator<T, void>[]) {
16
- const iterators = generators.map((gen) => gen[Symbol.asyncIterator]());
17
- const promises = new Map<number, ReturnType<typeof next<T, void>>>();
18
-
19
- for (let i = 0; i < iterators.length; i++) {
20
- promises.set(i, next(iterators[i]!, i));
21
- }
22
-
23
- let current: Awaited<ReturnType<typeof next>>;
24
-
25
- try {
26
- while (promises.size > 0) {
27
- yield (current = await Promise.race(promises.values()));
28
-
29
- if (current.result.done) {
30
- promises.delete(current.index);
31
- } else {
32
- promises.set(
33
- current.index,
34
- next(iterators[current.index]!, current.index),
35
- );
36
- }
37
- }
38
- } finally {
39
- for (const iterator of iterators) {
40
- try {
41
- iterator.return();
42
- } catch {
43
- // could have already returned
44
- }
45
- }
46
- }
47
- }
@@ -1,42 +0,0 @@
1
- import type { Params } from "../trie/index.js";
2
-
3
- export type MaybePromise<T> = T | Promise<T>;
4
-
5
- export type MaybeFunction<T> = T | (() => T);
6
-
7
- export type DeepArray<T> = T | DeepArray<T>[];
8
-
9
- export type ExtractParams<Pattern extends string = string> =
10
- Pattern extends `${infer _Start}:${infer Param}/${infer Rest}`
11
- ? { [k in Param | keyof ExtractParams<Rest>]: string }
12
- : Pattern extends `${infer _Start}:${infer Param}`
13
- ? { [k in Param]: string }
14
- : Pattern extends `${infer _Rest}*`
15
- ? { "*": string }
16
- : {};
17
-
18
- export type ExtractMultiParams<Patterns extends string[]> = Patterns extends [
19
- infer First extends string,
20
- ...infer Rest extends string[],
21
- ]
22
- ? Rest["length"] extends 0
23
- ? ExtractParams<First>
24
- : ExtractParams<First> | ExtractMultiParams<Rest>
25
- : never;
26
-
27
- export type InsertParams<
28
- Pattern extends string,
29
- P extends Params,
30
- > = Pattern extends `${infer Start}:${infer Param}/${infer Rest}`
31
- ? Param extends keyof P
32
- ? `${Start}${P[Param]}/${InsertParams<Rest, P>}`
33
- : Pattern
34
- : Pattern extends `${infer Start}:${infer Param}`
35
- ? Param extends keyof P
36
- ? `${Start}${P[Param]}`
37
- : Pattern
38
- : Pattern extends `${infer Start}*`
39
- ? "*" extends keyof P
40
- ? `${Start}${P["*"]}`
41
- : Pattern
42
- : Pattern;
package/src/util/hash.ts DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * Fast hashing algorithm - [djb2](http://www.cse.yorku.ca/~oz/hash.html)
3
- *
4
- * Adapted from
5
- * [SvelteKit](https://github.com/sveltejs/kit/blob/25d459104814b0c2dc6b4cf73b680378a29d8200/packages/kit/src/runtime/hash.js)
6
- *
7
- * @param s String to hash
8
- * @returns Hashed string
9
- */
10
- export const hash = (s: string) => {
11
- let hash = 5381;
12
-
13
- let i = s.length;
14
- while (i) hash = (hash * 33) ^ s.charCodeAt(--i);
15
-
16
- return (hash >>> 0).toString(36);
17
- };
File without changes
File without changes