const NAME = /^[a-zA-Z0-9]+/; const VALUE = '([a-zA-Z0-9\\-_~ %]+)'; function escapeRegExp(text: string): string { return text.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); } /** * A route pattern, compiled once to a regular expression: * * - `:name` matches one segment (letters, digits, `-_~ %`) into `name`; a name that appears twice gives an array; * - `*` matches anything (also `/`) into `_`; * - `(...)` is optional: `/users(/:id)`; * - `\\` makes the next character plain: `/files\\*`. * * `match()` returns the named values (`{}` when there are none) or `null`. A RegExp pattern returns its groups. * This is the syntax of the `url-pattern` package, which Cell used before. */ export class PathPattern { protected readonly regex: RegExp; protected readonly names: string[] = []; constructor(protected readonly pattern: string | RegExp) { if (pattern instanceof RegExp) { this.regex = pattern; return; } if (typeof pattern !== 'string') { throw new TypeError('argument must be a regex or a string'); } if (pattern === '') { throw new Error('argument must not be the empty string'); } if (/\s/.test(pattern)) { throw new Error('argument must not contain whitespace'); } const { source, rest } = this.compile(pattern, false); if (rest) { throw new Error(`could not parse pattern ${pattern}`); } this.regex = new RegExp(`^${source}$`); } match(path: string): Record | string[] | null { const match = this.regex.exec(path); if (!match) { return null; } if (this.pattern instanceof RegExp) { return match.slice(1); } const params: Record = {}; for (let i = 0; i < this.names.length; i++) { const value = match[i + 1]; if (value === undefined) { continue; } const name = this.names[i]; const existing = params[name]; if (existing === undefined) { params[name] = value; } else if (Array.isArray(existing)) { existing.push(value); } else { params[name] = [existing, value]; } } return params; } /** Compiles until the end, or until the `)` that closes an optional part; returns what is left after it. */ protected compile(pattern: string, optional: boolean): { source: string, rest: string } { let source = ''; let rest = pattern; while (rest) { const c = rest[0]; if (c === ')') { if (!optional) { break; } return { source, rest }; } if (c === '*') { this.names.push('_'); source += '(.*?)'; rest = rest.slice(1); } else if (c === '(') { const inner = this.compile(rest.slice(1), true); if (!inner.source || !inner.rest.startsWith(')')) { break; } source += `(?:${inner.source})?`; rest = inner.rest.slice(1); } else if (c === ':') { const name = NAME.exec(rest.slice(1))?.[0]; if (!name) { break; } this.names.push(name); source += VALUE; rest = rest.slice(1 + name.length); } else if (c === '\\' && rest.length > 1) { source += escapeRegExp(rest[1]); rest = rest.slice(2); } else { source += escapeRegExp(c); rest = rest.slice(1); } } return { source, rest }; } }