Repository navigation
Conversation
Closes #30536. When Bun.build reads a source file that carries a trailing `//# sourceMappingURL=data:application/json;...` comment (typically produced by an upstream compile step like .vue/.svelte/.mdx/ts-plugin → .js), the bundler already detected the URL at the lexer but dropped it on the floor. The output sourcemap's deepest `sources[]` entry was the intermediate .js file and `sourcesContent[]` carried the intermediate's bytes verbatim — including the literal `sourceMappingURL=` comment — so stack traces surfaced one hop short of the authored source. - `src/sourcemap/InputSourceMap.zig` (new): owns the parsed inner map + per-source contents, cleans up after itself. - `src/bundler/ParseTask.zig`: after parsing the JS, scan the source for a trailing `//# sourceMappingURL=data:...`. Inline data URLs are parsed (base64 and raw); external `.map` references are left for a follow-up. Gated on `source_map != .none` and `loader.canHaveSourceMap()`. - `src/bundler/Graph.zig`, `src/bundler/bundle_v2.zig`: new `InputFile.input_source_map` field; ownership moves from the parse result onto the file on consumption, freed at bundler teardown. - `src/js_printer/js_printer.zig`, `src/sourcemap/Chunk.zig`: threads the parsed map into `Chunk.Builder`. During `addSourceMapping`, translate each (line, column) through the inner map — on a hit, emit `source_index = 1 + inner.source_index` and the inner original (line, column); on a miss, fall back to slot 0 (the intermediate) so unmapped tokens still land in a real file. - `src/bundler/LinkerContext.zig`: each outer source in the output map's `sources[]` expands to `[intermediate, inner_0 .. inner_N-1]`. `sourcesContent[]` matches slot-for-slot: the intermediate's contents first, then each inner source's contents (drawn from the inner map). Chunk stitching uses `base + chunk.end_state.source_index` as the absolute end state so per-chunk mappings that vary source_index across their length compose correctly. - Repro from the issue (entry.ts → inner.js-with-inline-map → inner.ts): output `sources` now contains `../inner.ts`; `sourcesContent[authored_slot]` is the clean authored bytes with no sourceMappingURL comment. - Multi-inner-source maps (e.g. .vue compilers that split template/script) surface all inner sources. - Malformed or unrecognized inline maps fall back gracefully — build succeeds with the old behavior. - External `.map` references unchanged (out of scope here). - `sourcemap = none` builds skip the scan entirely. Five new cases in `test/bundler/bun-build-api.test.ts` covering: the base64 chain, the raw data-URL chain, multi-inner-source surfacing, malformed payload fallback, and external `.map` reference unchanged.
The ParseTask scan runs on `source.contents` regardless of whether the contents came from disk or an `onLoad` plugin return, so the plugin case from #6173 is covered by the same pipeline. Add an explicit regression test so it stays covered if the scanner ever moves. A custom-extension plugin that emits transformed JS with its own `//# sourceMappingURL=data:...` comment should have the pre-transform authored source show up in the final map's `sources[]` / `sourcesContent[]`. Uses a distinct inner-source filename so the slot assertion can tell the plugin intermediate apart from the chained authored source.
claude[bot] and coderabbit spotted three real issues in the initial
landing. One refactor fixes the first two; the third is just more
assertions.
1. InputSourceMap.parse: return `?*InputSourceMap` made the `errdefer`
blocks dead code — Zig only fires `errdefer` on error returns,
and the function had none. Every mid-parse `return null` (most
realistically `Mapping.parse` rejecting a malformed VLQ, which
passes all the JSON structure checks above it) leaked
`source_paths_slice`, `sources_content_slice`, and every
`allocator.dupe`d string on `bun.default_allocator` — never
reclaimed for the life of the process, nasty in long-running
dev-server / watch-mode callers.
Split into a public `parse` + internal `parseInternal` that
returns `ParseError!*InputSourceMap`. The `errdefer`s now fire
on every malformed-payload bail. OOM propagates through the
error union and the outer `parse` wraps it in
`bun.outOfMemory()` (fatal), while validation failures collapse
back to `null` — the original contract callers depend on.
Ownership-transfer sites (`psm.external_source_names =`,
building the result `InputSourceMap`) neuter the now-redundant
`errdefer`s by zeroing `paths_written` / `contents_written`
and re-pointing the slices at `&.{}`, so a future `try` added
between transfer and return can't double-free.
2. bundle_v2 onParseTaskComplete: the new `input_source_map` slot
was written without freeing any prior value, leaking on dev-server
/ watch-mode reparses where the same source index gets a fresh
map. Also, the early-failure path where `runResolutionForParseTask`
downgrades `.success` to `.err` was dropping the freshly parsed
map without deinit.
Both paths now explicitly `deinit()` before overwrite. The
success transfer also nulls the result slot so the old layout
can't be mistaken for still-owning after the move.
3. Test guards: four call sites pulled `m![1]` without first
asserting `m` matched. Added `expect(m).not.toBeNull()` so a
future output regression fails the test cleanly instead of
surfacing as an unhelpful TypeError on the `m![1]` coercion.
Rejected coderabbit's "restrict to file-backed inputs" suggestion:
plugin `onLoad` returns are explicitly in scope (closes #6173) and
covered by the test committed in 192b355. A blanket
`source.path.isFile()` gate would break that case.
Rejected claude[bot]'s suggestion to add a hostile-VLQ regression
test: it exposed a pre-existing panic inside `Mapping.parse`
(`addScalar` → `fromZeroBased` assert on negative column delta),
which is out of scope for this PR. The structural fix above removes
the leak on every failure path anyway; the test was documentation-
only and didn't need to sit atop a landmine.
coderabbit flag on the inline map scanner: the old
`lastIndexOf(source, "\n//# sourceMappingURL=")` would match the
needle anywhere in the file, including inside a string / template
literal that happens to contain the marker text. Per the Source Map
spec the comment MUST sit on the last line, so rewrite
`findSourceMappingURL` to trim trailing whitespace first, then only
prefix-match the final line.
Added two test-coverage improvements in the same commit:
- New test "sourceMappingURL marker in body is ignored": crafts an
intermediate that embeds a FULLY VALID inline map inside a template
literal, then follows it with a plain `export` on the last line.
Old scanner would chain through the embedded `hijack.ts` source;
new scanner ignores it.
- Strengthened "malformed inline map" assertion: decodes the output
map and verifies `sources` lists the intermediate (not some
fabricated path from the malformed payload) instead of just checking
that a sourceMappingURL comment was emitted.
Skipping coderabbit's third suggestion ("require `version` field")
because Bun's existing `sourcemap.parseJSON` treats `version` as
optional too (sourcemap.zig:82-86). Tightening it is worth doing but
needs to happen in both places together; out of scope for this PR.
Three more real bugs in the chaining landing that claude[bot] walked through in detail. Fixing all three: 1. `InputSourceMap.zig`: passing `std.math.maxInt(i32)` as `sources_count` to `Mapping.parse` disabled its `source_index >= sources_count` bounds check. A malformed inline map whose VLQ segment referenced an index past the end of its own `sources[]` would parse successfully. Downstream, the Builder emits `1 + inner.source_index` unclamped and LinkerContext reserves exactly `1 + external_source_names.len` slots per file, so the out-of-range index silently aliases the NEXT input file's slot range in the output — stack traces from file A get misattributed to file B. Pass the real `source_count` so such maps hit the `.fail` path and we fall back cleanly. Regression test: `inline map with out-of-range inner source_index is rejected` constructs a map with VLQ "AAAA;ACAA" (second mapping source_index = 1) against `sources: ["authored.ts"]` (len 1) and verifies `authored.ts` does NOT appear in the output `sources[]` after the fix. 2. `ParseTask.zig`: the dev-server HMR path in `runFromThreadPool` flips a parse-succeeded-with-errors `Success` into an `.err` by value-assigning a fresh `.err` payload and dropping the original `ast`. The prior commit already handled the resolve-error downgrade in `bundle_v2.runResolutionForParseTask`, but this second drop site leaks `ast.input_source_map` on every HMR rebuild of a file that both carries an inline map and logs parse errors. Deinit before the overwrite. 3. `LinkerContext.zig`: the `input_source_map` was plumbed into the print options unconditionally, but Bake's DevServer has its own sourcemap stitcher (`SourceMapStore.joinVLQ` + `PackedMap`) that hard-codes one `sources[]` slot per file and discards `chunk.end_state.source_index`. With `input_source_map` set, chunks now emit non-zero per-chunk `source_index` deltas that the DevServer stitcher would re-rebase across neighboring files' slots, corrupting served browser stack traces for any prebuilt `.js` carrying an inline `data:` sourcemap. Gate the field on `c.dev_server == null` until the DevServer stitcher is taught the slot-expansion layout (follow-up, separate PR). `test/bake/dev/sourcemap.test.ts` still passes; the existing Bun.build (non-dev) suite still passes too. Gate-check: `bun bd test bun-build-api` → 45/45 + 1 todo, `bake sourcemap.test.ts` → 2/2.
debian-13-x64-asan-test-bun failed with exit 2 on 706b461 (single shard out of 20 parallel). All other ASAN build lanes passed. Local bun bd (ASAN on by default) is clean on the full bundler suite and integration tests. Can't scrape which test failed from Buildkite anonymously; rolling the dice one time.
Gate hit this as `release with fix: BUILD FAILED` on my PR, but it's
a pre-existing race that any release build from a clean state can
trigger. Reproducing it is just:
rm -f build/release/bun-zig.*.o
build/release/bun scripts/build.ts --profile=release
[1/4] link bun-profile
[2/4] bun-profile --revision
/bin/sh: 1: /workspace/bun/build/release/bun: Permission denied
FAILED: bun-profile.smoke-test-passed
[4/4] strip bun
The smoke-test rule wraps its command in `${cfg.jsRuntime} stream.ts
check --console ...`. In configure.ts, jsRuntime is hard-wired to
`process.execPath` of whatever bun drove the build — and because
`build/release/` is ahead of the system bin dir on the standard dev
PATH, that's `build/release/bun`: the same file `strip bun` is
about to write. Ninja schedules the smoke test and strip
concurrently (no declared dep between them), the strip open(O_WRONLY)
races the jsRuntime execve, and execve fails with EACCES.
The race was masked by a warm cache: when the zig .o files are
already present, strip and smoke-test both finish so fast the window
closes. A clean zig recompile (PR commits touching anything the zig
build reads, or any CI box starting cold) opens the window wide
enough to hit reliably.
Fix: make the stripped binary an order-only input of the smoke test.
Ninja then serializes `strip bun` before `bun-profile --revision`
so jsRuntime execve lands on a quiescent file. Confirmed:
[1/5] link bun-profile
[3/5] strip bun
[3/5] bun-profile --revision
[build] done
Order-only (ninja's `||` edge) is the right tool here — the smoke
test doesn't consume `bun` as input, it just needs it to exist
and not be mid-write. Not an implicit dep, which would force a
rebuild of the stamp whenever strip runs.
Threaded through both the full-build (`emitBun`) and link-only
(`emitLinkOnly`) emit paths. Non-strip configs (debug, asan) pass
`undefined` and keep their current behavior — no stripped binary,
no race.
Fixes `test/internal/ban-words.test.ts` failing uniformly across every CI platform (debian 13, 25.04, 3.23 x64+aarch64+baseline+asan; macos 14+26 aarch64+x64; windows 2019+11 x64+aarch64+baseline). The test greps `src/` for each phrase in `test/internal/ban-limits.json` and asserts the count is <= the configured limit; `std.mem.indexOfAny(u8` is set to 0 (reason: "Use bun.strings.indexOfAny") and this PR added exactly one call, pushing the count from 0 to 1. `bun.strings.indexAnyComptime(target, comptime chars) ?usize` is a drop-in with the same `orelse` shape and comptime needle — no behavior change. Other callers in `src/` (resolve_path.zig, package_json.zig, bunx_command.zig, patch.zig) use the same pattern.
Root CLAUDE.md bans new behavior in .zig files — they're kept as a porting reference only. The 8 tests in this block exercise the chained input-sourcemap feature implemented in the .zig tree of this PR, which isn't wired into the live Rust bundler. Wrapping them in describe.todo keeps them as the intended-behavior spec for the eventual Rust port (per the file-by-file plan in the PR description) without red-lining every CI run. Flip back to describe() once InputSourceMap.rs + the Graph.rs / ParseTask.rs / LinkerContext.rs / Chunk.rs changes land.
Port of the Zig design in an earlier commit on this branch to Rust, since the bundler is now implemented in Rust (#30412). Same behavior, same 8 tests, different language. Files touched (Rust): - src/sourcemap/InputSourceMap.rs (new): owns *ParsedSourceMap + per-source contents; `parse` (validates v3 JSON, returns None on malformed), `parse_from_source` (last-line-anchored `//# sourceMappingURL=data:...` scan + base64/raw payload decode). - src/bundler/Graph.rs: `InputFile.input_source_map` column on the MultiArrayList + SoA accessor via `multi_array_columns!`. - src/bundler/ParseTask.rs: after getAST, scan `source.contents` for an inline map; gated on `source_map != None` + `can_have_source_map` + non-empty contents. Field added to `Success`. - src/bundler/ServerComponentParseTask.rs: wrapper Success constructor gets `input_source_map: None` (generated, not authored). - src/bundler/bundle_v2.rs: move from Success into the Graph SoA slot on parse completion; drain slots in `deinit_without_freeing_arena`. - src/bundler/LinkerContext.rs: `generate_source_map_for_chunk` expands outer `sources[]` to [intermediate, inner_0, …, inner_N-1] and mirrors `sourcesContent[]`; stitch the absolute source_index using `base + chunk.end_state.source_index`. Option threaded through to the printer, gated on `dev_server.is_none()` (Bake's SourceMapStore is a separate stitcher with a different layout). - src/sourcemap/Chunk.rs: `Builder.input_source_map`; in `add_source_mapping`, look up the intermediate (line, col) via `find_mapping`. On hit emit `mapped_source_index = 1 + inner.source_index` + inner's (line, col); on miss fall back to slot 0. - src/js_printer/lib.rs: `Options.input_source_map` forwarded into the builder in `get_source_map_builder`. Test suite in test/bundler/bun-build-api.test.ts flipped back from `describe.todo` to `describe` — all 8 pass: - base64 data URL: authored source surfaces - raw data URL: authored source surfaces - multi-inner-source map (e.g. .vue split): all surface - malformed payload: build succeeds, falls back - out-of-range inner source_index: rejected, no slot aliasing - in-body sourceMappingURL marker: ignored, no hijack - external .map reference: unchanged behavior - plugin onLoad inline map: regression guard for #6173 Closes #30536, also fixes #6173.
…ngURL= Matches Zig's `bun.strings.trim(_, " \r\t")` at InputSourceMap.zig:219. A leading space after `=` (e.g. `//# sourceMappingURL= data:...`) is spec-invalid but some toolchains emit it, and `parse_data_url`'s prefix check would fail on the leading space without this. Flagged by claude[bot] as a port-fidelity divergence.
Main's #30875 replaced the auto-derived Default impl for InputFile with an explicit one, which I missed in the last rebase — CI caught the missing-field on every build-rust lane. Add the None init. Fixes the build-rust failure in build #56341.
Only ParsedSourceMap is referenced; the mapping::parse call is fully-qualified through the lowercase module path. Flagged by claude[bot].
…ows UB topts is a shared borrow through a raw pointer into *transpiler. get_ast reborrows the same location mutably (also through the raw pointer), which pops topts's SharedReadOnly tag under Stacked Borrows — any subsequent topts.source_map read becomes Miri-detectable UB. Copy source_map out alongside module_type, before the `let _ = topts;` tombstone the prior author left for exactly this invariant. Flagged by claude[bot].
Main's e_string().string() takes &self now; the `mut` bindings at InputSourceMap.rs:116/126 became unused, which -D unused-mut turns into a hard error on the release build-rust lanes. mappings_e_string keeps its mut (slice() still takes &mut self).
When input_source_map chaining is active, prev_state.original_line holds the remapped *authored* line — wrong coordinate space for the intermediate file's line-offset table, so the O(1) find_line_with_hint fast path missed on every token and fell to binary search. Track the un-remapped intermediate line in a dedicated prev_intermediate_line field and hint from that. No behavior change (binary search was always the sound fallback); restores the per-token fast path on the chained feature path. Chunk.zig uses plain findLine (no hint), so it's unaffected. Flagged by claude[bot].
…xternal-input-sourcemaps
…dev server Extends the inline input-sourcemap chaining from #30539 to also: 1. Load external '//# sourceMappingURL=foo.map' references from disk (resolved relative to the input file). data: URLs were already handled; now linked sidecar .map files are too. http(s):// and protocol-relative URLs are skipped. Missing or malformed sidecars fall back silently to mapping against the intermediate. 2. Thread chained input sourcemaps through the Bun.serve dev server. SourceMapStore previously hard-coded one sources[] slot per input file; PackedMap now carries the inner-source list and render_json/join_vlq emit and stitch them in slot order. The printer's input_source_map path is no longer gated on dev_server == None. ErrorReportRequest uses the new Entry::lookup_source to resolve a flat source_index back to the right path/contents. Fixes #26713: Bun.serve HTML routes that reference a pre-built .js with a --sourcemap=linked sidecar now surface the authored source in browser DevTools instead of the intermediate .js.
|
Updated 1:30 PM PT - Aug 26th, 2026
❌ @robobun, your commit 3f2fc76 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 32473That installs a local version of the PR into your bun-32473 --bun |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds end-to-end sourcemap chaining for input files that embed a trailing ChangesSourcemap chaining through inline sourceMappingURL
Build script: smoke-test strip ordering
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Full details: Description checkExplanation The pull request description includes both required sections: "What does this PR do?" and "How did you verify your code works?" It provides a detailed problem statement, implementation summary, scope notes, known follow-ups, and test results. Comment |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
| /// The input file's own `//# sourceMappingURL=` map, when it has one. | ||
| /// `add_source_mapping` remaps each mapping through it so the output | ||
| /// points at the authored source rather than this intermediate file. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| /// Hint for `find_line_with_hint`, in the intermediate file's line | ||
| /// space. `prev_state.original_line` cannot serve: when chaining is | ||
| /// active it holds the remapped authored line instead. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| // call's intermediate line is the right answer or one/two lines | ||
| // before it >95% of the time; the fallback is a binary search. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| // Chunk-local source slots: 0 is the intermediate file, `1 + i` is | ||
| // inner `sources[i]`. The linker adds the chunk's absolute base | ||
| // when stitching. A miss in the inner map stays on slot 0. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| //! The sourcemap an input file points at via `//# sourceMappingURL=`. The | ||
| //! bundler chains through it so output maps reach the authored source | ||
| //! instead of stopping at the intermediate file. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| /// `sources_content[i]` pairs with `map.external_source_names[i]`; an | ||
| /// empty slot means the map carried no content for that source. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| /// Also reads a sidecar `.map` relative to `source_dir`. Remote URLs | ||
| /// and unreadable sidecars return `None`. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| /// Scheme or protocol-relative names are emitted verbatim, never joined | ||
| /// against a directory. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| // Consumers index `sources[]` by `1 + source_index` without clamping, | ||
| // so reject any VLQ entry outside the real source count here. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
| /// Only the last non-blank line counts (per spec), so a string literal | ||
| /// containing the marker earlier in the file cannot hijack the lookup. |
There was a problem hiding this comment.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
The comment linter flags any added comment spanning two or more lines, so keep each to a single line.
| // Use `join_abs` to produce an absolute inner path (when | ||
| // the inner map emitted a relative source name) that can | ||
| // then be re-relativized against `chunk_abs_dir`. | ||
| // `join_abs` returns a borrow into a thread-local buffer; | ||
| // we copy out immediately via `source_map_relative_path`. |
There was a problem hiding this comment.
🔴 write_sources_for joins untrusted inner sources[] names with unchecked join_abs (4 KB thread-local buffer), while its dev-server sibling collect_inner_sources was hardened to join_abs_string_buf_checked for exactly this input — the Bun.build path can panic on an overlong inner source name
Extended reasoning...
A .js bundler input references a sidecar .map (or inline data URL) whose sources[] contains an entry whose base_dir + name normalizes to more than PARSER_JOIN_INPUT_BUFFER_LEN (4096) bytes — e.g. a hostile/corrupt map with a 5 KB source name. join_abs::<Auto>(base_dir, name) writes the normalized result into the fixed 4096-byte PARSER_JOIN_INPUT_BUFFER and panics on the out-of-bounds slice write, aborting the whole Bun.build. On the base branch this input is ignored entirely (no chaining), so the build succeeds; after this PR it crashes. The author already recognized this hazard for the identical data at DevServer.rs::collect_inner_sources (comment: "Inner source names come from arbitrary .map JSON; use the length-checked join so an overlong entry falls back to the raw name rather than panicking on the PathBuffer") and at InputSourceMap.rs:68 for the sidecar URL, but write_sources_for — the Bun.build/LinkerContext path — was left on the unchecked variant. Fix: mirror the sibling and use join_abs_string_buf_checked (or join_abs_string_spill) here, falling…
Verification: normal — write_sources_for at src/bundler/LinkerContext.rs:1318 calls bun_paths::resolve_path::join_abs::<Auto>(base_dir, name) on name = ism.map.external_source_names[i], which is copied verbatim from the untrusted .map JSON's sources[] (src/sourcemap/InputSourceMap.rs:159-175, no length cap). join_abs → join_abs_string writes into the thread-local PARSER_JOIN_INPUT_BUFFER…
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-26. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
Closes #26713. Also closes #30536 and #6173 (this branch extends #30539 with external-map loading and dev-server support; if this lands, #30539 can be closed).
What does this PR do?
Repro
Before:
sources: ["bun://Bun/Bun HMR Runtime", ".../index.html", ".../main.js"]. Browser DevTools showsmain.js, notsrc/main.ts.After:
sources: [..., ".../main.js", ".../src/main.ts"],sourcesContentcarries the original TypeScript, and every mapping resolves through tosrc/main.ts.Same bug reproduces with
development: false(prod HTML bundler path) and plainBun.build({ entrypoints: ["./main.js"], sourcemap: "external" }).Cause
The bundler (and the dev server's re-bundler) emits a fresh sourcemap mapping the output to its immediate input (
main.js). The//# sourceMappingURL=main.js.mapcomment onmain.jsis detected by the lexer but never consumed, so the chain back tosrc/main.tsis dropped.#30539 added the chaining infrastructure for inline
data:URLs on theBun.build/LinkerContextpath, but left external.mapreferences out of scope and explicitly gated out the dev server becauseSourceMapStorehard-coded onesources[]slot per input file.Fix
External
.maploading (src/sourcemap/InputSourceMap.rs,src/bundler/ParseTask.rs): when the input lives in thefilenamespace and its trailingsourceMappingURLis not adata:URL, resolve it relative to the input's directory and read the sidecar viabun_sys::File::read_from.http(s):/// protocol-relative URLs are skipped. Read or parse failure falls back silently.Dev-server multi-source stitching (
src/runtime/bake/dev_server/{packed_map,source_map_store,incremental_graph}.rs,DevServer.rs):PackedMapgainsinner_sources: Box<[InnerSource]>(path + JSON-quoted content per inner source) andEndState.source_index(chunk-local index of the last mapping).finalize_bundlereadsgraph.input_files.input_source_mapper file, resolves inner source names to absolute paths against the intermediate's directory, JSON-quotes their contents, and passes them throughreceive_chunk.render_jsonemits each file's path followed by its inner-source paths insources[]and likewise forsourcesContent[].join_vlqtracks a running base index; each file's chunk starts at its base andprev_end_state.source_index = base + chunk.end_state.source_index, so chunk-local source indices compose correctly across files.Entry::lookup_sourcemaps a flatsource_indexback to(path, escaped_content);ErrorReportRequestuses it instead ofpaths[idx-1]/files[idx-1]so browser error reports remap through the chain too.The
self.dev_server.is_none()gate inLinkerContext::print_code_for_file_in_chunk_jsis removed now that the dev server stitcher handles multi-slot files.Merge note (f04b85e)
Main removed all
.zigreference files from the repo; this branch (via its base #30539) carried edits to seven of them plus a newInputSourceMap.zig. All conflicts were modify/delete on those.zigfiles; resolved by accepting main's deletion and removingInputSourceMap.zigtoo, since the functional changes are all in the.rscounterparts. Also adapted one call site toe::Number.valuebecoming a getter on main.Merge note (824273d)
Main replaced the linker's inline
relative_alloc+ POSIX-separator normalization with asource_map_relative_pathhelper inside the same loop that this PR had already rewritten into the multi-slotwrite_sources_forform. Kept this PR's loop and switchedwrite_sources_forto the new helper so the chained inner-source paths also get the Windows separator normalization.Merge note (9bb5246, abc24d7)
Main moved far (the
.zigremoval,bun_core::Stringownership,RefPtr, dead-code sweeps), so this merge had ten conflicts and some silent API drift. Nothing in the fix's behavior changed; every resolution was mechanical:scripts/build/bun.ts: main independently landed the samestrippedExeorder-only dependency (emitPostLink), so the build-script change this branch inherited from bundler: chain inline input sourcemaps through to output #30539 is now redundant. Took main's version.ParseTask.rs,packed_map.rs,incremental_graph.rs,source_map_store.rs: main'spubtopub(crate)sweep. Kept this PR's additions with the tightened visibility.GetResultlost its unusedEntryIndexon main; kept theentryreference.error_report_request.rs(main moved it out ofDevServer/):BunString::initis nowBunString::from_bytes.js_printer/lib.rsandsourcemap/Chunk.rs: main gaveNewBuildera real lifetime (LineOffsetTables<'a>), soinput_source_mapis nowOption<&'a InputSourceMap>and the'statictransmute that an earlier review flagged is gone.DevServer.rsandbun-build-api.test.ts: both sides appended at the same spot; kept both.InputSourceMap.rs(no conflict, but the APIs it used changed): the JSON parser is nowParsedJson::parse_jsonwith a row-basedJsonValuetree,mapping::parsereturns aResult, andstrings::contains_comptimewas removed.development: falseHTML routes to no sourcemaps (so original sources are not served publicly). The prod-bundler case opts back in with[serve.static] sourcemap = "linked", the same opt-in main's ownbun-serve-htmltests use.Verified after the merge: 7/7 in
26713.test.ts(5 still fail on the release bun), 10/10 in the inline-chain + adjacentbun-build-apitests, 2/2 inbake/dev/sourcemap, 29/29 inbun-serve-html.How did you verify your code works?
bun bd test test/regression/issue/26713.test.ts→ 5 pass (3 fail on current main; the 2 fallback cases pass on both):development: true) with linked sidecar → authored source + content surfacedevelopment: false) → authored source surfacesBun.buildwith external.map→ authored source + content surfacehttp://URL → build succeeds, falls back to intermediatebun bd test test/bake/dev/sourcemap.test.ts→ 2 pass (existing dev-server sourcemap coverage).bun bd test test/bundler/bun-build-api.test.ts→ 54 pass (8 inline-chain tests from #30539 + the rest).bun bd test test/js/bun/http/bun-serve-html.test.ts→ 16 pass.