diff --git a/core/plugins/cdn.ts b/core/plugins/cdn.ts index a68d708..49af166 100644 --- a/core/plugins/cdn.ts +++ b/core/plugins/cdn.ts @@ -69,6 +69,7 @@ import { Context, fromContext, withContext } from "../context/context.ts"; import { parsePackageName } from "@bundle/utils/parse-package-name"; import { getPackageOfVersion, getPackageTarballUrl, getRegistryURL, resolveVersion } from "@bundle/utils/npm-search"; +import { normalizeRegistryConfig, getRegistryForPackage } from "@bundle/utils/npmrc"; import { isUrlSpec, @@ -144,15 +145,17 @@ export function CdnResolution(StateContext: Context>) { const sideEffectsMatchersCache = fromContext("sideEffectsMatchersCache", StateContext) ?? new Map(); + // ── Registry configuration (for scoped registries / .npmrc support) ──── + // Normalize the registry config once at plugin init time. + // This enables routing different scopes to different registries, e.g.: + // @jsr → https://npm.jsr.io + // @mycompany → https://npm.mycompany.com + const registryConfig = normalizeRegistryConfig(LocalConfig.registry); + return async function (args: ESBUILD.OnResolveArgs): Promise { const conditions = getResolverConditions(args, effectiveResolveOpts); let argPath = args.path; - console.log({ - argPath, - conditions - }) - // ======================================================================== // Build initial manifest from config + inherited pluginData // ======================================================================== @@ -365,6 +368,11 @@ export function CdnResolution(StateContext: Context>) { effectiveExtraSubpath = spec.target.path; } + // Resolve the appropriate registry for this package's scope, e.g.: + // @jsr/std__path → https://npm.jsr.io (if configured via .npmrc) + // react → https://registry.npmjs.org (default) + const registry = getRegistryForPackage(effectiveName, registryConfig); + // ====================================================================== // URL-based dependencies - route through build.resolve() // This allows TarballPlugin or HttpPlugin to handle them @@ -459,7 +467,7 @@ export function CdnResolution(StateContext: Context>) { try { // Step 1: Resolve version range to exact version - const identifiedVersion = await resolveVersion(`${nameToResolve}@${versionToResolve}`); + const identifiedVersion = await resolveVersion(`${nameToResolve}@${versionToResolve}`, registry); if (identifiedVersion) effectiveAssumedVersion = identifiedVersion; } catch (e) { dispatchEvent(LOGGER_WARN, `[registry] Version resolution failed for ${nameToResolve}@${versionToResolve}, falling back to assumed version.`); @@ -472,7 +480,7 @@ export function CdnResolution(StateContext: Context>) { try { resolvedManifest = packageManifestsMap.get(packageId) ?? null; if (!resolvedManifest) { - resolvedManifest = await getPackageOfVersion(packageId); + resolvedManifest = await getPackageOfVersion(packageId, registry); if (resolvedManifest) { packageManifestsMap.set(packageId, resolvedManifest); } @@ -487,6 +495,7 @@ export function CdnResolution(StateContext: Context>) { resolvedManifest as FullPackageVersion | null, effectiveName, effectiveAssumedVersion, + registry, ); const combinedSubpath = joinSubpath(effectiveExtraSubpath, parsedSubpath); @@ -551,6 +560,12 @@ export function CdnResolution(StateContext: Context>) { let resolvedManifest = structuredClone(initialManifest); let resultSubpath = parsedSubpath; + // Track whether we successfully fetched the package's own manifest + // from the CDN. When false, resolvedManifest still holds the parent's + // version (from initialManifest), so we must prefer + // effectiveAssumedVersion for the final URL construction. + let manifestFetched = false; + // If the CDN supports package.json and some other npm stuff, it counts as an npm CDN if (NPM_CDN) { // For npm aliases, we need to resolve the aliased package name @@ -558,7 +573,7 @@ export function CdnResolution(StateContext: Context>) { const versionToResolve = effectiveAssumedVersion; try { - const identifiedVersion = await resolveVersion(`${nameToResolve}@${versionToResolve}`) + const identifiedVersion = await resolveVersion(`${nameToResolve}@${versionToResolve}`, registry) if (identifiedVersion) effectiveAssumedVersion = identifiedVersion; } catch (e) { dispatchEvent(LOGGER_WARN, `Couldn't identify the correct npm version based on the semver (${versionToResolve}) for package (${nameToResolve}). Be cautious this is an unusual situation, the bundle may silently break in odd ways.`); @@ -573,8 +588,18 @@ export function CdnResolution(StateContext: Context>) { // If the subpath is a directory check to see if that subpath has a `package.json`, // after which check if the parent directory has a `package.json` + // + // NOTE: We fetch the version-specific manifest from the registry API + // (e.g. registry.npmjs.org/pkgname/1.0.0) only for unscoped packages. + // For scoped packages, the registry's version endpoint uses `%2f` + // encoding (@scope%2fname/version) which breaks on some HTTP infra + // that decodes `%2f` before routing. Instead, for scoped packages + // we use the CDN-native path to fetch package.json directly. + const useRegistryEndpoint = !effectiveName.includes("/"); const manifestVariants = [ - { path: getRegistryURL(`${effectiveName}@${effectiveAssumedVersion}`).packageVersionURL }, + useRegistryEndpoint + ? { path: getRegistryURL(`${effectiveName}@${effectiveAssumedVersion}`, registry).packageVersionURL } + : { path: `${effectiveName}@${effectiveAssumedVersion}/package.json` }, // { path: `${effectiveName}@${effectiveAssumedVersion}/package.json` }, isDirectory ? { path: `${effectiveName}@${effectiveAssumedVersion}${parsedSubpath}/package.json`, @@ -597,6 +622,7 @@ export function CdnResolution(StateContext: Context>) { if (!res.ok) throw new Error(await res.text()); resolvedManifest = await res.json(); + manifestFetched = true; isSubpathDirectoryPackage = isDirectory ?? false; // If the package.json is not a sub-directory package, then we should cache it as such @@ -678,7 +704,16 @@ export function CdnResolution(StateContext: Context>) { // If the CDN is npm based then it should add the parsed version to the URL // e.g. https://unpkg.com/spring-easing@v1.0.0/ - const knownVersion = resolvedManifest?.version || effectiveAssumedVersion; + // + // When we successfully fetched this package's own manifest, its + // `version` field is authoritative. Otherwise resolvedManifest is + // still a clone of the *parent's* manifest, whose version would be + // wrong (e.g. jsonfile getting fs-extra's "11.2.0"). In that case + // fall back to effectiveAssumedVersion which was resolved from the + // npm registry and is correct. + const knownVersion = manifestFetched + ? (resolvedManifest?.version || effectiveAssumedVersion) + : effectiveAssumedVersion; const cdnVersionFormat = NPM_CDN ? "@" + knownVersion : ""; const { url } = getCDNUrl(`${effectiveName}${cdnVersionFormat}${resultSubpath}`, origin); @@ -691,7 +726,7 @@ export function CdnResolution(StateContext: Context>) { const packageId = `${effectiveName}@${knownVersion}`; if (!packageManifestsMap.get(packageId)) { try { - const _manifest = await getPackageOfVersion(packageId); + const _manifest = await getPackageOfVersion(packageId, registry); if (_manifest) packageManifestsMap.set(packageId, _manifest); } catch (e) { dispatchEvent(LOGGER_WARN, "Could not store the package.json manifests of the dependencies we fetched."); diff --git a/core/tests/19-registry-tarballs.test.ts b/core/tests/19-registry-tarballs.test.ts index 94880d6..3243fd9 100644 --- a/core/tests/19-registry-tarballs.test.ts +++ b/core/tests/19-registry-tarballs.test.ts @@ -21,6 +21,9 @@ * | 19.10 — getNpmTarballUrl construction | Tarball URL construction for scoped/unscoped packages | * | 19.11 — getPackageTarballUrl | Manifest dist.tarball preference vs fallback | * | 19.12 — npm: and jsr.registry: scheme helpers | Origin, path, URL generation for shorthand schemes | + * | 19.13 — parseNpmrc | .npmrc content parsing | + * | 19.14 — getRegistryForPackage | Registry lookup by scope | + * | 19.15 — normalizeRegistryConfig | Config normalization from various inputs | * | 19.16 — Scoped package %2f encoding | Registry URL encoding for scoped packages | * * @see docs/scenarios/19-registry-tarballs.md @@ -43,6 +46,12 @@ import { import { getCDNStyle, getCDNOrigin, getPureImportPath, getCDNUrl } from "../utils/cdn-format.ts"; import { getNpmTarballUrl, getPackageTarballUrl, getRegistryURL, escapePackageName } from "@bundle/utils/npm-search"; import { TAR_MULTI_EXTENSIONS, TAR_SHORT_EXTENSIONS } from "@bundle/utils/archive-detect"; +import { + parseNpmrc, + getRegistryForPackage, + normalizeRegistryConfig, + NPM_PUBLIC_REGISTRY, +} from "@bundle/utils/npmrc"; // ============================================================================= // 19.1 — isTarballUrl detection @@ -831,4 +840,187 @@ describe("19.16 — Scoped package %2f encoding in registry URLs", () => { // Verify there's no %2f in the tarball URL expect(url).not.toContain("%2f"); }); +}); + +// ============================================================================= +// 19.13 — parseNpmrc +// ============================================================================= + +describe("19.13 — parseNpmrc", () => { + test("parses default registry", () => { + const config = parseNpmrc("registry=https://registry.npmjs.org/"); + expect(config.registry).toBe("https://registry.npmjs.org/"); + expect(config.scopedRegistries).toBeUndefined(); + }); + + test("parses scoped registries", () => { + const config = parseNpmrc(` + @jsr:registry=https://npm.jsr.io + @mycompany:registry=https://npm.mycompany.com/ + `); + expect(config.scopedRegistries).toEqual({ + "@jsr": "https://npm.jsr.io", + "@mycompany": "https://npm.mycompany.com/", + }); + }); + + test("parses both default and scoped registries", () => { + const config = parseNpmrc(` + registry=https://my-registry.com/ + @jsr:registry=https://npm.jsr.io + `); + expect(config.registry).toBe("https://my-registry.com/"); + expect(config.scopedRegistries).toEqual({ + "@jsr": "https://npm.jsr.io", + }); + }); + + test("ignores comments (# and ;)", () => { + const config = parseNpmrc(` + # This is a comment + ; This is also a comment + registry=https://registry.npmjs.org/ + # @ignored:registry=https://should-not-appear.com + `); + expect(config.registry).toBe("https://registry.npmjs.org/"); + expect(config.scopedRegistries).toBeUndefined(); + }); + + test("ignores auth token lines", () => { + const config = parseNpmrc(` + registry=https://registry.npmjs.org/ + //registry.npmjs.org/:_authToken=some-secret-token + //npm.jsr.io/:_authToken=another-token + `); + expect(config.registry).toBe("https://registry.npmjs.org/"); + // Auth tokens should NOT appear in the config + expect(config.scopedRegistries).toBeUndefined(); + }); + + test("strips environment variable references", () => { + const config = parseNpmrc("registry=https://registry.npmjs.org/${NPM_TOKEN}"); + expect(config.registry).toBe("https://registry.npmjs.org/"); + }); + + test("handles whitespace around =", () => { + const config = parseNpmrc("registry = https://registry.npmjs.org/"); + expect(config.registry).toBe("https://registry.npmjs.org/"); + }); + + test("handles empty input", () => { + const config = parseNpmrc(""); + expect(config.registry).toBeUndefined(); + expect(config.scopedRegistries).toBeUndefined(); + }); + + test("handles Windows line endings", () => { + const config = parseNpmrc("registry=https://registry.npmjs.org/\r\n@jsr:registry=https://npm.jsr.io\r\n"); + expect(config.registry).toBe("https://registry.npmjs.org/"); + expect(config.scopedRegistries).toEqual({ + "@jsr": "https://npm.jsr.io", + }); + }); + + test("scoped names are lowercased", () => { + const config = parseNpmrc("@JSR:registry=https://npm.jsr.io"); + expect(config.scopedRegistries).toEqual({ + "@jsr": "https://npm.jsr.io", + }); + }); + + test("ignores unknown directives", () => { + const config = parseNpmrc(` + strict-ssl=true + cache=/tmp/npm-cache + registry=https://registry.npmjs.org/ + proxy=http://proxy.example.com + `); + expect(config.registry).toBe("https://registry.npmjs.org/"); + expect(config.scopedRegistries).toBeUndefined(); + }); +}); + +// ============================================================================= +// 19.14 — getRegistryForPackage +// ============================================================================= + +describe("19.14 — getRegistryForPackage", () => { + const config = { + registry: "https://my-default-registry.com", + scopedRegistries: { + "@jsr": "https://npm.jsr.io", + "@mycompany": "https://npm.mycompany.com/", + }, + }; + + test("returns scoped registry for matching scope", () => { + expect(getRegistryForPackage("@jsr/std__path", config)).toBe("https://npm.jsr.io"); + }); + + test("returns scoped registry for different scope", () => { + expect(getRegistryForPackage("@mycompany/sdk", config)).toBe("https://npm.mycompany.com/"); + }); + + test("returns default registry for unscoped packages", () => { + expect(getRegistryForPackage("react", config)).toBe("https://my-default-registry.com"); + }); + + test("returns default registry for unknown scopes", () => { + expect(getRegistryForPackage("@unknown/pkg", config)).toBe("https://my-default-registry.com"); + }); + + test("returns fallback when no config", () => { + expect(getRegistryForPackage("react", null)).toBe(NPM_PUBLIC_REGISTRY); + }); + + test("returns fallback when config has no registries", () => { + expect(getRegistryForPackage("react", {})).toBe(NPM_PUBLIC_REGISTRY); + }); + + test("uses custom fallback", () => { + expect(getRegistryForPackage("react", null, "https://custom-fallback.com")).toBe("https://custom-fallback.com"); + }); + + test("scope matching is case-sensitive (scopes should be lowercase)", () => { + // @JSR was lowercased during parsing, so @JSR won't match the stored @jsr + expect(getRegistryForPackage("@JSR/something", config)).toBe("https://my-default-registry.com"); + }); +}); + +// ============================================================================= +// 19.15 — normalizeRegistryConfig +// ============================================================================= + +describe("19.15 — normalizeRegistryConfig", () => { + test("returns undefined for null/undefined input", () => { + expect(normalizeRegistryConfig(null)).toBeUndefined(); + expect(normalizeRegistryConfig(undefined)).toBeUndefined(); + }); + + test("treats plain URL string as default registry", () => { + const config = normalizeRegistryConfig("https://npm.jsr.io"); + expect(config).toEqual({ registry: "https://npm.jsr.io" }); + }); + + test("parses string with = as .npmrc content", () => { + const config = normalizeRegistryConfig("@jsr:registry=https://npm.jsr.io"); + expect(config?.scopedRegistries).toEqual({ + "@jsr": "https://npm.jsr.io", + }); + }); + + test("parses multi-line string as .npmrc content", () => { + const config = normalizeRegistryConfig( + "registry=https://my-reg.com\n@jsr:registry=https://npm.jsr.io" + ); + expect(config?.registry).toBe("https://my-reg.com"); + expect(config?.scopedRegistries).toEqual({ + "@jsr": "https://npm.jsr.io", + }); + }); + + test("passes through RegistryConfig object as-is", () => { + const input = { registry: "https://my-reg.com", scopedRegistries: { "@foo": "https://foo.com" } }; + expect(normalizeRegistryConfig(input)).toBe(input); + }); }); \ No newline at end of file