ovr 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,115 @@
1
+ import { Node, Route } from "../trie/index.js";
2
+ import { Context } from "./context.js";
3
+ export class Router {
4
+ /** Built tries per HTTP method */
5
+ #trieMap = new Map();
6
+ /** Added routes per HTTP method */
7
+ #routesMap = new Map();
8
+ #start;
9
+ #trailingSlash;
10
+ constructor(config = {}) {
11
+ this.#trailingSlash = config.trailingSlash ?? "never";
12
+ this.#start = config.start;
13
+ this.fetch = this.fetch.bind(this);
14
+ }
15
+ on(method, pattern, ...middleware) {
16
+ let patterns;
17
+ if (!Array.isArray(pattern))
18
+ patterns = [pattern];
19
+ else
20
+ patterns = pattern;
21
+ for (const p of patterns) {
22
+ const route = new Route(p, middleware);
23
+ const routes = this.#routesMap.get(method);
24
+ if (routes)
25
+ routes.push(route);
26
+ else
27
+ this.#routesMap.set(method, [route]);
28
+ }
29
+ return this;
30
+ }
31
+ get(patternOrPatterns, ...middleware) {
32
+ return this.on("GET", patternOrPatterns, ...middleware);
33
+ }
34
+ post(patternOrPatterns, ...middleware) {
35
+ return this.on("POST", patternOrPatterns, ...middleware);
36
+ }
37
+ /**
38
+ * @param basePattern pattern to mount the router to, each route will begin with this base
39
+ * @param router sub-router to mount
40
+ * @returns the base router instance
41
+ */
42
+ mount(basePattern, router) {
43
+ if (basePattern.at(-1) === "/")
44
+ basePattern = basePattern.slice(0, -1);
45
+ router.#routesMap.forEach((routes, method) => {
46
+ for (const route of routes) {
47
+ if (this.#trailingSlash !== "always" &&
48
+ route.pattern === "/" &&
49
+ basePattern !== "") {
50
+ route.pattern = "";
51
+ }
52
+ this.on(method, basePattern + route.pattern, ...route.store);
53
+ }
54
+ });
55
+ return this;
56
+ }
57
+ /**
58
+ * @param req [`Request` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
59
+ * @returns [`Response` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response)
60
+ */
61
+ async fetch(req) {
62
+ const c = new Context(req, new URL(req.url), this.#trailingSlash);
63
+ try {
64
+ if (this.#start)
65
+ c.state = this.#start(c);
66
+ let trie = this.#trieMap.get(req.method);
67
+ if (!trie) {
68
+ const routes = this.#routesMap.get(req.method);
69
+ if (routes) {
70
+ // build trie
71
+ trie = new Node();
72
+ for (const route of routes)
73
+ trie.add(route);
74
+ this.#trieMap.set(req.method, trie);
75
+ }
76
+ }
77
+ if (trie) {
78
+ const match = trie.find(c.url.pathname);
79
+ if (match) {
80
+ Object.assign(c, match);
81
+ await this.#compose(match.route.store)(c, () => Promise.resolve());
82
+ }
83
+ }
84
+ }
85
+ catch (error) {
86
+ if (c.error)
87
+ c.error(c, error);
88
+ else
89
+ throw error;
90
+ }
91
+ return c.build();
92
+ }
93
+ /**
94
+ * Combines all middleware into a single function.
95
+ * Adapted from [koa-compose](https://github.com/koajs/compose/blob/master/index.js)
96
+ *
97
+ * @param middleware
98
+ * @returns single function middleware function
99
+ */
100
+ #compose(middleware) {
101
+ return (c, next) => {
102
+ let index = -1;
103
+ const dispatch = async (i) => {
104
+ if (i <= index)
105
+ throw new Error("next() called multiple times");
106
+ index = i;
107
+ const mw = i === middleware.length ? next : middleware[i];
108
+ if (!mw)
109
+ return;
110
+ return mw(c, dispatch.bind(null, i + 1));
111
+ };
112
+ return dispatch(0);
113
+ };
114
+ }
115
+ }
@@ -0,0 +1,75 @@
1
+ export declare class Route<Store> {
2
+ /** Route pattern */
3
+ pattern: string;
4
+ /** Store returned when route is found */
5
+ store: Store;
6
+ constructor(pattern: string, store: Store);
7
+ }
8
+ declare class ParamNode<Store> {
9
+ /** Name of the parameter (without the colon ":") */
10
+ name: string;
11
+ /** Matched route */
12
+ route: Route<Store> | null;
13
+ /** Static child node */
14
+ staticChild: Node<Store> | null;
15
+ constructor(name: string);
16
+ }
17
+ export declare class Node<Store> {
18
+ /** Unique segment of the pattern trie */
19
+ segment: string;
20
+ /** Static child node map, key is the first character in the segment */
21
+ staticMap: Map<number, Node<Store>> | null;
22
+ /** Parametric child node */
23
+ paramChild: ParamNode<Store> | null;
24
+ /** Matched route */
25
+ route: Route<Store> | null;
26
+ /** Matched wildcard route */
27
+ wildcardRoute: Route<Store> | null;
28
+ /**
29
+ * @param segment pattern segment
30
+ * @param staticChildren static children nodes to add to staticMap
31
+ */
32
+ constructor(segment?: string, staticChildren?: Node<Store>[]);
33
+ /**
34
+ * @param segment new segment
35
+ * @returns a clone of the Node with a new segment
36
+ */
37
+ clone(segment: string): Node<unknown>;
38
+ /**
39
+ * If the current segment is "api/posts/"
40
+ * and "api/movies/" is added,
41
+ * the node will need to be reassigned to "api/" and create two static children.
42
+ *
43
+ * @param charIndex where to split the node
44
+ * @param segment new segment to use
45
+ * @returns the new child produced from the new segment
46
+ */
47
+ fork(charIndex: number, segment: string): Node<Store>;
48
+ /**
49
+ * node.segment = "static/static",
50
+ * staticSegment = "static/",
51
+ * then the node needs to be split to accommodate the shorter segment
52
+ *
53
+ * @param segment
54
+ */
55
+ split(segment: string): void;
56
+ /**
57
+ * @param name name of the param
58
+ * @returns the existing child with the same name, or creates a new
59
+ */
60
+ setParamChild(name: string): ParamNode<Store>;
61
+ /**
62
+ * @param route route return when pattern is matched
63
+ * @returns this - the Node
64
+ */
65
+ add(route: Route<Store>): this;
66
+ /**
67
+ * @param pathname Path to find
68
+ * @returns `Route` and the matched `params` if found, otherwise `null`
69
+ */
70
+ find(pathname: string): {
71
+ route: Route<Store>;
72
+ params: Record<string, string>;
73
+ } | null;
74
+ }
75
+ export {};
@@ -0,0 +1,265 @@
1
+ export class Route {
2
+ /** Route pattern */
3
+ pattern;
4
+ /** Store returned when route is found */
5
+ store;
6
+ constructor(pattern, store) {
7
+ if (pattern[0] !== "/") {
8
+ throw new Error(`Invalid route: ${pattern} - route pattern must begin with "/"`);
9
+ }
10
+ this.pattern = pattern;
11
+ this.store = store;
12
+ }
13
+ }
14
+ class ParamNode {
15
+ /** Name of the parameter (without the colon ":") */
16
+ name;
17
+ /** Matched route */
18
+ route = null;
19
+ /** Static child node */
20
+ staticChild = null;
21
+ constructor(name) {
22
+ this.name = name;
23
+ }
24
+ }
25
+ export class Node {
26
+ /** Unique segment of the pattern trie */
27
+ segment;
28
+ /** Static child node map, key is the first character in the segment */
29
+ staticMap = null;
30
+ /** Parametric child node */
31
+ paramChild = null;
32
+ /** Matched route */
33
+ route = null;
34
+ /** Matched wildcard route */
35
+ wildcardRoute = null;
36
+ /**
37
+ * @param segment pattern segment
38
+ * @param staticChildren static children nodes to add to staticMap
39
+ */
40
+ constructor(segment = "/", staticChildren) {
41
+ this.segment = segment;
42
+ if (staticChildren?.length) {
43
+ this.staticMap ??= new Map();
44
+ for (const child of staticChildren) {
45
+ this.staticMap.set(child.segment.charCodeAt(0), child);
46
+ }
47
+ }
48
+ }
49
+ /**
50
+ * @param segment new segment
51
+ * @returns a clone of the Node with a new segment
52
+ */
53
+ clone(segment) {
54
+ const clone = new Node(segment);
55
+ clone.staticMap = this.staticMap;
56
+ clone.paramChild = this.paramChild;
57
+ clone.route = this.route;
58
+ clone.wildcardRoute = this.wildcardRoute;
59
+ return clone;
60
+ }
61
+ /**
62
+ * If the current segment is "api/posts/"
63
+ * and "api/movies/" is added,
64
+ * the node will need to be reassigned to "api/" and create two static children.
65
+ *
66
+ * @param charIndex where to split the node
67
+ * @param segment new segment to use
68
+ * @returns the new child produced from the new segment
69
+ */
70
+ fork(charIndex, segment) {
71
+ const existingChild = this.clone(this.segment.slice(charIndex)); // "posts/"
72
+ const newChild = new Node(segment.slice(charIndex)); // "movies/"
73
+ Object.assign(this,
74
+ // "api/" with the above as children
75
+ new Node(this.segment.slice(0, charIndex), [existingChild, newChild]));
76
+ return newChild;
77
+ }
78
+ /**
79
+ * node.segment = "static/static",
80
+ * staticSegment = "static/",
81
+ * then the node needs to be split to accommodate the shorter segment
82
+ *
83
+ * @param segment
84
+ */
85
+ split(segment) {
86
+ const secondHalf = this.clone(this.segment.slice(segment.length));
87
+ Object.assign(this, new Node(segment, [secondHalf]));
88
+ }
89
+ /**
90
+ * @param name name of the param
91
+ * @returns the existing child with the same name, or creates a new
92
+ */
93
+ setParamChild(name) {
94
+ if (this.paramChild && this.paramChild.name !== name) {
95
+ throw new Error(`Cannot create parameter "${name}" because a different parameter ` +
96
+ `("${this.paramChild.name}") already exists in this location.\n\n${this}`);
97
+ }
98
+ return (this.paramChild ??= new ParamNode(name));
99
+ }
100
+ /**
101
+ * @param route route return when pattern is matched
102
+ * @returns this - the Node
103
+ */
104
+ add(route) {
105
+ let current = this;
106
+ let pattern = route.pattern; // created to not modify the original
107
+ const endsWithWildcard = pattern.endsWith("*");
108
+ if (endsWithWildcard)
109
+ pattern = pattern.slice(0, -1);
110
+ const paramSegments = pattern.match(/:.+?(?=\/|$)/g) ?? []; // match the params
111
+ const staticSegments = pattern.split(/:.+?(?=\/|$)/); // split on the params
112
+ // if the last segment is a param without a trailing slash
113
+ // then there will be an empty string, remove
114
+ if (staticSegments.at(-1) === "")
115
+ staticSegments.pop();
116
+ let paramIndex = 0;
117
+ // for each static segment, if there are no static segments, this is skipped
118
+ for (let staticIndex = 0; staticIndex < staticSegments.length; staticIndex++) {
119
+ let staticSegment = staticSegments[staticIndex];
120
+ if (staticIndex > 0) {
121
+ // there is only a second static segment (could just be "/")
122
+ // if there is a param to split them, so there must be a param here
123
+ const paramChild = current.setParamChild(
124
+ // param without the ":" (only increment when this is reached)
125
+ paramSegments[paramIndex++].slice(1));
126
+ if (!paramChild.staticChild) {
127
+ // new - create node with the next static segment
128
+ current = paramChild.staticChild = new Node(staticSegment);
129
+ continue; // next segment - no need to check since it's new
130
+ }
131
+ // there's already a static child - need to check if it's a match
132
+ current = paramChild.staticChild;
133
+ }
134
+ // check if the staticSegment matches the current node
135
+ for (let charIndex = 0;;) {
136
+ if (charIndex === staticSegment.length) {
137
+ // finished iterating through the staticSegment
138
+ if (charIndex < current.segment.length) {
139
+ // too short
140
+ current.split(staticSegment);
141
+ }
142
+ break; // next segment
143
+ }
144
+ if (charIndex === current.segment.length) {
145
+ // passed the end of the current node
146
+ if (!current.staticMap) {
147
+ // new pattern, create new leaf
148
+ current.staticMap = new Map();
149
+ }
150
+ else {
151
+ // there's already static children,
152
+ // check to see if there's a leaf that starts with the char
153
+ const staticChild = current.staticMap.get(staticSegment.charCodeAt(charIndex));
154
+ if (staticChild) {
155
+ // re-run loop with existing staticChild
156
+ current = staticChild;
157
+ staticSegment = staticSegment.slice(charIndex);
158
+ charIndex = 0;
159
+ continue;
160
+ }
161
+ }
162
+ // otherwise, add new staticChild
163
+ const staticChild = new Node(staticSegment.slice(charIndex));
164
+ current.staticMap.set(staticSegment.charCodeAt(charIndex), staticChild);
165
+ current = staticChild;
166
+ break; // next segment
167
+ }
168
+ if (staticSegment[charIndex] !== current.segment[charIndex]) {
169
+ // different than the node - fork
170
+ current = current.fork(charIndex, staticSegment);
171
+ break; // next segment
172
+ }
173
+ // character is the same - rerun to check next char
174
+ charIndex++;
175
+ }
176
+ }
177
+ if (paramIndex < paramSegments.length) {
178
+ // final segment is a param
179
+ current.setParamChild(paramSegments[paramIndex].slice(1)).route ??=
180
+ route;
181
+ }
182
+ else if (endsWithWildcard) {
183
+ // final segment is a wildcard
184
+ current.wildcardRoute ??= route;
185
+ }
186
+ else {
187
+ // final segment is static
188
+ current.route ??= route;
189
+ }
190
+ return this;
191
+ }
192
+ /**
193
+ * @param pathname Path to find
194
+ * @returns `Route` and the matched `params` if found, otherwise `null`
195
+ */
196
+ find(pathname) {
197
+ if (
198
+ // too short
199
+ pathname.length < this.segment.length ||
200
+ // segment does not match current node segment
201
+ !pathname.startsWith(this.segment)) {
202
+ return null;
203
+ }
204
+ if (pathname === this.segment) {
205
+ // reached the end of the path
206
+ if (this.route)
207
+ return {
208
+ route: this.route,
209
+ params: {},
210
+ };
211
+ if (this.wildcardRoute)
212
+ return {
213
+ route: this.wildcardRoute,
214
+ params: { "*": "" },
215
+ };
216
+ return null;
217
+ }
218
+ if (this.staticMap) {
219
+ // check for a static leaf that starts with the first character
220
+ const staticChild = this.staticMap.get(pathname.charCodeAt(this.segment.length));
221
+ if (staticChild) {
222
+ const result = staticChild.find(pathname.slice(this.segment.length));
223
+ if (result)
224
+ return result;
225
+ }
226
+ }
227
+ // check for param leaf
228
+ if (this.paramChild) {
229
+ const slashIndex = pathname.indexOf("/", this.segment.length);
230
+ // if there is not a slash immediately following this.segment
231
+ if (slashIndex !== this.segment.length) {
232
+ // there is a valid parameter
233
+ if (
234
+ // param is the end of the pathname
235
+ slashIndex === -1 &&
236
+ this.paramChild.route) {
237
+ return {
238
+ route: this.paramChild.route,
239
+ params: {
240
+ [this.paramChild.name]: pathname.slice(this.segment.length),
241
+ },
242
+ };
243
+ }
244
+ else if (this.paramChild.staticChild) {
245
+ // there's a static node after the param
246
+ // this is how there can be multiple params, "/" in between
247
+ const result = this.paramChild.staticChild.find(pathname.slice(slashIndex));
248
+ if (result) {
249
+ // add original params to the result
250
+ result.params[this.paramChild.name] = pathname.slice(this.segment.length, slashIndex);
251
+ return result;
252
+ }
253
+ }
254
+ }
255
+ }
256
+ // check for wildcard leaf
257
+ if (this.wildcardRoute) {
258
+ return {
259
+ route: this.wildcardRoute,
260
+ params: { "*": pathname.slice(this.segment.length) },
261
+ };
262
+ }
263
+ return null;
264
+ }
265
+ }
@@ -0,0 +1 @@
1
+ export type MaybePromise<T> = T | Promise<T>;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @param iterables `AsyncIterable` array to merge into one
3
+ */
4
+ export declare function mergeAsyncIterables<T>(iterables: AsyncIterable<T>[]): AsyncGenerator<{
5
+ index: number;
6
+ done: true;
7
+ value?: undefined;
8
+ } | {
9
+ index: number;
10
+ value: T;
11
+ done: false;
12
+ }, void, unknown>;
@@ -0,0 +1,39 @@
1
+ class IterableHandler {
2
+ index;
3
+ iterator;
4
+ promise;
5
+ constructor(index, iterable) {
6
+ this.index = index;
7
+ this.iterator = iterable[Symbol.asyncIterator]();
8
+ this.promise = this.next();
9
+ }
10
+ next() {
11
+ return (this.promise = this.iterator.next().then((result) => ({
12
+ result,
13
+ handler: this,
14
+ })));
15
+ }
16
+ }
17
+ function* getPromises(handlers) {
18
+ for (const handler of handlers)
19
+ yield handler.promise;
20
+ }
21
+ /**
22
+ * @param iterables `AsyncIterable` array to merge into one
23
+ */
24
+ export async function* mergeAsyncIterables(iterables) {
25
+ const handlers = new Set();
26
+ for (let i = 0; i < iterables.length; i++)
27
+ handlers.add(new IterableHandler(i, iterables[i]));
28
+ while (handlers.size) {
29
+ const { result, handler } = await Promise.race(getPromises(handlers));
30
+ if (result.done) {
31
+ handlers.delete(handler);
32
+ yield { index: handler.index, done: true };
33
+ }
34
+ else {
35
+ yield { index: handler.index, value: result.value, done: false };
36
+ handler.next();
37
+ }
38
+ }
39
+ }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "ovr",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
7
- "url": "git+https://github.com/rossrobino/robino.git"
7
+ "url": "git+https://github.com/rossrobino/ovr.git"
8
8
  },
9
9
  "type": "module",
10
10
  "types": "./dist/index.d.ts",
@@ -13,6 +13,14 @@
13
13
  ".": {
14
14
  "types": "./dist/index.d.ts",
15
15
  "default": "./dist/index.js"
16
+ },
17
+ "./jsx-runtime": {
18
+ "types": "./dist/jsx-runtime.d.ts",
19
+ "default": "./dist/jsx-runtime.js"
20
+ },
21
+ "./jsx-dev-runtime": {
22
+ "types": "./dist/jsx-dev-runtime.d.ts",
23
+ "default": "./dist/jsx-dev-runtime.js"
16
24
  }
17
25
  },
18
26
  "files": [
@@ -20,9 +28,12 @@
20
28
  "README.md"
21
29
  ],
22
30
  "scripts": {
31
+ "test": "vitest run",
32
+ "test:dev": "vitest",
23
33
  "check": "tsc --noEmit",
24
34
  "dev": "tsc --watch",
25
35
  "build": "tsc",
36
+ "format": "prettier --write .",
26
37
  "changeset": "changeset",
27
38
  "version": "changeset version",
28
39
  "release": "npm run build && changeset publish"
@@ -31,6 +42,9 @@
31
42
  "@changesets/cli": "^2.28.1",
32
43
  "@robino/prettier": "^1.0.2",
33
44
  "@robino/tsconfig": "^1.0.2",
34
- "typescript": "^5.8.2"
35
- }
45
+ "prettier": "^3.5.3",
46
+ "typescript": "^5.8.2",
47
+ "vitest": "^3.0.9"
48
+ },
49
+ "prettier": "@robino/prettier"
36
50
  }