@oomfware/stacker 0.1.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/LICENSE +14 -0
- package/README.md +286 -0
- package/dist/index.d.mts +548 -0
- package/dist/index.mjs +1102 -0
- package/dist/testing.d.mts +33 -0
- package/dist/testing.mjs +121 -0
- package/dist/types-Dj7Al7f8.d.mts +129 -0
- package/dist/url-CoOVqRk_.mjs +37 -0
- package/package.json +74 -0
- package/src/build.ts +53 -0
- package/src/cache.ts +53 -0
- package/src/codec.ts +182 -0
- package/src/history/memory.ts +155 -0
- package/src/history/navigation.ts +213 -0
- package/src/history/types.ts +133 -0
- package/src/index.ts +52 -0
- package/src/keys.ts +41 -0
- package/src/match.ts +180 -0
- package/src/react/context.ts +18 -0
- package/src/react/hooks.ts +178 -0
- package/src/react/link.tsx +61 -0
- package/src/react/outlet.tsx +18 -0
- package/src/react/router-view.tsx +79 -0
- package/src/router.ts +397 -0
- package/src/routes.ts +325 -0
- package/src/testing.ts +2 -0
- package/src/url.ts +41 -0
- package/src/view-model.ts +78 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { a as HistoryLocation, i as HistoryListener, o as HistoryNavigateOptions, r as HistoryEntry, t as History } from "./types-Dj7Al7f8.mjs";
|
|
2
|
+
//#region src/history/memory.d.ts
|
|
3
|
+
/** options for the memory history constructor. */
|
|
4
|
+
interface MemoryHistoryOptions {
|
|
5
|
+
/** initially active entry index. */
|
|
6
|
+
readonly index?: number;
|
|
7
|
+
/** initial entry relative URLs. */
|
|
8
|
+
readonly initialEntries?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* in-memory history manager for testing.
|
|
12
|
+
*
|
|
13
|
+
* replicates browser navigation ledger semantics, including history replacement, entry stack pruning, and
|
|
14
|
+
* state traversal.
|
|
15
|
+
*/
|
|
16
|
+
declare class MemoryHistory implements History {
|
|
17
|
+
#private;
|
|
18
|
+
constructor(options?: MemoryHistoryOptions);
|
|
19
|
+
get location(): HistoryLocation;
|
|
20
|
+
get canGoBack(): boolean;
|
|
21
|
+
get canGoForward(): boolean;
|
|
22
|
+
entries(): readonly HistoryEntry[];
|
|
23
|
+
push(to: string, options?: HistoryNavigateOptions): void;
|
|
24
|
+
replace(to: string, options?: HistoryNavigateOptions): void;
|
|
25
|
+
traverseTo(key: string): void;
|
|
26
|
+
go(delta: number): void;
|
|
27
|
+
back(): void;
|
|
28
|
+
forward(): void;
|
|
29
|
+
listen(listener: HistoryListener): () => void;
|
|
30
|
+
dispose(): void;
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
export { MemoryHistory, type MemoryHistoryOptions };
|
package/dist/testing.mjs
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { r as resolvePath, t as createPath } from "./url-CoOVqRk_.mjs";
|
|
2
|
+
import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
|
|
3
|
+
//#region src/history/memory.ts
|
|
4
|
+
const ROOT = {
|
|
5
|
+
hash: "",
|
|
6
|
+
pathname: "/",
|
|
7
|
+
search: ""
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* in-memory history manager for testing.
|
|
11
|
+
*
|
|
12
|
+
* replicates browser navigation ledger semantics, including history replacement, entry stack pruning, and
|
|
13
|
+
* state traversal.
|
|
14
|
+
*/
|
|
15
|
+
var MemoryHistory = class {
|
|
16
|
+
#entries;
|
|
17
|
+
#index;
|
|
18
|
+
#idSeq = 0;
|
|
19
|
+
#keySeq = 0;
|
|
20
|
+
#updates = new SimpleEventEmitter();
|
|
21
|
+
constructor(options = {}) {
|
|
22
|
+
const initialEntries = options.initialEntries ?? ["/"];
|
|
23
|
+
this.#entries = initialEntries.map((to, i) => this.#make(to, ROOT, this.#nextId(), this.#nextKey(), i, null));
|
|
24
|
+
this.#index = Math.max(0, Math.min(options.index ?? this.#entries.length - 1, this.#entries.length - 1));
|
|
25
|
+
}
|
|
26
|
+
get location() {
|
|
27
|
+
return this.#current();
|
|
28
|
+
}
|
|
29
|
+
get canGoBack() {
|
|
30
|
+
return this.#index > 0;
|
|
31
|
+
}
|
|
32
|
+
get canGoForward() {
|
|
33
|
+
return this.#index < this.#entries.length - 1;
|
|
34
|
+
}
|
|
35
|
+
entries() {
|
|
36
|
+
return this.#entries.map((location) => ({
|
|
37
|
+
id: location.id,
|
|
38
|
+
index: location.index,
|
|
39
|
+
key: location.key,
|
|
40
|
+
sameDocument: true,
|
|
41
|
+
state: location.state,
|
|
42
|
+
url: createPath(location)
|
|
43
|
+
}));
|
|
44
|
+
}
|
|
45
|
+
push(to, options = {}) {
|
|
46
|
+
const base = this.#current();
|
|
47
|
+
this.#index += 1;
|
|
48
|
+
const location = this.#make(to, base, this.#nextId(), this.#nextKey(), this.#index, options.state ?? null);
|
|
49
|
+
this.#entries = [...this.#entries.slice(0, this.#index), location];
|
|
50
|
+
this.#emit({
|
|
51
|
+
action: "push",
|
|
52
|
+
info: options.info,
|
|
53
|
+
location
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
replace(to, options = {}) {
|
|
57
|
+
const current = this.#current();
|
|
58
|
+
const location = this.#make(to, current, this.#nextId(), current.key, this.#index, options.state ?? null);
|
|
59
|
+
this.#entries = this.#entries.with(this.#index, location);
|
|
60
|
+
this.#emit({
|
|
61
|
+
action: "replace",
|
|
62
|
+
info: options.info,
|
|
63
|
+
location
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
traverseTo(key) {
|
|
67
|
+
const index = this.#entries.findIndex((entry) => entry.key === key);
|
|
68
|
+
if (index === -1) throw new Error(`stacker: no history entry with key '${key}'`);
|
|
69
|
+
this.go(index - this.#index);
|
|
70
|
+
}
|
|
71
|
+
go(delta) {
|
|
72
|
+
const next = Math.max(0, Math.min(this.#index + delta, this.#entries.length - 1));
|
|
73
|
+
if (next === this.#index) return;
|
|
74
|
+
this.#index = next;
|
|
75
|
+
this.#emit({
|
|
76
|
+
action: "traverse",
|
|
77
|
+
info: void 0,
|
|
78
|
+
location: this.#current()
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
back() {
|
|
82
|
+
this.go(-1);
|
|
83
|
+
}
|
|
84
|
+
forward() {
|
|
85
|
+
this.go(1);
|
|
86
|
+
}
|
|
87
|
+
listen(listener) {
|
|
88
|
+
return this.#updates.subscribe(listener);
|
|
89
|
+
}
|
|
90
|
+
dispose() {
|
|
91
|
+
this.#updates = new SimpleEventEmitter();
|
|
92
|
+
}
|
|
93
|
+
#nextId() {
|
|
94
|
+
return `i${this.#idSeq++}`;
|
|
95
|
+
}
|
|
96
|
+
#nextKey() {
|
|
97
|
+
return `k${this.#keySeq++}`;
|
|
98
|
+
}
|
|
99
|
+
#make(to, base, id, key, index, state) {
|
|
100
|
+
const { hash, pathname, search } = resolvePath(to, base);
|
|
101
|
+
return {
|
|
102
|
+
hash,
|
|
103
|
+
id,
|
|
104
|
+
index,
|
|
105
|
+
key,
|
|
106
|
+
pathname,
|
|
107
|
+
search,
|
|
108
|
+
state
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
#current() {
|
|
112
|
+
const location = this.#entries[this.#index];
|
|
113
|
+
if (location === void 0) throw new Error("stacker: memory history has no active entry");
|
|
114
|
+
return location;
|
|
115
|
+
}
|
|
116
|
+
#emit(update) {
|
|
117
|
+
this.#updates.emit(update);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
//#endregion
|
|
121
|
+
export { MemoryHistory };
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
//#region src/history/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* the type of navigation that produced a history update.
|
|
4
|
+
*
|
|
5
|
+
* - `push` — a new entry was added.
|
|
6
|
+
* - `replace` — the active entry was replaced.
|
|
7
|
+
* - `traverse` — navigation occurred to an existing entry.
|
|
8
|
+
*/
|
|
9
|
+
type HistoryAction = 'push' | 'replace' | 'traverse';
|
|
10
|
+
/** an entry in the browser session history ledger. */
|
|
11
|
+
interface HistoryEntry {
|
|
12
|
+
/** unique per-revision identifier. */
|
|
13
|
+
readonly id: string;
|
|
14
|
+
/** entry position in the ledger. */
|
|
15
|
+
readonly index: number;
|
|
16
|
+
/** slot identity preserved across replacements. */
|
|
17
|
+
readonly key: string;
|
|
18
|
+
/** whether traversal to this entry stays within the current document. */
|
|
19
|
+
readonly sameDocument: boolean;
|
|
20
|
+
/** state associated with the entry. */
|
|
21
|
+
readonly state: unknown;
|
|
22
|
+
/** entry URL or null if hidden. */
|
|
23
|
+
readonly url: string | null;
|
|
24
|
+
}
|
|
25
|
+
/** active history entry with parsed URL components. */
|
|
26
|
+
interface HistoryLocation {
|
|
27
|
+
/** URL fragment including the leading hash symbol. */
|
|
28
|
+
readonly hash: string;
|
|
29
|
+
/** per-revision identifier. */
|
|
30
|
+
readonly id: string;
|
|
31
|
+
/** entry position in the ledger. */
|
|
32
|
+
readonly index: number;
|
|
33
|
+
/** slot identity. */
|
|
34
|
+
readonly key: string;
|
|
35
|
+
/** URL pathname starting with a slash. */
|
|
36
|
+
readonly pathname: string;
|
|
37
|
+
/** URL query string including the leading question mark. */
|
|
38
|
+
readonly search: string;
|
|
39
|
+
/** state associated with the entry. */
|
|
40
|
+
readonly state: unknown;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* how a history write treats the user's place on the page — scroll position and focus, which the browser
|
|
44
|
+
* resets together and which a write therefore cannot sensibly split apart.
|
|
45
|
+
*
|
|
46
|
+
* - `auto` — a new screen. the browser restores scroll on a traversal or resets it on a push, and moves focus
|
|
47
|
+
* to the new content.
|
|
48
|
+
* - `preserve` — the same screen with different state, like an in-place parameter patch. scroll and focus are
|
|
49
|
+
* both left exactly where the user put them.
|
|
50
|
+
*/
|
|
51
|
+
type HistoryScrollBehavior = 'auto' | 'preserve';
|
|
52
|
+
/** options for history write operations. */
|
|
53
|
+
interface HistoryNavigateOptions {
|
|
54
|
+
/** arbitrary metadata passed to history listeners. */
|
|
55
|
+
readonly info?: unknown;
|
|
56
|
+
/** scroll and focus behavior. */
|
|
57
|
+
readonly scroll?: HistoryScrollBehavior;
|
|
58
|
+
/** state data associated with the entry. */
|
|
59
|
+
readonly state?: unknown;
|
|
60
|
+
}
|
|
61
|
+
/** history update details dispatched to listeners. */
|
|
62
|
+
interface HistoryUpdate {
|
|
63
|
+
readonly action: HistoryAction;
|
|
64
|
+
/** metadata passed to the write operation. */
|
|
65
|
+
readonly info: unknown;
|
|
66
|
+
readonly location: HistoryLocation;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* history update callback subscriber.
|
|
70
|
+
*
|
|
71
|
+
* listeners can return a promise to defer scroll restoration and focus resets.
|
|
72
|
+
*/
|
|
73
|
+
type HistoryListener = (update: HistoryUpdate) => void | Promise<void>;
|
|
74
|
+
/** history manager interface modeled on the web navigation API. */
|
|
75
|
+
interface History {
|
|
76
|
+
/** whether a backward entry exists. */
|
|
77
|
+
readonly canGoBack: boolean;
|
|
78
|
+
/** whether a forward entry exists. */
|
|
79
|
+
readonly canGoForward: boolean;
|
|
80
|
+
/** active history location. */
|
|
81
|
+
readonly location: HistoryLocation;
|
|
82
|
+
/** navigates back one entry. */
|
|
83
|
+
back(): void;
|
|
84
|
+
/** detaches listeners and cleans up resources. */
|
|
85
|
+
dispose(): void;
|
|
86
|
+
/**
|
|
87
|
+
* lists all entries in the ledger.
|
|
88
|
+
*
|
|
89
|
+
* @returns array of history entries
|
|
90
|
+
*/
|
|
91
|
+
entries(): readonly HistoryEntry[];
|
|
92
|
+
/** navigates forward one entry. */
|
|
93
|
+
forward(): void;
|
|
94
|
+
/**
|
|
95
|
+
* navigates by a delta offset.
|
|
96
|
+
*
|
|
97
|
+
* @param delta number of entries to move
|
|
98
|
+
*/
|
|
99
|
+
go(delta: number): void;
|
|
100
|
+
/**
|
|
101
|
+
* subscribes to history updates.
|
|
102
|
+
*
|
|
103
|
+
* @param listener update callback
|
|
104
|
+
* @returns unsubscribe function
|
|
105
|
+
*/
|
|
106
|
+
listen(listener: HistoryListener): () => void;
|
|
107
|
+
/**
|
|
108
|
+
* pushes a new history entry.
|
|
109
|
+
*
|
|
110
|
+
* @param to destination relative URL
|
|
111
|
+
* @param options navigation options
|
|
112
|
+
*/
|
|
113
|
+
push(to: string, options?: HistoryNavigateOptions): void;
|
|
114
|
+
/**
|
|
115
|
+
* replaces the active history entry.
|
|
116
|
+
*
|
|
117
|
+
* @param to destination relative URL
|
|
118
|
+
* @param options navigation options
|
|
119
|
+
*/
|
|
120
|
+
replace(to: string, options?: HistoryNavigateOptions): void;
|
|
121
|
+
/**
|
|
122
|
+
* navigates to an existing entry by key.
|
|
123
|
+
*
|
|
124
|
+
* @param key target entry key
|
|
125
|
+
*/
|
|
126
|
+
traverseTo(key: string): void;
|
|
127
|
+
}
|
|
128
|
+
//#endregion
|
|
129
|
+
export { HistoryLocation as a, HistoryListener as i, HistoryAction as n, HistoryNavigateOptions as o, HistoryEntry as r, HistoryUpdate as s, History as t };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region src/url.ts
|
|
2
|
+
const parsePath = (to) => {
|
|
3
|
+
let pathname = to;
|
|
4
|
+
let search = "";
|
|
5
|
+
let hash = "";
|
|
6
|
+
const hashIndex = pathname.indexOf("#");
|
|
7
|
+
if (hashIndex >= 0) {
|
|
8
|
+
hash = pathname.slice(hashIndex);
|
|
9
|
+
pathname = pathname.slice(0, hashIndex);
|
|
10
|
+
}
|
|
11
|
+
const searchIndex = pathname.indexOf("?");
|
|
12
|
+
if (searchIndex >= 0) {
|
|
13
|
+
search = pathname.slice(searchIndex);
|
|
14
|
+
pathname = pathname.slice(0, searchIndex);
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
hash,
|
|
18
|
+
pathname,
|
|
19
|
+
search
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
const resolvePath = (to, base) => {
|
|
23
|
+
const resolved = new URL(to, `http://_${createPath(base)}`);
|
|
24
|
+
return {
|
|
25
|
+
hash: resolved.hash,
|
|
26
|
+
pathname: resolved.pathname,
|
|
27
|
+
search: resolved.search
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
const createPath = ({ hash, pathname, search }) => {
|
|
31
|
+
let out = pathname || "/";
|
|
32
|
+
if (search && search !== "?") out += search.startsWith("?") ? search : `?${search}`;
|
|
33
|
+
if (hash && hash !== "#") out += hash.startsWith("#") ? hash : `#${hash}`;
|
|
34
|
+
return out;
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
37
|
+
export { parsePath as n, resolvePath as r, createPath as t };
|
package/package.json
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@oomfware/stacker",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "type-safe stack router for React",
|
|
5
|
+
"license": "0BSD",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://codeberg.org/oomfware/stacker"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/",
|
|
12
|
+
"src/",
|
|
13
|
+
"!src/**/*.test.ts",
|
|
14
|
+
"!src/**/*.test.tsx",
|
|
15
|
+
"!src/**/*.test-d.ts",
|
|
16
|
+
"!src/test-support.ts"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"types": "./dist/index.d.mts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.mts",
|
|
23
|
+
"default": "./dist/index.mjs"
|
|
24
|
+
},
|
|
25
|
+
"./testing": {
|
|
26
|
+
"types": "./dist/testing.d.mts",
|
|
27
|
+
"default": "./dist/testing.mjs"
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@mary-ext/simple-event-emitter": "^1.0.2"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@testing-library/dom": "^10.4.1",
|
|
39
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
40
|
+
"@testing-library/react": "^16.3.2",
|
|
41
|
+
"@types/node": "^26.1.1",
|
|
42
|
+
"@types/react": "^19.2.17",
|
|
43
|
+
"@types/react-dom": "^19.2.3",
|
|
44
|
+
"@vitejs/plugin-react": "^6.0.3",
|
|
45
|
+
"@vitest/browser": "^4.1.10",
|
|
46
|
+
"@vitest/browser-playwright": "^4.1.10",
|
|
47
|
+
"bumpp": "^11.1.0",
|
|
48
|
+
"oxfmt": "^0.59.0",
|
|
49
|
+
"oxlint": "^1.74.0",
|
|
50
|
+
"oxlint-tsgolint": "^0.24.0",
|
|
51
|
+
"playwright": "^1.61.1",
|
|
52
|
+
"react": "^19.2.7",
|
|
53
|
+
"react-dom": "^19.2.7",
|
|
54
|
+
"tsdown": "^0.22.8",
|
|
55
|
+
"typescript": "^7.0.2",
|
|
56
|
+
"vite": "^8.1.4",
|
|
57
|
+
"vitest": "^4.1.10"
|
|
58
|
+
},
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"react": ">=19.0.0",
|
|
61
|
+
"react-dom": ">=19.0.0"
|
|
62
|
+
},
|
|
63
|
+
"scripts": {
|
|
64
|
+
"build": "oxlint && tsdown",
|
|
65
|
+
"dev": "tsdown --watch",
|
|
66
|
+
"fmt": "oxfmt",
|
|
67
|
+
"lint": "oxlint",
|
|
68
|
+
"play": "vite",
|
|
69
|
+
"test": "vitest run",
|
|
70
|
+
"test:types": "vitest run --typecheck.only",
|
|
71
|
+
"test:watch": "vitest",
|
|
72
|
+
"typecheck": "tsc -b"
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/build.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { getDefault, isOptional } from './codec.ts';
|
|
2
|
+
import type { BuildParamsOf, RouteName, RouteRegistry } from './routes.ts';
|
|
3
|
+
import { createPath } from './url.ts';
|
|
4
|
+
|
|
5
|
+
const SEGMENT = /:([A-Za-z_]\w*)/g;
|
|
6
|
+
|
|
7
|
+
export type BuildArgs<R, K extends RouteName<R>> =
|
|
8
|
+
Record<never, never> extends BuildParamsOf<R, K>
|
|
9
|
+
? [params?: BuildParamsOf<R, K>]
|
|
10
|
+
: [params: BuildParamsOf<R, K>];
|
|
11
|
+
|
|
12
|
+
export class Builder<R extends RouteRegistry<unknown> = RouteRegistry<unknown>> {
|
|
13
|
+
readonly #registry: R;
|
|
14
|
+
|
|
15
|
+
constructor(registry: R) {
|
|
16
|
+
this.#registry = registry;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
build<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): string {
|
|
20
|
+
return this.buildPath(name, args[0] ?? {});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
buildPath(name: string, params: Readonly<Record<string, unknown>> = {}): string {
|
|
24
|
+
const leaf = this.#registry.leaves.get(name);
|
|
25
|
+
if (leaf === undefined) {
|
|
26
|
+
throw new Error(`stacker: unknown route '${name}'`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const pathname = leaf.path.replaceAll(SEGMENT, (_full, paramName: string) => {
|
|
30
|
+
const codec = leaf.params[paramName];
|
|
31
|
+
const value = params[paramName];
|
|
32
|
+
if (codec === undefined || value === undefined) {
|
|
33
|
+
throw new Error(`stacker: missing path param '${paramName}' for route '${name}'`);
|
|
34
|
+
}
|
|
35
|
+
return encodeURIComponent(codec.encode(value));
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const search = new URLSearchParams();
|
|
39
|
+
for (const [paramName, codec] of Object.entries(leaf.query)) {
|
|
40
|
+
const value = params[paramName];
|
|
41
|
+
if (value === undefined) {
|
|
42
|
+
if (!isOptional(codec) && getDefault(codec) === undefined) {
|
|
43
|
+
throw new Error(`stacker: missing required query param '${paramName}' for route '${name}'`);
|
|
44
|
+
}
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
search.set(paramName, codec.encode(value));
|
|
48
|
+
}
|
|
49
|
+
const query = search.toString();
|
|
50
|
+
|
|
51
|
+
return createPath({ hash: '', pathname, search: query ? `?${query}` : '' });
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/cache.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export interface CacheEntryRef {
|
|
2
|
+
readonly index: number;
|
|
3
|
+
readonly key: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface CachePolicy {
|
|
7
|
+
readonly max: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* computes which history entries to keep warm based on active index and recency.
|
|
12
|
+
*
|
|
13
|
+
* retains the active entry plus backward entries using an LRU policy. forward entries are dropped.
|
|
14
|
+
*/
|
|
15
|
+
export const computeCachedKeys = (
|
|
16
|
+
entries: readonly CacheEntryRef[],
|
|
17
|
+
activeIndex: number,
|
|
18
|
+
recency: readonly string[],
|
|
19
|
+
policy: CachePolicy,
|
|
20
|
+
): Set<string> => {
|
|
21
|
+
const cached = new Set<string>();
|
|
22
|
+
|
|
23
|
+
const active = entries.find((entry) => entry.index === activeIndex);
|
|
24
|
+
if (active === undefined) {
|
|
25
|
+
throw new Error(`stacker: no history entry at active index ${activeIndex}`);
|
|
26
|
+
}
|
|
27
|
+
cached.add(active.key);
|
|
28
|
+
|
|
29
|
+
const backward = new Map<string, CacheEntryRef>();
|
|
30
|
+
for (const entry of entries) {
|
|
31
|
+
if (entry.index < activeIndex) {
|
|
32
|
+
backward.set(entry.key, entry);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let kept = 0;
|
|
37
|
+
const take = (key: string): void => {
|
|
38
|
+
if (kept >= policy.max || cached.has(key) || !backward.has(key)) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
cached.add(key);
|
|
42
|
+
kept += 1;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
for (const key of recency) {
|
|
46
|
+
take(key);
|
|
47
|
+
}
|
|
48
|
+
for (const entry of [...backward.values()].toSorted((a, b) => b.index - a.index)) {
|
|
49
|
+
take(entry.key);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return cached;
|
|
53
|
+
};
|
package/src/codec.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// #region codec primitive
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* a bidirectional codec for a single route parameter.
|
|
5
|
+
*
|
|
6
|
+
* returning `undefined` from `decode` signals validation failure, which causes the matcher to skip the
|
|
7
|
+
* candidate route.
|
|
8
|
+
*/
|
|
9
|
+
export interface Codec<T> {
|
|
10
|
+
/**
|
|
11
|
+
* parses a raw URL segment.
|
|
12
|
+
*
|
|
13
|
+
* @param raw the percent-decoded path segment or query value
|
|
14
|
+
* @returns the decoded value, or `undefined` if the segment is invalid
|
|
15
|
+
*/
|
|
16
|
+
decode(raw: string): T | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* serializes a value to a raw URL segment.
|
|
19
|
+
*
|
|
20
|
+
* @param value the value to serialize
|
|
21
|
+
* @returns the raw string value
|
|
22
|
+
*/
|
|
23
|
+
encode(value: T): string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const OPTIONAL: unique symbol = Symbol('stacker.optional');
|
|
27
|
+
const DEFAULT: unique symbol = Symbol('stacker.default');
|
|
28
|
+
|
|
29
|
+
/** a codec whose parameter may be absent. */
|
|
30
|
+
export interface OptionalCodec<T> extends Codec<T> {
|
|
31
|
+
readonly [OPTIONAL]: true;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** a codec whose parameter has a default fallback. */
|
|
35
|
+
export interface DefaultedCodec<T> extends Codec<T> {
|
|
36
|
+
readonly [DEFAULT]: T;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** extracts the value type a codec decodes to. */
|
|
40
|
+
export type Infer<C> = C extends Codec<infer T> ? T : never;
|
|
41
|
+
|
|
42
|
+
// #endregion
|
|
43
|
+
|
|
44
|
+
// #region type-level param shapes
|
|
45
|
+
|
|
46
|
+
// `Codec<T>` is invariant, so the bound must use `any`; `const` generics preserve each exact codec type.
|
|
47
|
+
// oxlint-disable-next-line typescript/no-explicit-any -- invariance bound, see note above
|
|
48
|
+
export type CodecRecord = { readonly [name: string]: Codec<any> };
|
|
49
|
+
|
|
50
|
+
type Prettify<T> = { [K in keyof T]: T[K] } & {};
|
|
51
|
+
|
|
52
|
+
type AnyOptional = { readonly [OPTIONAL]: true };
|
|
53
|
+
type AnyDefaulted = { readonly [DEFAULT]: unknown };
|
|
54
|
+
|
|
55
|
+
type OptionalKeys<P extends CodecRecord> = {
|
|
56
|
+
[K in keyof P]: P[K] extends AnyOptional ? K : never;
|
|
57
|
+
}[keyof P];
|
|
58
|
+
|
|
59
|
+
type DefaultedKeys<P extends CodecRecord> = {
|
|
60
|
+
[K in keyof P]: P[K] extends AnyDefaulted ? K : never;
|
|
61
|
+
}[keyof P];
|
|
62
|
+
|
|
63
|
+
export type DecodeShape<P extends CodecRecord> = Prettify<
|
|
64
|
+
{ [K in Exclude<keyof P, OptionalKeys<P>>]: Infer<P[K]> } & { [K in OptionalKeys<P>]?: Infer<P[K]> }
|
|
65
|
+
>;
|
|
66
|
+
|
|
67
|
+
export type BuildShape<P extends CodecRecord> = Prettify<
|
|
68
|
+
{ [K in Exclude<keyof P, DefaultedKeys<P> | OptionalKeys<P>>]: Infer<P[K]> } & {
|
|
69
|
+
[K in DefaultedKeys<P> | OptionalKeys<P>]?: Infer<P[K]>;
|
|
70
|
+
}
|
|
71
|
+
>;
|
|
72
|
+
|
|
73
|
+
// #endregion
|
|
74
|
+
|
|
75
|
+
// #region primitives
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* creates a codec for a string segment.
|
|
79
|
+
*
|
|
80
|
+
* @returns the string codec
|
|
81
|
+
*/
|
|
82
|
+
export const string = (): Codec<string> => ({
|
|
83
|
+
decode: (raw) => raw,
|
|
84
|
+
encode: (value) => value,
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* creates a codec for a safe integer.
|
|
89
|
+
*
|
|
90
|
+
* @returns the integer codec
|
|
91
|
+
*/
|
|
92
|
+
export const integer = (): Codec<number> => ({
|
|
93
|
+
decode: (raw) => {
|
|
94
|
+
// reject leading zeros, `-0`, a leading `+`, exponents, and decimals to ensure round-tripping.
|
|
95
|
+
if (!/^(?:0|-[1-9]\d*|[1-9]\d*)$/.test(raw)) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
const value = Number(raw);
|
|
99
|
+
return Number.isSafeInteger(value) ? value : undefined;
|
|
100
|
+
},
|
|
101
|
+
encode: (value) => {
|
|
102
|
+
if (!Number.isSafeInteger(value) || Object.is(value, -0)) {
|
|
103
|
+
throw new Error(`stacker: integer() cannot encode ${value}`);
|
|
104
|
+
}
|
|
105
|
+
return String(value);
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* creates a codec for a boolean value.
|
|
111
|
+
*
|
|
112
|
+
* @returns the boolean codec
|
|
113
|
+
*/
|
|
114
|
+
export const boolean = (): Codec<boolean> => ({
|
|
115
|
+
decode: (raw) => {
|
|
116
|
+
switch (raw) {
|
|
117
|
+
case 'false': {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
case 'true': {
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
default: {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
encode: (value) => (value ? 'true' : 'false'),
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* creates a codec for a fixed set of string values.
|
|
133
|
+
*
|
|
134
|
+
* @param values the allowed string values
|
|
135
|
+
* @returns the enum codec
|
|
136
|
+
*/
|
|
137
|
+
export const enumOf = <const V extends readonly string[]>(values: V): Codec<V[number]> => {
|
|
138
|
+
const set: ReadonlySet<string> = new Set(values);
|
|
139
|
+
return {
|
|
140
|
+
decode: (raw) => (set.has(raw) ? raw : undefined),
|
|
141
|
+
encode: (value) => value,
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* wraps a codec to allow its parameter to be absent.
|
|
147
|
+
*
|
|
148
|
+
* @param codec the inner codec
|
|
149
|
+
* @returns the optional codec
|
|
150
|
+
*/
|
|
151
|
+
export const optional = <T>(codec: Codec<T>): OptionalCodec<T> => ({
|
|
152
|
+
decode: (raw) => codec.decode(raw),
|
|
153
|
+
encode: (value) => codec.encode(value),
|
|
154
|
+
[OPTIONAL]: true,
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* wraps a codec with a default value.
|
|
159
|
+
*
|
|
160
|
+
* @param codec the inner codec
|
|
161
|
+
* @param fallback the default value
|
|
162
|
+
* @returns the defaulted codec
|
|
163
|
+
*/
|
|
164
|
+
export const withDefault = <T>(codec: Codec<T>, fallback: T): DefaultedCodec<T> => ({
|
|
165
|
+
decode: (raw) => codec.decode(raw),
|
|
166
|
+
encode: (value) => codec.encode(value),
|
|
167
|
+
[DEFAULT]: fallback,
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
// #endregion
|
|
171
|
+
|
|
172
|
+
// #region runtime reflection
|
|
173
|
+
|
|
174
|
+
export const isOptional = (codec: Codec<unknown>): codec is OptionalCodec<unknown> => {
|
|
175
|
+
return OPTIONAL in codec;
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
export const getDefault = (codec: Codec<unknown>): readonly [unknown] | undefined => {
|
|
179
|
+
return DEFAULT in codec ? [(codec as DefaultedCodec<unknown>)[DEFAULT]] : undefined;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// #endregion
|