All files / src/sourcemap-url index.ts

100% Statements 16/16
100% Branches 10/10
100% Functions 2/2
100% Lines 15/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            1x   7x     7x 8x 8x 7x 7x   7x 8x   7x   1x   6x       6x 5x   5x            
import type { OutputChunk, Plugin as RollupPlugin } from "rollup";
 
interface SourcemapUrlPluginOptions {
  replaceUrl: (url: string) => string;
}
 
export const sourcemapUrl = (
  options: SourcemapUrlPluginOptions,
): RollupPlugin => ({
  name: "sourcemap-url",
  generateBundle(outputOptions, bundle) {
    for (const fileName of Object.keys(bundle)) {
      const chunk = bundle[fileName] as OutputChunk;
      if (chunk.map) {
        const splitCode = chunk.code.split("\n");
        let lineIndex = splitCode.length - 1;
        // find the last line that is not empty
        while (lineIndex >= 0 && splitCode[lineIndex].trim() === "") {
          lineIndex--;
        }
        if (lineIndex < 0) {
          // empty file
          continue;
        }
        const match = splitCode[lineIndex].match(
          /\/\/# sourceMappingURL=([^\s]+)/,
        );
        // if the last line is a sourceMappingURL, replace it
        if (match && match[1]) {
          splitCode[lineIndex] =
            `//# sourceMappingURL=${options.replaceUrl(match[1])}`;
          chunk.code = splitCode.join("\n");
        }
      }
    }
  },
});