import remapping from "@jridgewell/remapping"; import type { SourceMapInput } from "rollup"; /** Minimal chunk shape shared by Rollup and Rolldown OutputChunk. */ interface ChunkLike { fileName: string; map?: { toString(): string } | null; } /** Minimal bundle shape shared by Rollup and Rolldown OutputBundle. */ interface BundleLike { [key: string]: { type: string; source?: string | Uint8Array }; } /** * Composes `newMap` with the chunk's existing sourcemap (if any), updates * `chunk.map`, and patches the corresponding `.map` asset in the bundle so * the change is written to disk (Rollup v3+ emits sourcemaps as separate * assets before `generateBundle`). */ export function composeSourcemap( chunk: ChunkLike, newMap: SourceMapInput, bundle: BundleLike, ): void { if (!chunk.map) { chunk.map = newMap as unknown as typeof chunk.map; return; } const composedMap = remapping( [newMap as never, chunk.map as never], () => null, ); chunk.map = composedMap as unknown as typeof chunk.map; // Rollup v3+ emits sourcemaps as separate assets before generateBundle. // Try the conventional key first; fall back to scanning for a `.map` asset // whose source references this chunk (covers custom sourcemapFileNames). // Inline sourcemaps (`sourcemap: 'inline'`) don't produce a separate asset // so updating chunk.map above is sufficient for that case. const mapKey = chunk.fileName + ".map" in bundle ? chunk.fileName + ".map" : Object.keys(bundle).find((key) => { const entry = bundle[key]; return ( key.endsWith(".map") && entry.type === "asset" && typeof entry.source === "string" && entry.source.includes(chunk.fileName) ); }); if (mapKey) { const mapAsset = bundle[mapKey]; if (mapAsset.type === "asset") { mapAsset.source = JSON.stringify(composedMap); } } }