Skip to content

css: keep the earlier copy of a file with a conditional layer in every import order - #46934

Closed
robobun wants to merge 2 commits into
robobun/b6517831/css-layer-before-importfrom
robobun/99b5b433/css-conditional-layer-gate
Closed

robobun wants to merge 2 commits into
robobun/b6517831/css-layer-before-importfrom
robobun/99b5b433/css-conditional-layer-gate

Conversation

@robobun

@robobun robobun commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Parked draft on #41572. It waits for two answers (this comment) and for #46733, #46232 and #46357.

Problem

  • bun build takes a layer that a CSS file declares only inside @media or @supports as always declared. g.css = @media print{@layer a{.g{color:green}}} ahead of x.css, y.css, x.css prints @media print{@layer a{.g{color:green}}}@layer u{.t{color:#00f}}@layer a{.t{color:red}}. On a screen the sources give .t blue, the bundle red.
  • css: emit @layer statements that precede @import before the imported files #41572 keeps the earlier copy of such a file only behind an @layer statement ahead of an @import (layers_matter, findImportedFilesInCSSOrder.rs:404).

Fix

Background

  • A cascade layer gets its priority where its name first appears. Inside @media or @supports the name counts only while the condition holds (css-cascade-5 "Layer Ordering").
  • For a file imported twice the bundler prints the last copy, and a plain list of layer names for the earlier one.
  • esbuild 0.28.2 prints the bundle of main. No user reported this.
  • Considered: a list with the rule around each name (Notes).

Downsides

  • Such a file prints once more per list of import conditions (92 KB file, two style sheets: 272,487 bytes, 136,284 before).
  • Six inputs that are right on main are wrong here (todo cases, Notes).
  • Parse: +5 instructions per @media block. .text +2,816 bytes.
Notes

Status. This draft is parked. The two questions are in this comment. Commit 1 does not depend on the answers and is offered to #41572 there. Commit 2 is the part that waits.

Repro (main at 5c6d4e2, bun 1.4.3 and #41572 at 1bae41a print the same bytes, and esbuild 0.28.2 prints the same rules in the same order):

printf '@import "./g.css";\n@import "./x.css";\n@import "./y.css";\n@import "./x.css";\n' > entry.css
printf '@media print { @layer a { .g { color: green } } }\n' > g.css
printf '@layer a { .t { color: red } }\n' > x.css
printf '@layer u { .t { color: blue } }\n' > y.css
bun build ./entry.css --minify
# main: @media print{@layer a{.g{color:green}}}@layer u{.t{color:#00f}}@layer a{.t{color:red}}
# here: @media print{@layer a{.g{color:green}}}@layer a;@layer u{.t{color:#00f}}@layer a{.t{color:red}}

The second read of the flat list is the list that stands for a duplicate import:

printf '@import "./tokens.css";\n@import "./other.css";\n@import "./tokens.css";\n' > entry.css
printf '@media (prefers-color-scheme: dark) { @layer theme { :root { --bg: black } } }\n' > tokens.css
printf '@layer base { .t { color: blue } }\n@layer theme { .t { color: red } }\n' > other.css
bun build ./entry.css --minify
# main: @layer theme;@layer base{.t{color:#00f}}@layer theme{.t{color:red}}@media (prefers-color-scheme:dark){@layer theme{:root{--bg:black}}}
# here: @media (prefers-color-scheme:dark){@layer theme{:root{--bg:black}}}@layer base{.t{color:#00f}}@layer theme{.t{color:red}}@media (prefers-color-scheme:dark){@layer theme{:root{--bg:black}}}

In light mode the source files give .t red. The bundle of main gives blue (Chrome 153). A file that is imported first and states the order (@layer base, theme;) makes the bundle of main right.

The two commits.

  • Commit 1 (129b6ca64b, +112/-33 in src/css/css_parser.rs, 14 cases css/CSSAtLayerOrderFirstDeclaration*, 4 fail on css: emit @layer statements that precede @import before the imported files #41572). css: emit @layer statements that precede @import before the imported files #41572 sets has_conditional_layer_names in on_layer_rule: for each name inside a conditional block it scans every earlier name for an equal one. That scan is quadratic (20,000 layers that 20,000 @media blocks name again: a build takes 7,022 M instructions on css: emit @layer statements that precede @import before the imported files #41572, 803 M on main and 816 M here). It also flags a file that needs no copy: @layer a.b {...} @media print { @layer a {...} } (the sublayer name declares a), @media all { @layer a {...} }, and a file whose own @import "./x.css" layer(a) declares a. Here the parser notes which names were registered inside a conditional block (mark_conditional_layer_names, cold, called from the end of a block that has a name in it). At the end of the parse one pass with a trie of layer names answers the question (first_declares_a_layer_under_a_condition, cold). A file with no layer inside a conditional block runs neither. The trie is keyed by (parent, segment): a set of whole name prefixes gives the same answer and is quadratic in the segments of one name. @media not all counts as a condition: the minifier removes the rule, so the kept copy declares nothing, as the file, and a list would declare the names.
  • Commit 2 (+20/-9 in findImportedFilesInCSSOrder.rs). layers_matter is visitor.has_conditional_layer_file || <a pre-import entry>. With it on, the passes of css: emit @layer statements that precede @import before the imported files #41572 do the rest: such a file does not stand for a list, its earlier copy stays whole, and of several earlier copies under one list of import conditions only the first stays. A CSS module with composes keeps its earlier copy when that copy has no import conditions (css/CSSAtLayerConditionalComposesModule). A copy under import conditions is still a list, because such a module fails to print inside a wrapper (css modules: drop a rejected composes instead of failing the file at print time #38538).

Which rules count. Chrome 153, one page per case:

  • @media and @supports: a layer named inside (block or statement, also a sublayer of a named layer) is in the layer order only while the condition holds.
  • @-moz-document url-prefix(): Chrome and Safari do not have the rule, so they declare nothing. Firefox applies it to every page (not run here: Firefox is not installed).
  • @container, @scope, @starting-style, and a style rule: a browser that has the rule declares the layer in every case, so these stay plain names, as in css: emit @layer statements that precede @import before the imported files #41572. A browser that has @layer and not the rule drops the rule (for example Chrome 99 to 104 for @container), and the flat list is wrong there, with the bytes of main.

A page with two style sheets (css/CSSAtLayerConditionalTwoStyleSheetsOfAPage). index.html links a.css and b.css, and both import tokens.css from the second repro. bun build ./index.html makes one import order from both style sheets, so the first copy of tokens.css is a list on main: .t is blue there and red from the source page. The dev server makes one import order per style sheet, but it links the style sheets in reverse order (#28117), so this page is blue under bun ./index.html on main and here.

Generated graphs. Two checks. A graph is right when, in every state of its conditions, .t gets the rule that the sources give it and every layer has its sublayers in the same order.

The check in the tree (test/bundler/css-layer-order.ts, scripts/css-layer-fuzz.ts) has a new conditions option: some rules are inside @media (min-width: Npx) or @supports (top: Npx), and each state of those conditions is evaluated. Five graphs are pinned in css.test.ts. bun scripts/css-layer-fuzz.ts <bun> 4000 1 <baseline> --conditions:

4,000 graphs each Right on the baseline, wrong here Repaired
against #41572 0 204
against #41572, --empty-blocks 3 39
against main, --empty-blocks --no-leading-statements 24 239

The --empty-blocks rows are the empty named @layer block that the minifier removes from a kept copy (#46733).

A larger generator (not in the tree) also writes @-moz-document, @container, @scope, @starting-style, @media all and @media not all, nested conditions, @layer statements ahead of imports, cyclic imports, and imports with layer(x), supports() and media conditions. Its model agrees with Chrome 153 on 1,070 cases, and the check in the tree agrees with it on 15,064 states.

20,000 graphs each Wrong on #41572 Wrong here Right on #41572, wrong here Right on main, wrong here
options above 2,206 157 0 0
plus bare layer imports 2,620 810 2 0
plus external imports 15,033 14,467 0 not run

Inputs that are right on main and wrong here (todo cases, each checked in Chrome). A file with a conditional layer turns layers_matter on for the whole import order, and the kept copies and lists of that handling are not right everywhere yet:

Open concerns from the self-review. Seventeen were raised. Ten are done: the split into two commits, the corrected account (esbuild's changelog, the real price of a kept copy, counts against main, the dev server), the cases for the flag, the two cases with external imports, five pinned graphs, and the todo cases above. Seven wait for the answers, because they change the remedy or need more test tools:

  • The keep rule does not ask whether the earlier copy is needed. A copy stays also when nothing between it and the next copy declares a layer, and when an earlier file already declares the layer in every case. Two pages that share a style sheet on main can get two here.
  • A file under several lists of import conditions (bare, screen, print) keeps one copy per list.
  • Each composes ... from statement is a visit, so the number of statements can decide whether a module prints twice.
  • @namespace is also lost through a cyclic import's layer entry and through a list that stays. Only two paths have a todo case.
  • The checks write no !important, no unnamed @layer {} block, no @namespace and only one entry point.
  • The dev server calls the pass once per style sheet, and no test reads what it serves for such a file.

The compact list that this draft does not have. A first version (branch robobun/99b5b433/css-conditional-layer-names, no PR) recorded each conditional name with its rule in the parser and printed @media print{@layer a;} in place of the earlier copy. That is the form of esbuild's list, with the condition added. It is +442/-151 lines in src/ against +132/-42 here.

Kept copy (this draft) Compact list
First row above, wrong graphs 157 160
Second row, right on #41572 and wrong 2 57
An unnamed @layer {} with !important in such a file (css/CSSAtLayerConditionalUnnamedBlockWithImportant) right wrong
A 92 KB file that two style sheets import, raw bytes 272,487 136,320
Release .text against #41572 +2,816 +10,752

Measurements. Release builds of main 5c6d4e2, of #41572 at 1bae41a, and of this branch.

  • Instructions for one top-level block with no layer in it, counted by single-step in gdb from the entry of parse_block to its return:
Block main #41572 here
@media (min-width:1px){.a{color:red}} 5,991 5,994 5,999
@supports (display:grid){.a{color:red}} 5,993 5,996 5,995
@-moz-document url-prefix(){.a{color:red}} 6,003 6,006 6,008

Suites. bun bd test (debug build with ASAN): test/bundler/esbuild/css.test.ts 149 pass and 15 todo, test/bundler/css/ 184 pass, test/js/bun/css/css.test.ts 1,315 pass, test/bundler/bundler_html.test.ts 26 pass, test/bake/dev/css.test.ts 18 pass, test/regression/issue/20546.test.ts and 28914.test.ts pass.

Other open PRs.


[human-review] gate passed · iteration 0 · 5 files touched

fails on main (without fix)
ASAN without fix: 37 failed, 15 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/esbuild/css.test.ts
bun test v1.4.4 (367d939d9)

test/bundler/esbuild/css.test.ts:
(pass) bundler > css/CSSEntryPoint [487.97ms]
(pass) bundler > css/CSSEntryPointEmpty [79.85ms]
(pass) bundler > css/CSSNesting [96.28ms]
(pass) bundler > css/CSSAtImportMissing [90.47ms]
(pass) bundler > css/CSSAtImportSimple [94.49ms]
(pass) bundler > css/CSSAtImportDiamond [95.26ms]
(pass) bundler > css/CSSAtImportCycle [85.08ms]
(pass) bundler > css/CSSUrlImport [86.51ms]
(pass) bundler > css/ImportCSSFromJSComposes [117.47ms]
(pass) bundler > css/ImportCSSFromJSComposesFromMissingImport [300.95ms]
(pass) bundler > css/ImportCSSFromJSComposesFromNotCSS [86.88ms]
(pass) bundler > css/ImportCSSFromJSComposesCircular [102.31ms]
(pass) bundler > css/ImportCSSFromJSComposesFromCircular [114.66ms]
(pass) bundler > css/ImportCSSFromJSComposesIDSelector [75.31ms]
(pass) bundler > css/ImportCSSFromJSComposesElementSelector [80.07ms]
(pass) bundler > css/ImportCSSFromJSComposesCompoundSelector [86.64ms]
(pass) bundler > css/ImportCSSFromJSComposesC
... (truncated)

release without fix: 33 failed, 15 skipped
bun test v1.4.4-canary.1 (1bae41a98)

test/bundler/esbuild/css.test.ts:
(pass) bundler > css/CSSEntryPoint [75.22ms]
(pass) bundler > css/CSSEntryPointEmpty [17.58ms]
(pass) bundler > css/CSSNesting [11.32ms]
(pass) bundler > css/CSSAtImportMissing [14.98ms]
(pass) bundler > css/CSSAtImportSimple [23.56ms]
(pass) bundler > css/CSSAtImportDiamond [16.21ms]
(pass) bundler > css/CSSAtImportCycle [10.63ms]
(pass) bundler > css/CSSUrlImport [21.32ms]
(pass) bundler > css/ImportCSSFromJSComposes [17.31ms]
(pass) bundler > css/ImportCSSFromJSComposesFromMissingImport [46.43ms]
(pass) bundler > css/ImportCSSFromJSComposesFromNotCSS [14.56ms]
(pass) bundler > css/ImportCSSFromJSComposesCircular [14.93ms]
(pass) bundler > css/ImportCSSFromJSComposesFromCircular [15.33ms]
(pass) bundler > css/ImportCSSFromJSComposesIDSelector [11.65ms]
(pass) bundler > css/ImportCSSFromJSComposesElementSelector [7.59ms]
(pass) bundler > css/ImportCSSFromJSComposesCompoundSelector [13.03ms]
(pass) bundler > css/ImportCSSFromJSComposesComplexSelector [20.36ms]
(pass) bundler > css/ImportCSSFromJSComposesPseudoClass [31.93ms]
(pass) bundler > css/ImportCSSFromJSComposesAttributeSelector [11.59ms]
... (truncated)
passes on PR (with fix)
ASAN with fix: 15 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/esbuild/css.test.ts
bun test v1.4.4 (367d939d9)

test/bundler/esbuild/css.test.ts:
(pass) bundler > css/CSSEntryPoint [477.84ms]
(pass) bundler > css/CSSEntryPointEmpty [96.12ms]
(pass) bundler > css/CSSNesting [90.69ms]
(pass) bundler > css/CSSAtImportMissing [77.49ms]
(pass) bundler > css/CSSAtImportSimple [95.23ms]
(pass) bundler > css/CSSAtImportDiamond [85.71ms]
(pass) bundler > css/CSSAtImportCycle [76.22ms]
(pass) bundler > css/CSSUrlImport [89.70ms]
(pass) bundler > css/ImportCSSFromJSComposes [124.05ms]
(pass) bundler > css/ImportCSSFromJSComposesFromMissingImport [322.34ms]
(pass) bundler > css/ImportCSSFromJSComposesFromNotCSS [68.45ms]
(pass) bundler > css/ImportCSSFromJSComposesCircular [108.99ms]
(pass) bundler > css/ImportCSSFromJSComposesFromCircular [120.91ms]
(pass) bundler > css/ImportCSSFromJSComposesIDSelector [98.70ms]
(pass) bundler > css/ImportCSSFromJSComposesElementSelector [117.08ms]
(pass) bundler > css/ImportCSSFromJSComposesCompoundSelector [84.58ms]
(pass) bundler > css/ImportCSSFromJSComposes
... (truncated)

release with fix: 15 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 1283ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/110] build.rs build_script_build
[2/110] rustc bun_platform 
[3/110] rustc bun_core 
[4/110] rustc bun_safety 
[5/110] rustc bun_output 
[6/110] rustc bun_zlib_sys 
[7/110] rustc bun_zstd 
[8/110] rustc bun_brotli 
[9/110] rustc bun_picohttp 
[10/110] rustc bun_base64 
[11/110] rustc bun_boringssl_sys 
[12/110] rustc bun_ptr 
[13/110] rustc bun_cares_sys 
[14/110] rustc bun_lsquic_sys 
[15/110] rustc bun_errno 
[16/110] rustc bun_clap 
[17/110] rustc bun_valkey 
[18/110] rustc bun_tcc_sys 
[19/110] rustc bun_text_diff 
[20/110] rustc bun_paths 
[21/110] rustc bun_shell_parser 
warning: `feature(generic_const_exprs)` is not supported with the next-generation trait solver
 --> src/shell_parser/lib.rs:1:30
  |
1 | #![feature(adt_const_params, generic_const_exprs, allocator_api)]
  |                              ^^^^^^^^^^^^^^^^^^^
  |
  = note: `-Znext-solver=globally` is currently enabled by default for testing
  = note: reverted the setting to `-Znext-solver=coherence` for this crate
  = note: the curre
... (truncated)
diff hotspot
scripts/css-layer-fuzz.ts                          |   5 +-
 .../linker_context/findImportedFilesInCSSOrder.rs  |  29 +-
 src/css/css_parser.rs                              | 145 +++-
 test/bundler/css-layer-order.ts                    |  72 +-
 test/bundler/esbuild/css.test.ts                   | 801 +++++++++++++++++++++
 5 files changed, 993 insertions(+), 59 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                                                      reads  edits  tests
scripts/css-layer-fuzz.ts                                     0      0     51
…c/bundler/linker_context/findImportedFilesInCSSOrder.rs      4      0     49
src/css/css_parser.rs                                         6      1     49
test/bundler/css-layer-order.ts                               0      0     53
test/bundler/esbuild/css.test.ts                              5      2     49

… pass

The flag for a file that first declares a layer inside @media,
@supports or @-moz-document came from a scan in on_layer_rule: each
name inside such a block was compared with every earlier name. The scan
is quadratic, and it also sets the flag when the file declares the
layer in every case: through a sublayer name ("a.b" declares "a"),
inside "@media all", or with an @import of the file that has layer()
and no condition. Such a file then printed a second copy that it does
not need.

The parser now notes which names were registered inside a conditional
block, from the end of a block that has a name in it. One pass at the
end of the parse, with a trie of layer names, answers whether one of
those names is the first declaration of its layer. A file with no layer
inside a conditional block runs neither.
…y import order

The import order pass keeps the earlier copy of a file that first
declares a layer under a condition, and does not let the file stand for
a list of layer names, only when a file has an @layer statement ahead
of an @import. It now does so for every import order with such a file.

A CSS module with "composes" keeps its earlier copy when that copy has
no import conditions.

The generated-graph check (test/bundler/css-layer-order.ts) can put
rules inside @media and @supports, and evaluates each state of those
conditions.
@robobun

robobun commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:41 PM PT - Oct 25th, 2026

✅ @robobun, your commit 8a5d5309286f570bb6b51c225eb09af861a12025 passed in Build #132830! 🎉


🧪   To try this PR locally:

bunx bun-pr 46934

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

bun-46934 --bun

@robobun

robobun commented Oct 25, 2026

Copy link
Copy Markdown
Collaborator Author

Status

Reproduced on main at 5c6d4e2 and on #41572 at 1bae41a:

printf '@import "./g.css";\n@import "./x.css";\n@import "./y.css";\n@import "./x.css";\n' > entry.css
printf '@media print { @layer a { .g { color: green } } }\n' > g.css
printf '@layer a { .t { color: red } }\n' > x.css
printf '@layer u { .t { color: blue } }\n' > y.css
bun build ./entry.css --minify

The bundle is @media print{@layer a{.g{color:green}}}@layer u{.t{color:#00f}}@layer a{.t{color:red}}. On a screen the source files give .t blue and the bundle gives red (Chrome 153). With this branch the bundle keeps @layer a; and gives blue.

PR: #46934 (draft, parked until the two questions on #41572 have an answer).

Jarred-Sumner added a commit that referenced this pull request Oct 27, 2026
### What does this PR do?

Consolidates the open pull requests on the CSS parser (`src/css`:
parsing, minifying, lowering, printing, CSS modules) into one.

179 open pull requests were in scope. Each was judged by one rule: **the
output must mean to a browser what the input meant.** Every claim was
run through a build of `main`, a build with the change, lightningcss
1.33 and Chromium 156 (CSSOM, computed values, painted pixels for colors
and gradients), and counted against 10,116 real stylesheets: the
published CSS of about 190 popular npm packages, plus stylesheets from
open source repositories. 107 land here, whole or in part, most of them
cut down. The source diff is net negative.

Of the 10,116, 9,509 are stylesheets that someone ships. The rest are
test fixtures of other tools (521), Tailwind v4 source that needs its
plugin (59) and SCSS, PostCSS or template source (27).

| 9,509 shipped stylesheets | `main` | this branch |
|---|---|---|
| fail to build | 71 | 35 |
| ... of those, valid CSS that Bun rejects | | 0 |
| minified output reads differently in Chromium than the input | 552 | 2
|
| CSS modules with a name that is referenced but not defined, or
exported but not defined | 166 | 0 |

| all 10,116 | `main` | this branch |
|---|---|---|
| fail to build | 192 | 141 |
| minified output reads differently in Chromium than the input | 593 |
15 |
| build on `main`, fail here | | 0 |
| right on `main`, wrong here (minified, and at the default targets) | |
0 |
| size of the minified output, no targets | 162.32 MB | 162.47 MB
(+0.093%) |
| size of the output at the default targets | 224.1 MB | 210.2 MB
(-6.2%) |

A syntax error is a build error, with one exception: the IE star hack
`*zoom: 1` is skipped, because tachyons and handsontable ship it. The 35
shipped stylesheets that fail are invalid CSS: 28 have a selector that
Chromium drops (semantic-ui-css, swiper, @ionic/core, Adobe Spectrum,
xp.css), 2 an `@import` after other rules, and one each `@supports not X
and Y`, a nested `@keyframes`, a stray comma, a selector list in
`::slotted()`, `@media screen\0` (govuk-frontend). The 2 that read
differently fold a `color-mix()` inside a gradient (see the known gaps).

The growth of the minified output is rules and declarations that `main`
deleted by mistake: 87 KB of rules, 45 KB of prefixed declarations that
only browser targets can rule out.

#### Popular CSS that `main` breaks today

- normalize.css, modern-normalize, sanitize.css: `font-family:
monospace, monospace` is collapsed to `monospace`, which changes the
font size from 16px to 13px (#46662).
- CKEditor 5, Tabler, Carbon, VitePress, Ionic, PatternFly, Excalidraw:
a rule of custom properties is deleted as a "duplicate" of a later rule
with the same selector and other custom properties. 37 stylesheets lose
1,681 custom properties (#33684).
- Material Components, daisyUI, DocSearch, plyr: a `var()` size loses to
its own fallback (#42101).
- nextra, daisyUI, CKEditor: declarations written after a nested rule
are moved above it (#45462).
- antd 4, purecss, govuk-frontend: browser hacks in selector lists start
to apply everywhere (#42100).
- foundation-sites, flatpickr, 98.css, blueprintjs, scalar,
react-datepicker: the build fails on valid CSS (#46756, #38552, #38534).
tachyons, handsontable: it fails on the IE star hack (#46751).
- nodejs.org, Mantine: a CSS module exports classes that no rule
defines, because the `@apply` or `@mixin` in them is moved out of the
rule (#46759).
- hint.css and 42 more: `z-index: 1000001` and `1000000` become the same
number (#46715).
- Adobe Spectrum: `--version: 5.0.1` prints as `5.1`.
- A quarter of all stylesheets: minified output has a stray space in
`align-items: center` (#41993).

#### Behavior changes to look at first

1. **`light-dark()` is kept as written at the default browser targets**
(#42009). The lowered form `var(--buncss-light, a) var(--buncss-dark,
b)` is invalid unless a compiled `color-scheme` covers the element: 184
of the 215 real stylesheets that get it never define the variable, so
every browser drops the declaration. The docs section on the polyfill is
removed.
2. **`border` is not built from longhands** (#42072):
`border-width:0;border-style:solid;border-color:red` stays three
declarations, because `border` also resets `border-image`. 305 real
stylesheets grow by 30 KB in total; `bootstrap.min.css` by 113 bytes, 5
gzipped. No real stylesheet was found where the old merge shows, so this
is the one to drop if size matters more. 14 existing expectations
change.
3. **A CSS module no longer exports names that only occur inside
`:global(...)`** (#45487). 73 real modules lose 202 export keys, all of
them names that no rule has. `import { g }` or `composes: g` of such a
name becomes a build error.
4. **Container names and `@counter-style` names stay global in a CSS
module** (#45247 by @mikamikasuki). `main` hashes the `@container` name
but not `container-name`, so a named query never matches.
postcss-modules (Vite, css-loader, Next.js) keeps them global;
lightningcss and esbuild hash both. Global keeps a container that is
queried from another file or from JS working.
5. **Syntax errors are build errors, also two that `main` lets
through**: a media query that stops short (`@media screen and {`,
`@media not {`, `@import "a.css" screen and;`) and `@media (width <) foo
{`. No stylesheet of the 10,116 has either. A condition that is valid by
the grammar though no browser knows it, `( ... )` or `fn( ... )`, is
kept as written (#46756): `(min-width:0\0)`, `(not(hover))`.
6. **Declarations after a nested rule stay where they were written**, as
a nested declarations rule (#45462). Changes the output of 199 real
stylesheets; in a fuzz of 2,850 nested programs compared by computed
style, `main` was wrong in 1,056 and the pull request's code, before it
was trimmed here, in none.
7. **`Bun.color`**: `color()` inputs are converted instead of returned
as a string (`Bun.color("color(srgb 1 0 0)", "hex")` was `"color(srgb 1
0 0)"`); `currentColor`, system colors and `light-dark()` give `null` in
the converting formats instead of the keyword as a string; a relative
color or `color-mix()` outside sRGB is clipped, not gamut-mapped
(`hsl(from oklch(100% .399 336.3) h s l)` is `#ff5bff`, was `#fff`).
8. The `:-moz-any()` and `:-webkit-any()` copies of rules with `:is()`
are gone at the default targets (#45945, #42029). The `:-webkit-any()`
copy outranked the original rule: `.title{color:blue}
:is(h1,h2,h3){color:red}` painted red. 5.8% of all default-target output
was the `:-moz-any()` copies.
9. `Property` grows from 216 to 224 bytes: `Url` stores its text as a
slice so that two `url()` values can be compared (#46895). The pull
request packed a pointer and a `u32` behind `unsafe` to avoid that.

#### Not in this PR, needs a decision

- **Raise the default browser targets (#40369) and add a `cssTarget`
option (#40368).** Today: Chrome 80, Edge 80, Firefox 78, Safari 14,
Opera 67, and no public way to change them. At Vite 8's floor the output
of the 9,924 stylesheets is 15.3% smaller (3.9% gzipped). About a dozen
fixes here only matter at today's floor, and code for older targets is
unreachable without the option.
- Vendor prefixes for `user-select`, `appearance`, `hyphens` and five
more (#45814): 1,116 real stylesheets lack a prefix they need at the
default targets. And for `backdrop-filter` (#44648): 173.
- Clip instead of gamut-map in the sRGB fallback of a plain wide-gamut
color: deletes about 90 lines, changes every pinned fallback hex. If the
mapping stays, #44647 by @oddharsh makes it closer to what browsers
paint (colors off by 2/255 or more: 168 to 110 of 3,170 real ones).

#### Changes

**Rules: duplicates, merging, nesting, fallbacks**

- The `:-moz-any()` copy of every rule with `:is()` or `:not(a, b)` is
gone: Firefox 78 has `:is()` (#45945). 1,164 real stylesheets
- Keep declarations written after a nested rule in place with a nested
declarations rule (#45462). 379 real stylesheets
- With nesting compiled away, an unknown at-rule inside a style rule was
moved out of it: `.wrapper{@apply flex}` printed a bare `@apply flex;`
and the rule was gone, so a CSS module exported a class that no rule
defines. It now stays in a block under the compiled selector. 72 real
modules with Tailwind's `@apply`, 25 with Mantine's `@mixin` (#46759).
316 real stylesheets
- Keep !important in the rules generated for logical properties and
color-scheme (#38597). 311 real stylesheets
- With browser targets, remove an earlier duplicate rule only when its
declaration block is equal (#46861). 171 real stylesheets
- Compare custom property names in `PropertyId` equality and importance
in duplicate-rule detection (#33684). 40 real stylesheets
- Keep same-condition @supports rules and empty named @layer blocks
(#46733). 31 real stylesheets
- Keep target-added vendor prefix passes on cloned and re-minified
rules, and never print a bare `:full-screen` (#43339). 12 real
stylesheets
- Keep the selectors on rules added for color fallbacks and logical
properties (#43240). 3 real stylesheets
- A later declaration of a property drops the `@supports` color copies
of the earlier one, which printed after the rule and won (#45560). 2
real stylesheets
- Do not merge style rules in a stylesheet that holds `revert-rule`
(#46953). 1 real stylesheets
- `@import ... supports(-webkit-mask: none)` kept its prefix (#38589)

**Properties and shorthands**

- Print align-items:center without a stray space when no safe/unsafe
keyword is given (#41993). 3,317 real stylesheets
- Emit the physical longhands instead of the inset shorthand for targets
without it (#38583). 1,452 real stylesheets
- Keep the stops of an upward gradient as written, and drop a `50%` hint
only at the midpoint (#46790). 104 real stylesheets
- Emit unparsed border-block-* declarations when compiling logical
borders (#38582). 89 real stylesheets
- Keep repeated font families and dedupe only the inserted system-ui
fallbacks (#46662). 88 real stylesheets
- A `width` / `height` / `min-*` / `max-*` with `var()` or `env()` was
printed before the plain fallback written above it, so the fallback won
(#42101). 26 real stylesheets
- Keep box-orient and box-direction when flex-direction or flex-flow
follows (#45672). 16 real stylesheets
- Write held prefixed background declarations at every flush (#46882). 6
real stylesheets
- Derive equality for Size2D and BorderRadius, and keep every prefix in
the border-radius handler (#45665). 2 real stylesheets
- Print `none` instead of an empty border-image, mask-border or
mask-box-image value (#45143). 2 real stylesheets
- Keep font/transition sub-properties on the side of the shorthand they
were written on (#41990). 2 real stylesheets
- CSS-wide keywords are not names: `font:12px Arial;font-family:inherit`
printed `font:12px inherit`, `color-scheme:inherit` and
`color-scheme:auto` printed `normal`, `transition-property:unset` was
folded into `transition` (#42022). 2 real stylesheets
- Only fold font longhands into `font` when the rule declared a `font`
(#45459)
- Keep a font family name quoted when its identifiers do not read back
as the same name (#46606)
- Stop rewriting valid positions into ones browsers reject (#45197)
- `border` is no longer built from longhands unless the rule also sets
what `border` resets (`border-image`), and an author's `border-image`
reset is no longer dropped. `transition` is likewise only written where
the rule wrote one, because it resets `transition-behavior` (#42072)
- `border; border-image: <gradient>; border-image-slice: 1` lost the
gradient in every default build (#42018)
- A prefixed `linear-gradient` keeps its direction, written or
generated: the prefixed syntax names the starting side and measures
angles differently (#46697)

**At-rules**

- Print @font-face format() keywords as strings (#37979). 439 real
stylesheets
- Print @supports `not` conditions without a leading space (#38559). 88
real stylesheets
- Reset after the number token of a unicode-range (#45835). 33 real
stylesheets
- Keep `<general-enclosed>` media and container conditions as written
(#46756). 24 real stylesheets
- A strict range such as `(width < 768px)` lowered for old targets still
matched at exactly 768px. The step is now `.02px`. The `not all and`
form for other units is not taken (#46806). 18 real stylesheets
- Keep scanning an @supports condition after a nested block (#38552). 9
real stylesheets
- Every `@counter-style name` printed as `@counter-stylename`, which
browsers drop (also #46692). In a CSS module the name now stays global,
like the `list-style` that refers to it (#33679). 9 real stylesheets
- Keep a keyframe whose block has an invalid item (#46288). 2 real
stylesheets
- Read an @Property initial-value on the stylesheet's parser, keep an
unmatched value as written (#45806). 2 real stylesheets
- `@media {}` is `all`. A media query that stops after `and`, `or` or
`not` (`@media screen and {`) is a build error; `main` printed `not all`
or dropped the condition, silently. The `@layer` and type selector parts
are not taken (#46869). 2 real stylesheets
- Accept a name-only `@container` and a `style()` feature with no value
(#46689). 1 real stylesheets
- Parse `<timeline-range-name> <percentage>` keyframe selectors (#45652)
- Allow `or` inside parentheses after a media type (#45088)
- Print the `=` comparison in media and container queries as `=`
(#45071)
- Parse the @font-palette-values font-family descriptor as a list of
family names (#45484)

**Selectors**

- Never wrap a selector list in :is() (#46787). 414 real stylesheets
- Stop emitting :-webkit-any() copies of :is() that outrank the original
rule (#42029). 373 real stylesheets
- With browser targets, a selector list with a vendor-prefixed member
was split, which revives hacks that rely on other engines dropping the
whole list: `.s *::-ms-backdrop,.s{flex:auto}` applied everywhere.
Rewritten; the list is printed as written (#42100). 42 real stylesheets
- Print the vendor prefix on downleveled :any-link, :read-only,
:read-write, :placeholder-shown and :autofill (#42131). 12 real
stylesheets
- Fix nesting lowering of a `&` that does not lead its selector
(#43047). 8 real stylesheets
- `@scope`: `&` and implicit selectors compile to `:where(:scope)`,
relative selectors and bare declarations parse (#43165). 7 real
stylesheets
- Only reject bare :global / :local pseudo-classes in CSS modules
(#38534). 5 real stylesheets
- Stop truncating `@scope to (...)` and stop replacing `&` in the
scope-end selector (#43146). 2 real stylesheets
- `[xl|href$=".pdf"]` lost its namespace prefix (#45159). 2 real
stylesheets
- Match An+B keywords exactly and take only `+` as the leading sign
(#42953). 1 real stylesheets
- Parse ::details-content and ::picker() like ::part() (#45504). 1 real
stylesheets
- Parse :window-inactive as an ordinary pseudo-class, and accept it
after ::selection (#45815)
- Print :nth-col(1) and :nth-last-col(1) in functional form (#41575)
- `li::before::marker` failed the build (#45810)
- `&` inside `:nth-child(... of S)` is resolved when nesting is compiled
away. The second selector serializer (326 lines) is deleted (#43024)

**Colors and `Bun.color`**

- Keep light-dark() as written under the default browser targets
(#42009). 227 real stylesheets
- Number and percentage channels parse in `lab()`, `lch()`, `oklab()`,
`oklch()`, `hsl()` and `hwb()`; the hue of `lch` / `oklch` is no longer
scaled by alpha (#45084). 130 real stylesheets
- `Bun.color` returns `null` for `currentColor`, system colors and
`light-dark()` in the converting formats, instead of the CSS keyword as
a string (#33047). 130 real stylesheets
- Relative colors: channel keywords are on the scale of their function
(`rgb(from #369 calc(r + 10) g b)`), the origin's alpha is kept, a
relative color kept as written gets no `@supports` copies, and a result
outside sRGB is not folded (#45362). 31 real stylesheets
- Keep rotate: 0deg out of none, and keep the origin alpha in relative
colors (#38486). 13 real stylesheets
- Compute the D50 reference white in f32 so greys convert to lab(l 0 0)
like lightningcss (#38535). 7 real stylesheets
- Return a missing hue for a grey from conversions into lch, oklch, hsl
and hwb (#45201). 5 real stylesheets
- Fix color(a98-rgb), srgb-linear relative colors and color-mix(in
xyz-d50) (#38487). 4 real stylesheets
- Match named colors without regard to ASCII case (#45092). 3 real
stylesheets
- Fold min(), max() and clamp() over plain numbers (#39515)
- `calc(l - .08)` in a percentage channel of a relative color became NaN
and printed `#000` (also #45970) (#45971)
- Bun.color: convert color() inputs instead of returning them as a CSS
string (#38488)
- A `color-mix(in srgb, ...)` result outside sRGB prints `color(srgb
...)` instead of a gamut-mapped hex (#39269)

**`calc()` and numbers**

- Rounding to 6 significant digits ate into the integer part:
`z-index:2147483647` became `2147480000`, `max-width:9999999px` became
`10000000px`, `--x:1234567.5` became `1234570`. It now only cuts a
fraction short: a value kept as tokens prints its source text, a typed
value prints every integer digit and at least one digit of the fraction
(#46715). 43 real stylesheets
- A number without a unit is no longer repaired into `px`
(`height:1.5715` is dropped by a standards-mode browser, so it prints as
written), `calc(-1 * 0)` is not a length, and on a property of the range
[0,∞] (sizes, border radii, padding, border and outline widths, gap,
`flex-basis`, `font-size`) a `calc()` that folds below zero prints `0`
instead of an invalid negative literal, and a negative literal no longer
replaces the valid declaration before it (`width:10px;width:-5px`
printed `width:-5px`) (#42104). 24 real stylesheets
- Print numbers from the f32's shortest digits, not its f64 expansion
(#38565). 17 real stylesheets
- Print negative numbers below 1 with a single minus sign (#38516)
- Keep math functions over two different length units as written
(#38489)
- Fold rem() with a truncated quotient, so it keeps the sign of the
dividend (#32286)
- A one-argument `min()` / `max()` around a sum printed without any
function (`width:100% - 20px`) (#46145)
- `round()` breaks ties upward and handles a negative step as browsers
do (#45249)

**CSS modules**

- A CSS module exports its `@keyframes` names (`styles.spin`). Hashing
is unchanged (#46720). 145 real stylesheets
- A name inside `:global(...)` prints plain but was exported as
`name_<hash>`, a class no rule has (also #38573) (#45487). 90 real
stylesheets
- Keep container names global in CSS modules (#45247). 6 real
stylesheets
- Tag the keyframes name when an `animation` value falls back to raw
tokens (#46034). 6 real stylesheets
- In a plain stylesheet `composes: a from "./b.css"` was treated as an
import: the file was inlined and an absolute path printed (#45961). 4
real stylesheets
- Drop a rejected composes instead of failing the file at print time
(#38538). 1 real stylesheets
- Keep every rule's custom properties for the composes conflict check
(#38523)
- Keep composes working after a nested rule in the same block (#38520)
- `IdentOrRef::hash` read 2 of 16 bytes, so in release builds every
class of a module hashed alike (#30784)

**Tokens, `url()`, diagnostics**

- The block skip stack no longer allocates on every block exit (#39533)
- Report the diagnostic's line without its line breaks in
position.lineText (#38342). 192 real stylesheets
- Compare `url()` values by their text (#46895). 26 real stylesheets
- Values kept as tokens keep the blanks they were written with instead
of having them re-invented at print time: `attr(x type(<number>))`
printed `type(< number> )`, which browsers drop. Minified output still
drops the blanks that cannot matter (#45577). 19 real stylesheets
- The IE star hack (`*zoom:1`) failed the whole build. The declaration
is skipped, as every browser does. It is the one syntax error that
builds: tachyons, handsontable and jasmine ship it (#46751). 8 real
stylesheets
- The path of a copied asset spliced into `url()` is always quoted, so a
file name with a space or a parenthesis cannot end the `url()` (#41557).
7 real stylesheets
- Move the skip loop of parse_until_before out of the generic body
(#39520)
- Remove dead code from bun_css: the unused `impl Default for Property`
(#45618)
- Default the at-rule and qualified-rule parser traits, drop the
url_to_css shim (#31999)

**Speed**

Four inputs that took quadratic or exponential time, or produced output
out of proportion, are now linear, with no new limit and no extra pass
(#31639, #42243, #38531, #43421).

**Tests only**

- `css-fuzz.test.ts` never ran in CI and timed out on debug builds; it
is a deterministic table now (#38500)
- `nth-anplusb-ident.test.ts` counts heaps in a child process (#46331)
- `color.test.ts` checks the ansi-16 sweep with one `expect()` (#42824)
- Not CSS, but it failed this PR's CI and fails on `main` too:
`ws-proxy.test.ts` on Windows, "a message sent during a TLS
renegotiation arrives after it". The helper server now renegotiates from
the callback of the frame's write (#46170)

**No pull request covered these**

- `--v: 5.0.1` printed as `5.1`, `--w: 1.0.0` as `10`, `--x: 1+2` as
`12`, `2n+1` as `2n1`: a number token that touches another keeps its
source text.
- `color-scheme: auto` printed as `normal`, and `color-scheme: dark
light` as `light dark`.
- A bare `:global` or `:local` in a CSS module sets the scope of the
names after it, up to the end of the selector, as in css-loader. It was
a build error.
- The scrollbar states (`a:horizontal`,
`::-webkit-scrollbar{&:horizontal{}}`) are valid in a plain compound, as
in WebKit and Blink.
- Without browser targets, `-webkit-box-align`, `-ms-flex-align` and the
like were dropped next to their standard form (flatpickr,
foundation-sites, materialize-css: 28 stylesheets), and
`-webkit-fill-available` before `-moz-available` (beercss).
- `(-o-min-device-pixel-ratio: 2/1)` printed as `2`.
- `sin()`, `cos()` and `tan()` are exact at multiples of 90deg:
`calc(100px * cos(90deg))` printed `-.00000437114px`.
- A `display-p3` color at targets that have P3 but not the other
`color()` spaces (Safari 10.1 to 14) got itself as a fallback.
- `width: rem(-18px, 5px)` folds to a negative literal once `rem()` is
right; it prints `0`.
- Consecutive nested declarations rules, which arise when same-query
`@media` blocks in one rule merge, are folded into one and count against
the existing selector expansion limit as the `&{}` rules they replace
did.

#### Known and not fixed here

- Four longhands are still folded into a `transition` the author did not
write where the targets add a prefixed copy of a property (`mask-image`
at Chrome 80): only the shorthand gives the copy its own times.
- A later `background`, `box-shadow` or `border-*` declaration still
loses to the `@supports` copy of an earlier `var()` value of the same
property with a wide-gamut color. Same on `main`; #45560 is taken for
the properties of the fallback handler and for unparsed values only.
- A merged rule prints the unprefixed name in the passes of the rule it
absorbed: `.d::-webkit-input-placeholder{}.d::-moz-placeholder{}` prints
`::placeholder` for the second (#42106, not taken: it breaks the merge
of prefix-equivalent rules).
- The `border`, `outline` and `font` shorthands, `line-height`,
`scroll-padding`, `background-size` and a few more still print a
`calc()` that folds below zero as a negative literal. No real stylesheet
has one.
- `all` is not a property Bun knows, so `a{margin-top:1px;all:unset}`
prints `all` first. Same on `main`.
- A selector kept as raw tokens loses the blank before `*` when
minified: `--sel: .dark *` prints `.dark*`. Same on `main`.
- `width:calc(0% + 12px)` folds to `12px`, which lays out differently in
a table cell. Same on `main`.
- The `:dir()` / `:lang()` rules of a lowered logical property print
before the nested rules of their rule, so a logical declaration written
after a nested rule of equal specificity still loses to it. Same on
`main`.
- A fraction is still rounded to 6 significant digits (`12345.678`
prints `12345.7`, `33.3333333333%` prints `33.3333%`). Keeping every
digit would add up to 282 KB over the corpus.
- `@keyframes "quoted"` is hashed in a module but not exported.
- In a module, a keyframes name inside a `var()` fallback is not hashed:
`animation: var(--enter, fade 1s)`. Same on `main`.
- A `color-mix()` or relative color folded to a hex inside a gradient
changes the interpolation from Oklab to sRGB (VS Code, clawhub).
Printing `color(srgb ..)` instead needs a fallback for `mask-image`,
`list-style-image` and custom properties at the default targets, which
have none.
- A comma list in `@container` still fails the build.
- After a bare `:global`, names that are hashed at print time
(`::view-transition-old(foo)`) are still hashed; inside `:global(...)`
they are not.

#### Pull requests in scope that do not land here

- Duplicates of a pull request that lands here: #36961 (of #37979),
#38478 (of #46662), #38480 (of #46733), #38482 (of #46715), #38491 (of
#38500), #38508 (of #45201), #38513 (of #45362), #38573 (of #45487),
#38640 (of #38500), #45525 (of #45247), #45589 (of #46756), #45970 (of
#45971)
- Already fixed on `main`: #38674
- Right, but for input nobody writes (0 of 10,116 stylesheets, and not
new syntax): #31916, #38526, #38592, #39349, #41139, #41801, #42042,
#42484, #43078, #45604, #45908, #46086, #46221, #46224, #46273, #46694,
#46707, #46737, #46755, #46816, #46870, #46934
- Right or harmless, but not worth their code, their bigger output or
the behavior they change: #30905, #31924, #33332, #34426, #36225,
#38006, #38512, #38547, #38551, #38561, #38572, #38576, #38607, #38623,
#38667, #38692, #42106, #42912, #42918, #43407, #43434, #44700, #45442,
#45546, #45747, #45759, #45825, #45946, #46061, #46127, #46206
- Need a decision (see above), stay open: #40368, #40369, #44647,
#44648, #45814
- Stays open: #45787

Out of scope: CSS linking and chunking in the bundler, the dev server,
docs-only pull requests, and repository-wide sweeps that touch `src/css`
in passing.

Thanks to @mikamikasuki (#45247), @alii (#39520, #31999) and @oddharsh,
whose measurements on #40369 and #41990 were used.

Fixes #16727.
Fixes #24770.
Fixes #30772.
Fixes #44704.
Fixes #45089.
Fixes #45237.
Fixes #46872.

### How did you verify your code works?

- The 35 CSS test files pass on a debug build, also with
`FORCE_COLOR=1`. 600+ of the tests in this branch fail on a build of
`main`. An earlier head of this branch passed all 179 CI jobs that ran.
- The reproduction of each issue listed above was run on `main` (wrong)
and on this branch (right).
- Differential run over the 10,116 stylesheets, `main` against this
branch, minified without targets and through `Bun.build` at the default
targets: no stylesheet that builds on `main` fails; Chromium 156
compares the output with the input rule by rule (CSSOM, then computed
values on a sized element in a standards-mode document, colors as
painted pixels in sRGB and P3). The comparison has 195 control pairs
that must read equal or different. For stylesheets that read differently
on both builds, mostly because of lowering, the sets of differences were
compared; the three new ones are two minifier fixtures that are wrong on
both and one comparison artifact.
- CSS modules are checked for consistency instead, since hashed names
defeat the comparison: every reference points at a name the output
defines, every export exists.
- `Bun.color`: 59 inputs in 13 formats on both builds; every changed
cell was read.
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Not taken in #47025 (7942008), which consolidated the open CSS parser pull requests. The fix is right, but none of the 10,116 real stylesheets it was checked against has this input, and it is not new syntax. Reopen it if the input shows up in real CSS.

@robobun

robobun commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

Understood. Two notes for a later reopen:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants