Skip to content

bundler(html): emit <link rel="preload" as="style"> as a standalone CSS chunk - #36011

Closed
robobun wants to merge 16 commits into
mainfrom
farm/fff4846f/html-preload-style-standalone
Closed

robobun wants to merge 16 commits into
mainfrom
farm/fff4846f/html-preload-style-standalone

Conversation

@robobun

@robobun robobun commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

<link rel="preload" as="style" href="./x.css"> is a fetch-only hint: the stylesheet is not applied until the page does so itself (the common async-CSS pattern is onload="this.rel='stylesheet'").

bun build ./index.html was treating this the same as rel="stylesheet": the referenced CSS was merged into the page's applied CSS chunk, the preload tag was deleted, and a rel="stylesheet" link was injected. Styles the source page never applied were now render-applied in the built output, and there was nothing left to swap to.

$ printf 'body{color:red}\n' > later.css
$ printf 'console.log(1)\n' > a.js
$ cat > index.html <<HTML
<!doctype html>
<link rel="preload" as="style" href="./later.css">
<script type="module" src="./a.js"></script>
<p>no applied stylesheet in this page</p>
HTML
$ bun build ./index.html --outdir=./out && cat out/index.html

Before:

<!doctype html>


<p>no applied stylesheet in this page</p>
<link rel="stylesheet" crossorigin href="./index-50njcp54.css"><script type="module" crossorigin src="./index-st6j3bdd.js"></script>

Cause

TAG_HANDLERS in src/bundler/HTMLScanner.rs mapped link[as='style'][href] to ImportKind::At, the same kind as link[rel='stylesheet'], so the file was folded into the page's CSS chunk by findImportedCSSFilesInJSOrder and the original tag was removed by generateCompileResultForHtmlChunk.

Fix

Map link[as='style'] to ImportKind::Url so it is distinguishable from an applied stylesheet, and give the referenced file its own CSS chunk instead of merging it:

  • ReachableFileVisitor records CSS files reached from HTML via a url-kind record in html_preload_css_entry_points.
  • LinkerGraph::load appends those as entry points (new entry_point::Kind::HtmlPreload), mirroring the dynamic-import path, so computeChunks emits each as a standalone Content::Css chunk with @import/url() resolved.
  • computeChunks content-hashes the HtmlPreload chunk key and records entry_point_chunk_indices for the preload source explicitly. When the same file is also referenced via rel="stylesheet", the two chunks dedupe and both the preload href and the injected stylesheet href point at the same output.
  • findImportedCSSFilesInJSOrder skips url-kind records whose target is CSS so the preload is not also folded into the page bundle.
  • generateCompileResultForHtmlChunk rewrites the preload href to that chunk's unique key instead of removing the tag, and debug_asserts the looked-up chunk is CSS. Under --compile --target=browser (standalone single-file output) the tag is dropped: there is no separate file to preload and writing a chunk key into an href would inline raw CSS into the attribute.

The preloaded CSS keeps going through the CSS loader, so its own @import and url() dependencies are resolved and emitted. This is order-independent when the same file is referenced by both rel="preload" as="style" and rel="stylesheet", in both default and --production builds.

Dev server is unchanged: it already removed the preload tag before this change and still does; computeChunks does not run on that path so the chunk lookup is not available. That is the same semantic gap as the original bug and can be fixed separately.

After:

<!doctype html>
<link rel="preload" as="style" href="./later-50njcp54.css">

<p>no applied stylesheet in this page</p>
<script type="module" crossorigin src="./index-st6j3bdd.js"></script>

Verification

New tests in test/bundler/bundler_html.test.ts:

  • html/preload-as-style: page with both an applied stylesheet and a preload; the preload tag survives with a hashed href, the preloaded file is emitted standalone, and the applied bundle does not contain the preloaded rules.
  • html/preload-as-style-only: page with only a preload gets no injected rel="stylesheet".
  • html/preload-as-style-css-deps: @import is inlined and url() is resolved (data-URI content asserted) in the standalone output.
  • html/preload-as-style-shared-{preload,stylesheet}-first{,-production}: the same file referenced by both a preload and a stylesheet resolves to one output file, with both hrefs equal, in both tag orders and in both default and --production builds.

And in test/bundler/standalone.test.ts:

  • drops <link rel=preload as=style>: --compile --target=browser removes the preload tag rather than inlining CSS into its href.

All eight fail on current canary and pass with this change. bundler_html.test.ts, bundler_html_server.test.ts, html-import-manifest.test.ts, standalone.test.ts, esbuild/css.test.ts, and esbuild/splitting.test.ts continue to pass.


[review] gate passed · iteration 4 · 10 files touched

fails on main (without fix)
ASAN without fix: 11 FAILED
$ 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/html-import-manifest.test.ts test/bundler/standalone.test.ts
bun test v1.4.0 (9b2d4e1fa)

test/bundler/standalone.test.ts:
(pass) compile --target=browser > inlines JS and CSS into HTML [132.87ms]
56 | 
57 |     const html = await result.outputs[0].text();
58 |     // The preload tag is dropped: a single-file bundle has no separate file to
59 |     // preload, and inlining the CSS into an href attribute would corrupt the
60 |     // markup.
61 |     expect(html).not.toContain("preloaded-rule");
                          ^
error: expect(received).not.toContain(expected)

Expected to not contain: "preloaded-rule"
Received: "<!DOCTYPE html>\n\n<style>/* ../../tmp/compile-browser-preload-as-style_2jMceG/later.css */\nbody {\n  content: \"preloaded-rule\";\n}\n</style><script type=\"module\">// ../../tmp/compile-browser-preload-as-style_2jMceG/app.js\nconsole.log(\"app\");\n</script>\n"

      at <anonymous> (/workspace/bun/test/bundler/standalone.test.ts:61:22)
(fail) compile --target=browser 
... (truncated)

release without fix: 1 FAILED
bun test v1.4.0-canary.1 (3974cf594)

test/bundler/standalone.test.ts:
(pass) compile --target=browser > inlines JS and CSS into HTML [5.10ms]
(pass) compile --target=browser > drops <link rel=preload as=style> instead of inlining CSS into the href [2.70ms]
(pass) compile --target=browser > uses type=module on inline scripts [2.19ms]
(pass) compile --target=browser > top-level await works with inline scripts [2.14ms]
(pass) compile --target=browser > escapes </script> in inlined JS [1.48ms]
(pass) compile --target=browser > escapes </style> in inlined CSS [3.79ms]
(pass) compile --target=browser > deep import chain with re-exports and multiple files [2.80ms]
(pass) compile --target=browser > CSS imported from JS and via link tag (deduplicated) [2.54ms]
(pass) compile --target=browser > nested CSS @import chain [1.98ms]
(pass) compile --target=browser > Bun.build() with outdir writes files to disk [2.18ms]
(pass) compile --target=browser > Bun.build() with outdir and image assets [1.86ms]
(pass) compile --target=browser > inlines images as data: URIs [1.72ms]
(pass) compile --target=browser > handles CSS url() references [1.82ms]
(pass) compile --target=browser > non
... (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/bundler/bundler_html.test.ts test/bundler/html-import-manifest.test.ts test/bundler/standalone.test.ts
bun test v1.4.0 (9b2d4e1fa)

test/bundler/standalone.test.ts:
(pass) compile --target=browser > inlines JS and CSS into HTML [180.28ms]
(pass) compile --target=browser > drops <link rel=preload as=style> instead of inlining CSS into the href [101.23ms]
(pass) compile --target=browser > uses type=module on inline scripts [71.85ms]
(pass) compile --target=browser > top-level await works with inline scripts [59.89ms]
(pass) compile --target=browser > escapes </script> in inlined JS [53.70ms]
(pass) compile --target=browser > escapes </style> in inlined CSS [51.17ms]
(pass) compile --target=browser > deep import chain with re-exports and multiple files [69.80ms]
(pass) compile --target=browser > CSS imported from JS and via link tag (deduplicated) [65.60ms]
(pass) compile --target=browser > nested CSS @import chain [58.79ms]
(pass) compile --target=browser > Bun.build() with outdir writes files to disk [66.81ms]
(pass) compile --targ
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 970ms (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/bundler/HTMLScanner.rs                         |   4 +-
 src/bundler/LinkerContext.rs                       |   5 +
 src/bundler/LinkerGraph.rs                         |  20 +-
 src/bundler/bundle_v2.rs                           |  17 ++
 src/bundler/linker_context/computeChunks.rs        |  30 ++-
 .../findImportedCSSFilesInJSOrder.rs               |   8 +-
 .../generateCompileResultForHtmlChunk.rs           |  32 +++-
 test/bundler/bundler_html.test.ts                  | 205 +++++++++++++++++++++
 test/bundler/html-import-manifest.test.ts          |  85 +++++++++
 test/bundler/standalone.test.ts                    |  30 +++
 10 files changed, 429 insertions(+), 7 deletions(-)

gate history · 7 passed · 0 rejected · iteration 4

evidence per changed file
file                                                      reads  edits  tests
src/bundler/HTMLScanner.rs                                    2      2      0
src/bundler/LinkerContext.rs                                  5      1      0
src/bundler/LinkerGraph.rs                                    3      1      0
src/bundler/bundle_v2.rs                                     11      8      0
src/bundler/linker_context/computeChunks.rs                   7      5      0
…bundler/linker_context/findImportedCSSFilesInJSOrder.rs      1      3      0
…ler/linker_context/generateCompileResultForHtmlChunk.rs      4      6      0
test/bundler/bundler_html.test.ts                             4      4      0
test/bundler/html-import-manifest.test.ts                     2      2      0
test/bundler/standalone.test.ts                               1      1      0

…sset

A <link rel="preload" as="style"> is a fetch-only hint; the stylesheet is
not applied until the page does so itself (the common async-CSS pattern is
onload="this.rel='stylesheet'"). The HTML bundler was treating this the
same as rel="stylesheet": the CSS was merged into the page's applied CSS
chunk, the preload tag was deleted, and a rel="stylesheet" link was
injected, so styles the source page never applied were now render-applied
in the built output.

Map link[as="style"][href] to ImportKind::Url (matching as="font" /
as="image" preloads) and drop the CSS exclusion from the HTML url-asset
loader override so the file is emitted standalone with its href rewritten,
leaving the preload tag in place.
@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

HTML <link rel="preload" as="style"> references are classified as URL imports, tracked as CSS entry points, emitted through dedicated chunk logic, and rewritten to generated CSS paths. Standalone compiled HTML removes these preload elements. Bundler, manifest, and standalone tests cover the behavior.

HTML preload CSS flow

Layer / File(s) Summary
Classify and collect preload CSS references
src/bundler/HTMLScanner.rs, src/bundler/bundle_v2.rs
Style preload links use URL imports, and reachable HTML imports record CSS targets in bundle state.
Register HTML preload entry points
src/bundler/LinkerGraph.rs, src/bundler/LinkerContext.rs
Collected preload sources are registered as HtmlPreload entry points and cleared after graph loading.
Build and route preload CSS chunks
src/bundler/linker_context/computeChunks.rs, src/bundler/linker_context/findImportedCSSFilesInJSOrder.rs
Preload CSS chunks retain correct indices through sorting, while URL CSS imports are excluded from JavaScript CSS ordering.
Rewrite HTML output and validate behavior
src/bundler/linker_context/generateCompileResultForHtmlChunk.rs, test/bundler/*
HTML preload URLs are rewritten to generated CSS chunks or removed in standalone output, with bundler and manifest coverage added.

Possibly related PRs

  • oven-sh/bun#36012: Shares the HTML attribute-rewriting pipeline while adding separate srcset candidate handling.
  • oven-sh/bun#36013: Directly overlaps HTML link classification and rewriting behavior for preload resources.
  • oven-sh/bun#36015: Modifies the same HTML URL-rewriting path in HTMLLoader::on_tag.

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 is concise, specific, and matches the main change: treating HTML preload styles as standalone CSS chunks.
Description check ✅ Passed It clearly covers the change and verification, though it uses Problem/Cause/Fix/Verification 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 8:06 PM PT - Jul 26th, 2026

❌ @autofix-ci[bot], your commit 9b2d4e1 has 1 failures in Build #82951 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 36011

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

bun-36011 --bun

Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/HTMLScanner.rs Resolved
Comment thread src/bundler/bundle_v2.rs Resolved
The first iteration forced the preloaded file through Loader::File, which
emitted it byte-for-byte and left @import/url() references unresolved.

Instead, keep the CSS loader so the file's own dependency graph is
walked, but give it its own CSS chunk rather than folding it into the
page's applied stylesheet:

  - ReachableFileVisitor records CSS files reached from HTML via a
    url-kind import in html_preload_css_entry_points.
  - LinkerGraph::load appends those as entry points (new
    entry_point::Kind::HtmlPreload), mirroring the dynamic-import path,
    so computeChunks emits each as a standalone Content::Css chunk with
    @import/url() resolved.
  - findImportedCSSFilesInJSOrder skips url-kind records whose target is
    CSS so the preloaded file is not also merged into the page bundle.
  - generateCompileResultForHtmlChunk rewrites the preload href to that
    chunk's unique key instead of removing the tag.

This is order-independent when the same file is referenced by both a
preload and a rel="stylesheet" link, and the applied stylesheet keeps
going through the CSS graph in that case.
Comment thread src/bundler/bundle_v2.rs Resolved
Comment thread src/bundler/bundle_v2.rs Resolved
@robobun robobun changed the title bundler(html): emit <link rel="preload" as="style"> as a standalone asset bundler(html): emit <link rel="preload" as="style"> as a standalone CSS chunk Jul 26, 2026
Comment thread test/bundler/bundler_html.test.ts Resolved
Comment thread src/bundler/bundle_v2.rs Resolved
When the same file is referenced by both rel="preload" as="style" and
rel="stylesheet", the preload entry point and the page's CSS chunk have
identical import order. Key the HtmlPreload chunk by content hash so it
dedupes into the page chunk, and record the (source_index, chunk_index)
mapping explicitly so entry_point_chunk_indices is set even when the
deduped chunk's own entry_point.source_index is the HTML file. The HTML
rewrite now writes the same href to the preload and the injected
stylesheet link, and debug_asserts the looked-up chunk is CSS instead of
silently leaving a stale or wrong href.

Tests: strengthen the shared-file tests to assert preload and stylesheet
hrefs match, add --production variants, and make the css-deps test assert
the resolved url() data URI contents.
… HTML mode

In --compile --target=browser builds a chunk unique_key is replaced by the
chunk's raw bytes, so writing it into an href would inline the CSS text
into the attribute value. A single-file bundle has no separate file to
preload, so remove the tag instead. Covered by a new test in
standalone.test.ts.
When the page applies other stylesheets besides the preloaded one, the
preload gets its own output containing exactly what the source declared
so an onload swap applies only that file, and the page bundle separately
contains every applied stylesheet. The bytes are duplicated across the
two outputs; that is the tradeoff for preserving the source declaration.
A fresh HtmlPreload CSS chunk previously had entry_bits containing only
its own appended entry bit, which is beyond the parse-graph entry_points
count that HTMLImportManifest::write sizes its intersection bitset to. In
server-target builds with >=2 HTML imports the preload output was emitted
but omitted from the owning page's manifest.

Use the CSS file's full file entry_bits (which mark every entry point that
reaches it, including the HTML page) so the manifest's has_intersection
check associates the chunk with the right page. Covered by
html-import/preload-as-style-in-manifest.

@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 `@src/bundler/bundle_v2.rs`:
- Around line 5127-5128: Update the CSS-target handling in
finish_from_bake_dev_server so preload-style CSS imports are excluded from
start.css_entry_points, matching the existing ImportKind::Url filtering used by
the other CSS traversal path. Preserve registration of non-preload CSS targets
and the surrounding entry-point reset behavior.
🪄 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: dab90309-28bc-4895-8f1d-84efaa2ce936

📥 Commits

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

📒 Files selected for processing (10)
  • src/bundler/HTMLScanner.rs
  • src/bundler/LinkerContext.rs
  • src/bundler/LinkerGraph.rs
  • src/bundler/bundle_v2.rs
  • src/bundler/linker_context/computeChunks.rs
  • src/bundler/linker_context/findImportedCSSFilesInJSOrder.rs
  • src/bundler/linker_context/generateCompileResultForHtmlChunk.rs
  • test/bundler/bundler_html.test.ts
  • test/bundler/html-import-manifest.test.ts
  • test/bundler/standalone.test.ts

Comment thread src/bundler/bundle_v2.rs Resolved
robobun and others added 2 commits July 26, 2026 23:13
640f1b5 set entry_bits = file bits only when creating a fresh chunk.
When the HtmlPreload entry content-hash-dedupes into a page CSS chunk
another entry already created, the existing chunk kept only that page's
bits, so a page that only preloads the file was omitted from its own
HTML-import manifest while its emitted preload href still pointed at the
chunk. OR the file's entry_bits into the existing chunk so every
referencing page's manifest lists it. Covered by
html-import/preload-as-style-in-manifest-deduped.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/bundler/linker_context/computeChunks.rs (1)

168-178: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve manifest ownership when a preload creates the deduplicated chunk first.

If a preload of preload.css is processed before a normal stylesheet style.css with identical content, the stylesheet hits found_existing while is_html_preload is false. Its entry bits are never merged, so its HTML import manifest omits the shared CSS chunk.

  • src/bundler/linker_context/computeChunks.rs#L168-L178: merge entry_bits when either the incoming entry or the existing chunk’s entry point is HtmlPreload.
  • test/bundler/html-import-manifest.test.ts#L406-L445: add the reverse-order case using distinct CSS files with identical content; assert both manifests contain the same CSS chunk.
🤖 Prompt for 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.

In `@src/bundler/linker_context/computeChunks.rs` around lines 168 - 178, The
deduplication path only merges entry bits when the incoming chunk is an HTML
preload, so reverse-order deduplication loses manifest ownership. In
src/bundler/linker_context/computeChunks.rs:168-178, update the found_existing
handling around css_chunk_entry so it merges entry_bits when either the incoming
entry or the existing chunk’s entry point is HtmlPreload. In
test/bundler/html-import-manifest.test.ts:406-445, add the reverse-order case
with distinct identical-content CSS files and assert both HTML manifests
reference the same CSS chunk.
🤖 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.

Outside diff comments:
In `@src/bundler/linker_context/computeChunks.rs`:
- Around line 168-178: The deduplication path only merges entry bits when the
incoming chunk is an HTML preload, so reverse-order deduplication loses manifest
ownership. In src/bundler/linker_context/computeChunks.rs:168-178, update the
found_existing handling around css_chunk_entry so it merges entry_bits when
either the incoming entry or the existing chunk’s entry point is HtmlPreload. In
test/bundler/html-import-manifest.test.ts:406-445, add the reverse-order case
with distinct identical-content CSS files and assert both HTML manifests
reference the same CSS chunk.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 31b97712-3a48-4f83-9ac9-14969d7fdc21

📥 Commits

Reviewing files that changed from the base of the PR and between 3974cf5 and ea49600.

📒 Files selected for processing (2)
  • src/bundler/linker_context/computeChunks.rs
  • test/bundler/html-import-manifest.test.ts

@robobun

robobun commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

Re the outside-diff finding on computeChunks.rs:168-178 ("preload creates the deduplicated chunk first"): that ordering is not reachable. HtmlPreload entries are appended to linker_graph.entry_points after every user-specified and dynamic-import entry in LinkerGraph::load, so computeChunks always processes every page's JS-entry CSS chunk before any HtmlPreload entry runs. When an HtmlPreload entry content-hash-matches an existing chunk, found_existing is true and the for_each/set merge at :173-178 fires. The content-hash itself is over the CSS import order (source indices), so distinct files with identical bytes do not collide. The broader "non-preload dedup does not widen entry_bits" on the JS-entry-CSS path at :258 is pre-existing and independent of this PR.

@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 after four review iterations — the earlier findings (standalone-HTML href inlining, --production chunk-index mapping, HTMLImportManifest entry_bits on fresh and deduped chunks) are all addressed with tests. Deferring because this threads a new HtmlPreload entry-point kind through the linker's chunk computation, and the shared-with-extra-stylesheet semantics (preload gets its own output, bytes duplicated) is a user-facing bundler design call worth a maintainer sign-off.

What was reviewed:

  • computeChunks: content-hash keying, post-sort index remap, and the found_existing entry_bits OR — checked that HtmlPreload entries always run after page entries so the dedup ordering assumption holds.
  • generateCompileResultForHtmlChunk: the new branch guards compile_to_standalone_html and falls back to remove() in release when the chunk lookup is not CSS.
  • findImportedCSSFilesInJSOrder guard is scoped to Url+CSS so JS-imported CSS and rel=stylesheet (At) are unaffected.
  • Dev-server path is intentionally unchanged (pre-existing gap, noted in PR description).
Extended reasoning...

Overview

The PR changes how bun build handles <link rel="preload" as="style"> in HTML entry points: instead of folding the referenced CSS into the page's applied stylesheet bundle, it emits a standalone CSS chunk and rewrites the preload's href to point at it. This touches the HTML scanner tag table, BundleV2's reachable-file visitor, LinkerGraph::load (new entry_point::Kind::HtmlPreload), computeChunks (content-hash dedup + explicit chunk-index recording + entry_bits merge), findImportedCSSFilesInJSOrder (skip url-kind CSS), and generateCompileResultForHtmlChunk (rewrite href / drop under --compile). ~115 lines of Rust across 7 bundler files plus ~320 lines of new tests across three test files.

Security risks

None identified. The change is bundler output-shape logic; no new parsing of untrusted input, no path handling changes, no network/auth surface.

Level of scrutiny

High. computeChunks is core linker logic where chunk-index bookkeeping errors surface as wrong hrefs or missing manifest entries rather than crashes — exactly what the four prior review iterations caught (standalone-HTML raw-CSS-in-href, --production chunk-0 misroute, manifest omission on fresh chunks, manifest omission on deduped chunks). Each was fixed and covered by a targeted test. The remaining design decision — that a file referenced by both preload and stylesheet alongside other stylesheets ships its bytes twice — is pinned as intentional by html/preload-as-style-shared-with-extra-stylesheet, and the rationale (preserve source-declared preload target for the onload swap pattern) is defensible, but it's a user-visible bundler semantics choice.

Other factors

  • All prior inline findings (mine and CodeRabbit's) are resolved; the dev-server gap is explicitly scoped out with a stated reason.
  • Test coverage is thorough for the build path: both tag orders × both --production states, @import/url() resolution, standalone --compile, and two HTML-import-manifest scenarios (fresh chunk and deduped chunk across pages).
  • I re-checked the post-sort remap: html_preload_css_chunk_indices is only remapped inside if css_chunks.count() > 0, which is guaranteed whenever an HtmlPreload entry exists. The explicit entry_point_chunk_indices write after the main loop correctly covers the deduped case where the chunk's own entry_point.source_index() is the HTML page rather than the CSS file.
  • Not approving because this introduces a new entry-point kind and chunk-dedup path in the linker — the kind of change REVIEW.md flags for maintainer agreement ("new cross-cutting abstractions need maintainer agreement"), and the four-iteration history shows the interaction surface is subtle.

@robobun

robobun commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator Author

CI build 82951: 193/197 jobs passed. The only hard failure is test/js/node/test/parallel/test-worker-message-port-transfer-terminate.js SIGABRT on the debian x64-asan lane (JSC ExceptionScope::assertNoException()), which is unrelated to this bundler CSS change and has been reported for main-break triage. The remaining annotations (webview-chrome, no-orphans, complex-workspace, 20144) are flakes that passed on retry. All eleven new tests in bundler_html.test.ts, standalone.test.ts, and html-import-manifest.test.ts pass on every lane.

@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-26, it conflicts with main, and its last CI run failed. 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.

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