diff --git a/scripts/build/pattern.js b/scripts/build/pattern.js index 63e806c..2f9e5d4 100755 --- a/scripts/build/pattern.js +++ b/scripts/build/pattern.js @@ -7,9 +7,7 @@ const pattern = new RegExp( patterns .map((pattern) => pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) .join("|"), -) - .toString() - .slice(1, -1); +).source; const expression = new RegExp(patterns.join("|"), "i").toString(); diff --git a/src/index.ts b/src/index.ts index 1de7b7a..2dff947 100644 --- a/src/index.ts +++ b/src/index.ts @@ -31,6 +31,7 @@ let usedPattern: RegExp; export function isbot(userAgent?: string | null): boolean { if (typeof usedPattern === "undefined") { try { + // Build this RegExp dynamically to avoid syntax errors in older engines. usedPattern = new RegExp(fullPattern, "i"); } catch (error) { usedPattern = naivePattern; diff --git a/tests/spec/test.ts b/tests/spec/test.ts index 51a9f4a..a86edd6 100644 --- a/tests/spec/test.ts +++ b/tests/spec/test.ts @@ -10,6 +10,7 @@ import { createIsbot, createIsbotFromList, } from "../../src"; +import { fullPattern, regularExpression } from "../../src/pattern"; import { crawlers, browsers } from "../../fixtures"; let isbotInstance: any; @@ -131,7 +132,7 @@ describe("isbot", () => { afterAll(() => { jest.restoreAllMocks(); }); - test("Fallback regex detects commong crawlers", () => { + test("fallback regex detects commong crawlers", () => { USER_AGENT_COMMON.forEach((ua) => { if (!isbotInstance(ua)) { throw new Error(`Failed to detect ${ua} as bot`); @@ -186,5 +187,9 @@ describe("isbot", () => { ); expect(types).toMatchSnapshot(); }); + test("regular expressions exports are as expected", () => { + expect(pattern).toBe(regularExpression); + expect(new RegExp(fullPattern, "i").toString()).toBe(pattern.toString()); + }); }); });