Skip to content

bundler(html): rewrite prefetch/modulepreload/preload link hrefs - #36013

Closed
robobun wants to merge 12 commits into
mainfrom
claude/ae1514b3/html-link-preload-prefetch
Closed

robobun wants to merge 12 commits into
mainfrom
claude/ae1514b3/html-link-preload-prefetch

Conversation

@robobun

@robobun robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

bun build ./index.html only rewrites <link href> for a fixed allowlist of rel/as values. Any <link> outside that list keeps its original source path in the output, which is a guaranteed 404 because the target was either emitted under a hashed name or bundled into the entry chunk.

$ cat index.html
<link rel="prefetch" href="./i.png">
<link rel="modulepreload" href="./a.js">
<link rel="preload" as="script" href="./b.js">
<link rel="preload" as="fetch" href="./data.json" crossorigin>
<img src="./i.png"><script type="module" src="./a.js"></script>

$ bun build ./index.html --outdir=out && grep -oE '(src|href)="[^"]*"' out/index.html
href="./i.png"        # 404 (file emitted as i-<hash>.png)
href="./a.js"         # 404 (bundled into index-<hash>.js)
href="./b.js"         # 404 (never emitted)
href="./data.json"    # 404 (never emitted)
src="./i-53dyeqnw.png"
src="./index-fjf1hdtz.js"

This contradicts docs/bundler/html-static: "Any <link> tag with an href attribute pointing to a local file is rewritten to the new path, and hashed".

Fix

Add four resource-hint entries to TAG_HANDLERS in src/bundler/HTMLScanner.rs covering rel=prefetch, rel=modulepreload, as=script, and as=fetch|track|document|embed|object. These use a new TagHandler::hint constructor that sets ImportRecordFlags::WAS_HTML_RESOURCE_HINT and HANDLES_IMPORT_ERRORS on the record.

Behaviour per target type:

  • Non-code assets (images, JSON, VTT, etc.): the existing ImportKind::Url path emits the file with a content hash and the href is rewritten to the output path.
  • JS/CSS targets: bundled into the entry chunk with the native loader and the hint tag is dropped. This keeps the canonical modulepreload pattern working: <link rel=modulepreload href=./dep.js> + <script src=./main.js> where main.js imports dep.js bundles dep.js as JS (covered by html/link-preload-prefetch).
  • .html targets: emitted as raw hashed assets (the existing Url->File override now also fires for Loader::Html when WAS_HTML_RESOURCE_HINT is set), so <link rel=prefetch href=./page2.html> is copied verbatim with a rewritten href instead of being parsed as a nested HTML entry (html/link-hint-local-html). In dev-server mode these records skip the "Browser builds cannot import HTML files" guard and pass through untouched (test/bake/dev/html.test.ts).
  • Sibling HTML entry points: a hint record whose path_to_source_index_map lookup hits an Html-loaded slot is marked disabled so the reachability walk does not follow it, and the href passes through (the sibling is emitted under its own entry-point name, so the original href is already a valid output path; html/link-hint-sibling-entry).
  • Unresolvable hrefs (navigation routes like /dashboard, API endpoints like /api/user, external URLs, protocol-relative URLs): HANDLES_IMPORT_ERRORS lets these pass through untouched instead of failing the build (html/link-hint-unresolved).

Output for the repro above:

<link rel="prefetch" href="./i-53dyeqnw.png">
<link rel="preload" as="fetch" href="./data-jq8ssgva.json" crossorigin>
<img src="./i-53dyeqnw.png">
<script type="module" crossorigin src="./index-t1rzg9pe.js"></script>

(modulepreload and as=script tags are dropped because their targets are in the entry chunk.)

Trade-offs

Both stem from the resolve pipeline's first-wins loader pinning; fixing them requires deferring hint-only ParseTasks until the module graph is complete, which is a larger change than this 404 fix warrants.

  • A hint whose JS target is not otherwise referenced (<link rel="preload" as="script" href="./unused.js"> with no <script src> and no transitive import) is bundled into the entry chunk, matching the existing link[as=worker] handler.
  • A hint whose .json/.toml/text target is also statically imported from JS (<link rel=preload as=fetch href=./data.json> + import data from './data.json') pins the file to Loader::File via the pre-existing Url->File override, so the JS import sees the emitted path string instead of the parsed object. The as=fetch hint is for fetch() calls; a static import is bundled and needs no preload hint.

Verification

New html/link-preload-prefetch, html/link-hint-local-html, html/link-hint-sibling-entry, and html/link-hint-unresolved cases in test/bundler/bundler_html.test.ts, plus a dev-server pass-through case in test/bake/dev/html.test.ts. All 22 existing bundler_html cases still pass.


[review] gate passed · iteration 1 · 6 files touched

fails on main (without fix)
ASAN without fix: 2 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bake/dev/html.test.ts test/bundler/bundler_html.test.ts
bun test v1.4.0 (378ad584b)

test/bundler/bundler_html.test.ts:
(pass) bundler > html/basic [610.23ms]
(pass) bundler > html/implicit-relative-paths [109.39ms]
(pass) bundler > html/multiple-assets [129.45ms]
(pass) bundler > html/image-hashing [135.24ms]
(pass) bundler > html/external-assets [116.69ms]
(pass) bundler > html/mixed-assets [124.96ms]
(pass) bundler > html/js-imports [120.52ms]
(pass) bundler > html/css-imports [141.88ms]
(pass) bundler > html/multiple-entries [156.31ms]
(pass) bundler > html/script-src-is-entry-chunk-with-splitting [159.92ms]
(pass) bundler > html/shared-chunks [159.40ms]
(pass) bundler > html/js-importing-html [110.57ms]
// in/2nd.js
console.log("2nd");
// in/entry.js
console.log("Loaded HTML!");

(pass) bundler > html/js-importing-html-and-entry-point-side-effect-import [110.80ms]
(pass) bundler > html/js-importing-html-and-entry-point-default-import-fails [200.04ms]
(pass) bundler > html/circular-js-html [116.57ms]
(pass) bundler > html/css-
... (truncated)

release without fix: 1 FAILED
bun test v1.4.0-canary.1 (2d2add3db)

test/bundler/bundler_html.test.ts:
(pass) bundler > html/basic [35.25ms]
(pass) bundler > html/implicit-relative-paths [5.79ms]
(pass) bundler > html/multiple-assets [5.03ms]
(pass) bundler > html/image-hashing [4.85ms]
(pass) bundler > html/external-assets [3.82ms]
(pass) bundler > html/mixed-assets [10.45ms]
(pass) bundler > html/js-imports [5.30ms]
(pass) bundler > html/css-imports [4.41ms]
(pass) bundler > html/multiple-entries [4.94ms]
(pass) bundler > html/script-src-is-entry-chunk-with-splitting [7.05ms]
(pass) bundler > html/shared-chunks [6.20ms]
(pass) bundler > html/js-importing-html [3.64ms]
// in/2nd.js
console.log("2nd");
// in/entry.js
console.log("Loaded HTML!");

(pass) bundler > html/js-importing-html-and-entry-point-side-effect-import [3.90ms]
(pass) bundler > html/js-importing-html-and-entry-point-default-import-fails [3.60ms]
(pass) bundler > html/circular-js-html [3.40ms]
(pass) bundler > html/css-only [5.92ms]
(pass) bundler > html/absolute-paths [4.28ms]
(pass) bundler > html/no-sourcemap-comments [4.55ms]
(pass) bundler > html/no-sourcemap-comments-inline [3.47ms]
(pass) bundler > html/SharedCSSProductio
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/bake/dev/html.test.ts test/bundler/bundler_html.test.ts
bun test v1.4.0 (378ad584b)

test/bundler/bundler_html.test.ts:
(pass) bundler > html/basic [553.80ms]
(pass) bundler > html/implicit-relative-paths [111.26ms]
(pass) bundler > html/multiple-assets [113.24ms]
(pass) bundler > html/image-hashing [101.57ms]
(pass) bundler > html/external-assets [101.68ms]
(pass) bundler > html/mixed-assets [119.04ms]
(pass) bundler > html/js-imports [136.87ms]
(pass) bundler > html/css-imports [132.35ms]
(pass) bundler > html/multiple-entries [178.61ms]
(pass) bundler > html/script-src-is-entry-chunk-with-splitting [168.13ms]
(pass) bundler > html/shared-chunks [153.73ms]
(pass) bundler > html/js-importing-html [116.47ms]
// in/2nd.js
console.log("2nd");
// in/entry.js
console.log("Loaded HTML!");

(pass) bundler > html/js-importing-html-and-entry-point-side-effect-import [124.70ms]
(pass) bundler > html/js-importing-html-and-entry-point-default-import-fails [144.09ms]
(pass) bundler > html/circular-js-html [113.38ms]
(pass) bundler > html/css-
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 716ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[0/5] 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 v0.0.0 (/workspace/bun/src/output)
�[1m�[92m   Compiling�[0m bun_clap v0.0.0 (/workspace/bun/src/clap)
�[1m�[92m   Compiling�[0m bun_valkey v0
... (truncated)
diff hotspot
src/ast/import_record.rs                           |   4 +
 src/bundler/HTMLScanner.rs                         |  76 +++++----
 src/bundler/bundle_v2.rs                           |  27 +++-
 .../generateCompileResultForHtmlChunk.rs           |  19 +--
 test/bake/dev/html.test.ts                         |  26 +++
 test/bundler/bundler_html.test.ts                  | 174 +++++++++++++++++++++
 6 files changed, 282 insertions(+), 44 deletions(-)

gate history · 5 passed · 0 rejected · iteration 1

evidence per changed file
file                                                      reads  edits  tests
src/ast/import_record.rs                                      3      4      0
src/bundler/HTMLScanner.rs                                    4     11      0
src/bundler/bundle_v2.rs                                     14     12      0
…ler/linker_context/generateCompileResultForHtmlChunk.rs      2      4      0
test/bake/dev/html.test.ts                                    2      3      0
test/bundler/bundler_html.test.ts                             5     10      0

The HTML bundler's selector list for <link> tags only matched a fixed set
of rel/as values (stylesheet, icon, manifest, as=image|font|video|audio|
style|worker). Any other <link href> pointing at a local file, such as
rel=prefetch, rel=modulepreload, or rel=preload with as=script|fetch|
track|document|embed|object, was passed through untouched. The built page
shipped the original source path, which is a guaranteed 404 at runtime
(the referenced asset was either emitted under a hashed name or bundled
into the entry chunk).

Add the missing selectors:
- link[as='script'] and link[rel='modulepreload'] are treated as JS
  imports: the module is bundled into the entry chunk and the hint tag
  is dropped (there is no separate file left to preload).
- link[as='fetch'|'track'|'document'|'embed'|'object'] and
  link[rel='prefetch'] are treated as URL assets: the file is emitted,
  hashed, and the href is rewritten to the output path.
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Changes

HTML resource hints are classified during scanning, handled during bundling, and preserved or rewritten during HTML output generation. Tests cover preload, prefetch, modulepreload, local HTML, unresolved URLs, and dev-server behavior.

HTML resource hint handling

Layer / File(s) Summary
Scanner hint metadata
src/ast/import_record.rs, src/bundler/HTMLScanner.rs
Adds resource-hint flags, propagates TagHandler metadata into import records, and registers additional hint selectors.
Resource hint resolution
src/bundler/bundle_v2.rs
Disables resource-hint imports, treats HTML hint targets as file-loader inputs where applicable, and avoids HTML reachability edges.
HTML rewriting and validation
src/bundler/linker_context/..., test/bundler/bundler_html.test.ts, test/bake/dev/html.test.ts
Preserves unresolved hint URLs, rewrites resolved assets, and tests bundling and dev-server behavior.

Possibly related PRs

  • oven-sh/bun#36011: Both modify HTML preload handling in the scanner and HTML rewrite pipeline.
  • oven-sh/bun#36012: Both modify HTML scanner callbacks and tag-rewriting wiring.
  • oven-sh/bun#36015: Both modify HTML scanner import-record creation and tag URL classification.

Suggested reviewers: jarred-sumner

🚥 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 clearly and accurately summarizes the main change: rewriting HTML resource-hint link hrefs.
Description check ✅ Passed The description covers the required what/why/verification content, though it uses different section headings than the template.

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

@robobun

robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:13 PM PT - Jul 26th, 2026

✅ @robobun, your commit 378ad584b60b63603728cb3d21e77221e4e4530d passed in Build #82967! 🎉


🧪   To try this PR locally:

bunx bun-pr 36013

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

bun-36013 --bun

@robobun

robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status: the diff is green on every bundler_html and bake/dev/html lane; remaining reds are unrelated to this change.

  • binary-size (+540 KB vs canary #79916): identical delta appears on neighbouring PR builds (#82837, #82835, #82810, #82800). This is accumulated drift on main since the pinned canary, not this change.
  • test/js/node/tls/node-tls-getpeercert-leak.test.ts (#82945): RSS threshold test 1.5 MB over its 32 MB limit on debian-x64; unrelated to the HTML bundler, reported for main-break triage.
  • test/cli/install/migration/complex-workspace.test.ts, test/cli/hot/hot.test.ts, test/js/bun/webview/webview-chrome.test.ts, test/js/bun/terminal/terminal-platform-gaps.test.ts: tagged [flaky] by the runner; none touch the HTML bundler.

Review feedback addressed through edc3f02:

  • as=script / rel=modulepreload / rel=prefetch / as=fetch|track|document|embed|object are resource-hint selectors that set HANDLES_IMPORT_ERRORS so unresolved hrefs (routes, API endpoints) pass through.
  • JS targets bundle with the native loader and the hint tag is dropped (transitive-dep modulepreload works; covered by html/link-preload-prefetch).
  • .html targets emit as raw hashed assets (html/link-hint-local-html); dev-server HTML-import guard skips hint records (bake/dev/html.test.ts resource-hint test).

Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
…h-only hints

Address review: the first pass mapped link[as=script] / rel=modulepreload to
ImportKind::Stmt, which bundled the target into the entry chunk and executed
it on page load, and rel=prefetch hard-failed the build on navigation-route
hrefs. Both diverge from browser semantics where these tags are fetch-only.

Introduce ImportRecordFlags::WAS_HTML_RESOURCE_HINT and mark the three
resource-hint selectors with it. A hint record:
- forces Loader::File so the target is emitted as a raw hashed asset and
  the href is rewritten, regardless of extension (JS/CSS are not bundled
  or executed);
- sets HANDLES_IMPORT_ERRORS so an href that does not resolve to a local
  file (e.g. a navigation route) passes through untouched instead of
  failing the build;
- yields to the native loader if a later non-hint record in the same
  batch references the same path (tracked via ParseTask.is_html_resource_hint),
  so <link rel=modulepreload href=./a.js> followed by <script src=./a.js>
  still bundles a.js and drops the hint.

link[as=fetch|track|document|embed|object] stay as plain Url imports.
Comment thread src/ast/import_record.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/ParseTask.rs Resolved
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.

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

  • 🔴 src/bundler/HTMLScanner.rs:225-229 — The link[as='fetch'|'track'|'document'|'embed'|'object'] selector uses TagHandler::new() instead of TagHandler::hint(), so its records get neither HANDLES_IMPORT_ERRORS nor WAS_HTML_RESOURCE_HINT — the same failure class d0bf2cd fixed for as=script/modulepreload/prefetch. <link rel="preload" as="fetch" href="/api/user" crossorigin> (MDN's canonical preload-for-fetch pattern) now fails the build where it previously passed through, and <link rel="preload" as="document" href="./iframe.html"> is parsed with Loader::Html rather than emitted as a raw asset. This entry should use TagHandler::hint() like its siblings.

    Extended reasoning...

    What the bug is

    Commit d0bf2cd introduced TagHandler::hint() to give records WAS_HTML_RESOURCE_HINT + HANDLES_IMPORT_ERRORS, and applied it to link[as='script'], link[rel='modulepreload'], and link[rel='prefetch'] — three of the four new selectors this PR adds. The fourth new selector, at HTMLScanner.rs:225-229:

    TagHandler::new(
        "link[as='fetch'][href], link[as='track'][href], link[as='document'][href], link[as='embed'][href], link[as='object'][href]",
        "href",
        ImportKind::Url,
    ),

    still uses TagHandler::new(), so is_resource_hint = false and create_import_record (HTMLScanner.rs:78-85) never sets either flag on these records.

    But per the HTML spec the as attribute is only meaningful on rel=preload/rel=modulepreload — every element this selector matches is a fetch-only resource hint, exactly the class hint() was introduced to handle.

    Code path — unresolved href → build failure (regression)

    For <link rel="preload" as="fetch" href="/api/user" crossorigin> (MDN's documented pattern for preloading a fetch() response):

    1. HTMLScanner.rs:225 — link[as='fetch'][href] matches; create_import_record is called with is_resource_hint = false, so HANDLES_IMPORT_ERRORS is not set.
    2. HTMLScanner.rs:42-46 — leading / → the path is joined onto fs.top_level_dir.
    3. bundle_v2.rs:6083 — resolver returns ModuleNotFound (no ./api/user file in the project).
    4. bundle_v2.rs:6120-6128 — !import_record.flags.contains(HANDLES_IMPORT_ERRORS) is true → last_error = Some(err.into()) and add_resolve_error_with_text_dupe logs "Could not resolve". The build fails.

    Before this PR no selector matched as=fetch, so the tag passed through untouched and the build succeeded — this is a concrete regression on realistic input. The same applies to <link rel="preload" as="document" href="/settings"> (iframe navigation targets), which are commonly server routes.

    Code path — JS/CSS/HTML target → bundled/executed

    For <link rel="preload" as="document" href="./iframe.html"> (spec-defined use of as=document for <iframe>/<frame> navigation targets):

    1. Record is created with WAS_HTML_RESOURCE_HINT not set.
    2. bundle_v2.rs:6347-6349 — is_html_resource_hint = false, so the Loader::File force at line 6362 does not fire.
    3. bundle_v2.rs:6370-6378 — the fallback Url override explicitly excludes resolved_loader != Loader::Html, so .html keeps Loader::Html and is parsed/bundled as an HTML entry rather than emitted as a raw hashed asset.

    Similarly, <link rel="preload" as="fetch" href="./data.js"> keeps Loader::Js (excluded by !resolved_loader.is_javascript_like()), so the file is bundled into the entry chunk and, in the rewrite pass, generateCompileResultForHtmlChunk.rs hits loader.is_javascript_like() → element.remove() — the hint tag is silently deleted and the JS runs on page load. This is the exact fetch-only-semantics violation the earlier review flagged for rel=prefetch.

    Why existing code doesn't prevent it

    The two guards d0bf2cd added are keyed entirely on the flags this selector doesn't set:

    • bundle_v2.rs:6123-6125 gates the resolve error on !HANDLES_IMPORT_ERRORS.
    • bundle_v2.rs:6362 gates the Loader::File force on is_html_resource_hint.
    • generateCompileResultForHtmlChunk.rs:160-169 gates the pass-through-untouched branch on WAS_HTML_RESOURCE_HINT.

    None of these fire for TagHandler::new() entries. The fallback override at bundle_v2.rs:6370-6378 deliberately excludes JS/CSS/HTML so <script src>/<link rel=stylesheet> continue to bundle — which is correct for rel=manifest but wrong for rel=preload as=fetch|document.

    Step-by-step proof

    Input:

    <link rel="preload" as="fetch" href="/api/user" crossorigin>
    Step as=script (fixed) as=fetch (this bug)
    Selector TagHandler::hint(...) TagHandler::new(...)
    is_resource_hint true false
    HANDLES_IMPORT_ERRORS set not set
    Resolver: /api/user ModuleNotFound ModuleNotFound
    bundle_v2.rs:6123 skipped (flag set) → path.is_disabled = true, build continues last_error = Some(...) → build fails
    Rewrite pass is_resource_hint && path.is_disabled → tag passes through never reached

    The new html/link-hint-unresolved test covers rel=prefetch and rel=modulepreload but not as=fetch/as=document, so this gap has no test coverage.

    Impact

    • Build regression on any project preloading an API endpoint (as=fetch href=/api/...) or iframe route (as=document href=/route).
    • Semantic corruption when as=fetch|document points at a local .js/.css/.html file: the target is bundled/executed instead of emitted as a raw asset.

    Per REVIEW.md "Fix the whole class in the same PR": these are sibling entries in the same TAG_HANDLERS table added by the same PR, sharing the same failure mode; the fix commit applied hint() to three of them and missed this one. The pre-existing as=font|image|video|audio entries have the same construction, but those rarely point at routes or JS/HTML — as=fetch and as=document are specifically for API endpoints and iframe navigation targets, so the impact is materially different, and unlike them this selector is newly introduced by this PR.

    Fix

    Change the link[as='fetch'|'track'|'document'|'embed'|'object'][href] entry from TagHandler::new(...) to TagHandler::hint(...), and extend html/link-hint-unresolved with <link rel="preload" as="fetch" href="/api/user" crossorigin> to cover it.

Comment thread src/bundler/bundle_v2.rs Resolved
…hints; trim comments

as= is only valid on rel=preload|modulepreload, so these are always
fetch-only hints and need the same soft-resolve and force-File behaviour
as the other hint selectors. Without this, <link rel=preload as=fetch
href=/api/user> failed the build and <link rel=preload as=document
href=./iframe.html> was parsed as an HTML entry instead of emitted as a
raw asset. Extend html/link-hint-unresolved to cover as=fetch and
as=document route hrefs.

Also trim doc comments per comment-cop review.
Comment thread src/ast/import_record.rs Resolved
Comment thread src/bundler/ParseTask.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.

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

  • 🔴 src/bundler/bundle_v2.rs:6405-6412 — Escalating the cross-batch case above: it doesn't need two entry points or scheduling luck — the canonical single-entry modulepreload pattern hits it deterministically. <link rel="modulepreload" href="./dep.js"> + <script src="./main.js"> where main.js does import "./dep.js": the HTML batch pins dep.js to Loader::File and schedules its ParseTask before main.js's imports are ever resolved; when import "./dep.js" arrives, line 6387 hits and continues, so dep.js is parsed as a URL-string module (NoSideEffectsPureData) — a bare import is tree-shaken and a named import fails with "No matching export". That's the MDN-documented use case for modulepreload (preloading a dependency of the entry), and the new test only covers the degenerate case where hint and <script src> point at the same file. Note also that the fix suggested above (upgrade items_loader_mut()[id] at the 6387 hit) is insufficient here: dep.js's ParseTask has already been scheduled with Loader::File at line 6579 by the time main.js's parse result is drained.

    Extended reasoning...

    What the bug is

    The hint→non-hint loader restoration at lines 6409-6412 only runs inside the resolve_queue.get_or_put(...).found_existing branch, and resolve_queue is a per-parse-result local. The existing comment on this block already flags the cross-batch gap for a two-HTML-entry race; this escalates it: the same gap deterministically breaks the primary modulepreload use case with a single HTML entry point.

    <link rel="modulepreload"> exists to preload a dependency of the entry script, not the entry script itself — MDN's canonical example is:

    <link rel="modulepreload" href="./dep.js">
    <script type="module" src="./main.js"></script>
    // main.js
    import { x } from "./dep.js";   // or a bare: import "./dep.js";

    With this PR, dep.js is silently pinned to Loader::File and never bundled as JS.

    Code path

    index.html's parse result is handled on the bundle thread: run_resolution_for_parse_task → resolve_import_records → process_resolve_queue, all synchronous within on_parse_task_complete.

    1. resolve_import_records: the modulepreload record has WAS_HTML_RESOURCE_HINT → line 6362 forces import_record_loader = Loader::File. The <script src="./main.js"> record is non-hint → Loader::Js. Different paths, so the same-batch restoration at line 6409 never fires. Two fresh ParseTasks go into resolve_queue: dep.js with loader = Some(File), is_html_resource_hint = true; main.js with loader = Some(Js).
    2. process_resolve_queue: for dep.js, path_to_source_index_map.get_or_put at line 6509 inserts it; line 6537 writes input_files[dep].loader = File; File.should_copy_for_bundling() is true, so lines 6573-6575 set side_effects = NoSideEffectsPureData and push it to additional_files; line 6579 schedules dep.js's ParseTask with Loader::File. main.js is likewise inserted and scheduled with Loader::Js.

    main.js's parse result arrives (necessarily after step 2 — the HTML batch scheduled it):

    1. resolve_import_records sees import "./dep.js". WAS_HTML_RESOURCE_HINT is not set → is_html_resource_hint = false, import_record_loader = Js. Line 6387 hits — path_to_source_index_map already holds dep.js from step 2 — sets import_record.source_index and continues at line 6394. Lines 6401-6412 are unreachable. Nothing touches input_files[dep].loader, and dep.js's ParseTask is already running (or queued) with Loader::File.

    Link/emit: dep.js was parsed with the File loader — its AST is a synthetic default-export-of-URL-string with no user code. It's marked NoSideEffectsPureData, so a bare import "./dep.js" in main.js is tree-shaken. A named import (import { x } from "./dep.js") fails linking with "No matching export in 'dep.js' for import 'x'". The rewrite pass reads input_files[dep].loader = File, so the modulepreload href is rewritten to the raw emitted dep-<hash>.js. dep.js's top-level code never runs.

    Why the ordering is deterministic

    Unlike the two-entry-point scenario in the earlier comment (which depends on which HTML parse result the pool completes first), here main.js's ParseTask is created and scheduled by index.html's process_resolve_queue. on_parse_task_complete processes one result synchronously — resolve, then process queue — before draining the next, so dep.js is always in path_to_source_index_map before main.js's imports are resolved. No thread-pool luck required.

    Why existing code doesn't prevent it

    • The restoration at line 6409 is scoped to resolve_queue, which is fresh per parse result. main.js's batch never sees the ParseTask that carried is_html_resource_hint = true.
    • The path_to_source_index_map hit at line 6387 sets source_index and continues without inspecting or updating input_files[id].loader.
    • process_resolve_queue's found_existing branch (lines 6580-6596) is also unreached — main.js's batch never enqueues dep.js because line 6394 short-circuits first.
    • The PR's own test (html/link-preload-prefetch) only exercises the degenerate case where the modulepreload target and <script src> are the same file (./mod.js), which stays inside one resolve_queue and hits line 6409. Pointing the hint at a transitive dependency — the actual purpose of modulepreload — is not covered.

    Impact

    The primary real-world modulepreload pattern silently produces broken output: dependency code is dropped from the bundle (bare import), or the build fails with a misleading "No matching export" (named import). This is a regression for any project that adds a modulepreload hint for a module that is only reached transitively from the entry script.

    How to fix

    The suggestion in the earlier comment — upgrade items_loader_mut()[id] at the line-6387 hit when a non-hint record arrives for a hint-pinned slot — is not sufficient here on its own: by the time main.js's import is resolved, dep.js's ParseTask has already been scheduled (line 6579) with Loader::File and may already have been parsed. A working fix needs to either (a) defer scheduling hint-only ParseTasks until the graph settles (so a later non-hint reference can restore the loader before parse), or (b) on the line-6387 upgrade, also re-parse the file with its native loader (re-schedule / mark stale) and clear NoSideEffectsPureData + the additional_files entry. Whichever approach is taken, please add a test with <link rel="modulepreload" href="./dep.js"> + <script src="./main.js"> where main.js imports dep.js and asserts dep.js's code lands in the entry chunk.

Comment thread src/bundler/bundle_v2.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Forcing Loader::File for resource-hint records broke the canonical
modulepreload pattern: <link rel=modulepreload href=./dep.js> +
<script src=./main.js> where main.js imports dep.js. The hint record is
processed before main.js's imports are resolved, so dep.js was scheduled
with Loader::File and import {x} from './dep.js' failed with 'No matching
export'. The intra-batch loader restoration could not help because main.js's
import arrives in a later batch after dep.js's ParseTask is already
scheduled.

Revert to the simpler rule: hint records resolve and enqueue with their
native loader (so JS is bundled as JS) and set HANDLES_IMPORT_ERRORS so
unresolvable hrefs pass through. In the rewrite pass a JS/CSS target means
the file is in the entry chunk and the hint tag is dropped; a file-loader
target has its href rewritten to the hashed asset path.

This removes the ParseTask.is_html_resource_hint field and the bundle_v2.rs
loader machinery added in d0bf2cd, leaving only the flag, the soft-resolve,
and the selectors. The test now covers the transitive-dep case directly.

@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: 3

🤖 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 `@src/bundler/HTMLScanner.rs`:
- Around line 229-232: Update the modulepreload and prefetch selectors in the
TagHandler::hint entries to use the rel token-match operator, allowing each
token to match within space-separated rel values. Add or update coverage for
standalone and combined rel values, including both accepted option spellings.
- Around line 34-39: Update HTMLScanner::create_import_record to detect
resource-hint URLs beginning with // and bypass local-path normalization and
resolution, preserving the protocol-relative URL unchanged; explicitly retain
this behavior for accepted network-path forms, including IPv6 hosts. In
test/bundler/bundler_html.test.ts at lines 1097-1111, add a protocol-relative
external hint and assert the emitted value remains unchanged.

In `@test/bundler/bundler_html.test.ts`:
- Around line 1015-1043: Add preload fixtures for as="embed" and as="object" in
the html/link-preload-prefetch test, provide corresponding source assets, and
assert both links are rewritten to their emitted hashed asset paths. Keep the
existing coverage unchanged so all advertised non-code variants are validated.
🪄 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: b83b92bf-c371-45eb-a98c-9be366c5002a

📥 Commits

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

📒 Files selected for processing (4)
  • src/ast/import_record.rs
  • src/bundler/HTMLScanner.rs
  • src/bundler/linker_context/generateCompileResultForHtmlChunk.rs
  • test/bundler/bundler_html.test.ts

Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread test/bundler/bundler_html.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/bundle_v2.rs:6397-6405 — The intra-batch restoration doesn't cover the non-hint reference arriving via a transitive import — and unlike the multi-entry case already deferred on this thread, that hits deterministically on a single HTML entry. <link rel="modulepreload" href="./util.js"> + <script src="./main.js"> where main.js does import { helper } from "./util.js": the HTML batch pins util.js to Loader::File in path_to_source_index_map before main.js is scheduled, so main.js's import record hits the map and continues past the restoration, and the build fails with "No matching export in util.js for import 'helper'". Before this PR no selector matched modulepreload and this build succeeded; "modulepreload a module the entry script imports" is the primary MDN-documented use of rel=modulepreload (Vite emits exactly this for entry-chunk deps), so the "known limitation" wording (multi-entry, nondeterministic) does not cover it.

    Extended reasoning...

    What the bug is

    The hint→non-hint loader restoration at lines 6398-6404 fires only when both records land in the same resolve_queue — i.e. both appear directly in the same HTML file. The earlier comment on this thread showed that a non-hint record arriving from a different HTML entry bypasses it via the path_to_source_index_map hit; the author deferred that as narrow and thread-pool-nondeterministic. But the same bypass triggers deterministically on a single HTML entry whenever the hinted module is reached via a transitive JS import from the entry script rather than a direct <script src> — which is the canonical thing rel=modulepreload is for.

    Step-by-step proof (single entry)

    <!-- index.html -->
    <link rel="modulepreload" href="./util.js">
    <script type="module" src="./main.js"></script>
    // main.js
    import { helper } from "./util.js";
    helper();
    1. HTML batch — resolve_import_records: util.js's record has WAS_HTML_RESOURCE_HINT → line 6358 forces Loader::File; resolve_queue inserts a fresh ParseTask{loader=File, is_html_resource_hint=true}. main.js's record inserts ParseTask{loader=Js}. The two paths differ, so found_existing at line 6398 never fires in this batch.
    2. HTML batch — process_resolve_queue: runs synchronously on the bundle thread, inserts util.js into path_to_source_index_map, writes Loader::File into graph.input_files, and only then schedules main.js's ParseTask. So util.js is guaranteed to be in the map before main.js's own resolve pass runs.
    3. main.js batch — resolve_import_records: for its import "./util.js" record (no WAS_HTML_RESOURCE_HINT — the JS parser doesn't set it), import_record_loader = Js. But the path_to_source_index_map.get(path.text) check that runs before line 6397 hits, sets source_index, and continues. Lines 6398-6404 are never reached; input_files[util.js].loader stays File.
    4. Parse: util.js was scheduled with Loader::File → its AST is export default "<unique-key>"; the real module body (and the helper export) is discarded.
    5. Link: main.js's import { helper } from "./util.js" binds against a File-loader AST with no helper export → build fails with "No matching export in util.js for import 'helper'". For a bare side-effect import, the build succeeds but util.js's top-level statements silently disappear from the bundle.

    Why the existing restoration doesn't prevent it

    The restoration at lines 6398-6404 lives inside the resolve_queue.get_or_put(...).found_existing branch, and resolve_queue is created fresh per parse-result. The cross-batch dedup point — path_to_source_index_map — sits before it in the loop and continues directly, so any non-hint record arriving in a later batch never reaches the restoration. The PR's own test (html/link-preload-prefetch) only exercises hint + direct <script src> on the same path (both in the HTML batch, so found_existing fires); it doesn't cover hint + transitive import.

    Why this is a regression, not the documented limitation

    • Regression: before this PR no selector matched rel=modulepreload, so util.js was reached only via main.js's import → Loader::Js → bundled correctly. After this PR the build fails.
    • Deterministic: step 2 is structural — process_resolve_queue for the HTML batch populates the map before it creates main.js's ParseTask. No thread-pool ordering is involved.
    • Not covered by the PR's Known-limitation wording: that wording is explicitly "multiple HTML entry points where one only hints a JS file that another <script src>s, and the hint-only entry happens to complete first". This is single-entry and always-first.
    • Primary use case: MDN on rel=modulepreload: "provides a declarative way to preemptively fetch a module script and its dependencies" — i.e. preload modules the entry script will import. Vite's production output emits <link rel="modulepreload"> for exactly the entry chunk's transitive dependencies.
    • Also CSS: <link rel="prefetch" href="./theme.css"> + <link rel="stylesheet" href="./main.css"> where main.css @imports theme.css hits the same path — theme.css is pinned to Loader::File and the @import no longer bundles it.

    How to fix

    The suggestion from the earlier thread — track is_html_resource_hint on the input-file slot and upgrade at the path_to_source_index_map hit — has the same "ParseTask already scheduled" problem here. The structural fix is the deferral the author mentioned: don't schedule hint-only ParseTasks (or don't force Loader::File on them) until every non-hint reference that could reach the same path has been resolved. A narrower stopgap that unblocks this PR: don't add rel=modulepreload / as=script targets to resolve_queue at all when they resolve to a JS-like loader — leave the hint href as-is (pre-PR behavior for that tag) and let the real import pull the module in; the rewrite pass then drops the hint tag because loader.is_javascript_like(). That trades "build fails" back for "hint href is a 404", which is what shipped before.

  • 🔴 src/bundler/bundle_v2.rs:6347-6359 — The dev-server HTML guard at lines 6270-6288 runs before the new is_html_resource_hint computation at line 6347, so in dev-server/bake mode a hint targeting a local .html file — e.g. <link rel="prefetch" href="./page2.html"> (canonical next-page navigation prefetch) or <link rel="preload" as="document" href="./iframe.html"> — now hard-fails the build with "Browser builds cannot import HTML files." where before this PR the tag passed through untouched. HANDLES_IMPORT_ERRORS does not help here: it is only consulted on the ModuleNotFound path, not this one. Hoist the WAS_HTML_RESOURCE_HINT read above line 6270 and skip (or Loader::File-override) the guard for hint records — same "sibling arm before hint check" class as the FileMap comment above, but a distinct code path with a hard-error failure mode.

    Extended reasoning...

    What the bug is

    The new TagHandler::hint selectors (link[rel='prefetch'], link[as='document'], etc.) create import records for hrefs that were previously ignored by the scanner. When such a hint targets a local .html file that exists on disk, the resolver succeeds and — in dev-server/bake mode — execution reaches the dev-server guard at bundle_v2.rs:6270-6288 before the new is_html_resource_hint computation at line 6347. That guard tests path.loader(&self.transpiler.options.loaders) == Some(Loader::Html) && (import_record.loader.is_none() || == Html); both conjuncts hold for a hint record (HTMLScanner sets loader: None at HTMLScanner.rs:87), so it unconditionally emits "Browser builds cannot import HTML files." via add_range_error_fmt and continue 'outer. The Loader::File override that would have made this a raw-asset copy is never reached.

    Code path

    1. Scan — <link rel="prefetch" href="./page2.html"> matches the new link[rel='prefetch'][href] TagHandler::hint entry. create_import_record produces a record with flags = WAS_HTML_RESOURCE_HINT | HANDLES_IMPORT_ERRORS, loader: None.
    2. Resolve — bundle_v2.rs:6064 runs the disk resolver; ./page2.html exists, so resolution succeeds and path is set from resolve_result.path().
    3. Dev-server guard — bundle_v2.rs:6270: self.dev_server_handle() is Some in dev-server/bake mode. Line 6272-6274: path.loader(...) for a .html target is Some(Loader::Html); import_record.loader.is_none() is true. Both conjuncts satisfied.
    4. Line 6282-6287: log.add_range_error_fmt(..., "Browser builds cannot import HTML files."), then continue 'outer. Build fails.
    5. Line 6347 — is_html_resource_hint computation and the Loader::File override — is never reached.

    Why existing code doesn't prevent it

    • HANDLES_IMPORT_ERRORS is only consulted at lines 6123-6125 inside the ModuleNotFound branch of the resolve-failure path. On the resolve-success path there is no check for it before the dev-server guard fires; the guard emits the error unconditionally.
    • The new dev-server pass-through added in generateCompileResultForHtmlChunk.rs:167-168 ("Unresolved hint href: pass through untouched") only handles import_record.path.is_disabled — i.e. resolve-failure — and never runs anyway because resolve_import_records errored out before the rewrite pass.
    • The Loader::File override at line 6358 is placed after line 6288, so it cannot influence the guard's conditions.

    Step-by-step proof

    Dev-server / bake project with:

    <!-- index.html -->
    <link rel="prefetch" href="./page2.html">

    and page2.html present on disk (a second route the user is likely to navigate to — the MDN-documented use of rel=prefetch).

    • Before this PR: no TAG_HANDLERS entry matched link[rel='prefetch'], so no import record was created. The tag passed through untouched; the dev-server build succeeded.
    • After this PR: the new selector matches, a record is created with loader: None, resolution succeeds, and at line 6272 the dev-server guard sees .html + loader.is_none() → hard error "Browser builds cannot import HTML files."; the build fails.

    The same happens for <link rel="preload" as="document" href="./iframe.html"> (matches the new link[as='document'][href] hint selector).

    Impact

    Build-breaking regression in dev-server/bake mode on the canonical next-page navigation prefetch pattern (<link rel="prefetch" href="./other-page.html">) whenever the target exists on disk. This is the same "sibling arm runs before the hint handling" class as the already-flagged FileMap-arm comment on line 6363, but on a distinct code path (the dev-server HTML guard) and with a hard-error failure mode rather than wrong bundling — per REVIEW.md ("Fix the whole class in the same PR"), it belongs in the same change.

    How to fix

    Hoist the is_html_resource_hint read (and, ideally, the Loader::File override on import_record.loader) above the if let Some(dev_server) = self.dev_server_handle() block at line 6270, so the guard's import_record.loader.is_none() conjunct is false for hint records. Alternatively, add && !import_record.flags.contains(ImportRecordFlags::WAS_HTML_RESOURCE_HINT) to the guard's condition at line 6272-6274. Either way, a hint targeting a local .html should reach the raw-asset emission path, not the dev-server error.

Comment thread src/bundler/HTMLScanner.rs Resolved
In dev-server/bake mode, an HTML import record targeting a local .html file
hits the 'Browser builds cannot import HTML files' guard before loader
selection runs. A <link rel=prefetch href=./page2.html> or <link rel=preload
as=document href=./frame.html> hint would now reach that guard (before this
PR no selector matched it) and fail the build. Treat hint records the same
as unresolved hrefs here: mark is_disabled and continue so the rewrite pass
leaves the href untouched.
Comment thread src/bundler/bundle_v2.rs Resolved
@robobun

robobun commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

Addressing the two additional findings:

  • Transitive-import (modulepreload ./util.js + script src=./main.js where main imports util): reviewed stale code. 2bd81d6 removed the Loader::File force entirely; bundle_v2.rs/ParseTask.rs have zero diff from main. Verified on 2bd81d6: the build succeeds and util.js is bundled as JS with its named export intact. The html/link-preload-prefetch test now covers this exact shape (main.js imports dep.js, hint points at dep.js).
  • Dev-server HTML guard (<link rel=prefetch href=./page2.html> → "Browser builds cannot import HTML files"): fixed in 20de21f. Hint records hitting that guard are now marked is_disabled and continue, so the rewrite pass leaves the href untouched.

Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/ast/import_record.rs Resolved
…ale doc comment

A hint targeting a local .html file (<link rel=prefetch href=./page2.html>,
<link rel=preload as=document href=./frame.html>) kept Loader::Html after
2bd81d6 dropped the File-loader force, so page2.html was parsed as a nested
HTML entry and its scripts leaked into the current page's entry chunk. Extend
the existing HTML Url->File override to also fire for Loader::Html when the
record carries WAS_HTML_RESOURCE_HINT, so the target is copied as a raw asset
and the href is rewritten.

Also reword the WAS_HTML_RESOURCE_HINT doc comment: 'emit as a raw asset'
described the File-loader force removed in 2bd81d6.
Comment thread src/ast/import_record.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: 1

🤖 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 1115-1116: Update the assertion near the html script extraction so
the test always verifies that PAGE2_SCRIPT is absent, even when no index-*.js
tag is matched. Remove the conditional skip and directly assert the expected
emitted chunk or no-chunk result, while preserving the fixture’s intended
parent-output leak check.
🪄 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: 730114e0-ead2-416d-b547-7d186054562f

📥 Commits

Reviewing files that changed from the base of the PR and between 2bd81d6 and 5d17bb2.

📒 Files selected for processing (3)
  • src/ast/import_record.rs
  • src/bundler/bundle_v2.rs
  • test/bundler/bundler_html.test.ts

Comment thread test/bundler/bundler_html.test.ts Resolved
@robobun
robobun force-pushed the claude/ae1514b3/html-link-preload-prefetch branch from 4ef8f2f to 6e0a405 Compare July 26, 2026 22:19
Comment thread src/bundler/bundle_v2.rs Resolved
Covers the WAS_HTML_RESOURCE_HINT carve-out in the dev-server HTML-import
guard (bundle_v2.rs) and the is_resource_hint && path.is_disabled pass-through
in the rewrite pass (generateCompileResultForHtmlChunk.rs), neither of which
is reachable from itBundled.

@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: 1

🤖 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/bake/dev/html.test.ts`:
- Around line 374-397: Update the “resource-hint links pass through in dev
server” test to assert that the local ./page2.html prefetch link is present with
the expected href, alongside the existing unresolved-href assertions. Keep the
current fixture and other checks unchanged.
🪄 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: 9a011c21-1fc5-4166-a34c-929f7d0266d4

📥 Commits

Reviewing files that changed from the base of the PR and between 5d17bb2 and cd9d285.

📒 Files selected for processing (2)
  • test/bake/dev/html.test.ts
  • test/bundler/bundler_html.test.ts

Comment thread test/bake/dev/html.test.ts Resolved
Comment thread src/bundler/bundle_v2.rs
Comment on lines 6368 to +6374
&& !resolved_loader.should_copy_for_bundling()
&& !resolved_loader.is_javascript_like()
&& !resolved_loader.is_css()
&& resolved_loader != Loader::Html
&& (resolved_loader != Loader::Html
|| import_record
.flags
.contains(bun_ast::ImportRecordFlags::WAS_HTML_RESOURCE_HINT))

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.

🔴 The new as='fetch' / rel='prefetch' selectors feed .json/.toml/.txt targets into the pre-existing ImportKind::Url → Loader::File override, and because the HTML entry's records are resolved first, the target is registered in path_to_source_index_map with loader=File before any JS module's imports are seen. A later import data from './data.json' in bundled JS then reuses that slot and gets the emitted path string instead of the parsed object — a silent runtime regression vs main, where these tags weren't matched at all. The PR already handled this exact class for .js (2bd81d6, covered by the "not pinned to a file loader" assertion in html/link-preload-prefetch) and for .html (5d17bb2); JSON/TOML/text is the remaining sibling.

Extended reasoning...

What the bug is

The four new TagHandler::hint selectors (link[as='fetch'|'track'|'document'|'embed'|'object'], link[as='script'], link[rel='modulepreload'], link[rel='prefetch']) all use ImportKind::Url. When such a hint targets a file whose extension maps to a non-JS/CSS/HTML/should-copy loader — .json→Json, .toml→Toml, .txt→Text, etc. — the pre-existing override at bundle_v2.rs:6366-6377 fires (loader == Html && kind == Url && !should_copy && !is_js && !is_css) and forces import_record_loader = Loader::File. That forced loader flows into resolve_task.loader at line 6434, and process_resolve_queue then registers the path in path_to_source_index_map (line 6499) with new_input_file.loader = File (line 6527) — first-wins.

If a bundled JS module later does import data from './data.json', its import-record resolution hits the already-populated map entry at line 6386, sets source_index to the File-loaded slot at line 6391, and continues. The File loader's default export is the emitted path string, so data is "./data-<hash>.json" instead of the parsed {k:1} object.

Why it's a regression introduced by this PR

The override at 6366-6377 itself is unchanged from main (only the Html clause at 6371-6374 changed). What's new is that this PR adds selectors that feed it: on main, no TAG_HANDLERS entry matches as='fetch' or rel='prefetch', so a ./data.json referenced by such a hint is never scanned, and the file is reached only via main.js's import → Loader::Json → parsed object. After this PR the hint record is created during index.html's scan, resolved and enqueued in the same synchronous process_resolve_queue pass that schedules main.js's ParseTask, so it always wins the map slot.

The pre-existing rel='manifest' selector could technically hit the same override, but overlapping a manifest with a JS static import is implausible. as='fetch' and rel='prefetch' are specifically intended for data files, which developers do sometimes also statically import (e.g. <link rel="prefetch" href="./config.json"> for a future page + a lazy chunk that does import cfg from './config.json').

Step-by-step proof

<!-- index.html -->
<head>
  <link rel="preload" as="fetch" href="./data.json" crossorigin>
</head>
<body><script type="module" src="./main.js"></script></body>
// main.js
import data from "./data.json";
console.log(data.k);
// data.json
{"k":1}
  1. Scan — HTMLScanner matches link[as='fetch'][href] → import record with kind=Url, loader=None, WAS_HTML_RESOURCE_HINT|HANDLES_IMPORT_ERRORS. Separately matches script[src] → record for ./main.js.
  2. Resolve index.html's records (bundle_v2.rs:6356): for ./data.json, resolved_loader = Loader::Json (from extension). Json.should_copy_for_bundling() is false (loader.rs:114-123), Json.is_javascript_like() is false, Json.is_css() is false, Json != Html → override fires → import_record_loader = Loader::File. Line 6434: resolve_task.loader = Some(File).
  3. process_resolve_queue (same synchronous drain): line 6483 reads value.loader = Some(File); line 6499 map.get_or_put("…/data.json") inserts; line 6527 new_input_file.loader = File; line 6534 writes source_index into the map; line 6569 schedules the File ParseTask. In the same loop iteration, ./main.js is scheduled with Loader::Js — its own import records won't be resolved until its ParseTask completes on a later drain.
  4. Resolve main.js's records (later): for ./data.json, line 6386 path_to_source_index_map.get(path) returns the existing id → line 6391 import_record.source_index = existing → continue. The record's loader is set to Json at line 6380, but that's on the record; the input-file slot's loader stays File and the already-scheduled File ParseTask has emitted the path-string default export.
  5. Runtime: console.log(data.k) logs undefined (data is the string "./data-<hash>.json"). On main it logs 1.

Why existing code doesn't prevent it

  • The is_javascript_like() exclusion at line 6369 (which lets 2bd81d6's fix work for modulepreloaded .js) doesn't cover Loader::Json/Toml/Text.
  • The WAS_HTML_RESOURCE_HINT clause added at line 6374 only affects resolved_loader == Html.
  • path_to_source_index_map is first-wins by design; there's no reconciliation when a later import wants a different loader.
  • None of the three new tests cover a hint target that is also statically imported from JS with a data loader — html/link-preload-prefetch's data.json is reached only via the hint, and its dep.js overlap case exercises the .js sibling that 2bd81d6 already fixed.

Impact

Silent behavioral change: a JSON/TOML/text import that returned a parsed value on main now returns a path string, with no build error or warning. Per REVIEW.md's whole-class rule, the PR already fixed two siblings of this exact first-wins interaction (.js targets in 2bd81d6 — the test even comments "It must be bundled as JS (not pinned to a file loader), so `import { x } from './dep.js'` resolves" — and .html targets in 5d17bb2); JSON/TOML/text is the remaining member of the class the new selectors expose.

How to fix

Either exclude data loaders from the override the same way JS/CSS are excluded (but then a hint-only .json wouldn't be emitted as a raw asset, so that's wrong on its own), or — more targeted — when WAS_HTML_RESOURCE_HINT is set and the target already exists in path_to_source_index_map with a non-File loader, reuse that slot instead of forcing File; conversely, if the JS import arrives second, the fix needs the hint record to not pin the input-file loader. The simplest correct shape is probably: for hint records whose resolved_loader is a data loader (Json/Toml/Text/etc.), keep the native loader on the input_file slot (so a JS import gets the parsed object) and separately emit the raw bytes as an additional file for the href rewrite — mirroring what should_copy_for_bundling loaders already do. A regression test in html/link-preload-prefetch adding import data from './data.json' to main.js and asserting jsContent contains the JSON's value would pin it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verified. This is the JSON/TOML/text sibling of the first-wins loader-pinning interaction the PR already documents under Trade-off for JS targets, and it is triggered by the pre-existing Url->File override (unchanged from main except for the Html clause). Fixing it correctly (so a hint-only .json is emitted as a raw asset AND a hint-plus-JS-import .json gives a parsed object) requires deferring hint-only ParseTasks until the graph is complete, same as the JS case. I have added it to the Trade-off section in the PR description rather than expanding the loader-pinning workarounds further. The trigger (both <link rel=preload as=fetch href=./data.json> and import data from './data.json' for the same file) is unusual: preload-as-fetch is for fetch() calls, and a static import is bundled so there is nothing to preload.

Comment thread src/bundler/bundle_v2.rs Resolved
With entryPoints:[index.html, page2.html] and <link rel=prefetch
href=./page2.html> in index.html, page2.html is already in
path_to_source_index_map as an Html-loaded entry. Setting the hint record's
source_index to that slot made the reachability walk follow the edge and
pull page2's scripts into index's entry chunk. When a hint record hits an
existing Html-loaded map slot, mark is_disabled and continue without setting
source_index so the href passes through (page2.html is emitted under its own
entry-point name, so the original href is already a valid output path).
Comment thread src/bundler/bundle_v2.rs Resolved
Comment thread src/bundler/bundle_v2.rs Resolved
patch_import_record_source_indices re-derives source_index from
record.path.text for every record, which re-populated the source_index
that the sibling-entry hint guard had just left invalid when the hint href
was root-relative (/page2.html writes the absolute path into path.text via
HTMLScanner's leading-slash join, whereas ./page2.html leaves the literal
relative string). Skip records whose path.is_disabled is set, matching the
invariant the resolve loop already establishes (is_disabled records have
invalid source_index). Extend html/link-hint-sibling-entry to cover both
href shapes.

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

The three prior findings (dev-server test coverage, sibling-entry leak, root-relative patch_import_record_source_indices bypass) are now addressed and covered by tests. Deferring to a human for the remaining design call in the unresolved thread at bundle_v2.rs:6374 — whether the acknowledged JSON/TOML/text loader-pinning regression is acceptable as a documented trade-off — and because the fix accreted several special-case guards across the resolve loop that warrant a maintainer's read.

What was reviewed:

  • 378ad58's is_disabled skip in patch_import_record_source_indices against every other is_disabled = true site in src/bundler/ — the pre-existing sites either also invalidate source_index or hold unresolved paths that miss the map, so no behaviour change there.
  • The on_tag signature refactor against both HTMLProcessorHandler impls (scanner + HTMLLoader) — both updated; url_attribute recovered from tag in the loader.
  • WAS_HTML_RESOURCE_HINT uses bit 7, previously unused in ImportRecordFlags.
Extended reasoning...

Overview

Adds four resource-hint <link> selectors (rel=prefetch, rel=modulepreload, as=script, as=fetch|track|document|embed|object) to TAG_HANDLERS, tags their import records with a new WAS_HTML_RESOURCE_HINT flag, and threads that flag through four sites in bundle_v2.rs (dev-server HTML-import guard bypass, Url→File loader override for .html targets, sibling-HTML-entry disabling at the map hit, and an is_disabled skip in patch_import_record_source_indices) plus a dev-server pass-through arm in generateCompileResultForHtmlChunk.rs. Refactors HTMLProcessorHandler::on_tag to take the whole TagHandler. Four new itBundled cases and one devTest.

Security risks

None — bundler output-path rewriting; no auth, crypto, or untrusted-input parsing beyond what lol-html already handles.

Level of scrutiny

Medium-high. The change is behavioural in the bundler resolve loop, touches a shared helper (patch_import_record_source_indices) used by every import record, and went through three rounds of found-and-fixed bugs during review (dev-server coverage gap, sibling-entry cross-chunk leak, root-relative-href bypass of the sibling guard). Each fix added another special-case branch keyed on the new flag, which is the shape REVIEW.md warns about ("when a heuristic keeps sprouting counterexamples in review, redesign structurally").

Other factors

  • One inline thread from a prior run remains unresolved: the as=fetch/rel=prefetch selectors now feed .json/.toml/.txt into the pre-existing Url→File override, so a file that is both hint-referenced and statically imported from JS gets the path string instead of the parsed object — a strict regression vs main. The author verified it, declined to fix (would require deferring hint-only ParseTasks), and documented it in the PR description's Trade-offs. Whether that's acceptable to ship is a maintainer call.
  • The is_disabled skip in patch_import_record_source_indices is broader than the hint-record fix strictly requires; verifiers checked every other is_disabled = true writer in src/bundler/ and found no case where a disabled record's source_index needs re-populating, so this reads as a correct invariant tightening rather than an over-broad guard — but it is a change to a general codepath.
  • Test coverage is good: each of the four production behaviours and the dev-server pass-through has a dedicated case, and the sibling-entry test now covers both ./ and / href shapes per the last fix.

@robobun

robobun commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Overlap note: #41938 (now the single PR for the HTML URL-attribute work) touches the same code. It changes HTMLProcessorHandler::on_tag to on_url(url, kind) -> UrlAction, turns TAG_HANDLERS into a slice, and registers a link[rel~='preload'|'modulepreload'|'prefetch'][href] handler with an on_resource_hint hook that removes local hints in --compile --target=browser output only. In an --outdir build it leaves rel=prefetch / rel=modulepreload / rel=preload as=script|fetch|track|document hrefs as written, so the rewrite this PR does (hash and re-point non-code targets, drop hints whose target was bundled, pass unresolved hrefs through) is still unique. This branch has been conflicting with main since July; once #41938 lands, please rebase onto it and express the hint handlers through on_url / on_resource_hint rather than the TagHandler parameter on on_tag.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-27 and it conflicts with main. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

@robobun robobun closed this Sep 13, 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