Skip to content

bundler: compose source maps through an input file's sourceMappingURL map - #41934

Closed
robobun wants to merge 4 commits into
mainfrom
robobun/8f4ae7ce/bundler-input-sourcemaps
Closed

robobun wants to merge 4 commits into
mainfrom
robobun/8f4ae7ce/bundler-input-sourcemaps

Conversation

@robobun

@robobun robobun commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • bun build --sourcemap ignores an input file's own //# sourceMappingURL= map (the output of a tsc, esbuild or Svelte step, or a node_modules dist/*.js with a .map). The emitted map stops at the intermediate .js: sources: ["../lib/lib.js"] where esbuild gives ["../src/lib.ts"]. Stack traces under bun and node --enable-source-maps stop there too.
  • Cause: the lexer records the comment (Lexer::source_mapping_url) but nothing reads it. The linker builds sources from the input file alone (LinkerContext::generate_source_map_for_chunk).

Fix

  • ParseTask loads the map the comment names: a data: URL (base64 or percent-encoded) or a sidecar file, from //#, //@ or /* */ comments. InputSourceMap::parse applies sourceRoot and sections, resolves sources against the map's directory, and reads a missing sourcesContent entry from disk. A missing sidecar is skipped silently (as in esbuild); an unreadable or malformed map is a warning. Either way the file maps to itself as before.
  • The printer's chunk builder translates each mapping through that map and drops positions it does not cover. The linker writes the map's sources and sourcesContent in place of the intermediate file. This is esbuild's design, so the output matches esbuild's. --compile stores a null sourcesContent entry as empty instead of failing with InvalidSourceMap.
  • The lexer added a comment's start offset twice to pragma argument locations. Warnings about a pragma (these new ones, @jsxRuntime) now point at it.
  • Verified: test/bundler/bundler_edgecase.test.ts (edgecase/InputSourceMap*, 8 cases including --compile, all fail on 1.4.3) and bun-build-api.test.ts (pragma location). Self-reviewed: the --compile rejection of null sourcesContent and the missing-sidecar warning noise were raised and fixed.

Background

  • A source map's mappings tie output positions to (source index, line, column). Composing means looking each intermediate position up in the input map (InputSourceMap::find, a binary search per printed token) and emitting what it points at instead.
  • The bundler prints each file into a map chunk in parallel, with source indices counted from 0, and generate_source_map_for_chunk rebases them when it joins the chunks. A file with an input map now takes one sources slot per source of that map, so the rebase adds the file's base slot instead of assigning it.
  • The dev server joins per-file maps itself (SourceMapStore, one slot per file), so files get no input map when it is attached. That path is unchanged.
Notes

no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/bundler/bun-build-api.test.ts

When an input file ends in a sourceMappingURL comment (the output of a
previous tsc, esbuild or compiler step), bun build now loads that map
and translates every mapping it emits for the file through it. The
output map lists that map's sources and sourcesContent in place of the
intermediate file, so positions, error stacks and debuggers reach the
original sources. Inline data: URLs (base64 or percent-encoded) and
sidecar .map files are read, in //#, //@ and block comments; sourceRoot
and sections (index maps) are applied; missing sourcesContent entries
are read from disk. A map that cannot be loaded is a warning and the
file maps to itself as before.

The lexer recorded pragma argument locations with the comment's own
offset added twice, so warnings about a pragma outside the file's first
comment pointed past it. They now point at the argument.
@robobun

robobun commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 10:50 PM PT - Sep 8th, 2026

❌ @robobun, your commit 31f7af7 has 1 failures in Build #113462 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 41934

That installs a local version of the PR into your bun-41934 executable, so you can run:

bun-41934 --bun

Comment thread src/ast/ast_result.rs Resolved
Comment thread src/bundler/Graph.rs Resolved
Comment thread src/bundler/LinkerContext.rs Resolved
Comment thread src/bundler/LinkerContext.rs Resolved
Comment thread src/bundler/ParseTask.rs Resolved
Comment thread src/bundler/input_source_map.rs Resolved
Comment thread src/bundler/input_source_map.rs Resolved
Comment thread src/bundler/input_source_map.rs Resolved
Comment thread src/bundler/input_source_map.rs Resolved
Comment thread src/js_parser/lexer.rs Resolved
Comment thread src/js_printer/lib.rs Resolved
Comment thread src/js_printer/lib.rs Resolved
Comment thread src/sourcemap/Chunk.rs Resolved
Comment thread src/sourcemap/Chunk.rs Resolved
Comment thread src/sourcemap/Chunk.rs Resolved
Comment thread src/sourcemap/Chunk.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
Comment thread src/sourcemap/InputSourceMap.rs Resolved
@robobun

robobun commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Collapsed every added multi-line comment under src/ to one line in 1ab837f and resolved the comment-cop threads.

@robobun
robobun marked this pull request as ready for review September 8, 2026 18:00
@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 6eb7ccb0-349a-40da-9c52-0bc5035d0c18

📥 Commits

Reviewing files that changed from the base of the PR and between b52d3e5 and 31f7af7.

📒 Files selected for processing (18)
  • src/ast/ast_result.rs
  • src/bundler/Graph.rs
  • src/bundler/LinkerContext.rs
  • src/bundler/ParseTask.rs
  • src/bundler/ServerComponentParseTask.rs
  • src/bundler/bundle_v2.rs
  • src/bundler/input_source_map.rs
  • src/bundler/lib.rs
  • src/js_parser/lexer.rs
  • src/js_parser/p.rs
  • src/js_printer/lib.rs
  • src/sourcemap/Chunk.rs
  • src/sourcemap/InputSourceMap.rs
  • src/sourcemap/lib.rs
  • src/standalone_graph/StandaloneModuleGraph.rs
  • test/bundler/bun-build-api.test.ts
  • test/bundler/bundler_edgecase.test.ts
  • test/bundler/expectBundled.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.

Walkthrough

The parser records sourceMappingURL comments. The bundler loads eligible input maps, propagates them through graph inputs, and composes generated source maps with original sources and locations. Tests cover inline, sidecar, indexed, missing, invalid, and partially mapped inputs.

Changes

Input source-map parsing

Layer / File(s) Summary
Parse and resolve source-map references
src/ast/ast_result.rs, src/js_parser/*, src/bundler/input_source_map.rs, src/sourcemap/InputSourceMap.rs
The parser records source-map comment spans. The loader resolves supported URLs and parses ordinary and indexed source maps, source paths, mappings, and contents.
Propagate maps through parse results
src/bundler/Graph.rs, src/bundler/ParseTask.rs, src/bundler/ServerComponentParseTask.rs, src/bundler/bundle_v2.rs
Eligible parsed files carry input maps into graph input files. Generated server-component results remain without input maps.
Compose generated source maps
src/js_printer/lib.rs, src/sourcemap/Chunk.rs, src/bundler/LinkerContext.rs
The printer and chunk builder remap generated positions through input maps. The linker emits composed sources and embedded contents.
Validate source-map behavior
test/bundler/bundler_edgecase.test.ts, test/bundler/bun-build-api.test.ts, test/bundler/expectBundled.ts
Tests cover source-map composition, URL forms, indexed sections, missing content, unmapped code, fallback behavior, runtime locations, and pragma offsets.

Suggested reviewers: jarred-sumner, alii, dylan-conway

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 31f7a

The source-map composition changes appear ready to merge, with no actionable merge-blocking risk identified.

Pre-merge checks: Passed 4
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely describes the main change: composing bundled source maps through an input file's sourceMappingURL map.
Description check Passed The description explains the problem, implementation, scope, compatibility behavior, and verification results. It does not use the exact template headings, but it provides the required information in …
Full details: Description check

Explanation

The description explains the problem, implementation, scope, compatibility behavior, and verification results. It does not use the exact template headings, but it provides the required information in equivalent sections.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review.

Reproduced on 1.4.3 (f42e980) with the two-file case from the report: lib/lib.js carrying esbuild's inline map for src/lib.ts, imported by entry.ts, built with bun build ./entry.ts --outdir out --sourcemap=linked --target=node. Before: sources: ["../lib/lib.js", "../entry.ts"] and new SourceMap(map).findEntry(3, 8) lands in lib.js. After: sources: ["../src/lib.ts", "../entry.ts"], findEntry(3, 8) gives ../src/lib.ts 5:8 (the same answer esbuild's bundle gives), and both bun out/entry.js (--target=bun) and node --enable-source-maps out/entry.js report the throw at src/lib.ts:6:9.

CI (build 113462, head 31f7af7): every lane passes except debian 13 x64-asan, where test/js/node/test/parallel/test-crypto-dh-leak.js fails; it fails on main too and is unrelated to this change.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this PR and didn't find any bugs. It adds a ~1000-line source-map composition subsystem (new VLQ/JSON parser for untrusted .map input, source-index rebasing in the linker, arena-adjacent ownership on InputFile), so a human look at the design and edge cases would still be worthwhile.

What was reviewed:

  • InputSourceMap::parse — adversarial input handling: i32::try_from on source counts, saturating adds on section offsets, VLQ parse errors surface as warnings not panics, OOM routed through ParseError rather than unwrap.
  • LinkerContext::generate_source_map_for_chunk — the rebase change from = mapping_source_index to += mapping_source_index matches the new per-file multi-slot layout; end_state.source_index is chunk-local (starts at 0) so addition is the right composition.
  • Lexer pragma offset fix — traced both single-line and block-comment call sites; the double-add of self.start is gone from all PragmaArg::scan callers.
  • Chunk::Builder — prev_input_line correctly split from prev_state.original_line since the latter now holds a post-remap value; line_starts_with_mapping only set when the input map actually covered the position.
Extended reasoning...

Overview

This PR makes bun build --sourcemap compose its output map through any //# sourceMappingURL= map an input file already carries, so the emitted sources point at original TypeScript/Svelte/etc. rather than intermediate JS. It adds a new bun_sourcemap::InputSourceMap type (405 lines: v3 JSON parsing including index-map sections, sourceRoot resolution per ECMA-426, file: URL handling with Windows drive-letter special-casing, percent-decoding, on-disk sourcesContent fill), a bundler-side loader that reads data:/sidecar/file: URLs on the parse worker, storage on Graph::InputFile as a global-heap Box explicitly dropped in deinit_without_freeing_arena, linker changes to emit N sources slots per input file and rebase chunk-local indices additively, and printer/Chunk::Builder changes to remap each mapping through the input map with a separate prev_input_line hint. A lexer bug (comment offset added twice to pragma-argument spans) is fixed alongside. Tests add ~290 lines of itBundled cases and helper functions.

Security risks

The new parser consumes untrusted .map JSON and VLQ-encoded mappings from disk or data: URLs. I checked the adversarial-input handling: source counts go through i32::try_from before becoming loop bounds, section offsets use saturating_add, negative offsets are rejected, mapping::parse failures and JSON parse failures produce ParseError (surfaced as a build warning) rather than panicking, and file reads go through bun_sys::File::read_from with errno-branched warnings. The url_scheme helper correctly distinguishes single-letter Windows drive prefixes from URL schemes. Path resolution uses bun_paths::resolve_path::join_abs_string_buf_checked with the pooled buffer, returning None on overflow rather than truncating. I did not find a way for a malformed map to escalate beyond a warning or to allocate unbounded memory beyond what the JSON parser itself would.

Level of scrutiny

High. This is a new feature spanning six crates with non-trivial index arithmetic (the += mapping_source_index rebase, per-section source offsets, the prev_input_line split), explicit memory lifecycle across an arena boundary, and behavior that every downstream consumer of bundler source maps depends on for correct stack traces. The design mirrors esbuild's (extractSourceMapFromComment, sourcemap_parser.go, ChunkBuilder.appendMapping) as stated in the description, and the deliberate divergences (warning vs. error on bad JSON, mozilla-style sourceRoot join, no names) are documented — a reviewer familiar with the esbuild reference should confirm the control-flow diff.

Other factors

Test coverage is thorough for the happy paths and several encodings (inline base64/percent data URLs, sidecar .map, sourceRoot, node_modules, minified, both comment forms), plus a regression test for the pragma-location fix. The PR description lists local runs of the sourcemap, jsx, comments, and dev-server suites. The dev-server (SourceMapStore, one slot per file) path is stated to be unchanged and gated by dev_server.is_none() in bundle_v2.rs. No CODEOWNERS entries cover these paths. Given the size, the number of interacting invariants, and the stated esbuild-parity goal, human review of the composition semantics and the linker rebase is warranted before merge.

…sourcesContent

A published package that names a .map it does not ship is common, so a
missing sidecar no longer warns (esbuild logs it at debug level too);
unreadable files, bad data: URLs and malformed maps still warn.

The standalone module graph rejected a null sourcesContent entry with
InvalidSourceMap, which made bun build --compile --sourcemap fail for an
input map whose original source is not on disk. It now stores such an
entry as empty, which the loader already treats as no contents.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

@robobun

robobun commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #45638.

#45638 carries the four commits of this PR, rebased onto a newer main. Three are unchanged, and the first differs only where ParseTask.rs conflicted. It adds six commits of fixes on top: one URL policy for input maps, two runtime fixes, the sidecar in --watch, and index map sections in any order.

Every test added here is in #45638: the eight edgecase/InputSourceMap* cases and the pragma location test. It adds twelve more tests, and it is linked to the user report #45372.

@robobun robobun closed this Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants