From 944e7d3ec4375371a2e70a55ac07cab4c61dc8b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Sat, 25 Nov 2023 23:46:44 +0900 Subject: [PATCH] fix(dynamic-import-vars): escape special glob characters (#1636) --- .../src/dynamic-import-to-glob.js | 5 ++++- .../test/src/dynamic-import-to-glob.test.mjs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/dynamic-import-vars/src/dynamic-import-to-glob.js b/packages/dynamic-import-vars/src/dynamic-import-to-glob.js index 4d3f30b3f..6dcf7d7fd 100644 --- a/packages/dynamic-import-vars/src/dynamic-import-to-glob.js +++ b/packages/dynamic-import-vars/src/dynamic-import-to-glob.js @@ -1,15 +1,18 @@ import path from 'path'; +import fastGlob from 'fast-glob'; + export class VariableDynamicImportError extends Error {} /* eslint-disable-next-line no-template-curly-in-string */ const example = 'For example: import(`./foo/${bar}.js`).'; function sanitizeString(str) { + if (str === '') return str; if (str.includes('*')) { throw new VariableDynamicImportError('A dynamic import cannot contain * characters.'); } - return str; + return fastGlob.escapePath(str); } function templateLiteralToGlob(node) { diff --git a/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs b/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs index a08624b49..17f50124c 100644 --- a/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs +++ b/packages/dynamic-import-vars/test/src/dynamic-import-to-glob.test.mjs @@ -268,3 +268,21 @@ test('throws when dynamic import imports does not contain a file extension', (t) ); t.true(error instanceof VariableDynamicImportError); }); + +test('escapes ()', (t) => { + const ast = parse('import(`./${foo}/(foo).js`);', { + sourceType: 'module' + }); + + const glob = dynamicImportToGlob(ast.body[0].expression.source); + t.is(glob, './*/\\(foo\\).js'); +}); + +test('escapes []', (t) => { + const ast = parse('import(`./${foo}/[foo].js`);', { + sourceType: 'module' + }); + + const glob = dynamicImportToGlob(ast.body[0].expression.source); + t.is(glob, './*/\\[foo\\].js'); +});