From ac9347f5c381aedd98df3365153110881297f706 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Aug 2025 19:32:48 -0700 Subject: [PATCH] Fix transitive package version resolution to support scoped packages --- src/lib/build/esmPlugin.ts | 42 +++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index a1d8c065..1d8a53b5 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -37,7 +37,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { setup(build) { // http(s) imports - build.onResolve({ filter: /^https?:\/\// }, async (args) => { + build.onResolve({ filter: /^https?:\/\// }, (args) => { return { path: args.path, namespace: "esm", @@ -50,17 +50,23 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { ? args.path.split("/").slice(0, 2).join("/") : args.path.split("/")[0]; - let packageKey = `node_modules/${packageName}`; - if (args.importer.startsWith("https://esm.sh/")) { - try { - const importerPackage = new URL(args.importer).pathname.split('/')[1]?.split('@')[0].replace(/^\*/, ''); - packageKey = `node_modules/${importerPackage}/node_modules/${packageName}`; - } catch { - // fallthrough - } + // Handle transitive dependency versions + const keys: string[] = []; + try { + const importerPackage = extractPackageName(args.importer); + keys.push( + `node_modules/${importerPackage}/node_modules/${packageName}`, + ); + } catch { + // fallthrough } - const packageInfo = packageLock.packages[packageKey] || packageLock.packages[`node_modules/${packageName}`]; + keys.push(`node_modules/${packageName}`); + + const packageInfo = keys + .map((key) => packageLock.packages[key]) + .find((info) => info); + const packagePath = args.path.slice(packageName.length); const version = packageInfo?.version; @@ -145,3 +151,19 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { }, }; } + +/** Extract package name from esm.sh-style URL */ +function extractPackageName(esmShURL: string): string { + const full = new URL(esmShURL) + .pathname + .slice(1) + .replace(/^\*/, ""); + + const base = full.startsWith("@") + ? full.split("/").slice(0, 2).join("/") + : full.split("/")[0]; + + return full.startsWith("@") + ? base.split("@").splice(0, 2).join("@") + : base.split("@")[0]; +}