From 073615d5138c9c6d4343ecf3888278ceaadfa2c7 Mon Sep 17 00:00:00 2001 From: Gregorio Litenstein Date: Sun, 23 Oct 2022 18:11:18 -0300 Subject: [PATCH] More thoroughly check for unbalanced patterns. --- src/index.spec.ts | 35 +++++++++++++++++++++++++++++++++++ src/index.ts | 6 ++++++ 2 files changed, 41 insertions(+) diff --git a/src/index.spec.ts b/src/index.spec.ts index a4cae6b..2b42c29 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -1897,6 +1897,27 @@ const TESTS: Test[] = [ [{ cid: "u123" }, null], ], ], + [ + "/test/{\\(:uid(\\d+)\\)}?", + undefined, + [ + "/test/", + { + name: "uid", + prefix: "(", + suffix: ")", + modifier: "?", + pattern: "\\d+", + }, + ], + [ + ["/test", null], + ["/test/", ["/test/", undefined]], + ["/test/123", null], + ["/test/(123)", ["/test/(123)", "123"]], + ], + [[{ uid: "123" }, "/test/(123)"]], + ], /** * Unnamed group prefix. @@ -2772,6 +2793,20 @@ describe("path-to-regexp", function () { }).toThrow(new TypeError("Unbalanced pattern at 5")); }); + it("should throw if ) appears unescaped and without an opening (", function () { + expect(function () { + pathToRegexp.pathToRegexp("/:fooab)c"); + }).toThrow( + new TypeError("Unescaped ) at 7: may be unmatched group finish.") + ); + }); + it("should throw on unbalanced patterns, even after completing a balanced one.", function () { + expect(function () { + pathToRegexp.pathToRegexp("/:test(\\w+)/:foo(\\d+))"); + }).toThrow( + new TypeError("Unescaped ) at 21: may be unmatched group finish.") + ); + }); it("should throw on missing pattern", function () { expect(function () { pathToRegexp.pathToRegexp("/:foo()"); diff --git a/src/index.ts b/src/index.ts index d754fee..5e0787f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,6 +45,12 @@ function lexer(str: string): LexToken[] { continue; } + if (char === ")") { + throw new TypeError( + `Unescaped ) at ${i}: may be unmatched group finish.` + ); + } + if (char === ":") { let name = ""; let j = i + 1;