From 9918d354f9ef5f4caff9e1abbb693674e5a71aed Mon Sep 17 00:00:00 2001 From: Ryan Weaver Date: Fri, 21 Jul 2023 10:42:04 -0400 Subject: [PATCH] [AssetMapper] Fixing import parsing from jsdelivr If a package imported 2x other packages, both where the package had no namespace (i.e. no "@" in the name), the 2 packages would be matched as one incorrectly. --- .../ImportMap/Resolver/JsDelivrEsmResolver.php | 5 +++-- .../Resolver/JsDelivrEsmResolverTest.php | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/AssetMapper/ImportMap/Resolver/JsDelivrEsmResolver.php b/src/Symfony/Component/AssetMapper/ImportMap/Resolver/JsDelivrEsmResolver.php index 99747047cf635..ca7c7b0eca5a1 100644 --- a/src/Symfony/Component/AssetMapper/ImportMap/Resolver/JsDelivrEsmResolver.php +++ b/src/Symfony/Component/AssetMapper/ImportMap/Resolver/JsDelivrEsmResolver.php @@ -25,6 +25,8 @@ final class JsDelivrEsmResolver implements PackageResolverInterface public const URL_PATTERN_VERSION = 'https://data.jsdelivr.com/v1/packages/npm/%s/resolved?specifier=%s'; public const URL_PATTERN_DIST = 'https://cdn.jsdelivr.net/npm/%s@%s%s/+esm'; + public const IMPORT_REGEX = '{from"/npm/([^@]*@?[\S]+)@([^/]+)/\+esm"}'; + private HttpClientInterface $httpClient; public function __construct( @@ -129,8 +131,7 @@ public function resolvePackages(array $packagesToRequire): array private function parseJsDelivrImports(string $content, array &$dependencies, bool $download, bool $preload): string { // imports from jsdelivr follow a predictable format - $regex = '{from"/npm/([^@]*@?[^@]+)@([^/]+)/\+esm"}'; - $content = preg_replace_callback($regex, function ($matches) use (&$dependencies, $download, $preload) { + $content = preg_replace_callback(self::IMPORT_REGEX, function ($matches) use (&$dependencies, $download, $preload) { $packageName = $matches[1]; $version = $matches[2]; diff --git a/src/Symfony/Component/AssetMapper/Tests/ImportMap/Resolver/JsDelivrEsmResolverTest.php b/src/Symfony/Component/AssetMapper/Tests/ImportMap/Resolver/JsDelivrEsmResolverTest.php index 643bee15da278..ca290d810b94c 100644 --- a/src/Symfony/Component/AssetMapper/Tests/ImportMap/Resolver/JsDelivrEsmResolverTest.php +++ b/src/Symfony/Component/AssetMapper/Tests/ImportMap/Resolver/JsDelivrEsmResolverTest.php @@ -234,4 +234,22 @@ public static function provideResolvePackagesTests(): iterable ], ]; } + + public function testImportRegex() + { + $subject = 'import{Color as t}from"/npm/@kurkle/color@0.3.2/+esm";import t from"/npm/jquery@3.7.0/+esm";import e from"/npm/popper.js@1.16.1/+esm";console.log("yo");'; + preg_match_all(JsDelivrEsmResolver::IMPORT_REGEX, $subject, $matches); + + $this->assertCount(3, $matches[0]); + $this->assertSame([ + '@kurkle/color', + 'jquery', + 'popper.js', + ], $matches[1]); + $this->assertSame([ + '0.3.2', + '3.7.0', + '1.16.1', + ], $matches[2]); + } }