@mapl/pattern-router 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aquapi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ A fast pattern router.
2
+
3
+ ## Usage
4
+ A subset of [URLPattern API](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API#automatic_group_prefixing_in_pathnames) patterns are supported.
5
+ ```ts
6
+ import { router_init, router_set, router_remove } from '@mapl/pattern-router';
7
+ import { router_compile_to_matcher } from '@mapl/pattern-router/match';
8
+
9
+ const router = router_init<(req: Request) => Response | Promise<Response>>();
10
+ router_set(router, 'GET', '/', (req) => new Response('Hi'));
11
+ router_set(router, 'GET', '/user/:id(\\d+)', (req, params) => new Response(`user id: ${params.id}`));
12
+ router_set(router, 'PUT', '/post/:id(\\d+)', (req, params) => updatePost(req, params.id));
13
+ router_remove(router, 'GET', '/user/:id(\\d+)');
14
+
15
+ const matcher = router_compile_to_matcher(router);
16
+ matcher.match('GET', '/'); // [(req) => new Response('Hi')]
17
+ matcher.match('GET', '/user/001'); // undefined
18
+ matcher.match('PUT', '/post/001'); // [(req, params) => updatePost(req, params.id), { id: '001' }]
19
+ matcher.match('PUT', '/post/a01'); // undefined
20
+ ```
21
+
22
+ ### Limitations
23
+ Wildcards and unnamed capture groups don't capture. Use named capture groups instead:
24
+ ```ts
25
+ router_set(router, 'GET', '/(\\d+)', ...);
26
+ // change to
27
+ router_set(router, 'GET', '/:id(\\d+)', ...);
28
+ // or without automatic group prefixing
29
+ router_set(router, 'GET', '{/:id(\\d+)}', ...);
30
+ ```
31
+
32
+ Named groups only capture the last matched value in group delimiters with `+` and `*` modifier.
33
+ ```ts
34
+ router_set(router, 'GET', '/post{/:id}+', ...); // '/post/a/b' -> { id: 'b' }
35
+ ```
36
+
37
+ ### JIT
38
+ To wrap compiled code pieces with routing code:
39
+ ```ts
40
+ import { router_init, router_set, router_remove } from '@mapl/pattern-router';
41
+ import { router_compile_to_code } from '@mapl/pattern-router/jit';
42
+
43
+ const router = router_init<string>();
44
+ router_set(router, 'GET', '/', 'return "Home"');
45
+ router_set(router, 'POST', '/forum/:forum+', 'return "Posting to " + matchedResult.groups.forum'); // access matched params
46
+
47
+ const match = (0, eval)(`(method, path) => {${router_compile_to_code(router, 'matchedResult', 'path', 'method')}}`);
48
+
49
+ match('GET', '/'); // "Home"
50
+ match('GET', '/about'); // undefined
51
+ match('POST', '/forum/@mapl/pattern-router'); // "Posting to @mapl/pattern-router"
52
+ ```
53
+
54
+ ### Types
55
+ To infer parameters types of a pattern:
56
+ ```ts
57
+ import type { InferParams } from '@mapl/pattern-router/tree/utils';
58
+
59
+ type T = InferParams<'/:id'>; // { id: string }
60
+ type T = InferParams<'/user/:id?'>; // { id: string | undefined }
61
+ type T = InferParams<'/book{s/:id}?'>; // { id: string | undefined }
62
+ ```
63
+
64
+ ## Compability
65
+ This library requires RegExp [duplicate named capture groups in different disjunction feature](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group#browser_compatibility) support.
package/index.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { type Tree } from "./tree/index.ts";
2
+ import { type LinearMap } from "./linear-map.ts";
3
+ export type Router<T> = LinearMap<string, Tree<T>>;
4
+ export declare const router_init: <T>() => Router<T>;
5
+ export declare const router_set_static: <T>(router: Router<T>, method: string, path: string, store: T) => void;
6
+ export declare const router_set_dynamic: <T>(router: Router<T>, method: string, path: string, store: T) => void;
7
+ export declare const router_set: <T>(router: Router<T>, method: string, path: string, store: T) => void;
8
+ /**
9
+ * @returns true if router is empty
10
+ */
11
+ export declare const router_remove_static: <T>(router: Router<T>, method: string, path: string) => boolean;
12
+ /**
13
+ * @returns true if router is empty
14
+ */
15
+ export declare const router_remove_dynamic: <T>(router: Router<T>, method: string, path: string) => boolean;
16
+ export declare const router_remove: <T>(router: Router<T>, method: string, path: string) => boolean;
package/index.js ADDED
@@ -0,0 +1 @@
1
+ import{tree_init,tree_remove_dynamic,tree_remove_static,tree_set_dynamic,tree_set_static}from"./tree/index.js";import{isDynamicPattern}from"./tree/utils.js";import{linear_map_add,linear_map_get,linear_map_index,linear_map_remove_reordered}from"./linear-map.js";export const router_init=()=>[[],[]];export const router_set_static=(router,method,path,store)=>{let idx=linear_map_index(router,method);if(-1===idx){let tree=tree_init();tree_set_static(tree,path,store);linear_map_add(router,method,tree)}else tree_set_static(linear_map_get(router,idx),path,store)};export const router_set_dynamic=(router,method,path,store)=>{let idx=linear_map_index(router,method);if(-1===idx){let tree=tree_init();tree_set_dynamic(tree,path,store);linear_map_add(router,method,tree)}else tree_set_dynamic(linear_map_get(router,idx),path,store)};export const router_set=(router,method,path,store)=>isDynamicPattern(path)?router_set_dynamic(router,method,path,store):router_set_static(router,method,path,store);export const router_remove_static=(router,method,path)=>{let idx=linear_map_index(router,method);return -1!==idx&&tree_remove_static(linear_map_get(router,idx),path)&&linear_map_remove_reordered(router,idx)};export const router_remove_dynamic=(router,method,path)=>{let idx=linear_map_index(router,method);return -1!==idx&&tree_remove_dynamic(linear_map_get(router,idx),path)&&linear_map_remove_reordered(router,idx)};export const router_remove=(router,method,path)=>isDynamicPattern(path)?router_remove_dynamic(router,method,path):router_remove_static(router,method,path);
package/jit.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { Router } from "./index.ts";
2
+ export declare const router_compile_to_code: (router: Router<string>, resultId: string, pathId: string, methodId: string) => string;
package/jit.js ADDED
@@ -0,0 +1 @@
1
+ import{tree_compile_to_code}from"./tree/jit.js";import{linear_map_index,linear_map_swap}from"./linear-map.js";export const router_compile_to_code=(router,resultId,pathId,methodId)=>{let matchAllIdx=linear_map_index(router,""),trees=router[1];-1!==matchAllIdx&&linear_map_swap(router,matchAllIdx,trees.length-1);let str="";for(let i=0,methods=router[0],treesLen=trees.length-(-1!==matchAllIdx),prefix=`if(${methodId}===`;i<treesLen;i++){str+=prefix+JSON.stringify(methods[i])+`){${tree_compile_to_code(trees[i],resultId,pathId)}}`;0===i&&(prefix="else "+prefix)}return -1!==matchAllIdx?str+tree_compile_to_code(trees[trees.length-1],resultId,pathId):str};
@@ -0,0 +1,23 @@
1
+ export interface LinearMap<
2
+ K,
3
+ V
4
+ > {
5
+ 0: K[];
6
+ 1: V[];
7
+ }
8
+ export declare const linear_map_is_empty: (m: LinearMap<any, any>) => boolean;
9
+ export declare const linear_map_index: <K>(m: LinearMap<K, any>, k: K) => number;
10
+ export declare const linear_map_get: <V>(m: LinearMap<any, V>, i: number) => V;
11
+ /**
12
+ * @returns true if no items remain
13
+ */
14
+ export declare const linear_map_remove_reordered: <V>(m: LinearMap<any, V>, i: number) => boolean;
15
+ export declare const linear_map_swap: <V>(m: LinearMap<any, V>, i: number, newIdx: number) => void;
16
+ export declare const linear_map_add: <
17
+ K,
18
+ V
19
+ >(m: LinearMap<K, V>, k: K, v: V) => void;
20
+ export declare const linear_map_set: <
21
+ K,
22
+ V
23
+ >(m: LinearMap<K, V>, k: K, v: V) => void;
package/linear-map.js ADDED
@@ -0,0 +1 @@
1
+ export const linear_map_is_empty=m=>0===m[0].length;export const linear_map_index=(m,k)=>m[0].indexOf(k);export const linear_map_get=(m,i)=>m[1][i];export const linear_map_remove_reordered=(m,i)=>{let lastIdx=m[0].length-1;if(-1===lastIdx)return!0;let keys=m[0],values=m[1];keys[i]=keys[lastIdx];keys.pop();values[i]=values[lastIdx];values.pop();return 0===keys.length};export const linear_map_swap=(m,i,newIdx)=>{if(i===newIdx)return;let keys=m[0],values=m[1],key=keys[i];keys[i]=keys[newIdx];keys[newIdx]=key;let value=values[i];values[i]=values[newIdx];values[newIdx]=value};export const linear_map_add=(m,k,v)=>{m[0].push(k);m[1].push(v)};export const linear_map_set=(m,k,v)=>{let keys=m[0],idx=keys.indexOf(k);if(-1===idx){keys.push(k);m[1].push(v)}else{keys[idx]=k;m[1][idx]=v}};
package/match.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { Router } from "./index.ts";
2
+ import { type Handlers } from "./tree/regex.ts";
3
+ interface Matcher0<in out T> {
4
+ match: (method: string, path: string) => [T] | [T, RegExpExecArray] | undefined;
5
+ methods: string[];
6
+ staticMaps: Map<string, T>[];
7
+ regexps: (RegExp | null)[];
8
+ handlers: Handlers<T>[];
9
+ }
10
+ interface Matcher1<in out T> extends Matcher0<T> {
11
+ matchAllStaticMap: Map<string, T>;
12
+ }
13
+ interface Matcher2<in out T> extends Matcher1<T> {
14
+ matchAllRegExp: RegExp;
15
+ matchAllHandler: Handlers<T>;
16
+ }
17
+ type Matcher<T> = Matcher0<T> | Matcher1<T> | Matcher2<T>;
18
+ export declare const router_compile_to_matcher: <T>(router: Router<T>) => Matcher<T>;
19
+ export {};
package/match.js ADDED
@@ -0,0 +1 @@
1
+ import{HANDLERS,node_compile_root_to_regexp,reset}from"./tree/regex.js";import{linear_map_index,linear_map_swap}from"./linear-map.js";let match0=function(method,path){let i=this.methods.indexOf(method);if(-1!==i){let handler=this.staticMaps[i].get(path);if(void 0!==handler)return[handler];if(null!==this.regexps[i]){let matchResult=this.regexps[i].exec(path);if(null!==matchResult)return[this.handlers[i][matchResult.lastIndexOf("")],matchResult]}}},match1=function(method,path){let i=this.methods.indexOf(method);if(-1!==i){let handler=this.staticMaps[i].get(path);if(void 0!==handler)return[handler];if(null!==this.regexps[i]){let matchResult=this.regexps[i].exec(path);if(null!==matchResult)return[this.handlers[i][matchResult.lastIndexOf("")],matchResult]}}let match=this.matchAllStaticMap.get(path);if(void 0!==match)return[match]},match2=function(method,path){{let i=this.methods.indexOf(method);if(-1!==i){let handler=this.staticMaps[i].get(path);if(void 0!==handler)return[handler];if(null!==this.regexps[i]){let matchResult=this.regexps[i].exec(path);if(null!==matchResult)return[this.handlers[i][matchResult.lastIndexOf("")],matchResult]}}}let handler=this.matchAllStaticMap.get(path);if(void 0!==handler)return[handler];let matchResult=this.matchAllRegExp.exec(path);if(null!==matchResult)return[this.matchAllHandler[matchResult.lastIndexOf("")],matchResult]};export const router_compile_to_matcher=router=>{let trees=router[1],staticMaps=[],regexps=[],handlers=[];{let matchAllIdx=linear_map_index(router,"");-1!==matchAllIdx&&matchAllIdx!==trees.length-1&&linear_map_swap(router,matchAllIdx,trees.length-1);for(let i=0,treesLen=trees.length-(-1!==matchAllIdx);i<treesLen;i++){let tree=trees[i];{let mp=new Map;for(let i=0,treeKeys=tree[0],treeValues=tree[1];i<treeKeys.length;i++)mp.set(treeKeys[i],treeValues[i]);staticMaps.push(mp)}if(null!==tree[2]){reset();regexps.push(new RegExp(node_compile_root_to_regexp(tree[2])));handlers.push(HANDLERS)}else{regexps.push(null);handlers.push(null)}}if(-1===matchAllIdx)return{match:match0,methods:router[0].slice(),staticMaps,regexps,handlers}}let methods=router[0].slice(0,-1),matchAllTree=trees[trees.length-1],matchAllStaticMap=new Map;for(let i=0,treeKeys=matchAllTree[0],treeValues=matchAllTree[1];i<treeKeys.length;i++)matchAllStaticMap.set(treeKeys[i],treeValues[i]);if(null===matchAllTree[2])return{match:match1,methods,staticMaps,regexps,handlers,matchAllStaticMap};reset();return{match:match2,methods,staticMaps,regexps,handlers,matchAllStaticMap,matchAllRegExp:new RegExp(node_compile_root_to_regexp(matchAllTree[2])),matchAllHandler:HANDLERS}};
package/package.json ADDED
@@ -0,0 +1 @@
1
+ {"name":"@mapl/pattern-router","version":"0.0.1","description":"A fast URLPattern router.","keywords":[],"homepage":"","license":"MIT","repository":"","type":"module","exports":{"./*":"./*.js",".":"./index.js","./tree":"./tree/index.js"}}
@@ -0,0 +1,16 @@
1
+ import { type LinearMap } from "../linear-map.ts";
2
+ import { type Node } from "./node.ts";
3
+ export interface Tree<T> extends LinearMap<string, T> {
4
+ 2: Node<T> | null;
5
+ }
6
+ export declare const tree_init: <T>() => Tree<T>;
7
+ export declare const tree_set_static: <T>(tree: Tree<T>, path: string, store: T) => void;
8
+ export declare const tree_set_dynamic: <T>(tree: Tree<T>, path: string, store: T) => void;
9
+ /**
10
+ * @returns true if the tree has no item
11
+ */
12
+ export declare const tree_remove_static: <T>(tree: Tree<T>, path: string) => boolean;
13
+ /**
14
+ * @returns true if the tree has no item
15
+ */
16
+ export declare const tree_remove_dynamic: <T>(tree: Tree<T>, path: string) => boolean;
package/tree/index.js ADDED
@@ -0,0 +1 @@
1
+ import{linear_map_add,linear_map_index,linear_map_is_empty,linear_map_remove_reordered}from"../linear-map.js";import{node_insert,node_remove}from"./node.js";import{validatePattern}from"./utils.js";export const tree_init=()=>[[],[],null];export const tree_set_static=linear_map_add;export const tree_set_dynamic=(tree,path,store)=>{validatePattern(path);node_insert(tree[2]??=["",null,null,null,null,null,null],path,0,store)};export const tree_remove_static=(tree,path)=>{let idx=linear_map_index(tree,path);return -1!==idx&&linear_map_remove_reordered(tree,idx)&&null===tree[2]};export const tree_remove_dynamic=(tree,path)=>{validatePattern(path);return null!==tree[2]&&node_remove(tree[2],path,0)&&(tree[2]=null,linear_map_is_empty(tree))};
package/tree/jit.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { Tree } from "./index.ts";
2
+ export declare const tree_compile_to_code: (tree: Tree<string>, resultId: string, pathId: string) => string;
package/tree/jit.js ADDED
@@ -0,0 +1 @@
1
+ import{node_compile_root_to_regexp,HANDLERS,reset}from"./regex.js";export const tree_compile_to_code=(tree,resultId,pathId)=>{let str="",keys=tree[0],values=tree[1];if(keys.length>0)for(let i=0,prefix=`if(${pathId}===`;i<keys.length;i++){str+=prefix+JSON.stringify(keys[i])+`){${values[i]}}`;0===i&&(prefix="else "+prefix)}if(null!==tree[2]){reset();str+=`let ${resultId}=/${node_compile_root_to_regexp(tree[2])}/.exec(${pathId});if(${resultId}!==null){`;for(let i=1,hasHandler=!1,startIf=`if(${resultId}[`;i<HANDLERS.length;i++)if(null!==HANDLERS[i]){str+=startIf+i+`]===""){${HANDLERS[i]}}`;if(!hasHandler){hasHandler=!0;startIf="else "+startIf}}str+="}"}return str};
package/tree/node.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { type LinearMap } from "../linear-map.ts";
2
+ export type Node<T> = [prefix: string, store: T | null, staticChildren: LinearMap<string, Node<T>> | null, delimGroups: LinearMap<string, ConnectNode<T>> | null, unnamedGroups: LinearMap<string, ConnectNode<T>> | null, namedGroups: LinearMap<string, ConnectNode<T>> | null, wildcard: ConnectNode<T> | null];
3
+ export type ConnectNode<T> = [store: T | null, next: Node<T> | null];
4
+ export declare const node_create: <T>(path: string, pathIdx: number, store: T) => Node<T>;
5
+ export declare const connect_node_insert_to_map: <T>(map: LinearMap<string, ConnectNode<T>>, groupKey: string, path: string, groupEndIdx: number, store: T) => void;
6
+ export declare const node_insert: <T>(node: Node<T>, path: string, pathIdx: number, store: T) => void;
7
+ /**
8
+ * @returns true if no items remain
9
+ */
10
+ export declare const connect_node_remove_from_map: (map: LinearMap<string, ConnectNode<any>>, key: string, path: string, pathIdx: number) => boolean;
11
+ /**
12
+ * @returns true if this connect node is empty
13
+ */
14
+ export declare const connect_node_remove: (node: ConnectNode<any>, path: string, pathIdx: number) => boolean;
15
+ /**
16
+ * @returns true if this node is empty
17
+ */
18
+ export declare const node_remove: (node: Node<any>, path: string, pathIdx: number) => boolean;
package/tree/node.js ADDED
@@ -0,0 +1 @@
1
+ import{linear_map_add,linear_map_get,linear_map_index,linear_map_remove_reordered}from"../linear-map.js";import{findGroupDelimEnd,findNamedGroupEnd,findUnnamedGroupEnd}from"./utils.js";export const node_create=(path,pathIdx,store)=>{let prevIdx=pathIdx;while(pathIdx<path.length){switch(path[pathIdx]){case"{":{let groupEndIdx=findGroupDelimEnd(path,pathIdx+1),groupKey=path.slice(pathIdx+1,groupEndIdx);return[path.slice(prevIdx,pathIdx),null,null,[[groupKey],[groupEndIdx===path.length?[store,null]:[null,node_create(path,groupEndIdx,store)]]],null,null,null]}case"(":{let groupEndIdx=findUnnamedGroupEnd(path,pathIdx+1),groupKey=path.slice(pathIdx,groupEndIdx);return[path.slice(prevIdx,pathIdx),null,null,null,[[groupKey],[groupEndIdx===path.length?[store,null]:[null,node_create(path,groupEndIdx,store)]]],null,null]}case"/":if(pathIdx+1===path.length||":"!==path[pathIdx+1])break;case":":{let groupEndIdx=findNamedGroupEnd(path,pathIdx,path.length),groupKey=path.slice(pathIdx,groupEndIdx);return[path.slice(prevIdx,pathIdx),null,null,null,null,[[groupKey],[groupEndIdx===path.length?[store,null]:[null,node_create(path,groupEndIdx,store)]]],null]}case"*":return[path.slice(prevIdx,pathIdx),null,null,null,null,null,pathIdx+1===path.length?[store,null]:[null,node_create(path,pathIdx+1,store)]]}pathIdx++}return[path.slice(prevIdx),store,null,null,null,null,null]};export const connect_node_insert_to_map=(map,groupKey,path,groupEndIdx,store)=>{let idx=linear_map_index(map,groupKey);if(-1===idx)linear_map_add(map,groupKey,groupEndIdx===path.length?[store,null]:[null,node_create(path,groupEndIdx,store)]);else{let connectNode=linear_map_get(map,idx);groupEndIdx===path.length?connectNode[0]=store:null===connectNode[1]?connectNode[1]=node_create(path,groupEndIdx,store):node_insert(connectNode[1],path,groupEndIdx,store)}};export const node_insert=(node,path,pathIdx,store)=>{let nodePath=node[0],nodePathIdx=0;while(1){let pathChar=path[pathIdx];if(nodePathIdx===nodePath.length){switch(pathChar){case"{":{let groupEndIdx=findGroupDelimEnd(path,pathIdx+1),groupKey=path.slice(pathIdx+1,groupEndIdx);null===node[3]?node[3]=[[groupKey],[groupEndIdx===path.length?[store,null]:[null,node_create(path,groupEndIdx,store)]]]:connect_node_insert_to_map(node[3],groupKey,path,groupEndIdx,store);return}case"(":{let groupEndIdx=findUnnamedGroupEnd(path,pathIdx+1),groupKey=path.slice(pathIdx,groupEndIdx);null===node[4]?node[4]=[[groupKey],[groupEndIdx===path.length?[store,null]:[null,node_create(path,groupEndIdx,store)]]]:connect_node_insert_to_map(node[4],groupKey,path,groupEndIdx,store);return}case"/":if(pathIdx+1===path.length||":"!==path[pathIdx+1])break;case":":{let groupEndIdx=findNamedGroupEnd(path,pathIdx,path.length),groupKey=path.slice(pathIdx,groupEndIdx);null===node[5]?node[5]=[[groupKey],[groupEndIdx===path.length?[store,null]:[null,node_create(path,groupEndIdx,store)]]]:connect_node_insert_to_map(node[5],groupKey,path,groupEndIdx,store);return}case"*":if(pathIdx+1===path.length)null===node[6]?node[6]=[store,null]:node[6][0]=store;else if(null===node[6])node[6]=[null,node_create(path,pathIdx+1,store)];else{let connectNode=node[6];if(null===connectNode[1])connectNode[1]=node_create(path,pathIdx+1,store);else{node=connectNode[1];pathIdx++;nodePath=node[0];nodePathIdx=0;continue}}return}if(null===node[2])node[2]=[[pathChar],[node_create(path,pathIdx,store)]];else{let map=node[2],idx=linear_map_index(map,pathChar);if(-1===idx)linear_map_add(map,pathChar,node_create(path,pathIdx,store));else{node=linear_map_get(map,idx);pathIdx++;nodePath=node[0];nodePathIdx=1;continue}}}else{let nodePathChar=nodePath[nodePathIdx];if(pathChar!==nodePathChar){let movedNode=[nodePath.slice(nodePathIdx),node[1],node[2],node[3],node[4],node[5],node[6]];nodePath=node[0]=nodePath.slice(0,nodePathIdx);node[1]=node[3]=node[4]=node[5]=node[6]=null;node[2]=[[nodePathChar],[movedNode]];continue}pathIdx++;nodePathIdx++;if(pathIdx!==path.length)continue;if(nodePathIdx<nodePath.length){let movedNode=[nodePath.slice(nodePathIdx),node[1],node[2],node[3],node[4],node[5],node[6]];node[0]=nodePath.slice(0,nodePathIdx);node[3]=node[4]=node[5]=node[6]=null;node[2]=[[nodePathChar],[movedNode]]}node[1]=store}return}};export const connect_node_remove_from_map=(map,key,path,pathIdx)=>{let idx=linear_map_index(map,key);return -1!==idx&&connect_node_remove(linear_map_get(map,idx),path,pathIdx)&&linear_map_remove_reordered(map,idx)};export const connect_node_remove=(node,path,pathIdx)=>pathIdx===path.length?(node[0]=null,null===node[1]):node_remove(node[1],path,pathIdx)&&(node[1]=null,null===node[0]);export const node_remove=(node,path,pathIdx)=>{if(!path.startsWith(node[0],pathIdx))return!1;pathIdx+=node[0].length;if(pathIdx===path.length){node[1]=null;return null===node[2]&&null===node[3]&&null===node[4]&&null===node[5]&&null===node[6]}{switch(path[pathIdx]){case"{":{if(null===node[3])return!1;let groupEndIdx=findGroupDelimEnd(path,pathIdx+1);return connect_node_remove_from_map(node[3],path.slice(pathIdx+1,groupEndIdx),path,groupEndIdx)&&(node[3]=null,null===node[1]&&null===node[2]&&null===node[4]&&null===node[5]&&null===node[6])}case"(":{if(null===node[4])return!1;let groupEndIdx=findUnnamedGroupEnd(path,pathIdx+1);return connect_node_remove_from_map(node[4],path.slice(pathIdx,groupEndIdx),path,groupEndIdx)&&(node[4]=null,null===node[1]&&null===node[2]&&null===node[3]&&null===node[5]&&null===node[6])}case"/":if(pathIdx+1===path.length||":"!==path[pathIdx+1])break;case":":{if(null===node[5])return!1;let groupEndIdx=findNamedGroupEnd(path,pathIdx,path.length);return connect_node_remove_from_map(node[5],path.slice(pathIdx,groupEndIdx),path,groupEndIdx)&&(node[5]=null,null===node[1]&&null===node[2]&&null===node[3]&&null===node[4]&&null===node[6])}case"*":return null!==node[6]&&connect_node_remove(node[6],path,pathIdx+1)&&(node[6]=null,null===node[1]&&null===node[2]&&null===node[3]&&null===node[4]&&null===node[5])}if(null===node[2])return!1;let map=node[2],idx=linear_map_index(map,path[pathIdx]);return -1!==idx&&node_remove(linear_map_get(map,idx),path,pathIdx)&&linear_map_remove_reordered(map,idx)&&(node[2]=null,null===node[1]&&null===node[3]&&null===node[4]&&null===node[5]&&null===node[6])}};
@@ -0,0 +1,12 @@
1
+ import type { ConnectNode, Node } from "./node.ts";
2
+ export type Handlers<T> = (T | null)[];
3
+ export declare const escapeStaticPart: (str: string) => string;
4
+ export declare const parseNamedGroup: (key: string, curIdx: number, endIdx: number) => string;
5
+ export declare let HANDLERS!: Handlers<any>;
6
+ export declare const reset: () => void;
7
+ /**
8
+ * @returns pattern with additional |
9
+ */
10
+ export declare const connect_node_compile_to_regexp: (connectNode: ConnectNode<unknown>) => string;
11
+ export declare const node_compile_to_regexp: (node: Node<unknown>) => string;
12
+ export declare const node_compile_root_to_regexp: (root: Node<unknown>) => string;
package/tree/regex.js ADDED
@@ -0,0 +1 @@
1
+ import{findNamedGroupEnd,findUnnamedGroupEnd,isModifier}from"./utils.js";export const escapeStaticPart=str=>str.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1");export const parseNamedGroup=(key,curIdx,endIdx)=>{let autoGroupPrefixing="/"===key[curIdx],startIdx=curIdx+(autoGroupPrefixing?2:1);curIdx=startIdx;let modifier=key[endIdx-1];while(1){if(curIdx===endIdx){let namedCapture=`(?<${key.slice(startIdx,endIdx+(isModifier(modifier)?-1:0))}>`;return autoGroupPrefixing?"?"===modifier?`(?:\\/${namedCapture}[^/]+))?`:"+"===modifier?`\\/${namedCapture}.+)`:"*"===modifier?`(?:\\/${namedCapture}.+))?`:`\\/${namedCapture}[^/]+)`:namedCapture+("?"===modifier?"[^/]+)?":"*"===modifier?"[^/]*)":"[^/]+)")}if("("===key[curIdx]){let regex="(?:"+key.slice(curIdx+1,findUnnamedGroupEnd(key,curIdx+1)),namedCapture=`(?<${key.slice(startIdx,curIdx)}>`;return autoGroupPrefixing?"?"===modifier?`(?:\\/${namedCapture+regex}))?`:"+"===modifier?`\\/${namedCapture+regex}(?:\\/${regex})*)`:"*"===modifier?`(?:\\/${namedCapture+regex}(?:\\/${regex})*))?`:`\\/${namedCapture+regex})`:namedCapture+("?"===modifier?regex+")?":"+"===modifier?`(?:${regex})+)`:"*"===modifier?`(?:${regex})*)`:regex+")")}curIdx++}};export let HANDLERS;export const reset=()=>{HANDLERS=[null]};export const connect_node_compile_to_regexp=connectNode=>{if(null!==connectNode[0]){HANDLERS.push(connectNode[0]);return null===connectNode[1]?"()$|":`(?:()$|${node_compile_to_regexp(connectNode[1])})|`}return node_compile_to_regexp(connectNode[1])+"|"};export const node_compile_to_regexp=node=>{let parts="",partsCnt=0;if(null!==node[1]){partsCnt=1;HANDLERS.push(node[1]);parts+="()$|"}if(null!==node[2])for(let i=0,staticChildren=node[2][1];i<staticChildren.length;i++,partsCnt++)parts+=node_compile_to_regexp(staticChildren[i])+"|";if(null!==node[3])for(let i=0,patterns=node[3][0],connectNodes=node[3][1];i<connectNodes.length;i++,partsCnt++){let patternPrevIdx=0,pattern=patterns[i],modifier=pattern[pattern.length-1],hasModifier="}"!==modifier,patternLen=pattern.length-(hasModifier?2:1);hasModifier&&(parts+="(?:");for(let patternIdx=0;patternIdx<patternLen;){switch(pattern[patternIdx]){case"(":{let patternRegexEnd=findUnnamedGroupEnd(pattern,patternIdx+1);parts+=escapeStaticPart(pattern.slice(patternPrevIdx,patternIdx))+"(?:"+pattern.slice(patternIdx+1,patternRegexEnd);patternPrevIdx=patternIdx=patternRegexEnd;continue}case":":{let groupEndIdx=findNamedGroupEnd(pattern,patternIdx,patternLen);HANDLERS.push(null);parts+=escapeStaticPart(pattern.slice(patternPrevIdx,patternIdx))+parseNamedGroup(pattern,patternIdx,groupEndIdx);patternPrevIdx=patternIdx=groupEndIdx+1;continue}}patternIdx++}parts+=escapeStaticPart(pattern.slice(patternPrevIdx,patternLen))+(hasModifier?")"+modifier:"")+connect_node_compile_to_regexp(connectNodes[i])}if(null!==node[4])for(let i=0,regexps=node[4][0],connectNodes=node[4][1];i<regexps.length;i++,partsCnt++)parts+="(?:"+regexps[i].slice(1)+connect_node_compile_to_regexp(connectNodes[i]);if(null!==node[5])for(let i=0,keys=node[5][0],connectNodes=node[5][1];i<keys.length;i++,partsCnt++){HANDLERS.push(null);parts+=parseNamedGroup(keys[i],0,keys[i].length)+connect_node_compile_to_regexp(connectNodes[i])}if(null!==node[6]){partsCnt++;parts+=".*"+connect_node_compile_to_regexp(node[6])}parts=partsCnt>1?`(?:${parts.slice(0,-1)})`:parts.slice(0,-1);return node[0].length>0?escapeStaticPart(node[0])+parts:parts};export const node_compile_root_to_regexp=root=>`^(?:${node_compile_to_regexp(root)}|$.)`;
@@ -0,0 +1,31 @@
1
+ export type Evaluate<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
2
+ export type SkipCaptureGroup<
3
+ Path extends string,
4
+ Stack extends 0[]
5
+ > = Path extends `${string}(${infer Rest}` ? SkipCaptureGroup<Rest, [...Stack, 0]> : Path extends `${string})${infer Rest}` ? Stack extends [...infer RestStack extends 0[], 0] ? SkipCaptureGroup<Rest, RestStack> : never : Stack["length"] extends 0 ? Path : never;
6
+ export type InferNamedGroup<
7
+ Group extends string,
8
+ OptionalSep extends string
9
+ > = Group extends `${infer Name}${OptionalSep}${infer Rest}` ? Evaluate<{ [key in Name]: string | undefined } & InferParams<Rest>> : Group extends `${infer Name}${"{" | "}" | "+" | "*" | "/" | "." | "@" | "[" | "]" | "-" | "=" | "%"}${infer Rest}` ? Evaluate<{ [key in Name]: string } & InferParams<Rest>> : Group extends `${infer Name}:${infer Rest}` ? Evaluate<{ [key in Name]: string } & InferNamedGroup<Rest, "?">> : { [key in Group]: string };
10
+ export type InferParams<Path extends string> = Path extends `${infer Prefix}(${infer Suffix}` ? InferParams<`${Prefix}${SkipCaptureGroup<Suffix, [0]>}`> : Path extends `${infer Prefix}{${infer Body}}?${infer Suffix}` ? Evaluate<InferParams<Prefix> & { [K in keyof InferParams<Body>]: string | undefined } & InferParams<Suffix>> : Path extends `${string}/:${infer Group}` ? InferNamedGroup<Group, "?" | "*"> : Path extends `${string}:${infer Group}` ? InferNamedGroup<Group, "?"> : {};
11
+ export declare const checkEndModifier: (path: string, groupEndIdx: number) => number;
12
+ /**
13
+ * @param path
14
+ * @param startIdx position after {
15
+ * @returns position after } or a modifier
16
+ */
17
+ export declare const findGroupDelimEnd: (path: string, startIdx: number) => number;
18
+ /**
19
+ * @param path
20
+ * @param startIdx position after (
21
+ * @returns position after )
22
+ */
23
+ export declare const findUnnamedGroupEnd: (path: string, startIdx: number) => number;
24
+ /**
25
+ * @param path
26
+ * @param startIdx position of : or /:
27
+ */
28
+ export declare const findNamedGroupEnd: (path: string, startIdx: number, len: number) => number;
29
+ export declare const isDynamicPattern: (pat: string) => boolean;
30
+ export declare const validatePattern: (pat: string) => URLPattern;
31
+ export declare const isModifier: (modifier: string) => boolean;
package/tree/utils.js ADDED
@@ -0,0 +1 @@
1
+ export const checkEndModifier=(path,groupEndIdx)=>{if(groupEndIdx<path.length)switch(path[groupEndIdx]){case"+":case"*":case"?":return groupEndIdx+1}return groupEndIdx};export const findGroupDelimEnd=(path,startIdx)=>checkEndModifier(path,path.indexOf("}",startIdx)+1);export const findUnnamedGroupEnd=(path,startIdx)=>{let stack=1;while(1){if(")"===path[startIdx]){if(0===--stack)return checkEndModifier(path,startIdx+1)}else"("===path[startIdx]&&stack++;startIdx++}};export const findNamedGroupEnd=(path,startIdx,len)=>{let groupEndIdx=startIdx+2;while(groupEndIdx<len){switch(path[groupEndIdx]){case"*":case"+":case"?":return groupEndIdx+1;case"(":groupEndIdx=findUnnamedGroupEnd(path,groupEndIdx+1);continue;case"{":case"}":case"/":case":":case".":case"@":case"[":case"]":case"-":case"=":case"%":return groupEndIdx}groupEndIdx++}return groupEndIdx};export const isDynamicPattern=pat=>/[({:*]/.test(pat);export const validatePattern=pat=>new URLPattern({pathname:pat});export const isModifier=modifier=>"?"===modifier||"+"===modifier||"*"===modifier;