-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathutils.ts
More file actions
211 lines (188 loc) · 6.29 KB
/
utils.ts
File metadata and controls
211 lines (188 loc) · 6.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { createMemo, getOwner, runWithOwner } from "solid-js";
import type {
MatchFilter,
MatchFilters,
Params,
PathMatch,
RouteDescription,
SearchParams,
SetParams,
SetSearchParams
} from "./types.js";
const hasSchemeRegex = /^(?:[a-z0-9]+:)?\/\//i;
const trimPathRegex = /^\/+|(\/)\/+$/g;
export const mockBase = "http://sr";
export function normalizePath(path: string, omitSlash: boolean = false) {
const s = path.replace(trimPathRegex, "$1");
return s ? (omitSlash || /^[?#]/.test(s) ? s : "/" + s) : "";
}
export function resolvePath(base: string, path: string, from?: string): string | undefined {
if (hasSchemeRegex.test(path)) {
return undefined;
}
const basePath = normalizePath(base);
const fromPath = from && normalizePath(from);
let result = "";
if (!fromPath || path.startsWith("/")) {
result = basePath;
} else if (fromPath.toLowerCase().indexOf(basePath.toLowerCase()) !== 0) {
result = basePath + fromPath;
} else {
result = fromPath;
}
return (result || "/") + normalizePath(path, !result);
}
export function invariant<T>(value: T | null | undefined, message: string): T {
if (value == null) {
throw new Error(message);
}
return value;
}
export function joinPaths(from: string, to: string): string {
return normalizePath(from).replace(/\/*(\*.*)?$/g, "") + normalizePath(to);
}
export function extractSearchParams(url: URL): SearchParams {
const params: SearchParams = {};
url.searchParams.forEach((value, key) => {
if (key in params) {
if (Array.isArray(params[key])) (params[key] as string[]).push(value);
else params[key] = [params[key] as string, value];
} else params[key] = value;
});
return params;
}
export function createMatcher<S extends string>(
path: S,
partial?: boolean,
matchFilters?: MatchFilters<S>
) {
const [pattern, splat] = path.split("/*", 2);
const segments = pattern.split("/").filter(Boolean);
const len = segments.length;
return (location: string): PathMatch | null => {
const locSegments = location.split("/").filter(Boolean);
const lenDiff = locSegments.length - len;
if (lenDiff < 0 || (lenDiff > 0 && splat === undefined && !partial)) {
return null;
}
const match: PathMatch = {
path: len ? "" : "/",
params: {}
};
const matchFilter = (s: string) =>
matchFilters === undefined ? undefined : (matchFilters as Record<string, MatchFilter>)[s];
for (let i = 0; i < len; i++) {
const segment = segments[i];
const dynamic = segment[0] === ":";
const locSegment = dynamic ? locSegments[i] : locSegments[i].toLowerCase();
const key = dynamic ? segment.slice(1) : segment.toLowerCase();
if (dynamic && matchSegment(locSegment, matchFilter(key))) {
match.params[key] = locSegment;
} else if (dynamic || !matchSegment(locSegment, key)) {
return null;
}
match.path += `/${locSegment}`;
}
if (splat) {
const remainder = lenDiff ? locSegments.slice(-lenDiff).join("/") : "";
if (matchSegment(remainder, matchFilter(splat))) {
match.params[splat] = remainder;
} else {
return null;
}
}
return match;
};
}
function matchSegment(input: string, filter?: string | MatchFilter): boolean {
const isEqual = (s: string) => s === input;
if (filter === undefined) {
return true;
} else if (typeof filter === "string") {
return isEqual(filter);
} else if (typeof filter === "function") {
return (filter as Function)(input);
} else if (Array.isArray(filter)) {
return (filter as string[]).some(isEqual);
} else if (filter instanceof RegExp) {
return (filter as RegExp).test(input);
}
return false;
}
export function scoreRoute(route: RouteDescription): number {
const [pattern, splat] = route.pattern.split("/*", 2);
const segments = pattern.split("/").filter(Boolean);
return segments.reduce(
(score, segment) => score + (segment.startsWith(":") ? 2 : 3),
segments.length - (splat === undefined ? 0 : 1)
);
}
export function createMemoObject<T extends Record<string | symbol, unknown>>(fn: () => T): T {
const map = new Map();
const owner = getOwner()!;
return new Proxy(<T>{}, {
get(_, property) {
if (!map.has(property)) {
runWithOwner(owner, () =>
map.set(
property,
createMemo(() => fn()[property])
)
);
}
return map.get(property)();
},
getOwnPropertyDescriptor() {
return {
enumerable: true,
configurable: true
};
},
ownKeys() {
return Reflect.ownKeys(fn());
},
has(_, property) {
return property in fn();
}
});
}
export function mergeSearchString(search: string, params: SetSearchParams) {
const merged = new URLSearchParams(search);
Object.entries(params).forEach(([key, value]) => {
if (value == null || value === "" || (value instanceof Array && !value.length)) {
merged.delete(key);
} else {
if (value instanceof Array) {
// Delete all instances of the key before appending
merged.delete(key);
value.forEach(v => {
merged.append(key, String(v));
});
} else {
merged.set(key, String(value));
}
}
});
const s = merged.toString();
return s ? `?${s}` : "";
}
export function expandOptionals(pattern: string): string[] {
let match = /(\/?\:[^\/]+)\?/.exec(pattern);
if (!match) return [pattern];
let prefix = pattern.slice(0, match.index);
let suffix = pattern.slice(match.index + match[0].length);
const prefixes: string[] = [prefix, (prefix += match[1])];
// This section handles adjacent optional params. We don't actually want all permuations since
// that will lead to equivalent routes which have the same number of params. For example
// `/:a?/:b?/:c`? only has the unique expansion: `/`, `/:a`, `/:a/:b`, `/:a/:b/:c` and we can
// discard `/:b`, `/:c`, `/:b/:c` by building them up in order and not recursing. This also helps
// ensure predictability where earlier params have precidence.
while ((match = /^(\/\:[^\/]+)\?/.exec(suffix))) {
prefixes.push((prefix += match[1]));
suffix = suffix.slice(match[0].length);
}
return expandOptionals(suffix).reduce<string[]>(
(results, expansion) => [...results, ...prefixes.map(p => p + expansion)],
[]
);
}