Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/cases.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1681,6 +1681,35 @@ export const MATCH_TESTS: MatchTestSet[] = [
},
],
},
{
path: "%25:foo..:bar",
options: {
delimiter: "%25",
},
tests: [
{
input: "%25hello..world",
expected: {
path: "%25hello..world",
params: { foo: "hello", bar: "world" },
},
},
{
input: "%25555..222",
expected: {
path: "%25555..222",
params: { foo: "555", bar: "222" },
},
},
{
input: "%25555....222%25",
expected: {
path: "%25555....222%25",
params: { foo: "555..", bar: "222" },
},
},
],
},

/**
* Array input is normalized.
Expand Down
8 changes: 8 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,14 @@ describe("path-to-regexp", () => {
});
});

describe("stringify errors", () => {
it("should error on unknown token", () => {
expect(() =>
stringify({ tokens: [{ type: "unknown", value: "test" } as any] }),
).toThrow(new TypeError("Unknown token type: unknown"));
});
});

describe.each(PARSER_TESTS)(
"parse $path with $options",
({ path, options, expected }) => {
Expand Down
77 changes: 51 additions & 26 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ export function pathToRegexp(
for (const input of pathsToArray(path, [])) {
const data = typeof input === "object" ? input : parse(input, options);
for (const tokens of flatten(data.tokens, 0, [])) {
sources.push(toRegExp(tokens, delimiter, keys, data.originalPath));
sources.push(toRegExpSource(tokens, delimiter, keys, data.originalPath));
}
}

Expand Down Expand Up @@ -544,12 +544,12 @@ function* flatten(
/**
* Transform a flat sequence of tokens into a regular expression.
*/
function toRegExp(
function toRegExpSource(
tokens: FlatToken[],
delimiter: string,
keys: Keys,
originalPath: string | undefined,
) {
): string {
let result = "";
let backtrack = "";
let isSafeSegmentParam = true;
Expand Down Expand Up @@ -588,7 +588,7 @@ function toRegExp(
/**
* Block backtracking on previous text and ignore delimiter string.
*/
function negate(delimiter: string, backtrack: string) {
function negate(delimiter: string, backtrack: string): string {
if (backtrack.length < 2) {
if (delimiter.length < 2) return `[^${escape(delimiter + backtrack)}]`;
return `(?:(?!${escape(delimiter)})[^${escape(backtrack)}])`;
Expand All @@ -600,40 +600,65 @@ function negate(delimiter: string, backtrack: string) {
}

/**
* Stringify token data into a path string.
* Stringify an array of tokens into a path string.
*/
export function stringify(data: TokenData) {
return data.tokens
.map(function stringifyToken(token, index, tokens): string {
if (token.type === "text") return escapeText(token.value);
if (token.type === "group") {
return `{${token.tokens.map(stringifyToken).join("")}}`;
}
function stringifyTokens(tokens: Token[]): string {
let value = "";
let i = 0;

const isSafe =
isNameSafe(token.name) && isNextNameSafe(tokens[index + 1]);
const key = isSafe ? token.name : JSON.stringify(token.name);
function name(value: string) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pulled name function out (which adds bytes) because it's needed to avoid a crash on name being missing before the token type error.

const isSafe = isNameSafe(value) && isNextNameSafe(tokens[i]);
return isSafe ? value : JSON.stringify(value);
}

if (token.type === "param") return `:${key}`;
if (token.type === "wildcard") return `*${key}`;
throw new TypeError(`Unexpected token: ${token}`);
})
.join("");
while (i < tokens.length) {
const token = tokens[i++];

if (token.type === "text") {
value += escapeText(token.value);
continue;
}

if (token.type === "group") {
value += `{${stringifyTokens(token.tokens)}}`;
continue;
}

if (token.type === "param") {
value += `:${name(token.name)}`;
continue;
}

if (token.type === "wildcard") {
value += `*${name(token.name)}`;
continue;
}

throw new TypeError(`Unknown token type: ${(token as any).type}`);
}

return value;
}

/**
* Stringify token data into a path string.
*/
export function stringify(data: TokenData): string {
return stringifyTokens(data.tokens);
}

/**
* Validate the parameter name contains valid ID characters.
*/
function isNameSafe(name: string) {
function isNameSafe(name: string): boolean {
const [first, ...rest] = name;
if (!ID_START.test(first)) return false;
return rest.every((char) => ID_CONTINUE.test(char));
return ID_START.test(first) && rest.every((char) => ID_CONTINUE.test(char));
}

/**
* Validate the next token does not interfere with the current param name.
*/
function isNextNameSafe(token: Token | undefined) {
if (!token || token.type !== "text") return true;
return !ID_CONTINUE.test(token.value[0]);
function isNextNameSafe(token: Token | undefined): boolean {
if (token && token.type === "text") return !ID_CONTINUE.test(token.value[0]);
return true;
}