Merge pull request #8857 from deepseek-harness/ci/css-selector-gate-v2

ci(css): reject costly unkeyed CSS selectors and retire existing ones
This commit is contained in:
imccyu authored and GitHub committed 2026-11-20 02:34:03 +08:00
commit 10d5578ce3
24 files changed
+862 -22

No files matched your search

+2 -2
View File
@@ -6,5 +6,5 @@
en: 7229c49e920aa5b3
zh: 1dd52db6b4d84952
/defensive-patterns/why-these-rules:
en: 3ba292a9f396a390
zh: 5b99713fe1169f9c
en: da275199da69cbec
zh: 6ffbd1ebf536bb67
+1 -1
View File
@@ -18,7 +18,7 @@ Five habits cover most of what follows, and each page is their application to on
|---|---|
| Package exports, package shape, build faces, dependency declarations | [package-surface.md](package-surface.md) |
| Remote services, `@Remote` methods, API dispatch, business ownership at the API layer | [remote-and-api.md](remote-and-api.md) |
| Client components, slots, stores, hooks, effects | [client-components.md](client-components.md) |
| Client components, slots, stores, hooks, effects, stylesheet selectors | [client-components.md](client-components.md) |
| Session reads, retention, conversation nodes, renderers | [conversation-and-session.md](conversation-and-session.md) |
| Timing, state representation, shared ownership, decentralization, refactors, migrations, performance evidence, disposal, callbacks, subprocesses | [general.md](general.md) |
+1 -1
View File
@@ -20,7 +20,7 @@
|---|---|
| 包导出面、包形态、构建面、依赖声明 | [package-surface.zh.md](package-surface.zh.md) |
| 远程服务、`@Remote` 方法、API 分发、API 层的业务归属 | [remote-and-api.zh.md](remote-and-api.zh.md) |
| 客户端组件、slots、store、hooks、effect | [client-components.zh.md](client-components.zh.md) |
| 客户端组件、slots、store、hooks、effect、样式表选择器 | [client-components.zh.md](client-components.zh.md) |
| Session 读取、持有、会话节点、renderer | [conversation-and-session.zh.md](conversation-and-session.zh.md) |
| 时序、状态表示、共享归属、去中心化、重构、迁移、性能证据、清理、回调、子进程 | [general.zh.md](general.zh.md) |
@@ -36,8 +36,11 @@
en: 580441bd6cce9ee9
zh: a5f093d8e7dec2ee
/client-component-rules/build-and-style-follow-their-owners:
en: 561df1e1709a004c
zh: 89ca6eb4533648b8
en: 10cf740d4a8bb15f
zh: 01a3265f58dee3a1
/client-component-rules/selectors-match-through-a-class-or-attribute-not-not-empty-or-has:
en: f37261ef34a9d593
zh: 83d9735801f6bb3d
/client-component-rules/a-key-states-what-it-identifies:
en: 1d6f9bdc2b267fef
zh: cf4d579ca877c422
@@ -414,6 +414,35 @@ const HUGE = '...several KB of text...' // large text inline in the module
The bundle carries text and binary data that belong in CSS and assets, diffs carry unreadable blobs, and a theme override can no longer reach that colour.
<a id="keyed-selectors"></a>
## Selectors match through a class or attribute, not `:not`, `:empty`, or `:has`
A selector's rightmost compound names the element it styles through a class, an id, an attribute, or a type; the component sets that class or attribute for the state the design needs. Chromium files each rule under the key of that compound and tests it only against elements carrying the key. A rule without a key is tested against every element whose style it recalculates, and `:not()`, `:empty`, and `:has()` are evaluated in full on each of them; a `:has()` on an ancestor makes every change inside the ancestor restyle its subtree. In a long Session one such rule turns each streamed delta or scroll frame into whole-document work, and no single diff shows it. A visual requirement such as "the gap after a non-empty row" or "the label while the row is focused" has a structural answer: the component knows the state and names it.
- Judged by: [`verify-css-selectors`](../../scripts/verify-css-selectors.ts) in the hygiene gates rejects a rightmost compound without a key that matches through `:not()`, `:empty`, or `:has()` (`:empty:not([class])`, `.row > :not(.nav)`), a selector that names no class, id, or attribute anywhere (`*`, `body *`, `:hover`), and `:has()` outside the rightmost compound (`.row:has(.x) .label`). A reviewer also rejects a rule that works around the check by spelling the same condition differently.
- Not covered: a keyed compound may use `:not()` or `:empty` (`.reasoning:empty`, `.row:not([hidden])`), because the key limits the candidates; class-scoped universal and positional selectors (`.card *`, `.list > :first-child`, `.list > * + *`) and `:has()` on the styled element itself (`.row:has(> .icon)`) are allowed. The base stylesheets the gate lists are exempt from the first two rules. [Component rules](../web-styling.md#component-rules) own the remaining selector style.
- Exception: a rule that cannot be keyed states why in a `/* css-selector-gate: <reason> */` comment on the line directly above it, and review accepts the reason. Existing selectors are recorded in [the gate's baseline](../../scripts/css-selectors.baseline.json); it only shrinks, and a fix runs `pnpm run verify-css-selectors --prune`.
- Fix: before writing `:not`, `:empty`, or `:has`, ask which element and which state the design means, then name both. Put a class or `data-*` attribute on the element the rule styles; derive state such as "has a status", "expanded", or "empty" in the component and render it as a class, `aria-*`, or `data-*` attribute; express "after a visible row" with a sibling combinator between keyed compounds; when a parent must restyle a child, set a custom property on the parent and read it in the child's keyed rule.
The component names the state, and each rule's rightmost compound is keyed:
```css
/* The row renders data-has-status exactly when it renders the status. */
.heading[data-has-status] .text { flex-basis: auto; }
/* Visible members carry their key; the sibling combinator spaces them. */
.content > [data-chat-flow-key]:not([hidden]) ~ [data-chat-flow-key]:not([hidden]) { margin-top: 4px; }
```
The rules derive the state from the DOM, so Chromium evaluates them on every restyled element and restyles subtrees on unrelated changes:
```css
.body > :empty:not([class]) { margin-bottom: -4px; }
.heading:has(.statusText) .text { flex-basis: auto; }
.content > :not([hidden]) ~ :not([hidden]) { margin-top: 4px; }
```
Streaming into a 240-turn history spent about 3 s of main-thread style recalculation on one such rule (Issue #8790).
## A key states what it identifies
Pass a `key` only when it names which entity or instance an element represents, and state that identity — a `turnId`, for example, is unique inside one session. Most lists already have a stable business id and need no extra key. A key invented to silence a warning or to encode render order states an identity the data does not have, and an array index is never that identity, because an insert or delete shifts every following item onto a different element.
@@ -416,6 +416,35 @@ const HUGE = '...several KB of text...' // large text inline in the module
包里带上了本该属于 CSS 与资源的文本和二进制数据,diff 里躺着无法阅读的 blob,主题覆盖也再够不到那个颜色。
<a id="keyed-selectors"></a>
## 选择器经 class 或属性匹配,不靠 `:not`、`:empty`、`:has`
选择器最右侧的复合选择器通过 class、id、属性或标签名指明它所设置样式的元素;设计需要的状态由组件设置成对应的 class 或属性。Chromium 按该复合选择器的键把每条规则归类,只拿带有该键的元素来测试它。没有键的规则会对每个需要重算样式的元素都测试一遍,其中的 `:not()`、`:empty`、`:has()` 也会在每个元素上完整求值;写在祖先上的 `:has()` 则使祖先内部任何变化都重算其整棵子树。在长会话里,一条这样的规则就能把每段流式内容或每一帧滚动变成整文档的工作,而单看任何一处 diff 都发现不了。诸如"非空行之后的间距""行获得焦点时的标签"这类视觉需求都有结构化的写法:组件知道这个状态,就把它命名出来。
- 判定方式:hygiene 检查组中的 [`verify-css-selectors`](../../scripts/verify-css-selectors.ts) 拒绝三类写法:最右侧复合选择器没有键、却通过 `:not()`、`:empty` 或 `:has()` 匹配(`:empty:not([class])`、`.row > :not(.nav)`);整个选择器没有任何 class、id 或属性(`*`、`body *`、`:hover`);`:has()` 不在最右侧复合选择器上(`.row:has(.x) .label`)。评审同样拒绝换一种写法绕过检查、表达同一条件的规则。
- 不在范围内:带键的复合选择器可以使用 `:not()` 或 `:empty`(`.reasoning:empty`、`.row:not([hidden])`),因为键已限定候选元素;以 class 限定的通配和位置选择器(`.card *`、`.list > :first-child`、`.list > * + *`)以及写在被设置样式元素自身上的 `:has()`(`.row:has(> .icon)`)都允许使用。检查列出的基础样式表不受前两类限制。其余选择器写法由[组件规则](../web-styling.zh.md#component-rules)负责。
- 例外:无法加键的规则在紧邻其上一行写 `/* css-selector-gate: <理由> */` 说明原因,并由评审认可该理由。现有选择器记录在[检查的基线](../../scripts/css-selectors.baseline.json)中;基线只减不增,修掉一处后运行 `pnpm run verify-css-selectors --prune`。
- 修法:写 `:not`、`:empty` 或 `:has` 之前,先问设计指的是哪个元素、哪种状态,再把两者都命名出来。给规则所设置样式的元素加 class 或 `data-*` 属性;"有状态""已展开""为空"之类的状态在组件中算出,渲染成 class、`aria-*` 或 `data-*` 属性;"位于可见行之后"用带键复合选择器之间的兄弟组合符表达;父元素需要改变子元素样式时,在父元素上设置 CSS 自定义属性,由子元素带键的规则读取。
组件命名状态,每条规则最右侧的复合选择器都带键:
```css
/* The row renders data-has-status exactly when it renders the status. */
.heading[data-has-status] .text { flex-basis: auto; }
/* Visible members carry their key; the sibling combinator spaces them. */
.content > [data-chat-flow-key]:not([hidden]) ~ [data-chat-flow-key]:not([hidden]) { margin-top: 4px; }
```
规则从 DOM 推导状态,Chromium 因而对每个需要重算样式的元素求值,并在无关变化时重算子树:
```css
.body > :empty:not([class]) { margin-bottom: -4px; }
.heading:has(.statusText) .text { flex-basis: auto; }
.content > :not([hidden]) ~ :not([hidden]) { margin-top: 4px; }
```
向 240 轮的历史流式输出时,一条这样的规则就占用了约 3 秒主线程样式重算时间(Issue #8790)。
## 传 key 就要说明它标识什么
只有当 `key` 指明元素代表哪个实体或实例时才传它,并把这份身份说清楚——例如 `turnId` 在一个 session 内唯一。多数列表本就有稳定的业务 id,不需要额外的 key。为消除警告或编码渲染顺序而造的 key,声明的是一份数据并不具备的身份;数组下标从来不是这份身份,因为插入或删除会把后面每一项挪到另一个元素上。
+2 -2
View File
@@ -9,8 +9,8 @@
en: dc8c41fbf9869179
zh: e45976a585cb9c86
/web-ui-style-reference/component-rules:
en: 2cc062ec3939d19f
zh: 87bb9246cfd2a713
en: 0298e22304ed51eb
zh: 1f23811e4fb0bfdf
/web-ui-style-reference/input-capabilities:
en: bf2e98bce68743e2
zh: fc58dcbb60bb944a
+1
View File
@@ -20,6 +20,7 @@ Global style sheets belong in `ui-theme/src/styles/`. Component styles live besi
- Pair font sizes with line heights and use the theme typography variables when an existing role matches.
- Keep source text, terminal output, and diff lines unwrapped when their component contract requires column preservation; use the shared scrollbar styles rather than component-specific scrollbar selectors.
- Put presentation in CSS. Inline React styles may pass component-local custom-property values but must not encode theme branches.
- Key a selector's rightmost compound with a class, id, attribute, or type instead of matching through `:not()`, `:empty`, or `:has()`, and keep `:has()` on the styled element; [`verify-css-selectors`](../scripts/verify-css-selectors.ts) enforces the [keyed-selector rule](defensive-patterns/client-components.md#keyed-selectors).
- A relative `url()` in a plugin stylesheet points to a file in the package's `src/client/assets/`, and the build rewrites it to the [package asset](../packages/client/AGENTS.md#dependency-declaration) URL. `data:`, `#fragment`, `/`-rooted, scheme, and empty `url('')` references stay unchanged, a relative file reference with a fragment or query fails the build, and stylesheets from dependencies are not rewritten.
- Put `:hover` selectors under `@media (hover: hover)`, independently of viewport width. Keep selected, expanded, pressed, and keyboard-focus styles outside that condition. Without hover, actions remain visible or accessible through an explicit control; pointer handlers ignore touch when opening hover-only previews. Preserve keyboard focus visibility and reduced-motion behavior.
- Rounded corners inherit the global superellipse smoothing from ui-theme's `corner-shape.css` on supporting engines. Pair `corner-shape: round` with every full-round `border-radius` (`50%`, `100%`, or a pill radius) so circles and capsules keep circular arcs; the ui-theme corner-shape spec enforces the pairing.
+1
View File
@@ -20,6 +20,7 @@
- 字体大小必须与行高配对;已有角色匹配时使用主题排版变量。
- 当组件约定要求保留列结构时,源码文本、终端输出和 diff 行不得换行;使用共享滚动条样式,不得定义组件专用滚动条选择器。
- 呈现规则写在 CSS 中。React 内联样式可以传递组件局部自定义属性值,但不得编码主题分支。
- 选择器最右侧的复合选择器用 class、id、属性或标签名作键,不靠 `:not()`、`:empty` 或 `:has()` 匹配;`:has()` 只写在被设置样式的元素上。[`verify-css-selectors`](../scripts/verify-css-selectors.ts) 执行这条[带键选择器规则](defensive-patterns/client-components.zh.md#keyed-selectors)。
- 插件样式表中的相对 `url()` 指向本包 `src/client/assets/` 中的文件,构建会将其改写为[包资源](../packages/client/AGENTS.md#dependency-declaration) URL。`data:`、`#fragment`、以 `/` 开头、带 scheme 的引用以及空 `url('')` 引用保持不变,带片段或查询串的相对文件引用会让构建失败,依赖包中的样式表不会被改写。
- 将 `:hover` 选择器放在 `@media (hover: hover)` 内,不依赖视口宽度。选中、展开、按下和键盘焦点样式保留在该条件之外。无 hover 时,操作保持可见或通过明确控件访问;打开纯悬停预览的指针事件处理忽略触摸。保留清晰可见的键盘焦点和减少动态效果行为。
- 支持的引擎上,圆角继承 ui-theme `corner-shape.css` 的全局超级椭圆平滑。每个正圆 `border-radius`(`50%`、`100%` 或胶囊半径)必须配对 `corner-shape: round`,使圆形与胶囊保持圆弧;ui-theme 的 corner-shape spec 强制这一配对。
+1
View File
@@ -113,6 +113,7 @@
"verify-concrete-terms": "tsx scripts/verify-concrete-terms.ts",
"verify-no-unknown-casts": "tsx scripts/verify-no-unknown-casts.ts",
"verify-empty-catch": "tsx scripts/verify-empty-catch.ts",
"verify-css-selectors": "tsx scripts/verify-css-selectors.ts",
"verify-cordis-root": "tsx scripts/verify-cordis-root.ts",
"verify-doc-refs": "tsx scripts/verify-doc-refs.ts",
"verify-subsystem-pages": "tsx scripts/verify-subsystem-pages.ts",
@@ -145,7 +145,7 @@
flex-direction: column;
}
.content > * { flex-shrink: 0; }
.content > :not([hidden]):not(:empty) ~ :not([hidden]):not(:empty) {
.content > :not([hidden]):not(:empty) ~ [data-chat-flow-key]:not([hidden]):not(:empty) {
margin-top: var(--dsh-chat-flow-gap, 4px);
}
.expandedBody {
@@ -155,12 +155,12 @@
}
/* Member spacing changes share the closing body's timing. */
:global([data-chat-motion]) .content > :not([data-chat-motion]) {
:global([data-chat-motion]) .content > [data-chat-flow-key]:not([data-chat-motion]) {
transition: margin-top 160ms cubic-bezier(0.4, 0, 0.2, 1);
}
@media (prefers-reduced-motion: reduce) {
:global([data-chat-motion]) .content > :not([data-chat-motion]) {
:global([data-chat-motion]) .content > [data-chat-flow-key]:not([data-chat-motion]) {
transition: none;
}
}
@@ -91,7 +91,7 @@
starts squeezing labels; the container is the composer row (InputBar .row —
anonymous query because CSS modules hash container-names per module). */
@container (max-width: 460px) {
.trigger:has(.triggerIcon) .triggerLabel {
.triggerIcon ~ .triggerLabel {
display: none;
}
}
@@ -51,7 +51,9 @@
margin-top: 8px;
}
.markdown :where(h4, h5, h6):has(+ :where(ul, ol)) {
.markdown :where(h4):has(+ :where(ul, ol)),
.markdown :where(h5):has(+ :where(ul, ol)),
.markdown :where(h6):has(+ :where(ul, ol)) {
margin-bottom: 8px;
}
@@ -422,7 +424,7 @@
color: inherit;
}
.compact :global(.md-code-block) > :has(> [data-code-block-banner]) {
.compact :global(.md-code-block) > div:has(> [data-code-block-banner]) {
position: static;
z-index: auto;
}
@@ -458,7 +460,15 @@
}
/* Keep KaTeX's inline baseline and scroll the containing block only when needed. */
.compact :is(p, h1, h2, h3, h4, h5, h6, ul, ol):has(:global(.katex)) {
.compact p:has(:global(.katex)),
.compact h1:has(:global(.katex)),
.compact h2:has(:global(.katex)),
.compact h3:has(:global(.katex)),
.compact h4:has(:global(.katex)),
.compact h5:has(:global(.katex)),
.compact h6:has(:global(.katex)),
.compact ul:has(:global(.katex)),
.compact ol:has(:global(.katex)) {
overflow-x: auto;
overflow-y: hidden;
/* KaTeX descenders can paint one pixel below a fractional line-box edge. */
@@ -1588,7 +1588,7 @@
height: 14px;
}
.list:not(:has(.recommendations)) > .empty {
.list:not(.listWithRecommendations) > .empty {
flex: 1;
justify-content: center;
min-height: 280px;
@@ -285,7 +285,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
</Tooltip>}
/>}
</div>
<div className={css.list}>
<div className={clsx(css.list, showRecommendations && css.listWithRecommendations)}>
{selected === undefined && <CatalogFeedback status={status} populated={rows.length > 0} onRetry={onRetry} t={t} />}
{status === 'ready' && rows.length === 0 && <div className={css.empty} role="status">
<ScheduleEmptyIllustration className={css.emptyIllustration} />
@@ -72,7 +72,7 @@
border-radius: 2px;
}
.heading:has(.statusText) .text {
.heading[data-has-status] .text {
flex-basis: 12em;
}
@@ -47,7 +47,7 @@ function DetailItem({ item, t, onOpenFile }: { item: ToolDetailItem } & DetailCo
return (
<li className={css.item} data-change={item.change?.value}>
{item.title !== undefined && (
<div className={css.heading}>
<div className={css.heading} data-has-status={status !== undefined || undefined}>
{status !== undefined && (
<span className={css.status} role="img" aria-label={item.change?.label ?? status.label}>
{item.change?.value === 'added' ? '+'
@@ -193,7 +193,7 @@
gap: 0;
}
.sectionHeader:has(.searchExpanded) .sectionLabelHidden {
.sectionHeader .wide.sectionLabelHidden {
margin-right: 0;
}
@@ -178,7 +178,7 @@ describe('WorkspaceBrowser.module.css list', () => {
expect(declarations('.searchExpanded')?.get('width')).toBe('100%')
expect(declarations('.searchExpanded')?.get('margin-inline')).toBe('0')
expect(declarations('.searchExpanded .searchButton')?.get('height')).toBe('32px')
expect(declarations('.sectionHeader:has(.searchExpanded) .sectionLabelHidden')?.get('margin-right')).toBe('0')
expect(declarations('.sectionHeader .wide.sectionLabelHidden')?.get('margin-right')).toBe('0')
expect(declarations('.list')?.get('overflow')).toBe('visible')
expect(declarations('.listArea')?.get('min-height')).toBe('0')
})
+106
View File
@@ -0,0 +1,106 @@
{
"packages/client/ui-chat/src/client/chat/ChatView.module.css": {
"has-outside-subject": {
":is(.column, :global([data-slot=\"conversation.chat.flow\"])) > :not([hidden]):not(.textInteraction):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty))) ~ :not([hidden]):not(.textInteraction):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty)))": 1,
":is(.column, :global([data-slot=\"conversation.chat.flow\"])) > :nth-last-child(0n+2 of :not([hidden]):not([data-pending-steering]):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty)))):is(.flowItem:not([data-chat-flow-kind=\"user\"]):not([data-chat-flow-kind=\"steering\"]):not([data-chat-flow-kind=\"turn-trigger\"]), [data-chat-group-key]) ~ .running > .runningDivider": 1,
":is(.column, :global([data-slot=\"conversation.chat.flow\"])) > [data-chat-flow-kind=\"turn-process\"]:not(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty)) + :not([hidden]):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty))):not(.running):not(:has(:scope > [data-slot=\"conversation.chat.node\"] > [data-chat-steering-batch]))": 1
},
"unkeyed-costly-subject": {
":is(.column, :global([data-slot=\"conversation.chat.flow\"])) > :not([hidden]):not(.textInteraction):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty))) ~ :not([hidden]):not(.textInteraction):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty)))": 1,
":is(.column, :global([data-slot=\"conversation.chat.flow\"])) > [data-chat-flow-kind=\"turn-process\"] + :not([hidden]):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty))):not(.running):not([data-submission-echo], [data-pending-steering]):not(:has(:scope > [data-slot=\"conversation.chat.node\"] > [data-chat-steering-batch]))": 1,
":is(.column, :global([data-slot=\"conversation.chat.flow\"])) > [data-chat-flow-kind=\"turn-process\"]:not(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty)) + :not([hidden]):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty))):not(.running):not(:has(:scope > [data-slot=\"conversation.chat.node\"] > [data-chat-steering-batch]))": 1,
":is(.column, :global([data-slot=\"conversation.chat.flow\"])) > [data-chat-group-part=\"response\"]:not([hidden]):not(:empty) + :not([hidden]):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty))):not(.running):not(:has(:scope > [data-slot=\"conversation.chat.node\"] > [data-chat-steering-batch]))": 1,
".column > .older + :global([data-slot=\"conversation.chat.flow\"]) > :not([hidden]):not(.textInteraction):not(.flowItem:is(:empty, :has(:scope > [data-slot=\"conversation.chat.node\"]:empty)))": 1,
".column[data-chat-motion] > :global([data-slot=\"conversation.chat.flow\"]) > :not([data-chat-motion])": 2,
".column[data-chat-motion] > :not([data-chat-motion])": 2,
".column[data-input-fold] > :global([data-slot=\"conversation.chat.flow\"]) > :not([data-chat-motion])": 1,
".column[data-input-fold] > :not([data-chat-motion])": 1
}
},
"packages/client/ui-chat/src/client/chat/MessageIconActions.module.css": {
"has-outside-subject": {
":is([data-chat-flow-kind=\"user\"], [data-chat-flow-kind=\"steering\"]):has(:scope ~ :is([data-chat-flow-kind=\"user\"], [data-chat-flow-kind=\"steering\"])) .actions": 1,
":is([data-chat-flow-kind=\"user\"], [data-chat-flow-kind=\"steering\"]):has(:scope ~ :is([data-chat-flow-kind=\"user\"], [data-chat-flow-kind=\"steering\"])):focus-within .actions": 1,
":is([data-chat-flow-kind=\"user\"], [data-chat-flow-kind=\"steering\"]):has(:scope ~ :is([data-chat-flow-kind=\"user\"], [data-chat-flow-kind=\"steering\"])):hover .actions": 1
}
},
"packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css": {
"has-outside-subject": {
".root:has([data-conversation-composer-overlay]) .widthHandle": 1,
".scrollBody:has([data-conversation-composer-overlay]) > :global([data-slot=\"conversation.session\"]) > .viewArea": 1,
".scrollBody:has([data-conversation-composer-overlay]) > .composerSeat": 1
}
},
"packages/client/ui-primitives/src/JsonTree.module.css": {
"has-outside-subject": {
".row:has(:scope > .copySlot) > .stringField .stringToggleSlot": 1,
".row:has(:scope > .stringField) > .copySlot": 1,
".row:hover:not(:has(.row:hover)) > .copySlot": 1
}
},
"packages/client/ui-primitives/src/markdown/MarkdownText.module.css": {
"unkeyed-costly-subject": {
".markdown li > *:last-child:not(:global(.md-code-block), .fenceSeat)": 1
}
},
"packages/client/ui-session-panel/src/client/SessionPanel.module.css": {
"has-outside-subject": {
".head:hover:has(:scope > .grip) > .actions": 1,
".panel :where([data-session-panel-row] > [data-row-part=\"body\"]:has([data-row-part=\"detail\"]) > [data-row-part=\"icon\"])": 1,
".section:not(:has(:scope > .body > [data-slot]:empty), :has(:scope > .body > [data-slot] > [data-slot]:only-child:empty)) ~ .section:not(:has(:scope > .body > [data-slot]:empty), :has(:scope > .body > [data-slot] > [data-slot]:only-child:empty))": 1
}
},
"packages/client/ui-shortcuts/src/client/Reference.module.css": {
"has-outside-subject": {
".row:has(:focus-visible) .rowActions": 1
}
},
"packages/client/ui-sidebar-browser/src/client/view/Browser.module.css": {
"has-outside-subject": {
":global(html:has([data-dockkit-pointer])) .webview": 1
}
},
"packages/client/ui-sidebar-documentpreview/src/client/pdf/PdfBody.module.css": {
"unkeyed-costly-subject": {
".text :global(.textLayer) > :not(:global(.markedContent))": 1
}
},
"packages/client/ui-sidebar-files/src/client/FilesBody.module.css": {
"unkeyed-costly-subject": {
"[data-files-navigator-row] > :not(.navigator)": 1
}
},
"packages/client/ui-sidebar/src/client/SidebarRoot.module.css": {
"has-outside-subject": {
".panelEntry:has(:focus-visible) .panelUnpin": 1,
".panelEntry:has(.panelUnpin):has(:focus-visible) .panelTrailing": 1,
".panelEntry:has(.panelUnpin):hover .panelTrailing": 1
}
},
"packages/client/ui-tool/src/client/tool/components/ToolRow.module.css": {
"has-outside-subject": {
".row:not([aria-expanded=\"true\"]):has(.fileTargetLink:hover) .diffAdded": 1,
".row:not([aria-expanded=\"true\"]):has(.fileTargetLink:hover) .diffRemoved": 1
}
},
"packages/client/ui-workspace/src/client/rows/Rows.module.css": {
"has-outside-subject": {
".sessionRow:has(.pinnedAction) .pinIndicator": 1
},
"unkeyed-costly-subject": {
".sessionRow .rowQuickActions > :global([data-slot]) > :not(.pinnedAction)": 1
}
},
"packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css": {
"unkeyed-costly-subject": {
".viewed > :not(.chevron):not(.name):not(.threads)": 1
}
},
"packages/experimental/timeline/src/client/timeline.css": {
"has-outside-subject": {
"body:has(.dsh-timeline[data-timeline-dock-open=\"true\"]) .timeline-dock[data-current-tree=\"true\"] .timeline-dock-action svg": 1,
"body:has(.dsh-timeline[data-timeline-dock-open=\"true\"]) .timeline-dock[data-current-tree=\"true\"] .timeline-dock-close": 1,
"body:has(.dsh-timeline[data-timeline-dock-open=\"true\"]) .timeline-dock[data-current-tree=\"true\"] .timeline-dock-open": 1
}
}
}
+1 -1
View File
@@ -384,7 +384,7 @@ describe('gate graph validation', () => {
'rescope-vendor', 'publint', 'constraints', 'default-product-isolation', 'product-use', 'official-bundle-catalog', 'provider-data', 'package-dependencies', 'application-entrypoints',
'dsh-package-licenses', 'node-next-types',
'optional-dependency-imports', 'client-packages', 'installer-locales', 'locale-metadata', 'client-ui-i18n', 'client-route-resolution', 'no-bare-dispatcher',
'plugin-record-callers', 'no-unknown-casts', 'empty-catch', 'cordis-root', 'no-top-level-await', 'plugin-entry-exports',
'plugin-record-callers', 'no-unknown-casts', 'empty-catch', 'css-selectors', 'cordis-root', 'no-top-level-await', 'plugin-entry-exports',
'cordis-config', 'runtime-closure',
])
})
+1
View File
@@ -427,6 +427,7 @@ function sharedHygieneGates(): Gate[] {
pnpmScript('plugin-record-callers', 'verify-plugin-record-callers', { label: 'plugin record callers' }),
pnpmScript('no-unknown-casts', 'verify-no-unknown-casts', { label: 'no new unknown casts' }),
pnpmScript('empty-catch', 'verify-empty-catch', { label: 'no new silent catches' }),
pnpmScript('css-selectors', 'verify-css-selectors', { label: 'bucketed CSS selectors' }),
pnpmScript('cordis-root', 'verify-cordis-root', { label: 'no new Cordis root reads' }),
pnpmScript('no-top-level-await', 'verify-no-top-level-await', { label: 'no module-scope await' }),
pnpmScript('plugin-entry-exports', 'verify-plugin-entry-exports', { label: 'plugin entry exports' }),
+154
View File
@@ -0,0 +1,154 @@
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
import { checkStylesheet, compareBaseline, countFindings, listStylesheets, parseBaseline, type CssSelectorDefect } from './verify-css-selectors.ts'
const root = resolve(import.meta.dirname, '..')
function defects(source: string, file = 'packages/client/x/src/a.module.css'): [number, CssSelectorDefect, string][] {
return checkStylesheet(file, source).map(finding => [finding.line, finding.defect, finding.selector])
}
describe('verify-css-selectors', () => {
it.each([
'.a', '#a', 'div', '[data-x]', '[data-x="y"]', ':root', 'a:link', 'a:any-link', ':focus', ':focus-visible',
':is(.a)', ':where(.a .b)', '.a::before', 'input::placeholder', '::-webkit-scrollbar-thumb', '.a :not(.b).c',
'.x:has(.y)', '.a:not(:has(.b))', '.a:has(.b .c)', ':global(.a) > :global(.b)', '.a :global(.b.c)',
'.a:hover', '.a:empty', ':is(:where(.a))',
])('accepts the bucketed subject %s', (selector) => {
expect(defects(`${selector} { color: red }`)).toEqual([])
})
it.each([
'.a > *', '.a *', '.card *', '.a > *:first-child', '.a :global(:first-child)', '.list > * + *', ':is(.a, .b)',
':where(.a, .b)', '.a :hover', '.a ::selection', '.a :disabled', ':is(.a, .b) *', ':where([data-x] *)', ':is(.a > *)',
':global(.a) > :global(*)', 'li > .a ~ *', ':is(.x:not(.y) > span, .z)', '.c > :where(.x:not(.y) *)',
])('accepts the scoped unkeyed subject %s', (selector) => {
expect(defects(`${selector} { color: red }`)).toEqual([])
})
it.each([
':empty:not([class])', '.a > :not(.b)', '.a > *:not(.b)', '.a :empty', '.a > :has(.b)', ':is(.a) > :is(:empty, .b)',
':global(.a) > :not(:global(.b))', '.a > .b + :not([hidden])', '.a > :nth-child(2 of :not(.b))',
])('rejects the unkeyed subject using :not(), :empty or :has() in %s', (selector) => {
expect(defects(`${selector} { color: red }`).map(([, defect]) => defect)).toEqual(['unkeyed-costly-subject'])
})
it.each([
'*', ':hover', '::before', '::-webkit-scrollbar', 'body *', 'html body > *', ':hover::before', 'div > *', '*:not(.a) *',
':is(.a, *) > *',
])('rejects the unscoped universal selector %s', (selector) => {
expect(defects(`${selector} { color: red }`).map(([, defect]) => defect)).toEqual(['global-universal'])
})
it('exempts framework stylesheets from subject rules but not from the :has() rule', () => {
const file = 'packages/client/web/src/base.css'
expect(defects('* { box-sizing: border-box }\nbody > :not(#root) { color: red }\n', file)).toEqual([])
expect(defects('.a:has(.b) .c { color: red }', file).map(([, defect]) => defect)).toEqual(['has-outside-subject'])
expect(defects('* { box-sizing: border-box }', 'packages/client/ui-theme/src/styles/x.css')).toEqual([])
expect(defects('* { box-sizing: border-box }', 'packages/client/ui-theme/src/client/x.module.css').map(([, defect]) => defect))
.toEqual(['global-universal'])
})
it.each([
'.a:has(.b) .c', '.a:has(.b) > .c', '.a:has(.b) + .c', ':is(.a:has(.b)) .c', '.c:not(.a:has(.b) .d)',
':global(.a:has(.b)) .c', '.c:is(:where(.a:has(.b) .d))',
])('rejects :has() outside the subject in %s', (selector) => {
expect(defects(`${selector} { color: red }`).map(([, defect]) => defect)).toEqual(['has-outside-subject'])
})
it('reports both defects of one selector and each selector of a list', () => {
expect(defects('.ok, .a:has(.b) > :not(.c), * { color: red }')).toEqual([
[1, 'unkeyed-costly-subject', '.a:has(.b) > :not(.c)'],
[1, 'has-outside-subject', '.a:has(.b) > :not(.c)'],
[1, 'global-universal', '*'],
])
})
it('reads rules inside at-rules and reports one-based lines', () => {
expect(defects('.a { color: red }\n@media (width < 768px) {\n .b > :not(.c) { color: red }\n}\n@supports (display: grid) {\n :hover { color: red }\n}\n'))
.toEqual([[3, 'unkeyed-costly-subject', '.b > :not(.c)'], [6, 'global-universal', ':hover']])
})
it('rejects nested rules instead of guessing what & resolves to', () => {
expect(defects('.a {\n color: red;\n & > * { color: blue }\n}\n').map(([, defect]) => defect)).toEqual(['nesting'])
})
it('accepts a rejected rule whose reason comment ends on the line directly above it', () => {
expect(defects('/* css-selector-gate: the scrollbar pseudo-element has no keyed form */\n::-webkit-scrollbar { width: 8px }\n')).toEqual([])
expect(defects('/*\n css-selector-gate: reason spanning\n two lines\n*/\n* { color: red }\n')).toEqual([])
})
it('rejects an exception comment that is empty, detached, or above an accepted rule', () => {
expect(defects('/* css-selector-gate: */\n* { color: red }\n')).toEqual([
[1, 'stale-exception', 'css-selector-gate:'],
[2, 'global-universal', '*'],
])
expect(defects('/* css-selector-gate: reason */\n\n* { color: red }\n')).toEqual([
[1, 'stale-exception', 'css-selector-gate: reason'],
[3, 'global-universal', '*'],
])
expect(defects('/* css-selector-gate: reason */\n.a { color: red }\n')).toEqual([[1, 'stale-exception', 'css-selector-gate: reason']])
})
it('parses plain stylesheets without CSS Modules syntax and names a file it cannot parse', () => {
expect(defects('.a > :not(.b) { color: red }', 'packages/client/x/src/plain.css').map(([, defect]) => defect)).toEqual(['unkeyed-costly-subject'])
expect(() => checkStylesheet('packages/client/x/src/bad.css', '.a { color: red')).not.toThrow()
expect(() => checkStylesheet('packages/client/x/src/bad.module.css', ':global(')).toThrow(/bad\.module\.css/u)
})
it('scans repository stylesheets outside vendor', () => {
const files = listStylesheets(root)
expect(files).toContain('packages/client/ui-chat/src/client/chat/ChatView.module.css')
expect(files.every(file => file.endsWith('.css') && !file.startsWith('vendor/'))).toBe(true)
})
it('serializes attribute operators, values and case flags so recorded selectors stay exact', () => {
expect(defects('[a="b c"][d^=e i] > :empty { color: red }').map(([, , selector]) => selector)).toEqual(['[a="b c"][d^="e" i] > :empty'])
})
describe('baseline', () => {
const file = 'packages/client/x/src/a.module.css'
const findings = checkStylesheet(file, '.a > :empty { color: red }\n.b > :empty { color: red }\n.c:has(.d) .e { color: red }\n')
it('counts findings by file, defect and selector', () => {
expect(countFindings(findings)).toEqual({ [file]: {
'has-outside-subject': { '.c:has(.d) .e': 1 },
'unkeyed-costly-subject': { '.a > :empty': 1, '.b > :empty': 1 },
} })
})
it('accepts recorded occurrences and rejects one beyond its count or in another file', () => {
const baseline = countFindings(findings)
expect(compareBaseline(findings, baseline)).toEqual({ added: [], stale: [] })
const extra = checkStylesheet(file, '.a > :empty { color: red }\n.a > :empty { color: blue }\n.b > :empty { color: red }\n.c:has(.d) .e { color: red }\n')
expect(compareBaseline(extra, baseline).added.map(finding => [finding.line, finding.selector])).toEqual([[2, '.a > :empty']])
const moved = findings.map(finding => ({ ...finding, file: 'packages/client/x/src/b.module.css' }))
expect(compareBaseline(moved, baseline).added).toHaveLength(3)
})
it('reports a recorded occurrence that no longer exists', () => {
const fixed = checkStylesheet(file, '.a > .f { color: red }\n.b > :empty { color: red }\n.c:has(.d) .e { color: red }\n')
expect(compareBaseline(fixed, countFindings(findings))).toEqual({ added: [], stale: [[file, 'unkeyed-costly-subject', '.a > :empty', 1]] })
})
it('never records nesting or stale exception comments', () => {
const unrecordable = checkStylesheet(file, '/* css-selector-gate: reason */\n.a { color: red }\n.b { & .c { color: red } }\n')
expect(countFindings(unrecordable)).toEqual({})
expect(compareBaseline(unrecordable, {}).added.map(finding => finding.defect)).toEqual(['stale-exception', 'nesting'])
})
it.each([
[[], /file-to-defects/u],
[{ 'a.ts': { 'global-universal': { '*': 1 } } }, /invalid baseline file/u],
[{ 'vendor/a.css': { 'global-universal': { '*': 1 } } }, /invalid baseline file/u],
[{ '../a.css': { 'global-universal': { '*': 1 } } }, /invalid baseline file/u],
[{ 'a.css': {} }, /invalid baseline file/u],
[{ 'a.css': { 'nesting': { '*': 1 } } }, /invalid baseline defect/u],
[{ 'a.css': { 'global-universal': {} } }, /invalid baseline defect/u],
[{ 'a.css': { 'global-universal': { '*': 0 } } }, /invalid baseline count/u],
[{ 'a.css': { 'global-universal': { '*': 1.5 } } }, /invalid baseline count/u],
])('rejects the malformed baseline %j', (value, message) => {
expect(() => parseBaseline(value)).toThrow(message)
})
})
})
+505
View File
@@ -0,0 +1,505 @@
/**
* Reject stylesheet selectors whose matching cost in Chromium grows with the whole document.
*
* Blink sorts each rule into a bucket by its subject compound, the compound after the last
* combinator: an id, class, attribute or type selector, a few pseudo-classes (`:focus`,
* `:focus-visible`, link states, `:root`, `:host`), some pseudo-elements, or a single-argument
* `:is()`/`:where()` whose own subject has one of these. A rule without such a key lands in the
* universal bucket and is tested on every restyled element; an ancestor class or attribute still
* lets Blink's ancestor filter reject most elements cheaply, but `:not()`, `:empty` and `:has()`
* cannot be rejected that way and are evaluated in full. The gate therefore rejects:
*
* - `unkeyed-costly-subject`: a subject without a bucket key that contains `:not()`, `:empty` or
* `:has()`, such as `.row > :not(.nav)` or `:empty:not([class])`. A keyed subject such as
* `.reasoning:empty` or `.row:not([hidden])` is accepted.
* - `global-universal`: a subject without a bucket key whose selector names no class, id or
* attribute anywhere, such as `*` or `body *`. Class-scoped forms such as `.card *`,
* `.page > *` and `.list > :first-child` are accepted.
* - `has-outside-subject`: a `:has()` outside the subject compound, such as `.row:has(.x) .child`,
* which makes changes inside the anchor's subtree invalidate the anchor's descendants.
*
* {@link FRAMEWORK_STYLESHEETS} hold document-wide base styles; only `has-outside-subject` applies
* to them. The corpus is every tracked or non-ignored `.css` file outside `vendor/`; CSS Modules
* `:global()`/`:local()` wrappers are transparent. Styles embedded in TypeScript strings are out of
* scope. A rule that must keep a rejected selector states why in a comment that ends on the line
* directly above the rule and starts with `css-selector-gate:`; an exception comment that no
* longer precedes a rejected rule is itself a finding. Nested CSS is rejected because the gate
* does not resolve `&`.
*
* Existing selectors are recorded in `scripts/css-selectors.baseline.json` by file, defect and
* serialized selector, with the number of occurrences. A finding beyond its recorded count fails;
* a recorded occurrence that no longer exists also fails until `--prune` removes it, so the list
* only shrinks.
*/
import { execFileSync } from 'node:child_process'
import { lstatSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { transform, type Selector, type SelectorComponent } from 'lightningcss'
const GATE = 'verify-css-selectors'
const root = resolve(import.meta.dirname, '..')
/** Comment prefix that records why a rule keeps a rejected selector. */
export const EXCEPTION_PREFIX = 'css-selector-gate:'
/** Why a selector is rejected. */
export type CssSelectorDefect = 'unkeyed-costly-subject' | 'global-universal' | 'has-outside-subject' | 'nesting' | 'stale-exception'
/** One rejected selector or stale exception comment. */
export interface CssSelectorFinding {
/** Repository-relative path with forward slashes. */
file: string
/** One-based line of the rule's selector list, or of the stale comment. */
line: number
defect: CssSelectorDefect
/** Serialized selector, or the comment text for a stale exception. */
selector: string
}
/**
* Repository-relative paths, or directory prefixes ending in `/`, of document-wide base and framework
* stylesheets. Each entry must match at least one scanned stylesheet.
*/
export const FRAMEWORK_STYLESHEETS: readonly string[] = [
'apps/desktop/renderer/',
'packages/client/ui-theme/src/styles/',
'packages/client/web/src/base.css',
]
/**
* Whether a stylesheet holds document-wide base styles.
* @param file - repository-relative path with forward slashes.
* @returns `true` when {@link FRAMEWORK_STYLESHEETS} names the file or a prefix of it.
*/
export function isFrameworkStylesheet(file: string): boolean {
return FRAMEWORK_STYLESHEETS.some(entry => entry.endsWith('/') ? file.startsWith(entry) : file === entry)
}
/** Pseudo-classes that give a compound its own Blink bucket. */
const BUCKETED_PSEUDO_CLASSES = new Set(['focus', 'focus-visible', 'link', 'visited', 'any-link', 'root', 'host', 'active-view-transition'])
/**
* Pseudo-elements Blink buckets by their own name; `::-webkit-scrollbar` itself is not one of them,
* only its parts are.
*/
const BUCKETED_PSEUDO_ELEMENTS = new Set(['placeholder', 'file-selector-button', 'details-content', 'part', 'slotted', 'cue', 'custom'])
const BUCKETED_SCROLLBAR_PARTS = new Set(['button', 'corner', 'thumb', 'track', 'track-piece'])
function unwrapModules(selector: Selector): SelectorComponent[] {
const out: SelectorComponent[] = []
for (const component of selector) {
if (component.type === 'pseudo-class' && (component.kind === 'global' || component.kind === 'local')) {
out.push(...unwrapModules(component.selector))
} else {
out.push(component)
}
}
return out
}
function compounds(selector: Selector): SelectorComponent[][] {
let current: SelectorComponent[] = []
const out = [current]
for (const component of unwrapModules(selector)) {
if (component.type === 'combinator') out.push(current = [])
else current.push(component)
}
return out
}
function subject(selector: Selector): SelectorComponent[] {
return compounds(selector).at(-1) ?? []
}
/**
* Whether Blink places a compound in a bucket other than the universal one.
* @param compound - simple selectors of one compound, in source order.
* @returns `true` when a component before any non-bucketing pseudo-element supplies a key.
*/
function isBucketed(compound: readonly SelectorComponent[]): boolean {
for (const component of compound) {
switch (component.type) {
case 'id':
case 'class':
case 'type':
case 'attribute':
return true
case 'pseudo-class':
if (BUCKETED_PSEUDO_CLASSES.has(component.kind)) return true
if ((component.kind === 'is' || component.kind === 'where') && component.selectors.length === 1) {
const [only] = component.selectors
if (only !== undefined && isBucketed(subject(only))) return true
}
break
case 'pseudo-element':
if (BUCKETED_PSEUDO_ELEMENTS.has(component.kind)) return true
if (component.kind === 'webkit-scrollbar' && BUCKETED_SCROLLBAR_PARTS.has(component.value)) return true
// Blink stops reading a compound at other pseudo-elements, such as `::before`.
return false
default:
break
}
}
return false
}
function nestedSelectors(component: SelectorComponent): readonly Selector[] {
if (component.type === 'pseudo-class') {
switch (component.kind) {
case 'not':
case 'is':
case 'where':
case 'any':
case 'has':
return component.selectors
case 'host':
return component.selectors == null ? [] : [component.selectors]
case 'nth-child':
case 'nth-last-child':
return component.of ?? []
default:
if ('selector' in component && Array.isArray(component.selector)) return [component.selector]
return []
}
}
if (component.type === 'pseudo-element' && 'selector' in component && Array.isArray(component.selector)) return [component.selector]
return []
}
function containsHas(components: readonly SelectorComponent[]): boolean {
return components.some(component => (component.type === 'pseudo-class' && component.kind === 'has')
|| nestedSelectors(component).some(containsHas))
}
/** Pseudo-classes Blink evaluates in full on every candidate element. */
const COSTLY_PSEUDO_CLASSES = new Set(['not', 'empty', 'has'])
/**
* Whether a subject compound matches through `:not()`, `:empty` or `:has()`, directly or through the
* subject compound of an `:is()`, `:where()` or `:nth-*(… of …)` argument.
* @param compound - simple selectors of a subject compound.
* @returns `true` when such a pseudo-class decides the match.
*/
function containsCostlyPseudo(compound: readonly SelectorComponent[]): boolean {
return compound.some(component => (component.type === 'pseudo-class' && COSTLY_PSEUDO_CLASSES.has(component.kind))
|| (component.type === 'pseudo-class' && nestedSelectors(component).some(argument => containsCostlyPseudo(subject(argument)))))
}
/**
* Whether a selector names a class, id or attribute that scopes its subject: in any compound
* before the subject, or in an `:is()`/`:where()` argument; `:not()` and `:has()` arguments do not
* scope the elements a selector matches.
* @param components - simple selectors and combinators of one complex selector.
* @returns `true` when such a key exists.
*/
function hasScopingKey(components: readonly SelectorComponent[]): boolean {
return components.some((component) => {
if (component.type === 'class' || component.type === 'id' || component.type === 'attribute') return true
if (component.type === 'pseudo-class' && (component.kind === 'is' || component.kind === 'where')) {
return component.selectors.every(argument => hasScopingKey(unwrapModules(argument)))
}
return false
})
}
function containsNesting(components: readonly SelectorComponent[]): boolean {
return components.some(component => component.type === 'nesting' || nestedSelectors(component).some(containsNesting))
}
/**
* Whether a `:has()` appears in a compound that is not the subject, including inside `:is()`,
* `:where()` and `:not()` arguments of such compounds and inside the non-subject compounds of
* arguments of the subject.
* @param selector - one complex selector.
* @returns `true` when the selector holds such a `:has()`.
*/
function hasOutsideSubject(selector: Selector): boolean {
const all = compounds(selector)
if (all.slice(0, -1).some(containsHas)) return true
return subject(selector).some(component => !(component.type === 'pseudo-class' && component.kind === 'has')
&& nestedSelectors(component).some(hasOutsideSubject))
}
const ATTRIBUTE_OPERATORS: Record<string, string> = {
'equal': '=', 'includes': '~=', 'dash-match': '|=', 'prefix': '^=', 'substring': '*=', 'suffix': '$=',
}
function serialize(selector: Selector): string {
return selector.map((component): string => {
switch (component.type) {
case 'combinator':
return { 'descendant': ' ', 'child': ' > ', 'next-sibling': ' + ', 'later-sibling': ' ~ ' }[component.value as string] ?? ` ${component.value} `
case 'class': return '.' + component.name
case 'id': return '#' + component.name
case 'type': return component.name
case 'universal': return '*'
case 'nesting': return '&'
case 'attribute': {
const operation = component.operation
if (operation == null) return '[' + component.name + ']'
const operator = ATTRIBUTE_OPERATORS[operation.operator] ?? operation.operator
const flag = operation.caseSensitivity === 'ascii-case-insensitive' ? ' i' : operation.caseSensitivity === 'explicit-case-sensitive' ? ' s' : ''
return '[' + component.name + operator + JSON.stringify(operation.value) + flag + ']'
}
case 'pseudo-class': {
const inner = nestedSelectors(component)
if ('a' in component && 'b' in component && typeof component.a === 'number' && typeof component.b === 'number') {
const step = `${component.a}n${component.b < 0 ? '' : '+'}${component.b}`
return ':' + component.kind + '(' + step + (inner.length > 0 ? ' of ' + inner.map(serialize).join(', ') : '') + ')'
}
return ':' + component.kind + (inner.length > 0 ? '(' + inner.map(serialize).join(', ') + ')' : '')
}
case 'pseudo-element': return '::' + component.kind + ('value' in component && typeof component.value === 'string' ? '-' + component.value : '')
default: return component.type
}
}).join('')
}
/** One exception comment: its last line and text. */
interface ExceptionComment {
line: number
text: string
}
function exceptionComments(source: string): ExceptionComment[] {
const comments: ExceptionComment[] = []
for (const match of source.matchAll(/\/\*([\s\S]*?)\*\//gu)) {
const text = (match[1] ?? '').trim()
if (!text.startsWith(EXCEPTION_PREFIX)) continue
const end = match.index + match[0].length
comments.push({ line: source.slice(0, end).split('\n').length, text })
}
return comments
}
/**
* Check one stylesheet.
* @param file - repository-relative path; `.module.css` enables CSS Modules parsing.
* @param source - stylesheet text.
* @returns rejected selectors and stale or empty exception comments, in source order.
* @throws when lightningcss cannot parse the stylesheet; the message names `file`.
*/
export function checkStylesheet(file: string, source: string): CssSelectorFinding[] {
const rejected: CssSelectorFinding[] = []
const framework = isFrameworkStylesheet(file)
try {
transform({
filename: file,
code: Buffer.from(source),
cssModules: file.endsWith('.module.css'),
visitor: {
Rule: {
style(rule) {
const line = rule.value.loc.line + 1
for (const selector of rule.value.selectors) {
const text = serialize(selector)
if (containsNesting(selector)) rejected.push({ file, line, defect: 'nesting', selector: text })
else {
if (!framework && !isBucketed(subject(selector))) {
if (containsCostlyPseudo(subject(selector))) rejected.push({ file, line, defect: 'unkeyed-costly-subject', selector: text })
else if (!hasScopingKey(unwrapModules(selector))) rejected.push({ file, line, defect: 'global-universal', selector: text })
}
if (hasOutsideSubject(selector)) rejected.push({ file, line, defect: 'has-outside-subject', selector: text })
}
}
},
},
},
})
} catch (error) {
throw new Error(`${GATE}: cannot parse stylesheet ${file}: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
}
const comments = exceptionComments(source)
const used = new Set<ExceptionComment>()
const findings = rejected.filter((finding) => {
if (finding.defect === 'nesting') return true
const comment = comments.find(candidate => candidate.line === finding.line - 1)
if (comment === undefined || comment.text.slice(EXCEPTION_PREFIX.length).trim() === '') return true
used.add(comment)
return false
})
for (const comment of comments) {
if (!used.has(comment)) findings.push({ file, line: comment.line, defect: 'stale-exception', selector: comment.text })
}
return findings.sort((a, b) => a.line - b.line)
}
/**
* List the stylesheets the gate scans.
* @param repoRoot - repository root containing the Git index.
* @returns sorted repository-relative `.css` paths outside `vendor/`.
* @throws when discovery finds no Client stylesheet or an eligible path is a symlink.
*/
export function listStylesheets(repoRoot: string): string[] {
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
cwd: repoRoot,
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
}).split('\0').map(file => file.replaceAll('\\', '/')).filter(file => file.endsWith('.css') && !file.startsWith('vendor/')))].sort()
const present = files.filter((file) => {
const stat = lstatSync(resolve(repoRoot, file), { throwIfNoEntry: false })
if (stat?.isSymbolicLink()) throw new Error(`${GATE}: stylesheet symlink is unsupported: ${file}`)
return stat?.isFile() === true
})
if (!present.some(file => file.startsWith('packages/client/'))) throw new Error(`${GATE}: stylesheet discovery omitted packages/client/`)
for (const entry of FRAMEWORK_STYLESHEETS) {
if (!present.some(file => isFrameworkStylesheet(file) && (entry.endsWith('/') ? file.startsWith(entry) : file === entry))) {
throw new Error(`${GATE}: framework stylesheet entry matches no stylesheet: ${entry}`)
}
}
return present
}
const MESSAGES: Record<CssSelectorDefect, string> = {
'unkeyed-costly-subject': 'subject compound has no id, class, attribute or type selector and uses :not(), :empty or :has(), which Chromium evaluates on every restyled element',
'global-universal': 'selector names no class, id or attribute, so Chromium tests it on every restyled element',
'has-outside-subject': ':has() outside the subject compound invalidates the anchor subtree on every change inside it',
'nesting': 'nested CSS is unsupported by this gate; write the rule unnested',
'stale-exception': `${EXCEPTION_PREFIX} comment does not directly precede a rejected rule`,
}
/** Defects an existing selector may be recorded for. */
const BASELINE_DEFECTS = ['unkeyed-costly-subject', 'global-universal', 'has-outside-subject'] as const
type BaselineDefect = typeof BASELINE_DEFECTS[number]
/** Recorded occurrences: file, then defect, then serialized selector, then count. */
export type CssSelectorBaseline = Record<string, Partial<Record<BaselineDefect, Record<string, number>>>>
/** Repository-relative path of the recorded existing selectors. */
export const BASELINE_PATH = 'scripts/css-selectors.baseline.json'
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isBaselineDefect(value: string): value is BaselineDefect {
return (BASELINE_DEFECTS as readonly string[]).includes(value)
}
/**
* Validate a parsed baseline.
* @param value - parsed JSON.
* @returns the baseline.
* @throws when an entry is not a positive count under a `.css` path and a recordable defect.
*/
export function parseBaseline(value: unknown): CssSelectorBaseline {
if (!isRecord(value)) throw new Error(`${GATE}: ${BASELINE_PATH} must be a file-to-defects object`)
const baseline: CssSelectorBaseline = {}
for (const [file, defects] of Object.entries(value)) {
if (!file.endsWith('.css') || file.startsWith('vendor/') || file.startsWith('/') || file.includes('\\')
|| file.split('/').includes('..') || !isRecord(defects) || Object.keys(defects).length === 0) {
throw new Error(`${GATE}: invalid baseline file: ${file}`)
}
const parsed: CssSelectorBaseline[string] = {}
for (const [defect, selectors] of Object.entries(defects)) {
if (!isBaselineDefect(defect) || !isRecord(selectors) || Object.keys(selectors).length === 0) {
throw new Error(`${GATE}: invalid baseline defect: ${file}: ${defect}`)
}
const counts: Record<string, number> = {}
for (const [selector, count] of Object.entries(selectors)) {
if (typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) {
throw new Error(`${GATE}: invalid baseline count: ${file}: ${defect}: ${selector}`)
}
counts[selector] = count
}
parsed[defect] = counts
}
baseline[file] = parsed
}
return baseline
}
/**
* Count findings in baseline form.
* @param findings - findings to record; only recordable defects are counted.
* @returns the baseline with files, defects and selectors in sorted order.
*/
export function countFindings(findings: readonly CssSelectorFinding[]): CssSelectorBaseline {
const baseline: CssSelectorBaseline = {}
for (const { file, defect, selector } of findings) {
if (!isBaselineDefect(defect)) continue
const counts = (baseline[file] ??= {})[defect] ??= {}
counts[selector] = (counts[selector] ?? 0) + 1
}
const sorted = <T>(record: Record<string, T>): [string, T][] => Object.entries(record).sort(([a], [b]) => a.localeCompare(b))
return Object.fromEntries(sorted(baseline).map(([file, defects]) => [file, Object.fromEntries(
sorted(defects as Record<string, Record<string, number>>).map(([defect, counts]) => [defect, Object.fromEntries(sorted(counts))]),
)]))
}
/** Findings beyond the baseline and recorded occurrences that no longer exist. */
export interface BaselineComparison {
added: CssSelectorFinding[]
/** `file`, defect, selector and the number of recorded occurrences that are gone. */
stale: [string, BaselineDefect, string, number][]
}
/**
* Compare findings with the recorded occurrences.
* @param findings - current findings.
* @param baseline - recorded occurrences.
* @returns new findings, including every non-recordable defect, and retired occurrences.
*/
export function compareBaseline(findings: readonly CssSelectorFinding[], baseline: CssSelectorBaseline): BaselineComparison {
const remaining = structuredClone(baseline)
const added: CssSelectorFinding[] = []
for (const finding of findings) {
const counts = isBaselineDefect(finding.defect) ? remaining[finding.file]?.[finding.defect] : undefined
const allowance = counts?.[finding.selector] ?? 0
if (counts !== undefined && allowance > 0) counts[finding.selector] = allowance - 1
else added.push(finding)
}
const stale: BaselineComparison['stale'] = []
for (const [file, defects] of Object.entries(remaining)) {
for (const defect of BASELINE_DEFECTS) {
for (const [selector, count] of Object.entries(defects[defect] ?? {})) if (count > 0) stale.push([file, defect, selector, count])
}
}
return { added, stale }
}
const REMEDY = `Name the element and state the design means: key the rightmost compound with a class or data/aria attribute the component sets, use a sibling combinator between keyed compounds, or let a parent set a custom property that a keyed child reads (docs/defensive-patterns/client-components.md#keyed-selectors). A rule that cannot be keyed states why in a "/* ${EXCEPTION_PREFIX} <reason> */" comment directly above it.`
/**
* Verify the repository against the baseline.
* @param repoRoot - repository root to scan.
* @param prune - rewrite the baseline without retired occurrences once no new finding exists.
* @returns the number of recorded occurrences still present.
* @throws for new findings, a malformed baseline, or retired occurrences without `prune`.
*/
export function verifyCssSelectors(repoRoot: string, prune = false): number {
const baseline = parseBaseline(JSON.parse(readFileSync(resolve(repoRoot, BASELINE_PATH), 'utf8')))
const findings = listStylesheets(repoRoot).flatMap(file => checkStylesheet(file, readFileSync(resolve(repoRoot, file), 'utf8')))
const { added, stale } = compareBaseline(findings, baseline)
if (added.length > 0) {
throw new Error(`${GATE}: ${added.length} new finding(s). ${REMEDY}\n`
+ added.map(finding => ` ${finding.file}:${finding.line}: ${finding.selector}\n ${MESSAGES[finding.defect]}`).join('\n'))
}
if (stale.length > 0) {
if (!prune) {
throw new Error(`${GATE}: remove retired baseline entries with pnpm run ${GATE} --prune.\n`
+ stale.map(([file, defect, selector, count]) => ` ${file}: ${defect}: ${selector} (${count})`).join('\n'))
}
writeFileSync(resolve(repoRoot, BASELINE_PATH), `${JSON.stringify(countFindings(findings), null, 2)}\n`)
}
return findings.length
}
/**
* Run the gate as a command: `--prune` retires stale entries, no argument verifies.
* @param args - command-line arguments after the script path.
* @param repoRoot - repository root to scan.
*/
export function main(args: readonly string[], repoRoot: string = root): void {
try {
if (args.length > 1 || (args.length === 1 && args[0] !== '--prune')) throw new Error(`Usage: pnpm run ${GATE} [--prune]`)
const remaining = verifyCssSelectors(repoRoot, args[0] === '--prune')
console.log(`${GATE}: OK (${remaining} recorded selector occurrence(s) remain)`)
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}
}
if (import.meta.filename === resolve(process.argv[1] ?? '')) main(process.argv.slice(2))