diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index c2bd71c5699f..722a2d8e2d57 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -665,7 +665,7 @@ pub mod parse_worker { } // ─────────────────────────────────────────────────────────────────────────── - // getEmptyCSSAST / getEmptyAST + // getEmptyAST // ─────────────────────────────────────────────────────────────────────────── // `transpiler: *mut Transpiler` stays raw. Callers @@ -673,27 +673,6 @@ pub mod parse_worker { // `(*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. - 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 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()), - )); - Ok(ast) - } - fn get_empty_ast( log: &mut Log, transpiler: *mut Transpiler, @@ -702,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"")? @@ -1286,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`). @@ -2662,7 +2647,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, @@ -2675,8 +2660,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..ffa0e2561757 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 c4c3e87f7cef..aa15c1d1a529 100644 --- a/src/bundler/linker_context/generateCompileResultForCssChunk.rs +++ b/src/bundler/linker_context/generateCompileResultForCssChunk.rs @@ -4,7 +4,7 @@ use core::sync::atomic::Ordering; 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; @@ -97,7 +97,6 @@ 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), ..Default::default() }; match css.to_css_with_writer( @@ -130,7 +129,6 @@ fn generate_compile_result_for_css_chunk_impl( } CssImportOrderKind::SourceIndex(idx) => { let printer_options = PrinterOptions { - targets: Targets::for_bundler_target(c.options.target), // 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 91d6aa58ef1e..92e166285640 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}; @@ -94,6 +94,19 @@ fn prepare_css_asts_for_chunk_impl(c: &LinkerContext, chunk: &mut Chunk, bump: & let Content::Css(css_chunk) = &mut chunk.content else { unreachable!() }; + // 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; @@ -140,14 +153,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(), - 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; } @@ -191,34 +197,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: Targets::for_bundler_target(c.options.target), // TODO: make this more configurable minify: c.options.minify_whitespace || c.options.minify_syntax @@ -295,8 +300,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) }, @@ -312,12 +317,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(), - composes: Default::default(), - ..BundlerStyleSheet::empty() - }; + root, + ); } CssImportOrderKind::SourceIndex(source_index) => { let source_index = *source_index; diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index bf1351905e39..e38cc84d7b1e 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -3115,7 +3115,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, @@ -3127,7 +3131,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 7401dd18f859..aab045a369c1 100644 --- a/src/css/css_parser.rs +++ b/src/css/css_parser.rs @@ -2373,6 +2373,8 @@ pub struct StyleSheet { /// [`ParserOptions::flags`] of the parse. pub flags: ParserFlags, pub layer_names: Vec, + /// 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, @@ -2394,11 +2396,21 @@ impl StyleSheet { css_modules: None, flags: ParserFlags::default(), layer_names: Vec::new(), + targets: Targets::default(), local_scope: LocalScope::default(), local_properties: LocalPropertyUsage::default(), 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`. @@ -2433,6 +2445,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); @@ -2518,6 +2531,7 @@ mod stylesheet_impl { bun_alloc::ArenaVec::new_in(arena), writer, options, + &self.targets, import_info, local_names, symbols, @@ -2727,6 +2741,7 @@ mod stylesheet_impl { css_modules: options.css_modules, flags: options.flags, layer_names, + targets: Targets::default(), local_scope: parser_extra.local_scope, local_properties, composes, @@ -2781,6 +2796,7 @@ mod stylesheet_impl { &'a self, arena: &'a Bump, options: &PrinterOptions<'a>, + targets: &Targets, import_info: Option>, ) -> Result { // #[cfg(feature = "sourcemap")] @@ -2796,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..84ec967df4c1 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: *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..7f813db39dea 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..161b5ad0a8a5 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..f805c6391f37 100644 --- a/test/bake/dev/bundle.test.ts +++ b/test/bake/dev/bundle.test.ts @@ -1745,9 +1745,9 @@ 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. +const twoParentsPerLevel = "&:is(.a, &.b) {\n"; devTest("editing an @imported stylesheet recovers from a failed CSS print", { files: { "index.html": emptyHtmlFile({ @@ -1756,10 +1756,9 @@ devTest("editing an @imported stylesheet recovers from a failed CSS print", { }), "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", + 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("/", { diff --git a/test/bake/dev/css.test.ts b/test/bake/dev/css.test.ts index 9ce744ae8636..11246724c2c4 100644 --- a/test/bake/dev/css.test.ts +++ b/test/bake/dev/css.test.ts @@ -811,6 +811,52 @@ 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": ` + .a { + color: red; + .b { + color: blue; + } + } + `, + }, + async test(dev) { + 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(); + }; + // 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).not.toContain("& .b"); + }; + + expectPrintedForBrowsers(await servedStylesheet(), "#00f"); + + // A hot update prints the stylesheet again. + await dev.write( + "styles.css", + ` + .a { + color: red; + .b { + color: tan; + } + } + `, + ); + expectPrintedForBrowsers(await servedStylesheet(), "tan"); + }, +}); + 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 c34b74f70db6..8e1951541acd 100644 --- a/test/bundler/bundler_html.test.ts +++ b/test/bundler/bundler_html.test.ts @@ -1,4 +1,7 @@ -import { describe, expect } from "bun:test"; +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { itBundled } from "./expectBundled"; describe("bundler", () => { @@ -1118,4 +1121,190 @@ 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). 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, ":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 + // - the bare "@layer foo;" left behind by the deduplicated layer import, + // printed together with its wrapping media condition + // - 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. + 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); +@import "./blank.css" layer(bar) (width >= 1000px); +.a { + color: red; + .b { + color: blue; + } +} +.d:fullscreen { + color: red; +} +@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; }`, + "/blank.css": Buffer.from(" \n\x0B"), + }; + + 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 {"); + } + + // 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("@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"); + } + + 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"], + async onAfterBundle(api) { + await expectBuiltLikeABrowserBuild(api.root, linkedStylesheet(api.join("out"))); + }, + }); + } + + itBundled(`html/css-browser-targets/html-entry-point-of-bun-build-${backend}`, { + outdir: "out/", + target: "bun", + backend, + files: browserTargetFiles, + entryPoints: ["/index.html"], + async onAfterBundle(api) { + await expectBuiltLikeABrowserBuild(api.root, linkedStylesheet(api.join("out"))); + }, + }); + } + + // 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, 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 + // 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", + files: { + ...browserTargetFiles, + "/server.ts": ` +import html from "./index.html"; +import "./styles.css"; +console.log(html);`, + }, + entryPoints: ["/server.ts"], + async onAfterBundle(api) { + await expectBuiltLikeABrowserBuild(api.root, linkedStylesheet(api.join("out"))); + expectBuiltForRuntime(api.readFile("out/server.css")); + }, + }); + + // 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", + 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"], + 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 ee584fe01569..60ff71a8f519 100644 --- a/test/js/bun/css/css-loader.test.ts +++ b/test/js/bun/css/css-loader.test.ts @@ -50,3 +50,68 @@ describe.concurrent("css loader default export", () => { expect(exitCode).toBe(0); }); }); + +describe.concurrent("bun build --no-bundle css", () => { + // 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; } }", + ".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, exitCode }).toEqual({ stderr: "", exitCode: 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(bundled); + expect(transpiled).toContain(".a .b {"); + }); + + 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(bundled); + expect(transpiled).toBe( + [ + ".a {", + " color: red;", + "", + " & .b {", + " color: #00f;", + " }", + "}", + "", + ".d:fullscreen {", + " color: red;", + "}", + "", + "@media (width >= 800px) {", + " .c {", + " color: green;", + " }", + "}", + "", + ].join("\n"), + ); + }); +});