MCPcopy Create free account
hub / github.com/btd/rollup-plugin-visualizer / getBytesPerFileUsingSourceMap

Function getBytesPerFileUsingSourceMap

plugin/sourcemap.ts:17–80  ·  view source on GitHub ↗
(
  bundleId: string,
  code: string,
  map: SourceMapConsumer,
  dir: string,
)

Source from the content-addressed store, hash-verified

15}
16
17const getBytesPerFileUsingSourceMap = (
18 bundleId: string,
19 code: string,
20 map: SourceMapConsumer,
21 dir: string,
22) => {
23 const modules: Record<string, SourceMapModuleRenderInfo> = {};
24 const modulesBySource = new Map<string, SourceMapModuleRenderInfo>();
25 const bundleDir = path.dirname(path.join(dir, bundleId));
26
27 let line = 1;
28 let lineStart = 0;
29 let lineEnd = 0;
30 let previous: GeneratedMapping | undefined;
31
32 const countSpan = (next?: GeneratedMapping): void => {
33 if (previous?.source == null) return;
34 // Columns and string offsets both use UTF-16; only the size uses UTF-8.
35 const start = Math.min(lineStart + previous.generatedColumn, lineEnd);
36 const end =
37 next?.generatedLine === previous.generatedLine
38 ? Math.min(lineStart + next.generatedColumn, lineEnd)
39 : lineEnd;
40 if (end <= start) return;
41
42 let module = modulesBySource.get(previous.source);
43 if (module == null) {
44 const id = path.resolve(bundleDir, previous.source);
45 module = modules[id] ??= { id, renderedLength: 0 };
46 modulesBySource.set(previous.source, module);
47 }
48 module.renderedLength += Buffer.byteLength(code.slice(start, end));
49 };
50
51 // Rollup and Rolldown emit flat maps. Stream their generated mappings without
52 // materializing characters or retaining the generated code for each module.
53 map.eachMapping(
54 (mapping) => {
55 // Original positions within the same source do not affect module sizes.
56 if (previous?.generatedLine === mapping.generatedLine && previous.source === mapping.source) {
57 return;
58 }
59 countSpan(mapping);
60
61 while (line < mapping.generatedLine && lineStart < code.length) {
62 const newline = code.indexOf("\n", lineStart);
63 lineStart = newline === -1 ? code.length : newline + 1;
64 line++;
65 }
66 if (previous?.generatedLine !== mapping.generatedLine) {
67 const newline = code.indexOf("\n", lineStart);
68 // Preserve the existing policy: include a mapped line's terminating LF,
69 // but do not extend its final mapping into an unmapped following line.
70 lineEnd = newline === -1 ? code.length : newline + 1;
71 }
72 previous = mapping;
73 },
74 null,

Callers 1

getSourcemapModulesFunction · 0.85

Calls 1

countSpanFunction · 0.85

Tested by

no test coverage detected