From fc91ba17422674553d1422cb1c7c93d71c1ab429 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20B=C3=B6hm?= Date: Sun, 7 Mar 2021 22:03:31 -0800 Subject: [PATCH] feat(parse): Ignore comments around selectors (#441) Fixes #391 --- package.json | 1 - src/parse.spec.ts | 11 +++++++++++ src/parse.ts | 11 +++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 64125926..1d179efa 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,6 @@ "build": "tsc", "prepare": "npm run build" }, - "dependencies": {}, "devDependencies": { "@types/jest": "^26.0.3", "@types/node": "^14.0.5", diff --git a/src/parse.spec.ts b/src/parse.spec.ts index 02ddb55e..9f6dea2d 100644 --- a/src/parse.spec.ts +++ b/src/parse.spec.ts @@ -47,4 +47,15 @@ describe("Broken selectors", () => { expect(() => parse(selector)).toThrow(Error); }); } + + it("should ignore comments", () => { + expect(parse("/* comment1 */ /**/ foo /*comment2*/")).toEqual([ + [ + { type: "descendant" }, + { name: "foo", namespace: null, type: "tag" }, + ], + ]); + + expect(() => parse("/*/")).toThrowError("Comment was not terminated"); + }); }); diff --git a/src/parse.ts b/src/parse.ts index 9edfa777..dd531597 100644 --- a/src/parse.ts +++ b/src/parse.ts @@ -245,6 +245,17 @@ function parseSelector( tokens = []; sawWS = false; stripWhitespace(1); + } else if ( + firstChar === "/" && + selector.charAt(selectorIndex + 1) === "*" + ) { + const endIndex = selector.indexOf("*/", selectorIndex + 2); + + if (endIndex < 0) { + throw new Error("Comment was not terminated"); + } + + selectorIndex = endIndex + 2; } else { if (sawWS) { ensureNotTraversal();