Repository navigation
Conversation
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.
|
Updated 10:50 PM PT - Sep 8th, 2026
❌ @robobun, your commit 31f7af7 has 1 failures in 🧪 To try this PR locally: bunx bun-pr 41934That installs a local version of the PR into your bun-41934 --bun |
|
Collapsed every added multi-line comment under |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughThe parser records ChangesInput source-map parsing
Suggested reviewers: Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to
|
|
Status: ready for review. Reproduced on 1.4.3 (f42e980) with the two-file case from the report: CI (build 113462, head 31f7af7): every lane passes except debian 13 x64-asan, where |
There was a problem hiding this comment.
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_fromon source counts, saturating adds on section offsets, VLQ parse errors surface as warnings not panics, OOM routed throughParseErrorrather than unwrap.LinkerContext::generate_source_map_for_chunk— the rebase change from= mapping_source_indexto+= mapping_source_indexmatches the new per-file multi-slot layout;end_state.source_indexis 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.startis gone from allPragmaArg::scancallers. Chunk::Builder—prev_input_linecorrectly split fromprev_state.original_linesince the latter now holds a post-remap value;line_starts_with_mappingonly 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.
|
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 Every test added here is in #45638: the eight |
Problem
bun build --sourcemapignores an input file's own//# sourceMappingURL=map (the output of a tsc, esbuild or Svelte step, or anode_modulesdist/*.jswith a.map). The emitted map stops at the intermediate.js:sources: ["../lib/lib.js"]where esbuild gives["../src/lib.ts"]. Stack traces underbunandnode --enable-source-mapsstop there too.Lexer::source_mapping_url) but nothing reads it. The linker buildssourcesfrom the input file alone (LinkerContext::generate_source_map_for_chunk).Fix
ParseTaskloads the map the comment names: adata:URL (base64 or percent-encoded) or a sidecar file, from//#,//@or/* */comments.InputSourceMap::parseappliessourceRootandsections, resolvessourcesagainst the map's directory, and reads a missingsourcesContententry 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.sourcesandsourcesContentin place of the intermediate file. This is esbuild's design, so the output matches esbuild's.--compilestores anullsourcesContententry as empty instead of failing withInvalidSourceMap.@jsxRuntime) now point at it.test/bundler/bundler_edgecase.test.ts(edgecase/InputSourceMap*, 8 cases including--compile, all fail on 1.4.3) andbun-build-api.test.ts(pragma location). Self-reviewed: the--compilerejection ofnullsourcesContentand the missing-sidecar warning noise were raised and fixed.Background
mappingstie 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.generate_source_map_for_chunkrebases them when it joins the chunks. A file with an input map now takes onesourcesslot per source of that map, so the rebase adds the file's base slot instead of assigning it.SourceMapStore, one slot per file), so files get no input map when it is attached. That path is unchanged.Notes
SourceMapStorehalf would restack on top of this. Add sourcemap support for onLoad plugins #20865 (draft) hooks the samejs_printer/chunk-builder seam foronLoadplugins; a plugin result with an inlinedata:map already composes here, a relative sidecar needs a file-namespace path. bun build --no-bundle: honor --sourcemap #41939 makes--no-bundleemit maps; whichever lands second can passInputSourceMapthrough the transform-only printer too. bundler: fix source map names, closing-brace mappings, null segments, and URL escaping #40834 (names, closing-brace mappings) is independent; if it lands first, input-mapnamescan be carried through in a follow-up. Remove dead code from bun_js_parser, bun_sys, bun_perf, the bake router, and the root-certs script #41127 deletesLexer::source_mapping_urlas dead code and has been asked to keep it.//#comment, keep the intermediate file assources[0]and map uncovered positions to it, and do not handlesectionsor percent-encodeddata:URLs. This PR follows esbuild instead (bundler.goextractSourceMapFromComment,js_parser/sourcemap_parser.go,sourcemap.goChunkBuilder.appendMapping), which is what the composition fuzz compares against.cover_lines_without_mappingsis off for a file with an input map: repeating the previous mapping at the start of an unmapped line would point wherever the input map last pointed.sourceRootis prepended with a/separator (mozillasource-mapbehavior) instead of being truncated at its last/.namesare not carried through, since bun does not emitnamesyet.--target=bun --sourcemap=linked,bun out/entry.jsnow prints the frameat f (src/lib.ts:6:9)with the TypeScript source line, andnode --enable-source-mapsdoes the same for--target=node. A--compiled executable reportssrc/lib.ts:6:9as well.bundler_edgecase(190),esbuild/default -t SourceMap,bun-build-api -t sourcemap,bundler_comments,bundler_jsx,test/js/bun/sourcemap/*,compile-sourcemap-internal,test/bake/dev/sourcemap,cli.test.ts.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