-
Notifications
You must be signed in to change notification settings - Fork 380
/
index.ts
597 lines (508 loc) · 13.1 KB
/
index.ts
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
const DEFAULT_DELIMITER = "/";
const NOOP_VALUE = (value: string) => value;
const ID_START = /^[$_\p{ID_Start}]$/u;
const ID_CONTINUE = /^[$\u200c\u200d\p{ID_Continue}]$/u;
const DEBUG_URL = "https://git.new/pathToRegexpError";
/**
* Encode a string into another string.
*/
export type Encode = (value: string) => string;
/**
* Decode a string into another string.
*/
export type Decode = (value: string) => string;
export interface ParseOptions {
/**
* A function for encoding input strings.
*/
encodePath?: Encode;
}
export interface MatchOptions {
/**
* Function for decoding strings for params, or `false` to disable entirely. (default: `decodeURIComponent`)
*/
decode?: Decode | false;
/**
* Matches the path completely without trailing characters. (default: `true`)
*/
end?: boolean;
/**
* Allows optional trailing delimiter to match. (default: `true`)
*/
trailing?: boolean;
/**
* Match will be case sensitive. (default: `false`)
*/
sensitive?: boolean;
/**
* The default delimiter for segments. (default: `'/'`)
*/
delimiter?: string;
}
export interface CompileOptions {
/**
* Function for encoding input strings for output into the path, or `false` to disable entirely. (default: `encodeURIComponent`)
*/
encode?: Encode | false;
/**
* The default delimiter for segments. (default: `'/'`)
*/
delimiter?: string;
}
type TokenType =
| "{"
| "}"
| "WILDCARD"
| "PARAM"
| "CHAR"
| "ESCAPED"
| "END"
// Reserved for use or ambiguous due to past use.
| "("
| ")"
| "["
| "]"
| "+"
| "?"
| "!";
/**
* Tokenizer results.
*/
interface LexToken {
type: TokenType;
index: number;
value: string;
}
const SIMPLE_TOKENS: Record<string, TokenType> = {
// Groups.
"{": "{",
"}": "}",
// Reserved.
"(": "(",
")": ")",
"[": "[",
"]": "]",
"+": "+",
"?": "?",
"!": "!",
};
/**
* Escape a regular expression string.
*/
function escape(str: string) {
return str.replace(/[.+*?^${}()[\]|/\\]/g, "\\$&");
}
/**
* Get the flags for a regexp from the options.
*/
function toFlags(options: { sensitive?: boolean }) {
return options.sensitive ? "s" : "is";
}
/**
* Tokenize input string.
*/
function* lexer(str: string): Generator<LexToken, LexToken> {
const chars = [...str];
let i = 0;
function name() {
let value = "";
if (ID_START.test(chars[++i])) {
value += chars[i];
while (ID_CONTINUE.test(chars[++i])) {
value += chars[i];
}
} else if (chars[i] === '"') {
let pos = i;
while (i < chars.length) {
if (chars[++i] === '"') {
i++;
pos = 0;
break;
}
if (chars[i] === "\\") {
value += chars[++i];
} else {
value += chars[i];
}
}
if (pos) {
throw new TypeError(`Unterminated quote at ${pos}: ${DEBUG_URL}`);
}
}
if (!value) {
throw new TypeError(`Missing parameter name at ${i}: ${DEBUG_URL}`);
}
return value;
}
while (i < chars.length) {
const value = chars[i];
const type = SIMPLE_TOKENS[value];
if (type) {
yield { type, index: i++, value };
} else if (value === "\\") {
yield { type: "ESCAPED", index: i++, value: chars[i++] };
} else if (value === ":") {
const value = name();
yield { type: "PARAM", index: i, value };
} else if (value === "*") {
const value = name();
yield { type: "WILDCARD", index: i, value };
} else {
yield { type: "CHAR", index: i, value: chars[i++] };
}
}
return { type: "END", index: i, value: "" };
}
class Iter {
#peek?: LexToken;
constructor(private tokens: Generator<LexToken, LexToken>) {}
peek(): LexToken {
if (!this.#peek) {
const next = this.tokens.next();
this.#peek = next.value;
}
return this.#peek;
}
tryConsume(type: TokenType): string | undefined {
const token = this.peek();
if (token.type !== type) return;
this.#peek = undefined; // Reset after consumed.
return token.value;
}
consume(type: TokenType): string {
const value = this.tryConsume(type);
if (value !== undefined) return value;
const { type: nextType, index } = this.peek();
throw new TypeError(
`Unexpected ${nextType} at ${index}, expected ${type}: ${DEBUG_URL}`,
);
}
text(): string {
let result = "";
let value: string | undefined;
while ((value = this.tryConsume("CHAR") || this.tryConsume("ESCAPED"))) {
result += value;
}
return result;
}
}
/**
* Plain text.
*/
export interface Text {
type: "text";
value: string;
}
/**
* A parameter designed to match arbitrary text within a segment.
*/
export interface Parameter {
type: "param";
name: string;
}
/**
* A wildcard parameter designed to match multiple segments.
*/
export interface Wildcard {
type: "wildcard";
name: string;
}
/**
* A set of possible tokens to expand when matching.
*/
export interface Group {
type: "group";
tokens: Token[];
}
/**
* A sequence of path match characters.
*/
export type Token = Text | Parameter | Wildcard | Group;
/**
* Tokenized path instance.
*/
export class TokenData {
constructor(public readonly tokens: Token[]) {}
}
/**
* Parse a string for the raw tokens.
*/
export function parse(str: string, options: ParseOptions = {}): TokenData {
const { encodePath = NOOP_VALUE } = options;
const it = new Iter(lexer(str));
function consume(endType: TokenType): Token[] {
const tokens: Token[] = [];
while (true) {
const path = it.text();
if (path) tokens.push({ type: "text", value: encodePath(path) });
const param = it.tryConsume("PARAM");
if (param) {
tokens.push({
type: "param",
name: param,
});
continue;
}
const wildcard = it.tryConsume("WILDCARD");
if (wildcard) {
tokens.push({
type: "wildcard",
name: wildcard,
});
continue;
}
const open = it.tryConsume("{");
if (open) {
tokens.push({
type: "group",
tokens: consume("}"),
});
continue;
}
it.consume(endType);
return tokens;
}
}
const tokens = consume("END");
return new TokenData(tokens);
}
/**
* Transform tokens into a path building function.
*/
function $compile<P extends ParamData>(
data: TokenData,
options: CompileOptions,
): PathFunction<P> {
const { encode = encodeURIComponent, delimiter = DEFAULT_DELIMITER } =
options;
const fn = tokensToFunction(data.tokens, delimiter, encode);
return function path(data: P = {} as P) {
const [path, ...missing] = fn(data);
if (missing.length) {
throw new TypeError(`Missing parameters: ${missing.join(", ")}`);
}
return path;
};
}
/**
* Compile a string to a template function for the path.
*/
export function compile<P extends ParamData = ParamData>(
path: Path,
options: CompileOptions & ParseOptions = {},
) {
return $compile<P>(
path instanceof TokenData ? path : parse(path, options),
options,
);
}
export type ParamData = Partial<Record<string, string | string[]>>;
export type PathFunction<P extends ParamData> = (data?: P) => string;
function tokensToFunction(
tokens: Token[],
delimiter: string,
encode: Encode | false,
) {
const encoders = tokens.map((token) =>
tokenToFunction(token, delimiter, encode),
);
return (data: ParamData) => {
const result: string[] = [""];
for (const encoder of encoders) {
const [value, ...extras] = encoder(data);
result[0] += value;
result.push(...extras);
}
return result;
};
}
/**
* Convert a single token into a path building function.
*/
function tokenToFunction(
token: Token,
delimiter: string,
encode: Encode | false,
): (data: ParamData) => string[] {
if (token.type === "text") return () => [token.value];
if (token.type === "group") {
const fn = tokensToFunction(token.tokens, delimiter, encode);
return (data) => {
const [value, ...missing] = fn(data);
if (!missing.length) return [value];
return [""];
};
}
const encodeValue = encode || NOOP_VALUE;
if (token.type === "wildcard" && encode !== false) {
return (data) => {
const value = data[token.name];
if (value == null) return ["", token.name];
if (!Array.isArray(value) || value.length === 0) {
throw new TypeError(`Expected "${token.name}" to be a non-empty array`);
}
return [
value
.map((value, index) => {
if (typeof value !== "string") {
throw new TypeError(
`Expected "${token.name}/${index}" to be a string`,
);
}
return encodeValue(value);
})
.join(delimiter),
];
};
}
return (data) => {
const value = data[token.name];
if (value == null) return ["", token.name];
if (typeof value !== "string") {
throw new TypeError(`Expected "${token.name}" to be a string`);
}
return [encodeValue(value)];
};
}
/**
* A match result contains data about the path match.
*/
export interface MatchResult<P extends ParamData> {
path: string;
params: P;
}
/**
* A match is either `false` (no match) or a match result.
*/
export type Match<P extends ParamData> = false | MatchResult<P>;
/**
* The match function takes a string and returns whether it matched the path.
*/
export type MatchFunction<P extends ParamData> = (path: string) => Match<P>;
/**
* Create path match function from `path-to-regexp` spec.
*/
function $match<P extends ParamData>(
data: TokenData[],
options: MatchOptions = {},
): MatchFunction<P> {
const {
decode = decodeURIComponent,
delimiter = DEFAULT_DELIMITER,
end = true,
trailing = true,
} = options;
const flags = toFlags(options);
const sources: string[] = [];
const keys: Array<Parameter | Wildcard> = [];
for (const { tokens } of data) {
for (const seq of flatten(tokens, 0, [])) {
const regexp = sequenceToRegExp(seq, delimiter, keys);
sources.push(regexp);
}
}
let pattern = `^(?:${sources.join("|")})`;
if (trailing) pattern += `(?:${escape(delimiter)}$)?`;
pattern += end ? "$" : `(?=${escape(delimiter)}|$)`;
const re = new RegExp(pattern, flags);
const decoders = keys.map((key) => {
if (decode === false) return NOOP_VALUE;
if (key.type === "param") return decode;
return (value: string) => value.split(delimiter).map(decode);
});
return Object.assign(
function match(input: string) {
const m = re.exec(input);
if (!m) return false;
const { 0: path } = m;
const params = Object.create(null);
for (let i = 1; i < m.length; i++) {
if (m[i] === undefined) continue;
const key = keys[i - 1];
const decoder = decoders[i - 1];
params[key.name] = decoder(m[i]);
}
return { path, params };
},
{ re },
);
}
export type Path = string | TokenData;
export function match<P extends ParamData>(
path: Path | Path[],
options: MatchOptions & ParseOptions = {},
): MatchFunction<P> {
const paths = Array.isArray(path) ? path : [path];
const items = paths.map((path) =>
path instanceof TokenData ? path : parse(path, options),
);
return $match(items, options);
}
/**
* Flattened token set.
*/
type Flattened = Text | Parameter | Wildcard;
/**
* Generate a flat list of sequence tokens from the given tokens.
*/
function* flatten(
tokens: Token[],
index: number,
init: Flattened[],
): Generator<Flattened[]> {
if (index === tokens.length) {
return yield init;
}
const token = tokens[index];
if (token.type === "group") {
const fork = init.slice();
for (const seq of flatten(token.tokens, 0, fork)) {
yield* flatten(tokens, index + 1, seq);
}
} else {
init.push(token);
}
yield* flatten(tokens, index + 1, init);
}
/**
* Transform a flat sequence of tokens into a regular expression.
*/
function sequenceToRegExp(
tokens: Flattened[],
delimiter: string,
keys: Array<Parameter | Wildcard>,
): string {
let result = "";
let backtrack = "";
let isSafeSegmentParam = true;
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (token.type === "text") {
result += escape(token.value);
backtrack = token.value;
isSafeSegmentParam ||= token.value.includes(delimiter);
continue;
}
if (token.type === "param" || token.type === "wildcard") {
if (!isSafeSegmentParam && !backtrack) {
throw new TypeError(`Missing text after "${token.name}": ${DEBUG_URL}`);
}
if (token.type === "param") {
result += `(${negate(delimiter, isSafeSegmentParam ? "" : backtrack)}+)`;
} else {
result += `(.+)`;
}
keys.push(token);
backtrack = "";
isSafeSegmentParam = false;
continue;
}
}
return result;
}
function negate(delimiter: string, backtrack: string) {
const values = [delimiter, backtrack].filter(Boolean);
const isSimple = values.every((value) => value.length === 1);
if (isSimple) return `[^${escape(values.join(""))}]`;
return `(?:(?!${values.map(escape).join("|")}).)`;
}