mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
fix(build): recover from esm.sh 500 on types-only (empty-runtime) packages
esm.sh's build pipeline returns HTTP 500 for packages that ship only TypeScript types with an effectively-empty runtime JS file (e.g. @solana/rpc-parsed-types, pulled in transitively by @solana/kit). The esm plugin treated this as fatal, blocking any project depending on such a package. When an esm.sh JS module fetch fails, fall back to jsDelivr's +esm endpoint to inspect the package's actual runtime. If it is effectively empty (no exports/imports/code after stripping comments, prologues, and source-map directives), synthesize an empty ES module so the build can proceed. Genuine non-empty failures are still re-thrown unchanged, and the fallback is scoped to JS module requests only (asset/CSS/JSON failures remain fatal).
This commit is contained in:
2 files changed
+237
No files matched your search
@@ -0,0 +1,132 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import {
|
||||
isEffectivelyEmptyModule,
|
||||
resolveEmptyModuleFallback,
|
||||
} from "./esmPlugin";
|
||||
|
||||
describe("isEffectivelyEmptyModule", () => {
|
||||
it("treats a file with only source-map comments as empty", () => {
|
||||
const source =
|
||||
"\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map";
|
||||
expect(isEffectivelyEmptyModule(source)).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a jsDelivr-bannered empty bundle as empty", () => {
|
||||
const source = [
|
||||
"/**",
|
||||
" * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.48.0.",
|
||||
" * Original file: /npm/@solana/[email protected]/dist/index.browser.mjs",
|
||||
" */",
|
||||
"//# sourceMappingURL=/sm/abc.map",
|
||||
].join("\n");
|
||||
expect(isEffectivelyEmptyModule(source)).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a 'use strict' prologue with no code as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("'use strict';\n//# sourceMappingURL=x.map")).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a bare `export {};` as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("export {};")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not treat a module with real exports as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("export const x = 1;")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat a module with imports as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("import './side-effect.js';")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat a module with executable code as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("console.log('hi');")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEmptyModuleFallback", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("synthesizes an empty module when jsDelivr runtime is empty", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => "\n//# sourceMappingURL=index.browser.mjs.map",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBe("export {};\n");
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://cdn.jsdelivr.net/npm/@solana/rpc-parsed-types/+esm",
|
||||
);
|
||||
});
|
||||
|
||||
it("recovers the version from the lockfile index", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => "//# sourceMappingURL=x.map",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const nameVersionToPaths = new Map<string, string[]>([
|
||||
["@solana/[email protected]", ["node_modules/@solana/rpc-parsed-types"]],
|
||||
]);
|
||||
|
||||
await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
||||
nameVersionToPaths,
|
||||
);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://cdn.jsdelivr.net/npm/@solana/[email protected]/+esm",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns undefined for a non-empty package (does not mask real failures)", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => "export const isNumber = () => true;",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*[email protected]?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when the jsDelivr fallback also fails", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: false,
|
||||
text: async () => "",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not attempt recovery for non-JS asset requests", async () => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/[email protected]/styles.css?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -447,6 +447,20 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
// Some packages ship only TypeScript types with an effectively-empty
|
||||
// runtime JS file (e.g. `@solana/rpc-parsed-types`). esm.sh's build
|
||||
// pipeline rejects these zero-export modules with an HTTP 500, even
|
||||
// though the package is perfectly valid — consumers only import its
|
||||
// types at compile time. When that happens, fall back to a raw CDN
|
||||
// (jsDelivr) to inspect the actual runtime. If the runtime is indeed
|
||||
// empty (no exports/imports/code), synthesize an empty ES module so
|
||||
// the build can proceed. Genuine failures (non-empty modules that
|
||||
// failed for other reasons) are re-thrown unchanged.
|
||||
const empty = await resolveEmptyModuleFallback(args.path, nameVersionToPaths);
|
||||
if (empty !== undefined) {
|
||||
return { contents: empty, loader: "js" };
|
||||
}
|
||||
|
||||
throw new Error(`Failed to fetch ${args.path}`);
|
||||
}
|
||||
|
||||
@@ -509,3 +523,94 @@ function extractPackageName(esmURL: string): { pkg?: string; version?: string }
|
||||
|
||||
return { pkg, version };
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a chunk of JavaScript is an "empty" runtime module — i.e.
|
||||
* it contains no executable code and no ES `import`/`export` statements once
|
||||
* comments and whitespace are stripped. This is the signature of a types-only
|
||||
* package whose compiled JS is intentionally empty.
|
||||
*/
|
||||
export function isEffectivelyEmptyModule(source: string): boolean {
|
||||
const stripped = source
|
||||
// Block comments (including jsDelivr/esm.sh banners and sourceMappingURL)
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
// Line comments (covers `//# sourceMappingURL=...`)
|
||||
.replace(/^\s*\/\/.*$/gm, "")
|
||||
// Directive prologues like `'use strict';` / `"use strict";`
|
||||
.replace(/^\s*(['"])use strict\1\s*;?\s*$/gm, "")
|
||||
.trim();
|
||||
|
||||
if (stripped.length === 0) return true;
|
||||
|
||||
// If there's any leftover content, only treat it as empty when it carries no
|
||||
// imports, exports, or other meaningful tokens. A bare `export {};` counts as
|
||||
// empty (it exports nothing), but anything else is a real module.
|
||||
if (/^export\s*\{\s*\}\s*;?$/.test(stripped)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* When esm.sh fails to build a module, attempt to recover by inspecting the
|
||||
* package's actual runtime via jsDelivr's `+esm` endpoint. If that runtime is
|
||||
* effectively empty (a types-only package), return an empty ES module string.
|
||||
* Returns `undefined` when the package is not empty (so the caller should treat
|
||||
* the original failure as fatal).
|
||||
*/
|
||||
export async function resolveEmptyModuleFallback(
|
||||
esmURL: string,
|
||||
nameVersionToPaths: Map<string, string[]>,
|
||||
): Promise<string | undefined> {
|
||||
let pkg: string | undefined;
|
||||
let version: string | undefined;
|
||||
|
||||
try {
|
||||
({ pkg, version } = extractPackageName(esmURL));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!pkg) return undefined;
|
||||
|
||||
// Only attempt the empty-module recovery for JavaScript module requests.
|
||||
// Asset/CSS/JSON failures are unrelated to the types-only-package problem and
|
||||
// should remain fatal.
|
||||
try {
|
||||
const ext = extname(new URL(esmURL).pathname).slice(1).toLowerCase();
|
||||
if (ext && !["js", "jsx", "mjs", "cjs", "ts", "tsx"].includes(ext)) {
|
||||
return undefined;
|
||||
}
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// The esm.sh URL for a transitive dependency often omits the version
|
||||
// (e.g. `*@solana/rpc-parsed-types?target=esnext`). Recover it from the
|
||||
// lockfile index when possible so the fallback fetch is deterministic.
|
||||
if (!version) {
|
||||
for (const key of nameVersionToPaths.keys()) {
|
||||
const at = key.lastIndexOf("@");
|
||||
if (at > 0 && key.slice(0, at) === pkg) {
|
||||
version = key.slice(at + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const spec = version ? `${pkg}@${version}` : pkg;
|
||||
const fallbackURL = `https://cdn.jsdelivr.net/npm/${spec}/+esm`;
|
||||
|
||||
try {
|
||||
const res = await fetch(fallbackURL);
|
||||
if (!res.ok) return undefined;
|
||||
|
||||
const text = await res.text();
|
||||
if (isEffectivelyEmptyModule(text)) {
|
||||
return "export {};\n";
|
||||
}
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
Reference in new issue
Block a user