All files / src/utils compose-sourcemap.ts

33.33% Statements 5/15
8.33% Branches 1/12
33.33% Functions 1/3
33.33% Lines 5/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 595x                                       5x         9x 9x 9x                                                              
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 {
  Eif (!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);
    }
  }
}