Skip to content

bundler(html): fix asset-URL classification and emit contract - #36015

Closed
robobun wants to merge 10 commits into
mainfrom
farm/68e9af33/html-build-asset-url-fixes
Closed

robobun wants to merge 10 commits into
mainfrom
farm/68e9af33/html-build-asset-url-fixes

Conversation

@robobun

@robobun robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Five fixes to how HTML entrypoints classify asset URLs and emit them, so the HTML build's asset-URL contract matches the CSS printer's.

Repro

# 1. protocol-relative URL treated as rooted path
printf '<script src="//cdn.example.com/x.js"></script>' > index.html
bun build ./index.html --outdir=dist
# error: Could not resolve: "/cdn.example.com/x.js"

# 2. srcset passed whole to the one-URL resolver
printf '<img srcset="./a.png 1x, ./b.png 2x">' > index.html; touch a.png b.png
bun build ./index.html --outdir=dist
# error: Could not resolve: "./a.png 1x, ./b.png 2x"

# 3. ?query/#fragment stripped on rewrite
printf '<img src="./sprites.svg#icon">' > index.html; touch sprites.svg
bun build ./index.html --outdir=dist && grep '#icon' dist/index.html
# (no match; written as <img src="./sprites-HASH.svg">)

# 4. CSS-inlined asset also referenced from HTML left with raw path
printf '<link rel="stylesheet" href="./s.css"><img src="./t.png">' > index.html
printf 'body{background:url(./t.png)}' > s.css; printf x > t.png
bun build ./index.html --outdir=dist && cat dist/index.html; ls dist/
# <img src="./t.png"> but no t.png in dist/

# 5. asset output-path collision is silent last-writer-wins
# (see naming/AssetNoOverwrite: two distinct .file inputs, --asset-naming=fixed.txt)

Cause

  • HTMLScanner::create_import_record rewrites any leading / as a rooted project path, so //cdn/x.js never reaches the resolver's own starts_with("//") external rule.
  • TAG_HANDLERS img[srcset]/source[srcset] push the whole attribute through the single-URL path.
  • HTMLLoader::on_tag replaces the whole attribute value with the unique key after the resolver already stripped ?# to find the file. The CSS printer re-appends the suffix from record.original_path; HTML didn't.
  • find_reachable_files counts only JS importers as copy-forcing, so an asset inlined in CSS and referenced only from HTML has its unique key cleared and the HTML rewrite is a silent no-op.
  • process_files_to_copy pushes each asset OutputFile with no output-path uniqueness check; the chunk-side "Multiple files share the same output path" guard only sees chunks.

Fix

  • HTMLScanner: skip the rooted-path branch when the second byte is also /.
  • HTMLScanner + HTMLLoader: shared SrcSetIter walks the WHATWG image-candidate grammar; scan creates one import record per candidate, rewrite rebuilds the attribute with descriptors preserved. Both passes drive the same iterator so record counts stay 1:1.
  • HTMLLoader::rewrite_one_url: re-append the source URL's ?# suffix to the emitted reference (fragment only for data: URIs), same as css/printer.rs.
  • find_reachable_files: any non-CSS importer forces the asset to be emitted. HTMLLoader falls back to the data: URI when no unique key exists instead of leaving the raw source path.
  • process_files_to_copy: map over asset output paths and raise DuplicateOutputPath with the existing error/note wording when two distinct content hashes collide; identical-content collisions are benign.

Verification

bun bd test test/bundler/bundler_html.test.ts test/bundler/bundler_naming.test.ts \
  -t "protocol-relative|srcset-candidates|preserves-query|shared-css-and-html|AssetNoOverwrite"

All five fail on main (4 in bundler_html.test.ts, naming/AssetNoOverwrite was previously todo: true) and pass with this change. The full bundler_html, bundler_naming, bundler_loader, bundler_edgecase, bundler_html_server and html-import-manifest suites pass.

Consolidates #36007, #36008, #36012 (the first three fixes) and adds the two emit-contract fixes that had no open PR.


[review] gate passed · iteration 3 · 5 files touched

fails on main (without fix)
ASAN without fix: 5 failed, 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bundler/bundler_html.test.ts test/bundler/bundler_naming.test.ts
bun test v1.4.0 (0e4276e15)

test/bundler/bundler_naming.test.ts:
(pass) bundler > naming/EntryNamingCollission [477.20ms]
(pass) bundler > naming/ImplicitOutbase1 [636.19ms]
(pass) bundler > naming/ImplicitOutbase2 [884.71ms]
(pass) bundler > naming/EntryNamingTemplate1 [899.91ms]
(todo) bundler > naming/EntryNamingTemplate2
(pass) bundler > naming/AssetNaming [381.37ms]
(pass) bundler > naming/AssetNamingMkdir [358.06ms]
(pass) bundler > naming/AssetNamingDir [349.03ms]
1365 |             return testRef(id, opts);
1366 |           }
1367 | 
1368 |           throw new Error("Bundle Failed\n" + [...allErrors].map(formatError).join("\n"));
1369 |         } else if (expectedErrors && expectedErrors.length > 0) {
1370 |           throw new Error("Errors were expected while bundling:\n" + expectedErrors.map(formatError).join("\n"));
                           ^
error: Errors were expected while bundling:
<bun>: Multiple files share the same output path
      at <anonymou
... (truncated)

release without fix: 2 skipped
bun test v1.4.0-canary.1 (c0ae41785)

test/bundler/bundler_naming.test.ts:
(pass) bundler > naming/EntryNamingCollission [18.50ms]
(pass) bundler > naming/ImplicitOutbase1 [33.72ms]
(pass) bundler > naming/ImplicitOutbase2 [40.58ms]
(pass) bundler > naming/EntryNamingTemplate1 [42.01ms]
(todo) bundler > naming/EntryNamingTemplate2
(pass) bundler > naming/AssetNaming [16.28ms]
(pass) bundler > naming/AssetNamingMkdir [15.70ms]
(pass) bundler > naming/AssetNamingDir [15.35ms]
(pass) bundler > naming/AssetNoOverwrite [2.67ms]
(pass) bundler > naming/AssetNoOverwriteSameContent [3.08ms]
(pass) bundler > naming/AssetFileLoaderPath1 [2.65ms]
ENOENT opening root directory "/tmp/bun-build-tests/bun-HZLCBM/naming/NonexistantRoot/lib"

(pass) bundler > naming/NonexistantRoot [9.46ms]
(todo) bundler > naming/EntrypointOutsideOfRoot
(pass) bundler > naming/WithPathTraversal [41.00ms]
(pass) bundler > naming/NonAsciiSourceFilenameSymbol [16.65ms]

test/bundler/bundler_html.test.ts:
(pass) bundler > html/basic [15.11ms]
(pass) bundler > html/implicit-relative-paths [3.76ms]
(pass) bundler > html/multiple-assets [3.00ms]
(pass) bundler > html/image-hashing [2.97ms]
(pass) bundler 
... (truncated)
passes on PR (with fix)
ASAN with fix: 2 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bundler/bundler_html.test.ts test/bundler/bundler_naming.test.ts
bun test v1.4.0 (0e4276e15)

test/bundler/bundler_naming.test.ts:
(pass) bundler > naming/EntryNamingCollission [495.90ms]
(pass) bundler > naming/ImplicitOutbase1 [634.96ms]
(pass) bundler > naming/ImplicitOutbase2 [924.12ms]
(pass) bundler > naming/EntryNamingTemplate1 [883.96ms]
(todo) bundler > naming/EntryNamingTemplate2
(pass) bundler > naming/AssetNaming [358.02ms]
(pass) bundler > naming/AssetNamingMkdir [358.22ms]
(pass) bundler > naming/AssetNamingDir [358.91ms]
(pass) bundler > naming/AssetNoOverwrite [81.69ms]
(pass) bundler > naming/AssetNoOverwriteSameContent [87.22ms]
(pass) bundler > naming/AssetFileLoaderPath1 [75.21ms]
ENOENT opening root directory "/tmp/bun-build-tests/bun-AaSlhc/naming/NonexistantRoot/lib"

(pass) bundler > naming/NonexistantRoot [155.21ms]
(todo) bundler > naming/EntrypointOutsideOfRoot
(pass) bundler > naming/WithPathTraversal [901.60ms]
(pass) bundler > naming/NonAsciiSourceFilenameSymbol [367.83ms]

test/bundler/bundler_html.t
... (truncated)

release with fix: 2 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 757ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/6] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[1/6] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys)
�[1m�[92m   Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety)
�[1m�[92m   Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys)
�[1m�[92m   Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys)
�[1m�[92m   Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd)
�[1m�[92m   Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp)
�[1m�[92m   Compiling�[0m bun_output v
... (truncated)
diff hotspot
src/bundler/HTMLScanner.rs                         | 128 +++++++++++-----
 src/bundler/bundle_v2.rs                           |  40 +++--
 .../generateCompileResultForHtmlChunk.rs           | 164 +++++++++++----------
 test/bundler/bundler_html.test.ts                  | 126 ++++++++++++++++
 test/bundler/bundler_naming.test.ts                |  23 ++-
 5 files changed, 356 insertions(+), 125 deletions(-)

gate history · 4 passed · 0 rejected · iteration 3

evidence per changed file
file                                                      reads  edits  tests
src/bundler/HTMLScanner.rs                                    6     10      0
src/bundler/bundle_v2.rs                                      9     13      0
…ler/linker_context/generateCompileResultForHtmlChunk.rs      8     12      0
test/bundler/bundler_html.test.ts                             5      3      0
test/bundler/bundler_naming.test.ts                           3      2      0

Five fixes to how HTML entrypoints classify and emit asset URLs:

- HTMLScanner: leave protocol-relative URLs (//host/...) for the
  resolver's external rule instead of rewriting them as rooted project
  paths.
- HTMLScanner/HTMLLoader: parse img[srcset]/source[srcset] with the
  WHATWG image-candidate grammar, one import record per candidate URL,
  and rewrite the attribute with descriptors preserved.
- HTMLLoader: re-append the ?query/#fragment suffix from the source URL
  to the hashed asset reference (mirroring the CSS printer).
- find_reachable_files: treat any non-CSS importer (HTML included) as a
  copy-forcing context so a CSS-inlined asset also referenced from HTML
  is still emitted on disk. HTMLLoader falls back to the data: URI when
  no unique key is available instead of leaving the raw source path.
- process_files_to_copy: hard-error on distinct-content asset output
  path collisions with the same 'Multiple files share the same output
  path' message the chunk pass emits; identical-content collisions are
  left alone.
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

HTML bundling now preserves protocol-relative URLs, parses and rewrites srcset candidates individually, retains descriptors and URL suffixes, correctly tracks inline assets, and detects conflicting additional output paths. Regression tests cover these behaviors and identical-content deduplication.

HTML bundling and asset output

Layer / File(s) Summary
HTML URL parsing and rewriting
src/bundler/HTMLScanner.rs, src/bundler/linker_context/generateCompileResultForHtmlChunk.rs, test/bundler/bundler_html.test.ts
Protocol-relative URLs remain external; srcset candidates are parsed and rewritten individually; descriptors, queries, and fragments are preserved.
Inline asset classification
src/bundler/bundle_v2.rs, test/bundler/bundler_html.test.ts
Inline asset tracking distinguishes CSS-inline assets from assets referenced by HTML, preserving emitted files when required.
Additional asset collision handling
src/bundler/bundle_v2.rs, test/bundler/bundler_naming.test.ts
Conflicting content at one output path reports an error, while identical-content collisions are accepted and tested.

Possibly related PRs

  • oven-sh/bun#36007: Updates protocol-relative URL handling in the HTML scanner and related tests.
  • oven-sh/bun#36012: Adds per-candidate srcset parsing and rewriting behavior.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
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 is concise and clearly summarizes the main change: HTML bundler asset-URL classification and emission behavior.
Description check ✅ Passed The description covers what changed and how it was verified, even though it uses custom sections instead of the template headings.

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

@robobun

robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:12 AM PT - Jul 27th, 2026

✅ @robobun, your commit 0e4276e1511485ee798ce9a901ddb3ce5bccbbf3 passed in Build #83118! 🎉


🧪   To try this PR locally:

bunx bun-pr 36015

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

bun-36015 --bun

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. bundler(html): treat protocol-relative URLs as external #36007 - Fixes protocol-relative URL classification in HTMLScanner.rs, which is one of the five fixes consolidated into this PR
  2. bundler(html): preserve ?query/#fragment when rewriting asset URLs #36008 - Preserves ?query/#fragment when rewriting asset URLs, which is one of the five fixes consolidated into this PR
  3. bundler(html): parse srcset into per-candidate imports #36012 - Parses srcset into per-candidate imports, which is one of the five fixes consolidated into this PR

🤖 Generated with Claude Code

@robobun

robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI build #82946 (latest, at c0ae417): bundler test lanes green. Remaining marks are unrelated to this diff:

  • binary-size: now info (comparison against stale canary #79916; same on every recent PR).
  • flaky unrelated tests (bun-install-registry.test.ts, valkey.test.ts), passed on retry.

All review feedback addressed. Ready for review.

Comment thread src/bundler/bundle_v2.rs Resolved
Comment thread test/bundler/bundler_html.test.ts Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/bundle_v2.rs Resolved
Comment thread src/bundler/bundle_v2.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/bundler/bundler_html.test.ts`:
- Around line 1043-1077: Expand the “html/srcset-candidates” test to cover
descriptor-less srcset candidates, trailing-comma termination, and candidates
separated by multiple spaces or newlines. Add fixture markup and assertions for
both img and source where applicable, verifying rewritten local assets,
preserved descriptors or absence of descriptors, ignored trailing entries, and
unchanged external URLs while confirming emitted asset contents.

In `@test/bundler/bundler_naming.test.ts`:
- Line 215: Update the bundler naming test assertion for the “Multiple files
share the same output path” error to also verify the conflicting output path and
each contributing input listed in the detail block, rather than matching only
the header. Preserve the existing header assertion while asserting the complete
collision details emitted by the bundling error.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: bf3a6e6a-740b-40d9-83b6-ae50df2ceb36

📥 Commits

Reviewing files that changed from the base of the PR and between 44f6469 and adff121.

📒 Files selected for processing (5)
  • src/bundler/HTMLScanner.rs
  • src/bundler/bundle_v2.rs
  • src/bundler/linker_context/generateCompileResultForHtmlChunk.rs
  • test/bundler/bundler_html.test.ts
  • test/bundler/bundler_naming.test.ts

Comment thread test/bundler/bundler_html.test.ts Resolved
Comment thread test/bundler/bundler_naming.test.ts Resolved

@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.

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 src/bundler/linker_context/generateCompileResultForHtmlChunk.rs:264 — The dev-server fallback branch returns RewrittenUrl::Value(import_record.path.pretty.to_vec()) without re-appending suffix, while the sibling unique-key branch just above got with_suffix(unique_key_for_additional_files, suffix). path.pretty is derived from the post-strip resolved path (e.g. /_bun/asset/{hash}.svg), so '&lt;img src="./sprites.svg#icon"&gt;' in dev-server mode still loses #icon — same bug class this PR fixes for the production path. One-line fix: return with_suffix(import_record.path.pretty, suffix);.

    Extended reasoning...

    What

    In rewrite_one_url, the PR adds ?query/#fragment re-appending via the with_suffix closure to the production unique-key branch, the data:-URI branches, and the dev-server unique-key branch — but not to the dev-server fallback:

    if self.linker.dev_server.is_some() {
        if !unique_key_for_additional_files.is_empty() {
            return with_suffix(unique_key_for_additional_files, suffix);   // ← got the fix
        } else if import_record.path.is_disabled
            || loader.is_javascript_like()
            || loader.is_css()
        {
            return RewrittenUrl::Remove;
        }
        return RewrittenUrl::Value(import_record.path.pretty.to_vec());    // ← didn't
    }

    Why the suffix is genuinely lost here

    import_record.path.pretty is derived from path.text — the resolver's post-strip path. HTML <img src> uses ImportKind::Url, for which is_from_css() is true (src/ast/lib.rs), so the resolver retries with ?# stripped and path.text carries no fragment. In dev-server mode with a cached asset, bundle_v2.rs sets import_record.source_index = Index::INVALID and path.pretty = "{ASSET_PREFIX}/{hash:016x}{ext}" computed from path.text — no fragment. With source_index invalid, unique_key_for_additional_files is b"" and loader defaults to Loader::File, so control falls through to the path.pretty.to_vec() return.

    Step-by-step

    1. Source: '&lt;img src="./sprites.svg#icon"&gt;', dev server running, sprites.svg already in the dev-server asset cache.
    2. Scan pass creates an ImportKind::Url record; resolver strips #icon to locate sprites.svg; dev-server asset path sets source_index = INVALID and pretty = "/_bun/asset/abcd….svg".
    3. Rewrite pass: original = b"./sprites.svg#icon", so suffix = b"#icon".
    4. self.linker.dev_server.is_some() → true. unique_key_for_additional_files is empty (source_index invalid). is_disabled/is_javascript_like()/is_css() all false for a .svg file loader.
    5. Falls through to return RewrittenUrl::Value(import_record.path.pretty.to_vec()) → "/_bun/asset/abcd….svg", no #icon.
    6. Browser fetches the sprite sheet but renders nothing — SVG fragment addressing (<use href>-style) needs the client-side #icon to select the symbol.

    Why existing code doesn't prevent it

    suffix is computed unconditionally at the top of the function and with_suffix is a local closure available to every branch, but this return simply doesn't call it. The production-mode sibling at the bottom of the function (return with_suffix(unique_key_for_additional_files, suffix)) and the dev-server unique-key branch two lines above both do. Nothing else in the pipeline re-attaches the fragment after this point — RewrittenUrl::Value is written to the attribute verbatim.

    Impact

    Dev-server-only, and the pre-PR line was set_attribute(element, url_attribute, import_record.path.pretty) — identical behavior, so this is not a regression. But it is exactly the bug class the PR sets out to fix ("?query/#fragment stripped on rewrite"), and REVIEW.md is explicit: "Fix the whole class in the same PR — same-class sites are ONE concern, not scope creep. Grep for every sibling site sharing the pattern." This is a same-function sibling two lines below a site that received the fix.

    Fix

    return with_suffix(import_record.path.pretty, suffix);

    If pretty can somehow already carry a suffix in dev-server mode (I couldn't find a path where it does), a comment stating why this branch is intentionally excluded would satisfy the same rule.

Comment thread src/bundler/bundle_v2.rs Resolved
Comment thread src/bundler/bundle_v2.rs Resolved

@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.

All prior inline feedback has been addressed (including the stale-comment nit at bundle_v2.rs:1646/1981 — now updated). I didn't find further issues, but this bundles five independent behavioural fixes (new SrcSetIter parser, rewrite_one_url refactor, the is_js→!is_css reachability-gate change, new asset output-path collision check) across ~430 lines of bundler emit/reachability code, so it's worth a human pass.

What was reviewed:

  • SrcSetIter against the WHATWG image-candidate grammar — trailing-comma, descriptor-less, whitespace-run cases all covered; scan and rewrite drive the same iterator so record indices stay 1:1.
  • rewrite_one_url: every value-producing arm (dev-server unique-key, dev-server pretty-path fallback, data:-URI, non-dev unique-key) now goes through with_suffix; data:-URI arm keeps fragment-only.
  • find_reachable_files gate widening: checked that the additional_files_imported_by_css_and_inlined branch is unaffected and the clear-site guard at ~1981 still reads the same bitset.
  • Asset-collision check: identical-content collisions correctly bypass the error; from input lines now use path.pretty matching the chunk-side message.
Extended reasoning...

Overview

Five HTML-bundler fixes in one PR: (1) //host/... no longer misclassified as project-rooted; (2) srcset walked per-candidate via a new SrcSetIter shared between scan and rewrite; (3) ?# suffix re-appended on rewritten asset URLs (mirroring the CSS printer); (4) HTML importers now force on-disk emission of CSS-inlined assets (is_js && is_inlined → is_inlined && !is_css); (5) asset output-path collisions now raise DuplicateOutputPath instead of silent last-writer-wins. on_tag was refactored into rewrite_one_url returning a RewrittenUrl enum so the srcset loop and the single-URL path share one code path. Four new bundler_html tests plus naming/AssetNoOverwrite un-todo'd and a same-content variant added.

Security risks

None identified. Inputs are build-time HTML/asset paths under the user's own control; no auth/crypto/network surface. The new SrcSetIter operates on borrowed byte slices with index-bounded loops — no allocation driven by untrusted lengths.

Level of scrutiny

Medium-high. This is production bundler output correctness: the reachability-gate change (!is_css) affects whether assets are emitted at all, the collision check turns a previously-silent build into a hard error, and SrcSetIter is a hand-rolled tokenizer for a WHATWG micro-grammar. None of it is hot-path perf-sensitive, but wrong output here ships to users' dist/.

Other factors

Three earlier review rounds from me flagged: sticky-remove nuking the whole <img> on one Remove candidate, dev-server path.pretty fallback dropping the suffix, absolute vs pretty path in the collision error, and stale doc-comments on the reachability bitset — all four are fixed in the current diff. CodeRabbit's srcset edge-case coverage ask was also taken (descriptor-less / newline / trailing-comma fixture). The PR consolidates three prior PRs plus two new fixes, which is a lot of surface for one change; the individual pieces look correct and are each covered by a test that fails on main, but the aggregate scope is why I'm deferring rather than approving.

Comment thread src/bundler/HTMLScanner.rs Resolved

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Too much code for something that should be simple.

…tIter

src/ is now net +86 (was +217): collision check is a single-pass
first-error, rewrite helper drops the intermediate enum ceremony and
debug logs, SrcSetIter uses iterator combinators over hand-rolled
index loops.
@robobun

robobun commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator Author

Trimmed in 0e4276e: src/ is now net +86 lines (was +217), in line with the ~80-100 the original estimate called for.

  • bundle_v2.rs +18: collision check is a single-pass first-error (no aggregation/notes); !is_css gate + comment updates.
  • HTMLScanner.rs +60: SrcSetIter (the srcset tokenizer, ~45 lines), // guard, srcset scan dispatch.
  • generateCompileResultForHtmlChunk.rs +8: on_tag refactored into next_record_url returning a three-variant enum; dropped the closure/debug-log/bounds-panic ceremony.

All 6 tests still pass. Happy to split into per-fix PRs instead if that's easier to review.

@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.

No new issues found, but this bundles five behavioral fixes plus a post-review simplification pass (0e4276e) that reshaped next_record_url, compacted SrcSetIter, and replaced the aggregated collision error with a first-hit-only message — worth a human pass on the final shape.

What was reviewed:

  • SrcSetIter tokenization vs. WHATWG step 8 (paren-depth, trailing-comma, descriptor-less, url-with-comma) — scan and rewrite drive the same iterator so record indices stay 1:1.
  • next_record_url refactor is behavior-preserving vs. the old inline on_tag (external/invalid-source/JS-CSS/standalone/unique-key ordering); all value-producing arms now go through the ?# re-append, including the dev-server path.pretty fallback.
  • find_reachable_files is_js→!is_css gate widens copy-forcing to HTML importers only; CSS-only-referenced inlined assets still get their additional_files cleared.
  • Asset collision check keys on dest_path and compares hash, so identical-content collisions pass (covered by AssetNoOverwriteSameContent).
Extended reasoning...

Overview

Five HTML-bundler fixes across three Rust files (HTMLScanner.rs, bundle_v2.rs, generateCompileResultForHtmlChunk.rs, net +86 in src/) plus ~150 lines of new itBundled tests: protocol-relative URL detection, a new SrcSetIter tokenizer used by both scan and rewrite passes, ?# suffix preservation on rewritten asset URLs, widening the CSS-inline copy-forcing gate from JS-only to any non-CSS importer, and a new asset output-path collision guard in process_files_to_copy.

Security risks

None identified. The inputs are project-local build inputs (HTML attribute values, on-disk asset paths); no network, auth, or privilege surfaces. SrcSetIter is bounds-safe (all indexing via .get()/.first()/computed positions on &[u8]).

Level of scrutiny

Medium-high. The bundler is production-critical, bundle_v2.rs is core, and this PR both changes a shared reachability gate (affects which assets are emitted for all builds, not just HTML) and introduces new error-producing behavior (the collision check). SrcSetIter is a hand-written mini-parser. Most importantly, the tip commit 0e4276e is a broad simplification pass that landed after every prior review round — the Rewrite enum + next_record_url shape, the compacted iterator, and the single-pass collision message are all newer than the resolved threads.

Other factors

  • All five fixes have failing-on-main tests; the mechgate evidence shows debug+ASAN and release both green.
  • Prior review rounds surfaced and resolved: srcset edge-case coverage, dev-server suffix arm, per-candidate Remove semantics, sibling-comment drift, WHATWG paren-depth. One pre-existing-behavior nit (non-srcset Remove on img[src]) was explicitly deferred with rationale.
  • The 0e4276e collision message dropped the per-input from input … lines that the chunk-side sibling (generateChunksInParallel.rs) prints — an intentional simplification per the author, but a wording divergence a maintainer may want to weigh.
  • The author explicitly offered to split into per-fix PRs; a human can decide whether to take that or land as-is.

Not a rubber-stamp candidate: five coupled fixes + a late refactor of the reviewed code is exactly the shape REVIEW.md asks a human to look at.

@robobun

robobun commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator Author

Status note on fix 4 (asset inlined in CSS and also referenced from HTML is never emitted, HTML keeps the raw src): this was reported again independently, and it still reproduces on current main (e697804) with release 1.4.0:

head -c 3000 /dev/urandom > logo.png
printf '.foo { background: url(./logo.png) }\n' > style.css
printf '<link rel="stylesheet" href="./style.css"><img src="./logo.png">' > index.html
bun build index.html --outdir out && ls out && grep -o 'src="[^"]*"' out/index.html
# out/ has no logo-*.png, index.html still says src="./logo.png"

find_reachable_files on main still gates on is_javascript_like() (src/bundler/bundle_v2.rs:1843), so the change here is still the relevant one. No second PR is being opened for it.

The branch now conflicts with main in two places: HTMLScanner.rs (the srcset hunk) and bundle_v2.rs, where the bitset fields of ReachableFileVisitor became pub(crate) next to the doc comment this PR edits. The find_reachable_files and process_files_to_copy hunks themselves still apply. Needs a rebase.

@robobun

robobun commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Heads-up on overlap: #42025 fixes the srcset item from this PR on its own (per-candidate parsing, also for <link imagesrcset>), rebased on current main. #36012 is closed in its favor. If #42025 lands first, the SrcSetIter part here drops out on rebase; the other four fixes are untouched.

@robobun

robobun commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Overlap update: the srcset work is now consolidated in #41938 (#42025 and #36012 are closed in its favor). #41938 also carries fixes 1 and 3 from this PR: //host URLs go to the resolver as written, and ?query#fragment is re-appended to the rewritten URL (fragment only on a data: URL). Fixes 4 (CSS-inlined asset also referenced from HTML is never emitted) and 5 (asset output-path collision) are not covered anywhere else. Once #41938 lands, please rebase this onto it and drop the SrcSetIter, // and suffix hunks, keeping 4 and 5. Note that on_tag becomes on_url(url, kind) -> UrlAction there, so next_record_url maps onto that directly.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-07-27.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 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