From 6b27adb857de803eaf2e8c64fca0f5c50f7fa01c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 16 Aug 2026 00:15:01 +0000 Subject: [PATCH 1/8] bundler: print the CSS of an HTML entry point in a server build with browser targets A --target=bun or --target=node build that contains an HTML file (imported from server code, or passed as an entry point) parses and minifies the stylesheets that HTML links with the client transpiler, so they are minified for the default browser targets. The linker then printed them with the build-wide target, which maps to the runtime CSS targets, so the transforms that happen at print time (compiling nesting, lowering media range syntax, rewriting light-dark() references) were skipped and the light-dark() polyfill was emitted half-way: definitions injected at minify time, references left as written. Pick the print targets per CSS chunk instead: a chunk whose entry point was parsed for the browser is printed with browser targets, every other chunk keeps the build's target as before. All four places the linker prints CSS (the stylesheets themselves, preserved external imports, the data: URL wrapper for nested external import conditions, and bare layer statements) go through the same helper. --- src/bundler/LinkerContext.rs | 24 ++++ .../generateCompileResultForCssChunk.rs | 10 +- .../linker_context/prepareCssAstsForChunk.rs | 5 +- test/bundler/bundler_html.test.ts | 136 +++++++++++++++++- 4 files changed, 168 insertions(+), 7 deletions(-) diff --git a/src/bundler/LinkerContext.rs b/src/bundler/LinkerContext.rs index bc47073ee17d..a4f552df448f 100644 --- a/src/bundler/LinkerContext.rs +++ b/src/bundler/LinkerContext.rs @@ -339,6 +339,30 @@ impl<'a> LinkerContext<'a> { && record.source_index.get() != source_index } + /// The targets to print a CSS chunk with. These must be the targets its + /// stylesheets were minified with (`ParseTask`): nesting, media range syntax + /// and `light-dark()` references are lowered at print time, and the + /// `light-dark()` polyfill is only complete when both halves agree. + /// + /// The stylesheets were minified by the transpiler of the graph the chunk's + /// entry point was parsed in. In a server build, an HTML entry point (passed + /// directly or imported from server code) and everything it links go + /// through the client transpiler, so the chunk is printed for browsers; + /// every other entry point's graph uses the build's own target. The entry + /// point's AST target is only trusted for `Browser`: a `#!/usr/bin/env bun` + /// hashbang marks the entry of a browser build `Bun`, and the separate SSR + /// graph marks its files `ServerComponentsSsr`, while the stylesheets of + /// both were still minified with the build's target. + pub(crate) fn css_targets_for_chunk(&self, chunk: &Chunk) -> crate::bun_css::Targets { + let entry_target = self.graph.ast.items_target()[chunk.entry_point.source_index() as usize]; + let target = if entry_target == Target::Browser { + Target::Browser + } else { + self.options.target + }; + crate::bun_css::Targets::for_bundler_target(target) + } + /// Note: this should call a `MimallocArena` debug hook /// (`helpCatchMemoryIssues`), but `Graph.heap` is currently /// `bun_alloc::Arena = bumpalo::Bump`, which has no such hook, so this is a diff --git a/src/bundler/linker_context/generateCompileResultForCssChunk.rs b/src/bundler/linker_context/generateCompileResultForCssChunk.rs index 7e1a52100a4f..6821f606f7af 100644 --- a/src/bundler/linker_context/generateCompileResultForCssChunk.rs +++ b/src/bundler/linker_context/generateCompileResultForCssChunk.rs @@ -5,7 +5,7 @@ use bun_ast::ImportRecord; use bun_collections::VecExt; use bun_threading::thread_pool as ThreadPoolLib; -use crate::bun_css::{BundlerStyleSheet, ImportInfo, LocalsResultsMap, PrinterOptions, Targets}; +use crate::bun_css::{BundlerStyleSheet, ImportInfo, LocalsResultsMap, PrinterOptions}; use crate::chunk::{Content, CssImportOrderKind}; use crate::linker_context_mod::LinkerContext; @@ -103,12 +103,14 @@ fn generate_compile_result_for_css_chunk_impl( ) }; + let targets = c.css_targets_for_chunk(chunk); + match &css_import.kind { CssImportOrderKind::Layers(_) => { let printer_options = PrinterOptions { // TODO: make this more configurable minify: c.options.minify_whitespace, - targets: Targets::for_bundler_target(c.options.target), + targets, ..Default::default() }; match css.to_css_with_writer( @@ -151,7 +153,7 @@ fn generate_compile_result_for_css_chunk_impl( let printer_options = PrinterOptions { // TODO: make this more configurable minify: c.options.minify_whitespace, - targets: Targets::for_bundler_target(c.options.target), + targets, ..Default::default() }; match css.to_css_with_writer( @@ -184,7 +186,7 @@ fn generate_compile_result_for_css_chunk_impl( } CssImportOrderKind::SourceIndex(idx) => { let printer_options = PrinterOptions { - targets: Targets::for_bundler_target(c.options.target), + targets, // TODO: make this more configurable minify: c.options.minify_whitespace || c.options.minify_syntax diff --git a/src/bundler/linker_context/prepareCssAstsForChunk.rs b/src/bundler/linker_context/prepareCssAstsForChunk.rs index 1d751736b867..fa0059d1c87f 100644 --- a/src/bundler/linker_context/prepareCssAstsForChunk.rs +++ b/src/bundler/linker_context/prepareCssAstsForChunk.rs @@ -10,7 +10,7 @@ use crate::bun_css::css_parser::{ BundlerSupportsRule, ImportRule, LayerName, LayerStatementRule, Location, ParserOptions, SmallList, }; -use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions, Targets}; +use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions}; use crate::bun_fs::Path; use bun_ast::{ImportKind, ImportRecord, ImportRecordFlags, ImportRecordTag, Index as AstIndex}; use bun_ast::{Loc, Range}; @@ -84,6 +84,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & // across the log write below (split borrow). let parse_graph = unsafe { &*c.parse_graph }; let asts = c.graph.ast.items_css(); + let targets = c.css_targets_for_chunk(chunk); // Prepare CSS asts // Remove duplicate rules across files. This must be done in serial, not @@ -221,7 +222,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & }); let printer_options = PrinterOptions { - targets: Targets::for_bundler_target(c.options.target), + targets, // TODO: make this more configurable minify: c.options.minify_whitespace || c.options.minify_syntax diff --git a/test/bundler/bundler_html.test.ts b/test/bundler/bundler_html.test.ts index 12e5f19398a3..7bebb04269cb 100644 --- a/test/bundler/bundler_html.test.ts +++ b/test/bundler/bundler_html.test.ts @@ -1,5 +1,5 @@ import { describe, expect } from "bun:test"; -import { itBundled } from "./expectBundled"; +import { type BundlerTestBundleAPI, itBundled } from "./expectBundled"; describe("bundler", () => { // Basic test for bundling HTML with JS and CSS @@ -1011,4 +1011,138 @@ body { expect(htmlContent).toMatch(/href=".*\.webmanifest"/); }, }); + + // A stylesheet linked from an HTML file is built for the browser even when the + // build itself targets bun or node (the HTML is imported from server code for + // Bun.serve, or passed to a server build as an entry point). Minifying already + // used the default browser targets; printing has to use them too, since + // nesting, media range syntax and light-dark() are only lowered while + // printing. This fixture reaches every place the linker prints CSS: + // + // - the stylesheet itself (nesting, the @media range, light-dark() references) + // - the preserved external @import, whose media condition is printed on its own + // - the external @import behind a conditional internal @import, which is + // printed into a data: URL stylesheet while the chunk is prepared + // - the bare "@layer foo;" left behind by the deduplicated layer import, + // printed together with its wrapping media condition + const browserTargetFiles = { + "/index.html": ` + + + + + + +`, + "/styles.css": ` +@import "https://example.com/external.css" screen and (width >= 500px); +@import "./dup.css" layer(foo) (width >= 600px); +@import "./other.css"; +@import "./dup.css" layer(foo) (width >= 600px); +@import "./nested.css" (width >= 700px); +:root { + color-scheme: light dark; +} +.a { + color: light-dark(white, black); + .b { + color: blue; + } +} +@media (width >= 800px) { + .c { + color: green; + } +}`, + "/dup.css": ".dup { color: red; }", + "/other.css": ".other { color: red; }", + "/nested.css": ` +@import "https://example.com/nested.css" (width >= 900px); +.nested { color: red; }`, + }; + + function expectPrintedForBrowsers(css: string) { + expect(css).toContain(".a .b {"); + expect(css).toContain("var(--buncss-light, #fff) var(--buncss-dark, #000)"); + expect(css).not.toContain("light-dark("); + expect(css).toContain("@media (min-width: 800px)"); + expect(css).toContain('@import "https://example.com/external.css" screen and (min-width: 500px);'); + expect(css).toContain( + '@import "data:text/css,@import \\"https://example.com/nested.css\\" (min-width: 900px);" (min-width: 700px);', + ); + expect(css).toContain("@media (min-width: 600px) {\n @layer foo;\n}"); + expect(css).not.toContain(">="); + } + + function readLinkedStylesheet(api: BundlerTestBundleAPI, htmlFile: string) { + const href = api.readFile(htmlFile).match(/href="(.*?\.css)"/)?.[1]; + if (!href) throw new Error(`No stylesheet is linked from ${htmlFile}`); + return api.readFile("out/" + href); + } + + // Reference: what a browser build prints. The server builds below must print + // the same stylesheet the same way. + itBundled("html/css-browser-targets/browser-build", { + outdir: "out/", + files: browserTargetFiles, + entryPoints: ["/index.html"], + onAfterBundle(api) { + expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); + }, + }); + + for (const target of ["bun", "node"] as const) { + itBundled(`html/css-browser-targets/imported-from-${target}-build`, { + outdir: "out/", + target, + files: { + ...browserTargetFiles, + "/server.ts": ` +import html from "./index.html"; +console.log(html);`, + }, + entryPoints: ["/server.ts"], + onAfterBundle(api) { + expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); + }, + }); + } + + itBundled("html/css-browser-targets/html-entry-point-of-bun-build", { + outdir: "out/", + target: "bun", + files: browserTargetFiles, + entryPoints: ["/index.html"], + onAfterBundle(api) { + expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); + }, + }); + + // The same stylesheet imported by the server code itself is part of the bun + // build, not of the browser one: it keeps the build's own (runtime) CSS + // targets for both minifying and printing. + itBundled("html/css-browser-targets/imported-by-server-code-keeps-runtime-targets", { + outdir: "out/", + target: "bun", + files: { + ...browserTargetFiles, + "/server.ts": ` +import "./styles.css"; +console.log("server");`, + }, + entryPoints: ["/server.ts"], + onAfterBundle(api) { + const css = api.readFile("out/server.css"); + expect(css).toContain("& .b {"); + expect(css).toContain("color: light-dark(#fff, #000);"); + expect(css).not.toContain("--buncss-light"); + expect(css).toContain("@media (width >= 800px)"); + expect(css).toContain('@import "https://example.com/external.css" screen and (width >= 500px);'); + expect(css).toContain( + '@import "data:text/css,@import \\"https://example.com/nested.css\\" (width >= 900px);" (width >= 700px);', + ); + expect(css).toContain("@media (width >= 600px) {\n @layer foo;\n}"); + expect(css).not.toContain("min-width"); + }, + }); }); From 69bcf66e67fdb0a6313fe3a9a918c4c894eb9290 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 16 Aug 2026 06:11:16 +0000 Subject: [PATCH 2/8] bundler: print each stylesheet with the targets it was minified for Record the minify targets on the StyleSheet (and on the empty sheet the bundler creates for an empty CSS file without minifying it) and print every stylesheet with the targets it carries; the layer statements, external imports and data: URL wrappers synthesized for a chunk take the targets of the chunk's stylesheets. This replaces deriving the print targets from the chunk's entry point in the linker, so print and minify agree by construction rather than by re-deriving the transpiler choice. The shared-stylesheet test now checks that each emitted copy is printed for the targets it was minified for instead of pinning the server build's targets, the fixture also covers an empty imported stylesheet, and a dev server test covers stylesheets linked from HTML there, whose printing changes in the same way. --- src/bundler/LinkerContext.rs | 24 ------- src/bundler/ParseTask.rs | 13 ++-- .../generateCompileResultForCssChunk.rs | 8 +-- .../linker_context/prepareCssAstsForChunk.rs | 28 ++++++++- src/css/css_parser.rs | 10 +++ test/bake/dev/css.test.ts | 37 +++++++++++ test/bundler/bundler_html.test.ts | 62 +++++++++++++------ 7 files changed, 126 insertions(+), 56 deletions(-) diff --git a/src/bundler/LinkerContext.rs b/src/bundler/LinkerContext.rs index a4f552df448f..bc47073ee17d 100644 --- a/src/bundler/LinkerContext.rs +++ b/src/bundler/LinkerContext.rs @@ -339,30 +339,6 @@ impl<'a> LinkerContext<'a> { && record.source_index.get() != source_index } - /// The targets to print a CSS chunk with. These must be the targets its - /// stylesheets were minified with (`ParseTask`): nesting, media range syntax - /// and `light-dark()` references are lowered at print time, and the - /// `light-dark()` polyfill is only complete when both halves agree. - /// - /// The stylesheets were minified by the transpiler of the graph the chunk's - /// entry point was parsed in. In a server build, an HTML entry point (passed - /// directly or imported from server code) and everything it links go - /// through the client transpiler, so the chunk is printed for browsers; - /// every other entry point's graph uses the build's own target. The entry - /// point's AST target is only trusted for `Browser`: a `#!/usr/bin/env bun` - /// hashbang marks the entry of a browser build `Bun`, and the separate SSR - /// graph marks its files `ServerComponentsSsr`, while the stylesheets of - /// both were still minified with the build's target. - pub(crate) fn css_targets_for_chunk(&self, chunk: &Chunk) -> crate::bun_css::Targets { - let entry_target = self.graph.ast.items_target()[chunk.entry_point.source_index() as usize]; - let target = if entry_target == Target::Browser { - Target::Browser - } else { - self.options.target - }; - crate::bun_css::Targets::for_bundler_target(target) - } - /// Note: this should call a `MimallocArena` debug hook /// (`helpCatchMemoryIssues`), but `Graph.heap` is currently /// `bun_alloc::Arena = bumpalo::Bump`, which has no such hook, so this is a diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index a4b7cc2acbaf..08c91a934fb9 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -604,7 +604,7 @@ pub mod parse_worker { // (`get_ast`, `run_with_source_code`) may also hold a raw pointer to // `(*transpiler).resolver`; materializing `&mut Transpiler` here would assert // exclusive access to the whole struct and invalidate that sibling pointer. - // We only touch the disjoint `options.define` field. + // We only touch the disjoint `options` field. fn get_empty_css_ast( log: &mut Log, transpiler: *mut Transpiler, @@ -615,14 +615,19 @@ pub mod parse_worker { let root = Expr::init(E::Object::default(), Loc { start: 0 }); // SAFETY: `transpiler` is a live worker-owned `*mut Transpiler`; `options` // is disjoint from any other field the caller may hold a pointer to. + let target = unsafe { (*transpiler).options.target }; + // SAFETY: see above. let define = unsafe { &mut (*transpiler).options.define }; let mut ast = JSAst::init( js_parser::new_lazy_export_ast(bump, define, opts, log, root, source, b"")? .ok_or(AnyError::ParserError)?, ); - ast.css = Some(crate::bundled_ast::CssAstRef::from_bump( - bump.alloc(bun_css::BundlerStyleSheet::empty()), - )); + let mut css = bun_css::BundlerStyleSheet::empty(); + // There is nothing to minify, but the linker still prints this sheet + // (wrapped in the conditions of the `@import` that reached it) with the + // sheet's targets, so record the ones `minify` would have used. + css.targets = bun_css::Targets::for_bundler_target(target); + ast.css = Some(crate::bundled_ast::CssAstRef::from_bump(bump.alloc(css))); Ok(ast) } diff --git a/src/bundler/linker_context/generateCompileResultForCssChunk.rs b/src/bundler/linker_context/generateCompileResultForCssChunk.rs index 6821f606f7af..62d34b2a277e 100644 --- a/src/bundler/linker_context/generateCompileResultForCssChunk.rs +++ b/src/bundler/linker_context/generateCompileResultForCssChunk.rs @@ -103,14 +103,12 @@ fn generate_compile_result_for_css_chunk_impl( ) }; - let targets = c.css_targets_for_chunk(chunk); - match &css_import.kind { CssImportOrderKind::Layers(_) => { let printer_options = PrinterOptions { // TODO: make this more configurable minify: c.options.minify_whitespace, - targets, + targets: css.targets, ..Default::default() }; match css.to_css_with_writer( @@ -153,7 +151,7 @@ fn generate_compile_result_for_css_chunk_impl( let printer_options = PrinterOptions { // TODO: make this more configurable minify: c.options.minify_whitespace, - targets, + targets: css.targets, ..Default::default() }; match css.to_css_with_writer( @@ -186,7 +184,7 @@ fn generate_compile_result_for_css_chunk_impl( } CssImportOrderKind::SourceIndex(idx) => { let printer_options = PrinterOptions { - targets, + targets: css.targets, // TODO: make this more configurable minify: c.options.minify_whitespace || c.options.minify_syntax diff --git a/src/bundler/linker_context/prepareCssAstsForChunk.rs b/src/bundler/linker_context/prepareCssAstsForChunk.rs index fa0059d1c87f..fec7215a1752 100644 --- a/src/bundler/linker_context/prepareCssAstsForChunk.rs +++ b/src/bundler/linker_context/prepareCssAstsForChunk.rs @@ -10,7 +10,7 @@ use crate::bun_css::css_parser::{ BundlerSupportsRule, ImportRule, LayerName, LayerStatementRule, Location, ParserOptions, SmallList, }; -use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions}; +use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions, Targets}; use crate::bun_fs::Path; use bun_ast::{ImportKind, ImportRecord, ImportRecordFlags, ImportRecordTag, Index as AstIndex}; use bun_ast::{Loc, Range}; @@ -18,7 +18,7 @@ use bun_collections::VecExt; use bun_core::strings; use bun_resolver::DataURL; -use crate::chunk::{Content, CssImportOrderKind}; +use crate::chunk::{Content, CssImportOrder, CssImportOrderKind}; // Raw pointers rather than `&mut` / `&` so that // (a) the container_of `container_of` recovery of `*mut BundleV2` from @@ -84,7 +84,6 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & // across the log write below (split borrow). let parse_graph = unsafe { &*c.parse_graph }; let asts = c.graph.ast.items_css(); - let targets = c.css_targets_for_chunk(chunk); // Prepare CSS asts // Remove duplicate rules across files. This must be done in serial, not @@ -98,6 +97,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & let Content::Css(css_chunk) = &mut chunk.content else { unreachable!() }; + let targets = chunk_targets(&css_chunk.imports_in_chunk_in_order, asts); let mut i: usize = css_chunk.imports_in_chunk_in_order.len() as usize; while i != 0 { i -= 1; @@ -150,6 +150,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & source_map_urls: Default::default(), license_comments: Default::default(), options: ParserOptions::default(None), + targets, composes: Default::default(), ..BundlerStyleSheet::empty() }; @@ -325,6 +326,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & source_map_urls: Default::default(), license_comments: Default::default(), options: ParserOptions::default(None), + targets, composes: Default::default(), ..BundlerStyleSheet::empty() }; @@ -434,6 +436,26 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & } } +/// The targets for the style sheets this pass synthesizes for a chunk (layer +/// statements, external `@import`s and their `data:` URL wrappers). Every +/// stylesheet in a chunk comes from the same module graph and so carries the +/// same `StyleSheet::targets`; the first one speaks for the chunk. A chunk +/// always contains at least one stylesheet, so the default is never reached. +fn chunk_targets(order: &[CssImportOrder], asts: &[crate::bundled_ast::CssCol]) -> Targets { + order + .iter() + .find_map(|entry| match entry.kind { + CssImportOrderKind::SourceIndex(idx) => Some( + asts[idx.get() as usize] + .as_deref() + .expect("css ast present") + .targets, + ), + _ => None, + }) + .unwrap_or_default() +} + /// Builds a `BundlerCssRuleList` whose backing storage is arena-owned. /// /// `CssRuleList::v` is a global `Vec`, but every rule slab built here must be diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index b2cfade3f66e..a2a0d8ee33d7 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2341,6 +2341,13 @@ pub struct StyleSheet { pub license_comments: Vec<&'static [u8]>, // TODO: lifetime — arena pub options: ParserOptions<'static>, // TODO: lifetime pub layer_names: Vec, + /// The targets the style sheet is compiled for. [`StyleSheet::minify`] + /// records the targets it ran with; until then this is `Targets::default()`. + /// Printing finishes what minifying started for these targets (compiling + /// nesting, lowering media ranges, rewriting the `light-dark()` references + /// whose fallback variables `minify` declared), so the sheet must be printed + /// with the same targets. + pub targets: Targets, /// Used when css modules is enabled. Maps `local name string` -> `Ref`. pub local_scope: LocalScope, @@ -2360,6 +2367,7 @@ impl StyleSheet { license_comments: Vec::new(), options: ParserOptions::default(None), layer_names: Vec::new(), + targets: Targets::default(), local_scope: LocalScope::default(), local_properties: LocalPropertyUsage::default(), composes: ComposesMap::default(), @@ -2386,6 +2394,7 @@ mod stylesheet_impl { where AtRule: for<'b> generic::DeepClone<'b>, { + self.targets = options.targets; let ctx = PropertyHandlerContext::new(arena, &options.targets, &options.unused_symbols); let mut handler = DeclarationHandler::new(arena); let mut important_handler = DeclarationHandler::new(arena); @@ -2672,6 +2681,7 @@ mod stylesheet_impl { license_comments, options, layer_names, + targets: Targets::default(), local_scope: parser_extra.local_scope, local_properties, composes, diff --git a/test/bake/dev/css.test.ts b/test/bake/dev/css.test.ts index 18d665708976..71a2b959c8f5 100644 --- a/test/bake/dev/css.test.ts +++ b/test/bake/dev/css.test.ts @@ -692,6 +692,43 @@ devTest("css import before create project relative", { }, }); +devTest("css linked from html is printed for the browser targets it was minified for", { + files: { + "index.html": emptyHtmlFile({ + styles: ["styles.css"], + body: `
hello
`, + }), + "styles.css": ` + :root { + color-scheme: light dark; + } + .a { + color: light-dark(white, black); + .b { + color: blue; + } + } + @media (width >= 600px) { + .a { + color: green; + } + } + `, + }, + async test(dev) { + const html = await (await dev.fetch("/")).text(); + const href = html.match(/]*href="([^"]+)"/)?.[1]; + if (!href) throw new Error("no stylesheet is linked from the served html: " + html); + const css = await (await dev.fetch(href)).text(); + expect(css).toContain(".a .b {"); + expect(css).toContain("--buncss-light: initial;"); + expect(css).toContain("var(--buncss-light, #fff) var(--buncss-dark, #000)"); + expect(css).not.toContain("light-dark("); + expect(css).toContain("@media (min-width: 600px)"); + expect(css).not.toContain(">="); + }, +}); + function extractCssUrl(backgroundImage: string): string { const url = backgroundImage.match(/url\((['"])(.*?)\1\)/); if (!url) { diff --git a/test/bundler/bundler_html.test.ts b/test/bundler/bundler_html.test.ts index 7bebb04269cb..a744cc2610c5 100644 --- a/test/bundler/bundler_html.test.ts +++ b/test/bundler/bundler_html.test.ts @@ -1014,10 +1014,10 @@ body { // A stylesheet linked from an HTML file is built for the browser even when the // build itself targets bun or node (the HTML is imported from server code for - // Bun.serve, or passed to a server build as an entry point). Minifying already - // used the default browser targets; printing has to use them too, since - // nesting, media range syntax and light-dark() are only lowered while - // printing. This fixture reaches every place the linker prints CSS: + // Bun.serve, or passed to a server build as an entry point), so it is minified + // for the default browser targets. It has to be printed for the same targets: + // nesting, media range syntax and light-dark() references are only lowered + // while printing. This fixture reaches every place the linker prints CSS: // // - the stylesheet itself (nesting, the @media range, light-dark() references) // - the preserved external @import, whose media condition is printed on its own @@ -1025,6 +1025,8 @@ body { // printed into a data: URL stylesheet while the chunk is prepared // - the bare "@layer foo;" left behind by the deduplicated layer import, // printed together with its wrapping media condition + // - an empty stylesheet (which the bundler never minifies), whose import + // conditions are still printed around it as "@layer bar;" const browserTargetFiles = { "/index.html": ` @@ -1040,6 +1042,7 @@ body { @import "./other.css"; @import "./dup.css" layer(foo) (width >= 600px); @import "./nested.css" (width >= 700px); +@import "./empty.css" layer(bar) (width >= 1000px); :root { color-scheme: light dark; } @@ -1059,6 +1062,7 @@ body { "/nested.css": ` @import "https://example.com/nested.css" (width >= 900px); .nested { color: red; }`, + "/empty.css": "", }; function expectPrintedForBrowsers(css: string) { @@ -1071,9 +1075,25 @@ body { '@import "data:text/css,@import \\"https://example.com/nested.css\\" (min-width: 900px);" (min-width: 700px);', ); expect(css).toContain("@media (min-width: 600px) {\n @layer foo;\n}"); + expect(css).toContain("@media (min-width: 1000px) {\n @layer bar;\n}"); expect(css).not.toContain(">="); } + // The same fixture printed for targets that support everything it uses. + function expectPrintedAsWritten(css: string) { + expect(css).toContain("& .b {"); + expect(css).toContain("color: light-dark(#fff, #000);"); + expect(css).not.toContain("--buncss-"); + expect(css).toContain("@media (width >= 800px)"); + expect(css).toContain('@import "https://example.com/external.css" screen and (width >= 500px);'); + expect(css).toContain( + '@import "data:text/css,@import \\"https://example.com/nested.css\\" (width >= 900px);" (width >= 700px);', + ); + expect(css).toContain("@media (width >= 600px) {\n @layer foo;\n}"); + expect(css).toContain("@media (width >= 1000px) {\n @layer bar;\n}"); + expect(css).not.toContain("min-width"); + } + function readLinkedStylesheet(api: BundlerTestBundleAPI, htmlFile: string) { const href = api.readFile(htmlFile).match(/href="(.*?\.css)"/)?.[1]; if (!href) throw new Error(`No stylesheet is linked from ${htmlFile}`); @@ -1118,31 +1138,33 @@ console.log(html);`, }, }); - // The same stylesheet imported by the server code itself is part of the bun - // build, not of the browser one: it keeps the build's own (runtime) CSS - // targets for both minifying and printing. - itBundled("html/css-browser-targets/imported-by-server-code-keeps-runtime-targets", { + // When the server code also imports the stylesheet itself, that copy belongs to + // the server build and is minified for whatever targets the build uses for its + // own target. Which targets those are is not pinned here; what matters is that + // each of the two emitted copies is printed for the targets it was minified + // for. The light-dark() polyfill shows which half ran: minifying declares the + // --buncss-* variables and printing rewrites the references, and either half + // on its own is broken. + itBundled("html/css-browser-targets/stylesheet-shared-with-server-code", { outdir: "out/", target: "bun", files: { ...browserTargetFiles, "/server.ts": ` +import html from "./index.html"; import "./styles.css"; -console.log("server");`, +console.log(html);`, }, entryPoints: ["/server.ts"], onAfterBundle(api) { - const css = api.readFile("out/server.css"); - expect(css).toContain("& .b {"); - expect(css).toContain("color: light-dark(#fff, #000);"); - expect(css).not.toContain("--buncss-light"); - expect(css).toContain("@media (width >= 800px)"); - expect(css).toContain('@import "https://example.com/external.css" screen and (width >= 500px);'); - expect(css).toContain( - '@import "data:text/css,@import \\"https://example.com/nested.css\\" (width >= 900px);" (width >= 700px);', - ); - expect(css).toContain("@media (width >= 600px) {\n @layer foo;\n}"); - expect(css).not.toContain("min-width"); + expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); + + const serverCopy = api.readFile("out/server.css"); + if (serverCopy.includes("--buncss-light: initial;")) { + expectPrintedForBrowsers(serverCopy); + } else { + expectPrintedAsWritten(serverCopy); + } }, }); }); From a8542a09265fece69892e34deea8f76862b5395e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 16 Aug 2026 06:16:12 +0000 Subject: [PATCH 3/8] bundler: shorten the comments on the recorded CSS targets --- src/bundler/ParseTask.rs | 4 +--- src/bundler/linker_context/prepareCssAstsForChunk.rs | 6 +----- src/css/css_parser.rs | 7 +------ 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 08c91a934fb9..18f422024f35 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -623,9 +623,7 @@ pub mod parse_worker { .ok_or(AnyError::ParserError)?, ); let mut css = bun_css::BundlerStyleSheet::empty(); - // There is nothing to minify, but the linker still prints this sheet - // (wrapped in the conditions of the `@import` that reached it) with the - // sheet's targets, so record the ones `minify` would have used. + // Never minified, but its `@import` conditions are still printed with the sheet's targets. css.targets = bun_css::Targets::for_bundler_target(target); ast.css = Some(crate::bundled_ast::CssAstRef::from_bump(bump.alloc(css))); Ok(ast) diff --git a/src/bundler/linker_context/prepareCssAstsForChunk.rs b/src/bundler/linker_context/prepareCssAstsForChunk.rs index fec7215a1752..9418551992a0 100644 --- a/src/bundler/linker_context/prepareCssAstsForChunk.rs +++ b/src/bundler/linker_context/prepareCssAstsForChunk.rs @@ -436,11 +436,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & } } -/// The targets for the style sheets this pass synthesizes for a chunk (layer -/// statements, external `@import`s and their `data:` URL wrappers). Every -/// stylesheet in a chunk comes from the same module graph and so carries the -/// same `StyleSheet::targets`; the first one speaks for the chunk. A chunk -/// always contains at least one stylesheet, so the default is never reached. +/// All of a chunk's stylesheets come from one module graph, so the first one's targets are the chunk's. fn chunk_targets(order: &[CssImportOrder], asts: &[crate::bundled_ast::CssCol]) -> Targets { order .iter() diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index a2a0d8ee33d7..20126cae6edd 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2341,12 +2341,7 @@ pub struct StyleSheet { pub license_comments: Vec<&'static [u8]>, // TODO: lifetime — arena pub options: ParserOptions<'static>, // TODO: lifetime pub layer_names: Vec, - /// The targets the style sheet is compiled for. [`StyleSheet::minify`] - /// records the targets it ran with; until then this is `Targets::default()`. - /// Printing finishes what minifying started for these targets (compiling - /// nesting, lowering media ranges, rewriting the `light-dark()` references - /// whose fallback variables `minify` declared), so the sheet must be printed - /// with the same targets. + /// Recorded by [`StyleSheet::minify`]; printing must lower for these same targets. pub targets: Targets, /// Used when css modules is enabled. Maps `local name string` -> `Ref`. From 08874386361d56816a2605f1bbb9c8f765895342 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:00:07 +0000 Subject: [PATCH 4/8] test: show the CSS targets with nesting, media ranges and a vendor prefix The default browser targets keep light-dark() as written since #47025, so the polyfill no longer tells a stylesheet built for browsers from one built for the runtime. Nesting and media range syntax show the targets a stylesheet was printed for. The :-webkit-full-screen copy of a :fullscreen rule shows the targets it was minified for. The server copy of a shared stylesheet is now asserted without a condition: the server build minifies and prints it for the runtime. --- test/bake/dev/css.test.ts | 18 +++++----- test/bundler/bundler_html.test.ts | 55 +++++++++++++------------------ 2 files changed, 32 insertions(+), 41 deletions(-) diff --git a/test/bake/dev/css.test.ts b/test/bake/dev/css.test.ts index c32358faaf88..a67ca2dcc360 100644 --- a/test/bake/dev/css.test.ts +++ b/test/bake/dev/css.test.ts @@ -818,15 +818,15 @@ devTest("css linked from html is printed for the browser targets it was minified body: `
hello
`, }), "styles.css": ` - :root { - color-scheme: light dark; - } .a { - color: light-dark(white, black); + color: red; .b { color: blue; } } + .d:fullscreen { + color: red; + } @media (width >= 600px) { .a { color: green; @@ -835,14 +835,14 @@ devTest("css linked from html is printed for the browser targets it was minified `, }, async test(dev) { - const html = await (await dev.fetch("/")).text(); + const html = await dev.fetch("/").text(); const href = html.match(/]*href="([^"]+)"/)?.[1]; if (!href) throw new Error("no stylesheet is linked from the served html: " + html); - const css = await (await dev.fetch(href)).text(); + const css = await dev.fetch(href).text(); + // Minifying for browsers adds the prefixed copy of the rule. + expect(css).toContain(".d:-webkit-full-screen {"); + // Printing for browsers lowers nesting and the media range. expect(css).toContain(".a .b {"); - expect(css).toContain("--buncss-light: initial;"); - expect(css).toContain("var(--buncss-light, #fff) var(--buncss-dark, #000)"); - expect(css).not.toContain("light-dark("); expect(css).toContain("@media (min-width: 600px)"); expect(css).not.toContain(">="); }, diff --git a/test/bundler/bundler_html.test.ts b/test/bundler/bundler_html.test.ts index 9f5d86dcc83a..fef01be567aa 100644 --- a/test/bundler/bundler_html.test.ts +++ b/test/bundler/bundler_html.test.ts @@ -1123,10 +1123,10 @@ body { // build itself targets bun or node (the HTML is imported from server code for // Bun.serve, or passed to a server build as an entry point), so it is minified // for the default browser targets. It has to be printed for the same targets: - // nesting, media range syntax and light-dark() references are only lowered - // while printing. This fixture reaches every place the linker prints CSS: + // nesting and media range syntax are only lowered while printing. This fixture + // reaches every place the linker prints CSS: // - // - the stylesheet itself (nesting, the @media range, light-dark() references) + // - the stylesheet itself (nesting, the @media range) // - the preserved external @import, whose media condition is printed on its own // - the external @import behind a conditional internal @import, which is // printed into a data: URL stylesheet while the chunk is prepared @@ -1134,6 +1134,9 @@ body { // printed together with its wrapping media condition // - an empty stylesheet (which the bundler never minifies), whose import // conditions are still printed around it as "@layer bar;" + // + // ".d:fullscreen" shows which targets the stylesheet was minified for: only + // minifying for browsers adds the ":-webkit-full-screen" copy of the rule. const browserTargetFiles = { "/index.html": ` @@ -1150,15 +1153,15 @@ body { @import "./dup.css" layer(foo) (width >= 600px); @import "./nested.css" (width >= 700px); @import "./empty.css" layer(bar) (width >= 1000px); -:root { - color-scheme: light dark; -} .a { - color: light-dark(white, black); + color: red; .b { color: blue; } } +.d:fullscreen { + color: red; +} @media (width >= 800px) { .c { color: green; @@ -1172,10 +1175,9 @@ body { "/empty.css": "", }; - function expectPrintedForBrowsers(css: string) { + function expectBuiltForBrowsers(css: string) { + expect(css).toContain(".d:-webkit-full-screen {"); expect(css).toContain(".a .b {"); - expect(css).toContain("var(--buncss-light, #fff) var(--buncss-dark, #000)"); - expect(css).not.toContain("light-dark("); expect(css).toContain("@media (min-width: 800px)"); expect(css).toContain('@import "https://example.com/external.css" screen and (min-width: 500px);'); expect(css).toContain( @@ -1186,11 +1188,10 @@ body { expect(css).not.toContain(">="); } - // The same fixture printed for targets that support everything it uses. - function expectPrintedAsWritten(css: string) { + // The same fixture minified and printed for targets that support everything it uses. + function expectBuiltForRuntime(css: string) { + expect(css).not.toContain("-webkit-"); expect(css).toContain("& .b {"); - expect(css).toContain("color: light-dark(#fff, #000);"); - expect(css).not.toContain("--buncss-"); expect(css).toContain("@media (width >= 800px)"); expect(css).toContain('@import "https://example.com/external.css" screen and (width >= 500px);'); expect(css).toContain( @@ -1214,7 +1215,7 @@ body { files: browserTargetFiles, entryPoints: ["/index.html"], onAfterBundle(api) { - expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); + expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); }, }); @@ -1230,7 +1231,7 @@ console.log(html);`, }, entryPoints: ["/server.ts"], onAfterBundle(api) { - expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); + expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); }, }); } @@ -1241,17 +1242,13 @@ console.log(html);`, files: browserTargetFiles, entryPoints: ["/index.html"], onAfterBundle(api) { - expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); + expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); }, }); - // When the server code also imports the stylesheet itself, that copy belongs to - // the server build and is minified for whatever targets the build uses for its - // own target. Which targets those are is not pinned here; what matters is that - // each of the two emitted copies is printed for the targets it was minified - // for. The light-dark() polyfill shows which half ran: minifying declares the - // --buncss-* variables and printing rewrites the references, and either half - // on its own is broken. + // When the server code also imports the stylesheet itself, that copy belongs + // to the server build, which minifies it for the runtime. Each of the two + // emitted copies is printed for the targets it was minified for. itBundled("html/css-browser-targets/stylesheet-shared-with-server-code", { outdir: "out/", target: "bun", @@ -1264,14 +1261,8 @@ console.log(html);`, }, entryPoints: ["/server.ts"], onAfterBundle(api) { - expectPrintedForBrowsers(readLinkedStylesheet(api, "out/index.html")); - - const serverCopy = api.readFile("out/server.css"); - if (serverCopy.includes("--buncss-light: initial;")) { - expectPrintedForBrowsers(serverCopy); - } else { - expectPrintedAsWritten(serverCopy); - } + expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); + expectBuiltForRuntime(api.readFile("out/server.css")); }, }); }); From 1572b57ad09fa6c3428b168d1641ea5142807e00 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 28 Oct 2026 04:46:33 +0000 Subject: [PATCH 5/8] css: print a stylesheet with the targets StyleSheet::minify recorded StyleSheet::to_css_with_writer reads the record, and PrinterOptions has no targets field. A print call cannot name targets that differ from the ones minify lowered the sheet for. - The linker builds its @layer, external @import and data: URL sheets with StyleSheet::synthesized, which takes the targets of the chunk's root stylesheet. - A blank CSS file goes through the same parse and minify arm as every other CSS file. get_empty_css_ast is removed. - bun build --no-bundle minifies a stylesheet with the targets of the build target. It passed none, and printed with the build target's. --- src/bundler/ParseTask.rs | 42 ++----- .../findImportedFilesInCSSOrder.rs | 3 +- .../generateCompileResultForCssChunk.rs | 3 - .../linker_context/prepareCssAstsForChunk.rs | 108 ++++++++---------- src/bundler/transpiler.rs | 7 +- src/css/css_parser.rs | 16 ++- src/css/printer.rs | 9 +- src/css_jsc/color_js.rs | 1 + src/css_jsc/css_internals.rs | 6 +- test/bake/dev/bundle.test.ts | 11 +- test/bake/dev/css.test.ts | 44 +++++-- test/bundler/bundler_html.test.ts | 93 +++++++++++---- test/js/bun/css/css-loader.test.ts | 91 +++++++++++++++ 13 files changed, 282 insertions(+), 152 deletions(-) diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 195109ae9f35..8de514c0b728 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -665,38 +665,14 @@ pub mod parse_worker { } // ─────────────────────────────────────────────────────────────────────────── - // getEmptyCSSAST / getEmptyAST + // getEmptyAST // ─────────────────────────────────────────────────────────────────────────── // `transpiler: *mut Transpiler` stays raw. Callers // (`get_ast`, `run_with_source_code`) may also hold a raw pointer to // `(*transpiler).resolver`; materializing `&mut Transpiler` here would assert // exclusive access to the whole struct and invalidate that sibling pointer. - // We only touch the disjoint `options` field. - fn get_empty_css_ast( - log: &mut Log, - transpiler: *mut Transpiler, - opts: ParserOptions<'static>, - bump: &'static Bump, - source: &'static Source<'static>, - ) -> core::result::Result, AnyError> { - let root = Expr::init(E::Object::default(), Loc { start: 0 }); - // SAFETY: `transpiler` is a live worker-owned `*mut Transpiler`; `options` - // is disjoint from any other field the caller may hold a pointer to. - let target = unsafe { (*transpiler).options.target }; - // SAFETY: see above. - let define = unsafe { &mut (*transpiler).options.define }; - let mut ast = JSAst::init( - js_parser::new_lazy_export_ast(bump, define, opts, log, root, source, b"")? - .ok_or(AnyError::ParserError)?, - ); - let mut css = bun_css::BundlerStyleSheet::empty(); - // Never minified, but its `@import` conditions are still printed with the sheet's targets. - css.targets = bun_css::Targets::for_bundler_target(target); - ast.css = Some(crate::bundled_ast::CssAstRef::from_bump(bump.alloc(css))); - Ok(ast) - } - + // We only touch the disjoint `options.define` field. fn get_empty_ast( log: &mut Log, transpiler: *mut Transpiler, @@ -705,7 +681,8 @@ pub mod parse_worker { source: &'static Source<'static>, ) -> core::result::Result, AnyError> { let root = Expr::init(RootType::default(), Loc::EMPTY); - // SAFETY: see `get_empty_css_ast` — disjoint field of a live `*mut Transpiler`. + // SAFETY: `transpiler` is a live worker-owned `*mut Transpiler`; `options` + // is disjoint from any other field the caller may hold a pointer to. let define = unsafe { &mut (*transpiler).options.define }; Ok(JSAst::init( js_parser::new_lazy_export_ast(bump, define, opts, log, root, source, b"")? @@ -1289,7 +1266,12 @@ pub mod parse_worker { Loader::Css => { // make css ast let mut import_records = Vec::::default(); - let source_code = &source.contents; + // A blank file is an empty stylesheet. U+000B is blank to the bundler, not to the CSS tokenizer. + let source_code: &[u8] = if strings::is_all_whitespace(&source.contents) { + b"" + } else { + &source.contents + }; let mut temp_log = Log::init(); // `temp_log` is flushed into `log` on every exit path via linear // control flow (scopeguard would alias `log`/`temp_log`). @@ -2702,7 +2684,7 @@ pub mod parse_worker { if let Some(message) = unsupported_directive { log.add_range_error(Some(source), UseDirective::range(entry_contents), message); Err(crate::Error::ParserError) - } else if !is_empty || loader.handles_empty_file() { + } else if !is_empty || loader.handles_empty_file() || loader.is_css() { get_ast( log, transpiler, @@ -2715,8 +2697,6 @@ pub mod parse_worker { &mut unique_key_for_additional_file, &task_ctx.linker.has_any_css_locals, ) - } else if loader.is_css() { - get_empty_css_ast(log, transpiler, opts, bump, source) } else if module_type == options::ModuleType::Esm { get_empty_ast::(log, transpiler, opts, bump, source) } else { diff --git a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs index cdf36706a970..304a22618984 100644 --- a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs +++ b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs @@ -1006,7 +1006,7 @@ fn debug_css_order_impl( order: &Vec, step: CssOrderDebugStep, ) { - use crate::bun_css::{ImportInfo, LocalsResultsMap, Printer, PrinterOptions}; + use crate::bun_css::{ImportInfo, LocalsResultsMap, Printer, PrinterOptions, Targets}; let tag = step.tag_name(); debug!("CSS order {}:\n", tag); @@ -1038,6 +1038,7 @@ fn debug_css_order_impl( bun_alloc::ArenaVec::new_in(&arena), &mut writer, &PrinterOptions::default(), + Targets::default(), Some(ImportInfo { import_records: &entry.condition_import_records, ast_urls_for_css, diff --git a/src/bundler/linker_context/generateCompileResultForCssChunk.rs b/src/bundler/linker_context/generateCompileResultForCssChunk.rs index 62d34b2a277e..56c0b880f4ac 100644 --- a/src/bundler/linker_context/generateCompileResultForCssChunk.rs +++ b/src/bundler/linker_context/generateCompileResultForCssChunk.rs @@ -108,7 +108,6 @@ fn generate_compile_result_for_css_chunk_impl( let printer_options = PrinterOptions { // TODO: make this more configurable minify: c.options.minify_whitespace, - targets: css.targets, ..Default::default() }; match css.to_css_with_writer( @@ -151,7 +150,6 @@ fn generate_compile_result_for_css_chunk_impl( let printer_options = PrinterOptions { // TODO: make this more configurable minify: c.options.minify_whitespace, - targets: css.targets, ..Default::default() }; match css.to_css_with_writer( @@ -184,7 +182,6 @@ fn generate_compile_result_for_css_chunk_impl( } CssImportOrderKind::SourceIndex(idx) => { let printer_options = PrinterOptions { - targets: css.targets, // TODO: make this more configurable minify: c.options.minify_whitespace || c.options.minify_syntax diff --git a/src/bundler/linker_context/prepareCssAstsForChunk.rs b/src/bundler/linker_context/prepareCssAstsForChunk.rs index 662dca14b646..5bb28a5e8b62 100644 --- a/src/bundler/linker_context/prepareCssAstsForChunk.rs +++ b/src/bundler/linker_context/prepareCssAstsForChunk.rs @@ -9,7 +9,7 @@ use crate::bun_css::css_parser::{ BundlerCssRule, BundlerCssRuleList, BundlerLayerBlockRule, BundlerMediaRule, BundlerSupportsRule, ImportRule, LayerName, LayerStatementRule, Location, SmallList, }; -use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions, Targets}; +use crate::bun_css::{BundlerStyleSheet, ImportConditions, ImportInfo, PrinterOptions}; use crate::bun_fs::Path; use bun_ast::{ImportKind, ImportRecord, ImportRecordFlags, ImportRecordTag, Index as AstIndex}; use bun_ast::{Loc, Range}; @@ -17,7 +17,7 @@ use bun_collections::VecExt; use bun_core::strings; use bun_resolver::DataURL; -use crate::chunk::{Content, CssImportOrder, CssImportOrderKind}; +use crate::chunk::{Content, CssImportOrderKind}; // Raw pointers rather than `&mut` / `&` so that // (a) the container_of `container_of` recovery of `*mut BundleV2` from @@ -96,7 +96,19 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & let Content::Css(css_chunk) = &mut chunk.content else { unreachable!() }; - let targets = chunk_targets(&css_chunk.imports_in_chunk_in_order, asts); + // The order is postorder, so the last source entry is the chunk's root. No root means no entries at all. + let Some(root) = css_chunk + .imports_in_chunk_in_order + .slice() + .iter() + .rev() + .find_map(|entry| match entry.kind { + CssImportOrderKind::SourceIndex(idx) => asts[idx.get() as usize].as_deref(), + _ => None, + }) + else { + return; + }; let mut i: usize = css_chunk.imports_in_chunk_in_order.len() as usize; while i != 0 { i -= 1; @@ -143,15 +155,7 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & } else { BundlerCssRuleList::default() }; - let mut ast = BundlerStyleSheet { - rules, - sources: Default::default(), - source_map_urls: Default::default(), - license_comments: Default::default(), - targets, - composes: Default::default(), - ..BundlerStyleSheet::empty() - }; + let mut ast = BundlerStyleSheet::synthesized(rules, root); wrap_rules_with_conditions(&mut ast, bump, &entry.conditions); css_chunk.asts[i] = ast; } @@ -195,34 +199,33 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & // `entry.conditions[j]`, i.e. a double-free / UAF. Wrap in // `ManuallyDrop` so the duplicate is abandoned instead; the rule // slab itself is arena-owned so it is reclaimed on arena reset. - let ast_import = core::mem::ManuallyDrop::new(BundlerStyleSheet { - license_comments: Default::default(), - sources: Default::default(), - source_map_urls: Default::default(), - rules: { - let mut import_rule = ImportRule { - // SAFETY: `bun_css` types its strings `'static`. This - // stylesheet is printed and dropped with the chunk. - url: unsafe { bun_ptr::detach_lifetime(p.pretty) }, - import_record_idx: entry.condition_import_records.len() - as u32, - loc: Location::dummy(), - ..Default::default() - }; - // SAFETY: shallow struct - // copy. The duplicate is never dropped (`ManuallyDrop` - // above), so the aliased heap stays singly-owned by - // `entry.conditions[j]`. - *import_rule.conditions_mut() = - unsafe { core::ptr::read(entry.conditions.at(j)) }; - arena_rule_list_one(bump, BundlerCssRule::Import(import_rule)) - }, - composes: Default::default(), - ..BundlerStyleSheet::empty() - }); + let ast_import = + core::mem::ManuallyDrop::new(BundlerStyleSheet::synthesized( + { + let mut import_rule = ImportRule { + // SAFETY: `bun_css` types its strings `'static`. This + // stylesheet is printed and dropped with the chunk. + url: unsafe { bun_ptr::detach_lifetime(p.pretty) }, + import_record_idx: entry.condition_import_records.len() + as u32, + loc: Location::dummy(), + ..Default::default() + }; + // SAFETY: shallow struct + // copy. The duplicate is never dropped (`ManuallyDrop` + // above), so the aliased heap stays singly-owned by + // `entry.conditions[j]`. + *import_rule.conditions_mut() = + unsafe { core::ptr::read(entry.conditions.at(j)) }; + arena_rule_list_one( + bump, + BundlerCssRule::Import(import_rule), + ) + }, + root, + )); let printer_options = PrinterOptions { - targets, // TODO: make this more configurable minify: c.options.minify_whitespace || c.options.minify_syntax @@ -305,8 +308,8 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & flags: ImportRecordFlags::default(), }); - css_chunk.asts[i] = BundlerStyleSheet { - rules: { + css_chunk.asts[i] = BundlerStyleSheet::synthesized( + { let mut import_rule = ImportRule::from_url_and_import_record_idx( // SAFETY: as for the `ImportRule` above. unsafe { bun_ptr::detach_lifetime(p.pretty) }, @@ -322,13 +325,8 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & unsafe { core::ptr::read(actual_conditions) }; arena_rule_list_one(bump, BundlerCssRule::Import(import_rule)) }, - sources: Default::default(), - source_map_urls: Default::default(), - license_comments: Default::default(), - targets, - composes: Default::default(), - ..BundlerStyleSheet::empty() - }; + root, + ); } CssImportOrderKind::SourceIndex(source_index) => { let source_index = *source_index; @@ -435,22 +433,6 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & } } -/// All of a chunk's stylesheets come from one module graph, so the first one's targets are the chunk's. -fn chunk_targets(order: &[CssImportOrder], asts: &[crate::bundled_ast::CssCol]) -> Targets { - order - .iter() - .find_map(|entry| match entry.kind { - CssImportOrderKind::SourceIndex(idx) => Some( - asts[idx.get() as usize] - .as_deref() - .expect("css ast present") - .targets, - ), - _ => None, - }) - .unwrap_or_default() -} - /// Builds a `BundlerCssRuleList` whose backing storage is arena-owned. /// /// `CssRuleList::v` is a global `Vec`, but every rule slab built here must be diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index b82c6f94f75e..9a035276b4ca 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -3100,7 +3100,11 @@ impl<'a> Transpiler<'a> { return None; } }; - if let Err(e) = sheet.minify(alloc, &bun_css::MinifyOptions::default(), &extra) { + let minify_options = bun_css::MinifyOptions { + targets: bun_css::Targets::for_bundler_target(self.options.target), + ..Default::default() + }; + if let Err(e) = sheet.minify(alloc, &minify_options, &extra) { self.log_mut().add_error_fmt( None, bun_ast::Loc::EMPTY, @@ -3112,7 +3116,6 @@ impl<'a> Transpiler<'a> { let result = match sheet.to_css( alloc, &bun_css::PrinterOptions { - targets: bun_css::Targets::for_bundler_target(self.options.target), minify: self.options.minify_whitespace, ..bun_css::PrinterOptions::default() }, diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index 13b78c9e52a0..985ead4c7269 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2373,8 +2373,8 @@ pub struct StyleSheet { /// [`ParserOptions::flags`] of the parse. pub flags: ParserFlags, pub layer_names: Vec, - /// Recorded by [`StyleSheet::minify`]; printing must lower for these same targets. - pub targets: Targets, + /// What [`StyleSheet::minify`] lowered this sheet for. [`StyleSheet::to_css_with_writer`] prints for the same targets. + pub(crate) targets: Targets, /// Used when css modules is enabled. Maps `local name string` -> `Ref`. pub local_scope: LocalScope, @@ -2402,6 +2402,15 @@ impl StyleSheet { composes: ComposesMap::default(), } } + + /// A sheet that the bundler builds, not parses. It prints for the targets `like` was minified for. + pub fn synthesized(rules: CssRuleList, like: &Self) -> Self { + Self { + rules, + targets: like.targets, + ..Self::empty() + } + } } /// Positions are `i32`, and a column at the end of the input is `len + 1`. @@ -2522,6 +2531,7 @@ mod stylesheet_impl { bun_alloc::ArenaVec::new_in(arena), writer, options, + self.targets, import_info, local_names, symbols, @@ -2786,6 +2796,7 @@ mod stylesheet_impl { &'a self, arena: &'a Bump, options: &PrinterOptions<'a>, + targets: Targets, import_info: Option>, ) -> Result { // #[cfg(feature = "sourcemap")] @@ -2801,6 +2812,7 @@ mod stylesheet_impl { bun_alloc::ArenaVec::new_in(arena), &mut dest, options, + targets, import_info, None, &symbols, diff --git a/src/css/printer.rs b/src/css/printer.rs index 8cfd98adc360..415c457e7162 100644 --- a/src/css/printer.rs +++ b/src/css/printer.rs @@ -20,8 +20,6 @@ pub struct PrinterOptions<'a> { pub minify: bool, /// An optional project root path, used to generate relative paths for sources used in CSS module hashes. pub project_root: Option<&'a [u8]>, - /// Targets to output the CSS for. - pub targets: Targets, /// Whether to analyze dependencies (i.e. `@import` and `url()`). /// If true, the dependencies are returned as part of the /// [ToCssResult](super::stylesheet::ToCssResult). @@ -44,10 +42,6 @@ impl<'a> PrinterOptions<'a> { PrinterOptions { minify, project_root: None, - targets: Targets { - browsers: None, - ..Targets::default() - }, analyze_dependencies: None, pseudo_classes: None, } @@ -262,6 +256,7 @@ impl<'a> Printer<'a> { scratchbuf: BumpVec<'a, u8>, dest: &'a mut dyn Write, options: &PrinterOptions<'a>, + targets: Targets, import_info: Option>, local_names: Option<&'a css::LocalsResultsMap>, symbols: &'a SymbolMap, @@ -270,7 +265,7 @@ impl<'a> Printer<'a> { sources: None, dest, minify: options.minify, - targets: options.targets, + targets, dependencies: if options.analyze_dependencies.is_some() { Some(BumpVec::new_in(arena)) } else { diff --git a/src/css_jsc/color_js.rs b/src/css_jsc/color_js.rs index 5032ac16ce62..ba143885f4d3 100644 --- a/src/css_jsc/color_js.rs +++ b/src/css_jsc/color_js.rs @@ -458,6 +458,7 @@ pub(crate) fn color<'a>( bun_alloc::ArenaVec::::new_in(&arena), &mut dest, &css::PrinterOptions::default(), + css::Targets::default(), None, None, &symbols, diff --git a/src/css_jsc/css_internals.rs b/src/css_jsc/css_internals.rs index 62972798c3f9..e729926cba93 100644 --- a/src/css_jsc/css_internals.rs +++ b/src/css_jsc/css_internals.rs @@ -159,10 +159,6 @@ fn testing_impl<'a>( TestKind::Normal => false, TestKind::Prefix => false, }, - targets: Targets { - browsers, - ..Default::default() - }, ..Default::default() }, Some(ImportRecordHandler::init_outside_of_bundler( @@ -272,9 +268,9 @@ pub(crate) fn attr_test<'a>( alloc, &PrinterOptions { minify, - targets, ..Default::default() }, + targets, Some(ImportRecordHandler::init_outside_of_bundler( &import_records, )), diff --git a/test/bake/dev/bundle.test.ts b/test/bake/dev/bundle.test.ts index 6e7e8359aa46..da865b81df16 100644 --- a/test/bake/dev/bundle.test.ts +++ b/test/bake/dev/bundle.test.ts @@ -1745,9 +1745,8 @@ devTest("recovers from importing a file in a directory that can't be opened", { }, }); -// Nested `:fullscreen` rules copy the body once per vendor prefix at each level, which the CSS -// printer rejects. This only fails because the dev server prints and minifies with different targets. -// If that changes, this test needs another stylesheet that fails to print. +// Compiling nesting away writes the parent selector for each `&`. With two per level the +// printer stops at its expansion limit. devTest("editing an @imported stylesheet recovers from a failed CSS print", { files: { "index.html": emptyHtmlFile({ @@ -1755,11 +1754,7 @@ devTest("editing an @imported stylesheet recovers from a failed CSS print", { body: "hello", }), "main.css": `@import "./child.css";\nbody { margin: 0; }\n`, - "child.css": - Array.from({ length: 30 }, (_, i) => `.x${i}:fullscreen {`).join("\n") + - "\ncolor: red;\n" + - Buffer.alloc(30, "}").toString() + - "\n", + "child.css": "&:is(.a, &.b) {\n".repeat(20) + "color: red;\n" + "}\n".repeat(20), }, async test(dev) { await using c = await dev.client("/", { diff --git a/test/bake/dev/css.test.ts b/test/bake/dev/css.test.ts index a67ca2dcc360..66d26d861469 100644 --- a/test/bake/dev/css.test.ts +++ b/test/bake/dev/css.test.ts @@ -835,16 +835,44 @@ devTest("css linked from html is printed for the browser targets it was minified `, }, async test(dev) { - const html = await dev.fetch("/").text(); - const href = html.match(/]*href="([^"]+)"/)?.[1]; - if (!href) throw new Error("no stylesheet is linked from the served html: " + html); - const css = await dev.fetch(href).text(); + const servedStylesheet = async () => { + const html = await dev.fetch("/").text(); + const href = html.match(/]*href="([^"]+)"/)?.[1]; + if (!href) throw new Error("no stylesheet is linked from the served html: " + html); + return await dev.fetch(href).text(); + }; // Minifying for browsers adds the prefixed copy of the rule. - expect(css).toContain(".d:-webkit-full-screen {"); // Printing for browsers lowers nesting and the media range. - expect(css).toContain(".a .b {"); - expect(css).toContain("@media (min-width: 600px)"); - expect(css).not.toContain(">="); + const expectBuiltForBrowsers = (css: string, leaf: string, width: string) => { + expect(css).toContain(".d:-webkit-full-screen {"); + expect(css).toContain(`.a .b {\n color: ${leaf};`); + expect(css).toContain(`@media (min-width: ${width})`); + expect(css).not.toContain(">="); + }; + + expectBuiltForBrowsers(await servedStylesheet(), "#00f", "600px"); + + // A hot update prints the stylesheet again. + await dev.write( + "styles.css", + ` + .a { + color: red; + .b { + color: tan; + } + } + .d:fullscreen { + color: red; + } + @media (width >= 700px) { + .a { + color: green; + } + } + `, + ); + expectBuiltForBrowsers(await servedStylesheet(), "tan", "700px"); }, }); diff --git a/test/bundler/bundler_html.test.ts b/test/bundler/bundler_html.test.ts index fef01be567aa..eddcd71137a1 100644 --- a/test/bundler/bundler_html.test.ts +++ b/test/bundler/bundler_html.test.ts @@ -1,4 +1,5 @@ -import { describe, expect } from "bun:test"; +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; import { type BundlerTestBundleAPI, itBundled } from "./expectBundled"; describe("bundler", () => { @@ -1132,8 +1133,9 @@ body { // printed into a data: URL stylesheet while the chunk is prepared // - the bare "@layer foo;" left behind by the deduplicated layer import, // printed together with its wrapping media condition - // - an empty stylesheet (which the bundler never minifies), whose import - // conditions are still printed around it as "@layer bar;" + // - a blank stylesheet, whose import conditions are still printed around it + // as "@layer bar;". U+000B is blank to the bundler, though the CSS + // tokenizer does not skip it. // // ".d:fullscreen" shows which targets the stylesheet was minified for: only // minifying for browsers adds the ":-webkit-full-screen" copy of the rule. @@ -1152,7 +1154,7 @@ body { @import "./other.css"; @import "./dup.css" layer(foo) (width >= 600px); @import "./nested.css" (width >= 700px); -@import "./empty.css" layer(bar) (width >= 1000px); +@import "./blank.css" layer(bar) (width >= 1000px); .a { color: red; .b { @@ -1172,7 +1174,7 @@ body { "/nested.css": ` @import "https://example.com/nested.css" (width >= 900px); .nested { color: red; }`, - "/empty.css": "", + "/blank.css": Buffer.from(" \n\x0B"), }; function expectBuiltForBrowsers(css: string) { @@ -1219,31 +1221,52 @@ body { }, }); - for (const target of ["bun", "node"] as const) { - itBundled(`html/css-browser-targets/imported-from-${target}-build`, { - outdir: "out/", - target, - files: { - ...browserTargetFiles, - "/server.ts": ` + for (const backend of ["api", "cli"] as const) { + for (const target of ["bun", "node"] as const) { + itBundled(`html/css-browser-targets/imported-from-${target}-build-${backend}`, { + outdir: "out/", + target, + backend, + files: { + ...browserTargetFiles, + "/server.ts": ` import html from "./index.html"; console.log(html);`, - }, - entryPoints: ["/server.ts"], + }, + entryPoints: ["/server.ts"], + onAfterBundle(api) { + expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); + }, + }); + } + + itBundled(`html/css-browser-targets/html-entry-point-of-bun-build-${backend}`, { + outdir: "out/", + target: "bun", + backend, + files: browserTargetFiles, + entryPoints: ["/index.html"], onAfterBundle(api) { expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); }, }); } - itBundled("html/css-browser-targets/html-entry-point-of-bun-build", { - outdir: "out/", - target: "bun", - files: browserTargetFiles, - entryPoints: ["/index.html"], - onAfterBundle(api) { - expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); - }, + // The CLI builds a standalone page as a bun-target build, with the HTML in a browser graph. + test("html/css-browser-targets/standalone-html-cli", async () => { + using dir = tempDir("html-css-browser-targets-standalone", browserTargetFiles); + await using proc = Bun.spawn({ + cmd: [bunExe(), "build", "--compile", "--target=browser", "./index.html", "--outdir", "out"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + const html = await Bun.file(`${dir}/out/index.html`).text(); + expectBuiltForBrowsers(html.slice(html.indexOf(""))); + expect(exitCode).toBe(0); }); // When the server code also imports the stylesheet itself, that copy belongs @@ -1265,4 +1288,30 @@ console.log(html);`, expectBuiltForRuntime(api.readFile("out/server.css")); }, }); + + // Minifying for browsers gives every ":fullscreen" rule a ":-webkit-full-screen" + // copy. With nesting compiled away the leaf prints once per prefix. Printed for + // the runtime, the nested rules printed once per prefix at every level: two + // to the power of 30 copies, which the printer rejects. + itBundled("html/css-browser-targets/nested-rules-with-prefixed-selectors", { + outdir: "out/", + target: "bun", + files: { + "/index.html": ``, + "/styles.css": + Array.from({ length: 30 }, (_, i) => `.x${i}:fullscreen {`).join("\n") + + "\ncolor: red;\n" + + Buffer.alloc(30, "}").toString(), + "/server.ts": ` +import html from "./index.html"; +console.log(html);`, + }, + entryPoints: ["/server.ts"], + onAfterBundle(api) { + const css = readLinkedStylesheet(api, "out/index.html"); + expect(css.match(/color: red;/g)).toHaveLength(2); + expect(css).toContain(".x0:-webkit-full-screen .x1:-webkit-full-screen"); + expect(css).toContain(".x0:fullscreen .x1:fullscreen"); + }, + }); }); diff --git a/test/js/bun/css/css-loader.test.ts b/test/js/bun/css/css-loader.test.ts index ee584fe01569..fe7d13dc292e 100644 --- a/test/js/bun/css/css-loader.test.ts +++ b/test/js/bun/css/css-loader.test.ts @@ -50,3 +50,94 @@ describe.concurrent("css loader default export", () => { expect(exitCode).toBe(0); }); }); + +describe.concurrent("bun build --no-bundle css", () => { + // ".d:fullscreen" gets its ":-webkit-full-screen" copy while the stylesheet is minified. + // Nesting and the media range are lowered while it is printed. + const files = { + "styles.css": [ + ".a { color: red; .b { color: blue; } }", + ".d:fullscreen { color: red; }", + "@media (width >= 800px) { .c { color: green; } }", + "", + ].join("\n"), + }; + + async function build(cwd: string, ...args: string[]) { + await using proc = Bun.spawn({ + cmd: [bunExe(), "build", ...args, "styles.css"], + env: bunEnv, + cwd, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + // Only a bundled stylesheet starts with a comment naming its source file. + return stdout.replace("/* styles.css */\n", ""); + } + + test("lowers css for the default (browser) target the same way a bundled build does", async () => { + using dir = tempDir("no-bundle-css-browser", files); + const [transpiled, bundled] = await Promise.all([build(String(dir), "--no-bundle"), build(String(dir))]); + expect(transpiled).toBe( + [ + ".a {", + " color: red;", + "}", + "", + ".a .b {", + " color: #00f;", + "}", + "", + ".d:-webkit-full-screen {", + " color: red;", + "}", + "", + ".d:fullscreen {", + " color: red;", + "}", + "", + "@media (min-width: 800px) {", + " .c {", + " color: green;", + " }", + "}", + "", + ].join("\n"), + ); + expect(transpiled).toBe(bundled); + }); + + test.each(["bun", "node"])("--target=%s leaves css alone the same way a bundled build does", async target => { + using dir = tempDir(`no-bundle-css-${target}`, files); + const [transpiled, bundled] = await Promise.all([ + build(String(dir), "--no-bundle", `--target=${target}`), + build(String(dir), `--target=${target}`), + ]); + expect(transpiled).toBe( + [ + ".a {", + " color: red;", + "", + " & .b {", + " color: #00f;", + " }", + "}", + "", + ".d:fullscreen {", + " color: red;", + "}", + "", + "@media (width >= 800px) {", + " .c {", + " color: green;", + " }", + "}", + "", + ].join("\n"), + ); + expect(transpiled).toBe(bundled); + }); +}); From 3f8f4c8cc0bd37b8387650f4bec8cec9551731d9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:18:32 +0000 Subject: [PATCH 6/8] css: pass Targets by reference, and compare each server build with a browser build in the tests Targets is 80 bytes. That is over the 64-byte limit that clippy sets for a value argument. The tests no longer name what the default browser targets lower. Each server build must print the stylesheet that a browser build of the same files prints, so a change of the default targets does not change them. --- .../findImportedFilesInCSSOrder.rs | 2 +- src/css/css_parser.rs | 4 +- src/css/printer.rs | 4 +- src/css_jsc/color_js.rs | 2 +- src/css_jsc/css_internals.rs | 2 +- test/bake/dev/css.test.ts | 29 +---- test/bundler/bundler_html.test.ts | 101 ++++++++---------- test/js/bun/css/css-loader.test.ts | 36 +------ 8 files changed, 64 insertions(+), 116 deletions(-) diff --git a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs index 304a22618984..ffa0e2561757 100644 --- a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs +++ b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs @@ -1038,7 +1038,7 @@ fn debug_css_order_impl( bun_alloc::ArenaVec::new_in(&arena), &mut writer, &PrinterOptions::default(), - Targets::default(), + &Targets::default(), Some(ImportInfo { import_records: &entry.condition_import_records, ast_urls_for_css, diff --git a/src/css/css_parser.rs b/src/css/css_parser.rs index 985ead4c7269..aab045a369c1 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2531,7 +2531,7 @@ mod stylesheet_impl { bun_alloc::ArenaVec::new_in(arena), writer, options, - self.targets, + &self.targets, import_info, local_names, symbols, @@ -2796,7 +2796,7 @@ mod stylesheet_impl { &'a self, arena: &'a Bump, options: &PrinterOptions<'a>, - targets: Targets, + targets: &Targets, import_info: Option>, ) -> Result { // #[cfg(feature = "sourcemap")] diff --git a/src/css/printer.rs b/src/css/printer.rs index 415c457e7162..84ec967df4c1 100644 --- a/src/css/printer.rs +++ b/src/css/printer.rs @@ -256,7 +256,7 @@ impl<'a> Printer<'a> { scratchbuf: BumpVec<'a, u8>, dest: &'a mut dyn Write, options: &PrinterOptions<'a>, - targets: Targets, + targets: &Targets, import_info: Option>, local_names: Option<&'a css::LocalsResultsMap>, symbols: &'a SymbolMap, @@ -265,7 +265,7 @@ impl<'a> Printer<'a> { sources: None, dest, minify: options.minify, - targets, + targets: *targets, dependencies: if options.analyze_dependencies.is_some() { Some(BumpVec::new_in(arena)) } else { diff --git a/src/css_jsc/color_js.rs b/src/css_jsc/color_js.rs index ba143885f4d3..7f813db39dea 100644 --- a/src/css_jsc/color_js.rs +++ b/src/css_jsc/color_js.rs @@ -458,7 +458,7 @@ pub(crate) fn color<'a>( bun_alloc::ArenaVec::::new_in(&arena), &mut dest, &css::PrinterOptions::default(), - css::Targets::default(), + &css::Targets::default(), None, None, &symbols, diff --git a/src/css_jsc/css_internals.rs b/src/css_jsc/css_internals.rs index e729926cba93..161b5ad0a8a5 100644 --- a/src/css_jsc/css_internals.rs +++ b/src/css_jsc/css_internals.rs @@ -270,7 +270,7 @@ pub(crate) fn attr_test<'a>( minify, ..Default::default() }, - targets, + &targets, Some(ImportRecordHandler::init_outside_of_bundler( &import_records, )), diff --git a/test/bake/dev/css.test.ts b/test/bake/dev/css.test.ts index 66d26d861469..11246724c2c4 100644 --- a/test/bake/dev/css.test.ts +++ b/test/bake/dev/css.test.ts @@ -824,14 +824,6 @@ devTest("css linked from html is printed for the browser targets it was minified color: blue; } } - .d:fullscreen { - color: red; - } - @media (width >= 600px) { - .a { - color: green; - } - } `, }, async test(dev) { @@ -841,16 +833,13 @@ devTest("css linked from html is printed for the browser targets it was minified if (!href) throw new Error("no stylesheet is linked from the served html: " + html); return await dev.fetch(href).text(); }; - // Minifying for browsers adds the prefixed copy of the rule. - // Printing for browsers lowers nesting and the media range. - const expectBuiltForBrowsers = (css: string, leaf: string, width: string) => { - expect(css).toContain(".d:-webkit-full-screen {"); + // Printing for browsers compiles the nesting. Printing for the runtime keeps "& .b {". + const expectPrintedForBrowsers = (css: string, leaf: string) => { expect(css).toContain(`.a .b {\n color: ${leaf};`); - expect(css).toContain(`@media (min-width: ${width})`); - expect(css).not.toContain(">="); + expect(css).not.toContain("& .b"); }; - expectBuiltForBrowsers(await servedStylesheet(), "#00f", "600px"); + expectPrintedForBrowsers(await servedStylesheet(), "#00f"); // A hot update prints the stylesheet again. await dev.write( @@ -862,17 +851,9 @@ devTest("css linked from html is printed for the browser targets it was minified color: tan; } } - .d:fullscreen { - color: red; - } - @media (width >= 700px) { - .a { - color: green; - } - } `, ); - expectBuiltForBrowsers(await servedStylesheet(), "tan", "700px"); + expectPrintedForBrowsers(await servedStylesheet(), "tan"); }, }); diff --git a/test/bundler/bundler_html.test.ts b/test/bundler/bundler_html.test.ts index eddcd71137a1..8e1951541acd 100644 --- a/test/bundler/bundler_html.test.ts +++ b/test/bundler/bundler_html.test.ts @@ -1,6 +1,8 @@ import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, tempDir } from "harness"; -import { type BundlerTestBundleAPI, itBundled } from "./expectBundled"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { itBundled } from "./expectBundled"; describe("bundler", () => { // Basic test for bundling HTML with JS and CSS @@ -1122,12 +1124,11 @@ body { // A stylesheet linked from an HTML file is built for the browser even when the // build itself targets bun or node (the HTML is imported from server code for - // Bun.serve, or passed to a server build as an entry point), so it is minified - // for the default browser targets. It has to be printed for the same targets: - // nesting and media range syntax are only lowered while printing. This fixture - // reaches every place the linker prints CSS: + // Bun.serve, or passed to a server build as an entry point). Every build below + // has to print it the way a browser build of the same files does. This + // fixture reaches every place the linker prints CSS: // - // - the stylesheet itself (nesting, the @media range) + // - the stylesheet itself (nesting, the @media range, ":fullscreen") // - the preserved external @import, whose media condition is printed on its own // - the external @import behind a conditional internal @import, which is // printed into a data: URL stylesheet while the chunk is prepared @@ -1136,9 +1137,6 @@ body { // - a blank stylesheet, whose import conditions are still printed around it // as "@layer bar;". U+000B is blank to the bundler, though the CSS // tokenizer does not skip it. - // - // ".d:fullscreen" shows which targets the stylesheet was minified for: only - // minifying for browsers adds the ":-webkit-full-screen" copy of the rule. const browserTargetFiles = { "/index.html": ` @@ -1177,17 +1175,30 @@ body { "/blank.css": Buffer.from(" \n\x0B"), }; - function expectBuiltForBrowsers(css: string) { - expect(css).toContain(".d:-webkit-full-screen {"); + function linkedStylesheet(outdir: string) { + const href = readFileSync(join(outdir, "index.html"), "utf8").match(/href="(.*?\.css)"/)?.[1]; + if (!href) throw new Error(`No stylesheet is linked from ${outdir}/index.html`); + return readFileSync(join(outdir, href), "utf8"); + } + + // The stylesheet that the HTML links, from a browser build of the files in `root`. + async function browserBuildStylesheet(root: string) { + await using proc = Bun.spawn({ + cmd: [bunExe(), "build", "./index.html", "--outdir", "browser-build"], + env: bunEnv, + cwd: root, + stdout: "pipe", + stderr: "pipe", + }); + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stderr, exitCode }).toEqual({ stderr: "", exitCode: 0 }); + return linkedStylesheet(join(root, "browser-build")); + } + + async function expectBuiltLikeABrowserBuild(root: string, css: string) { + expect(css).toBe(await browserBuildStylesheet(root)); + // A build for the runtime prints "& .b {". expect(css).toContain(".a .b {"); - expect(css).toContain("@media (min-width: 800px)"); - expect(css).toContain('@import "https://example.com/external.css" screen and (min-width: 500px);'); - expect(css).toContain( - '@import "data:text/css,@import \\"https://example.com/nested.css\\" (min-width: 900px);" (min-width: 700px);', - ); - expect(css).toContain("@media (min-width: 600px) {\n @layer foo;\n}"); - expect(css).toContain("@media (min-width: 1000px) {\n @layer bar;\n}"); - expect(css).not.toContain(">="); } // The same fixture minified and printed for targets that support everything it uses. @@ -1204,23 +1215,6 @@ body { expect(css).not.toContain("min-width"); } - function readLinkedStylesheet(api: BundlerTestBundleAPI, htmlFile: string) { - const href = api.readFile(htmlFile).match(/href="(.*?\.css)"/)?.[1]; - if (!href) throw new Error(`No stylesheet is linked from ${htmlFile}`); - return api.readFile("out/" + href); - } - - // Reference: what a browser build prints. The server builds below must print - // the same stylesheet the same way. - itBundled("html/css-browser-targets/browser-build", { - outdir: "out/", - files: browserTargetFiles, - entryPoints: ["/index.html"], - onAfterBundle(api) { - expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); - }, - }); - for (const backend of ["api", "cli"] as const) { for (const target of ["bun", "node"] as const) { itBundled(`html/css-browser-targets/imported-from-${target}-build-${backend}`, { @@ -1234,8 +1228,8 @@ import html from "./index.html"; console.log(html);`, }, entryPoints: ["/server.ts"], - onAfterBundle(api) { - expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); + async onAfterBundle(api) { + await expectBuiltLikeABrowserBuild(api.root, linkedStylesheet(api.join("out"))); }, }); } @@ -1246,8 +1240,8 @@ console.log(html);`, backend, files: browserTargetFiles, entryPoints: ["/index.html"], - onAfterBundle(api) { - expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); + async onAfterBundle(api) { + await expectBuiltLikeABrowserBuild(api.root, linkedStylesheet(api.join("out"))); }, }); } @@ -1263,10 +1257,10 @@ console.log(html);`, stderr: "pipe", }); const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stderr).toBe(""); - const html = await Bun.file(`${dir}/out/index.html`).text(); - expectBuiltForBrowsers(html.slice(html.indexOf(""))); - expect(exitCode).toBe(0); + expect({ stderr, exitCode }).toEqual({ stderr: "", exitCode: 0 }); + const html = readFileSync(join(String(dir), "out", "index.html"), "utf8"); + const inlined = html.slice(html.indexOf("")); + await expectBuiltLikeABrowserBuild(String(dir), inlined); }); // When the server code also imports the stylesheet itself, that copy belongs @@ -1283,16 +1277,16 @@ import "./styles.css"; console.log(html);`, }, entryPoints: ["/server.ts"], - onAfterBundle(api) { - expectBuiltForBrowsers(readLinkedStylesheet(api, "out/index.html")); + async onAfterBundle(api) { + await expectBuiltLikeABrowserBuild(api.root, linkedStylesheet(api.join("out"))); expectBuiltForRuntime(api.readFile("out/server.css")); }, }); - // Minifying for browsers gives every ":fullscreen" rule a ":-webkit-full-screen" - // copy. With nesting compiled away the leaf prints once per prefix. Printed for - // the runtime, the nested rules printed once per prefix at every level: two - // to the power of 30 copies, which the printer rejects. + // Minifying for browsers can give a rule a vendor-prefixed copy. With nesting + // compiled away the leaf prints once per prefix. Printed for the runtime, the + // nested rules printed once per prefix at every level: two to the power of + // 30 copies, which the printer rejects. itBundled("html/css-browser-targets/nested-rules-with-prefixed-selectors", { outdir: "out/", target: "bun", @@ -1307,10 +1301,9 @@ import html from "./index.html"; console.log(html);`, }, entryPoints: ["/server.ts"], - onAfterBundle(api) { - const css = readLinkedStylesheet(api, "out/index.html"); - expect(css.match(/color: red;/g)).toHaveLength(2); - expect(css).toContain(".x0:-webkit-full-screen .x1:-webkit-full-screen"); + async onAfterBundle(api) { + const css = linkedStylesheet(api.join("out")); + expect(css).toBe(await browserBuildStylesheet(api.root)); expect(css).toContain(".x0:fullscreen .x1:fullscreen"); }, }); diff --git a/test/js/bun/css/css-loader.test.ts b/test/js/bun/css/css-loader.test.ts index fe7d13dc292e..60ff71a8f519 100644 --- a/test/js/bun/css/css-loader.test.ts +++ b/test/js/bun/css/css-loader.test.ts @@ -52,8 +52,8 @@ describe.concurrent("css loader default export", () => { }); describe.concurrent("bun build --no-bundle css", () => { - // ".d:fullscreen" gets its ":-webkit-full-screen" copy while the stylesheet is minified. - // Nesting and the media range are lowered while it is printed. + // Minifying for browsers can add a prefixed copy of the ":fullscreen" rule. + // Printing for browsers compiles the nesting and can lower the media range. const files = { "styles.css": [ ".a { color: red; .b { color: blue; } }", @@ -72,8 +72,7 @@ describe.concurrent("bun build --no-bundle css", () => { stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stderr).toBe(""); - expect(exitCode).toBe(0); + expect({ stderr, exitCode }).toEqual({ stderr: "", exitCode: 0 }); // Only a bundled stylesheet starts with a comment naming its source file. return stdout.replace("/* styles.css */\n", ""); } @@ -81,33 +80,8 @@ describe.concurrent("bun build --no-bundle css", () => { test("lowers css for the default (browser) target the same way a bundled build does", async () => { using dir = tempDir("no-bundle-css-browser", files); const [transpiled, bundled] = await Promise.all([build(String(dir), "--no-bundle"), build(String(dir))]); - expect(transpiled).toBe( - [ - ".a {", - " color: red;", - "}", - "", - ".a .b {", - " color: #00f;", - "}", - "", - ".d:-webkit-full-screen {", - " color: red;", - "}", - "", - ".d:fullscreen {", - " color: red;", - "}", - "", - "@media (min-width: 800px) {", - " .c {", - " color: green;", - " }", - "}", - "", - ].join("\n"), - ); expect(transpiled).toBe(bundled); + expect(transpiled).toContain(".a .b {"); }); test.each(["bun", "node"])("--target=%s leaves css alone the same way a bundled build does", async target => { @@ -116,6 +90,7 @@ describe.concurrent("bun build --no-bundle css", () => { build(String(dir), "--no-bundle", `--target=${target}`), build(String(dir), `--target=${target}`), ]); + expect(transpiled).toBe(bundled); expect(transpiled).toBe( [ ".a {", @@ -138,6 +113,5 @@ describe.concurrent("bun build --no-bundle css", () => { "", ].join("\n"), ); - expect(transpiled).toBe(bundled); }); }); From f35644820b7b21b1971fe3afe4581c273a2302cb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 29 Oct 2026 01:07:17 +0000 Subject: [PATCH 7/8] test: build the repeated fixture strings with Buffer.alloc --- test/bake/dev/bundle.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/bake/dev/bundle.test.ts b/test/bake/dev/bundle.test.ts index da865b81df16..f805c6391f37 100644 --- a/test/bake/dev/bundle.test.ts +++ b/test/bake/dev/bundle.test.ts @@ -1747,6 +1747,7 @@ devTest("recovers from importing a file in a directory that can't be opened", { // Compiling nesting away writes the parent selector for each `&`. With two per level the // printer stops at its expansion limit. +const twoParentsPerLevel = "&:is(.a, &.b) {\n"; devTest("editing an @imported stylesheet recovers from a failed CSS print", { files: { "index.html": emptyHtmlFile({ @@ -1754,7 +1755,10 @@ devTest("editing an @imported stylesheet recovers from a failed CSS print", { body: "hello", }), "main.css": `@import "./child.css";\nbody { margin: 0; }\n`, - "child.css": "&:is(.a, &.b) {\n".repeat(20) + "color: red;\n" + "}\n".repeat(20), + "child.css": + Buffer.alloc(20 * twoParentsPerLevel.length, twoParentsPerLevel).toString() + + "color: red;\n" + + Buffer.alloc(20 * "}\n".length, "}\n").toString(), }, async test(dev) { await using c = await dev.client("/", { From 8a6566e80b498e2af20badd00be765589d560551 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:45:42 +0000 Subject: [PATCH 8/8] ci: retrigger