@atlaskit/eslint-plugin-ui-styling-standard 2.4.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +0 -1
  3. package/dist/cjs/presets/all-flat.codegen.js +1 -2
  4. package/dist/cjs/presets/all.codegen.js +1 -2
  5. package/dist/cjs/rules/index.codegen.js +1 -3
  6. package/dist/cjs/rules/no-imported-style-values/index.js +8 -1
  7. package/dist/cjs/rules/no-nested-selectors/index.js +13 -1
  8. package/dist/cjs/rules/utils/walk-style-call-properties.js +24 -11
  9. package/dist/es2019/presets/all-flat.codegen.js +1 -2
  10. package/dist/es2019/presets/all.codegen.js +1 -2
  11. package/dist/es2019/rules/index.codegen.js +1 -3
  12. package/dist/es2019/rules/no-imported-style-values/index.js +8 -1
  13. package/dist/es2019/rules/no-nested-selectors/index.js +13 -1
  14. package/dist/es2019/rules/utils/walk-style-call-properties.js +15 -12
  15. package/dist/esm/presets/all-flat.codegen.js +1 -2
  16. package/dist/esm/presets/all.codegen.js +1 -2
  17. package/dist/esm/rules/index.codegen.js +1 -3
  18. package/dist/esm/rules/no-imported-style-values/index.js +8 -1
  19. package/dist/esm/rules/no-nested-selectors/index.js +13 -1
  20. package/dist/esm/rules/utils/walk-style-call-properties.js +24 -11
  21. package/dist/types/presets/all-flat.codegen.d.ts +1 -1
  22. package/dist/types/presets/all.codegen.d.ts +1 -1
  23. package/dist/types/rules/index.codegen.d.ts +1 -1
  24. package/dist/types/rules/utils/walk-style-call-properties.d.ts +0 -1
  25. package/package.json +1 -1
  26. package/dist/cjs/rules/no-top-layer-unsafe-selectors/find-template-selectors.js +0 -232
  27. package/dist/cjs/rules/no-top-layer-unsafe-selectors/index.js +0 -425
  28. package/dist/cjs/rules/no-top-layer-unsafe-selectors/preserve-list-layout.js +0 -63
  29. package/dist/cjs/rules/no-top-layer-unsafe-selectors/rewrite-selector.js +0 -2415
  30. package/dist/cjs/rules/utils/walk-style-object-properties.js +0 -47
  31. package/dist/es2019/rules/no-top-layer-unsafe-selectors/find-template-selectors.js +0 -226
  32. package/dist/es2019/rules/no-top-layer-unsafe-selectors/index.js +0 -382
  33. package/dist/es2019/rules/no-top-layer-unsafe-selectors/preserve-list-layout.js +0 -57
  34. package/dist/es2019/rules/no-top-layer-unsafe-selectors/rewrite-selector.js +0 -2131
  35. package/dist/es2019/rules/utils/walk-style-object-properties.js +0 -29
  36. package/dist/esm/rules/no-top-layer-unsafe-selectors/find-template-selectors.js +0 -226
  37. package/dist/esm/rules/no-top-layer-unsafe-selectors/index.js +0 -419
  38. package/dist/esm/rules/no-top-layer-unsafe-selectors/preserve-list-layout.js +0 -57
  39. package/dist/esm/rules/no-top-layer-unsafe-selectors/rewrite-selector.js +0 -2409
  40. package/dist/esm/rules/utils/walk-style-object-properties.js +0 -41
  41. package/dist/types/rules/no-top-layer-unsafe-selectors/find-template-selectors.d.ts +0 -29
  42. package/dist/types/rules/no-top-layer-unsafe-selectors/index.d.ts +0 -3
  43. package/dist/types/rules/no-top-layer-unsafe-selectors/preserve-list-layout.d.ts +0 -12
  44. package/dist/types/rules/no-top-layer-unsafe-selectors/rewrite-selector.d.ts +0 -164
  45. package/dist/types/rules/utils/walk-style-object-properties.d.ts +0 -18
@@ -1,2409 +0,0 @@
1
- import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
2
- import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
3
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
4
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
5
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
6
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
7
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
8
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
9
- import selectorParser from 'postcss-selector-parser';
10
-
11
- /**
12
- * # Top layer selector safety transform
13
- *
14
- * A pure function over selector text. The `no-top-layer-unsafe-selectors` ESLint rule drives it
15
- * for its autofix. It is kept separate from the rule so that a bulk sweep over the sources an
16
- * ESLint rule cannot see (`.css` files, `injectGlobal` bodies) can run the same code rather than
17
- * a second copy of the rewrite.
18
- *
19
- * ## Why
20
- *
21
- * Design System layering surfaces (popup, tooltip, modal, drawer…) are moving out of React
22
- * portals and into the browser top layer behind the `platform-dst-top-layer` gate. The host
23
- * — a `<div popover>` or a `<dialog>` — becomes a real node in the consumer's DOM. Consumer
24
- * CSS that could never reach a portalled surface now matches it, and positional selectors
25
- * that counted only real children now count the host.
26
- *
27
- * The canonical guard forms, the specificity reasoning, and the list of patterns for which
28
- * no guard form exists live in the decision doc:
29
- *
30
- * `platform/packages/design-system/top-layer/notes/decisions/top-layer-unsafe-selectors.md`
31
- *
32
- * ## Why a guard is the right fix at all
33
- *
34
- * The governing principle, and the cleanest statement of when this transform helps rather than
35
- * harms:
36
- *
37
- * > A guard is safe when it **restores pre-flag behaviour**, and harmful when it **removes
38
- * > something the host had pre-flag**. Global-scope selectors reached the portalled host;
39
- * > consumer-scoped selectors did not.
40
- *
41
- * Pre-flag the host was portalled to `body`, so a consumer-scoped rule such as `& > div` never
42
- * matched it. Post-flag it does — that is the damage, and guarding restores what the consumer
43
- * used to render. A global rule such as `* { box-sizing: inherit }`, by contrast, matched the
44
- * portalled host all along; guarding it would take away something the host already had, which
45
- * is a behaviour change rather than a fix.
46
- *
47
- * The discriminator is **reach**, not property semantics — which is why no browser measurement
48
- * can settle it. A browser can say what `box-sizing` does; it cannot say what the DOM looked
49
- * like before the flag.
50
- *
51
- * Operationally, at `global` scope a compound with nothing but the document itself above it
52
- * (`html`, `body`, `:root`, `*`, or no ancestor at all) is left alone: `div`, `body div` and
53
- * `* + *` all reached the portalled surface's content already. A compound below a consumer's
54
- * own ancestor (`.sidebar div`, `.x > div`) is guarded as usual, because the host inside that
55
- * ancestor is a new match. See {@link isDocumentLevelCompound}.
56
- *
57
- * One ancestor is ambiguous: a bare `div`. The portal container and every surface wrapper were
58
- * divs, so `div span` at global scope may well have reached the surface's content already, yet
59
- * the author may equally have meant their own wrapper. The transform does not guess. A compound
60
- * whose ancestors are all document-level or bare `div`, with at least one bare `div`, is returned
61
- * as `excluded` with `reviewCause: 'div-ancestor'`, which a bulk caller can surface as a comment
62
- * at the site for a human to decide. See {@link isBareDivCompound}.
63
- *
64
- * ## Contract
65
- *
66
- * `rewriteSelector(selector)` is pure, total and idempotent. It accepts both nested
67
- * authoring selectors (containing `&`) and plain CSS selectors, so a `.css`-file sweep can
68
- * reuse it. It never returns a partial rewrite: a selector is either fully rewritten, or
69
- * provably already safe, or refused with a reason.
70
- *
71
- * A selector with no `&` reads differently depending on where it is written. Inside a style
72
- * object or a `css` template the authoring API scopes it to the component's own element, so
73
- * `:hover` means `&:hover` and `span` means `& span`. In a plain stylesheet it reaches the
74
- * whole document. The caller says which with {@link RewriteOptions.scope}; the ESLint rule
75
- * always passes `nested`.
76
- *
77
- * One family is **reported but not fixed**: any rewrite that would need an `of S` clause, which
78
- * is every positional pseudo-class. Compiled's extract mode drops the CSS for such a selector
79
- * outright, so the guard deletes styling instead of protecting it. See
80
- * {@link WITHDRAWN_POSITIONAL_FORMS} for the measurement. The planner refuses the family in
81
- * {@link planPositionals}, and a selector that already carries an `of` clause is refused
82
- * before planning starts.
83
- *
84
- * Every rewrite is specificity-neutral. That is enforced structurally, not merely tested:
85
- * the transform recomputes (a,b,c) branch-by-branch on its own output and downgrades the
86
- * result to `residue` if it does not match the input. It also re-checks its own output for a
87
- * nested `:has()`, which Chromium rejects outright.
88
- *
89
- * ## A note on the literal guard strings below
90
- *
91
- * The guard text is emitted *literally* into the rewritten selector at every site — never
92
- * interpolated from a constant in the generated code. A ratcheting rule matches raw source
93
- * text, so a guard interpolated from a constant in consumer code would make the ratchet's
94
- * count assertions vacuous. The constants here are internal to this module; what lands in
95
- * consumer source is always the full literal list.
96
- */
97
-
98
- /* -------------------------------------------------------------------------------------- */
99
- /* Guard forms — authoritative, from the decision doc */
100
- /* -------------------------------------------------------------------------------------- */
101
-
102
- /**
103
- * The narrow guard, `:not(:where(L))`. Appended where the matching element could *be* the
104
- * host: child-combinator compounds, sibling-combinator right-hand compounds, and the
105
- * leftmost compound of a selector.
106
- *
107
- * `[popover]` and `dialog` cover both routes into the top layer — `popover` for
108
- * popover-based surfaces, and `dialog` for modal and drawer, which use `showModal()` and set
109
- * no `popover` attribute.
110
- *
111
- * `style`, `script`, `template`, `link` and `noscript` are left out on purpose. They are
112
- * `display: none`, so a style that reaches them has no visible effect unless it sets
113
- * `display`, and that hazard predates the top layer. They only matter to positional
114
- * selectors, which have no guard form (see `S`).
115
- *
116
- * Specificity: `:where()` is weightless and `:not()` inherits the specificity of its
117
- * argument, so this contributes (0,0,0).
118
- */
119
- var NARROW_GUARD = ':not(:where([popover], dialog))';
120
-
121
- /**
122
- * The wide guard, `:not(:where(L_wide))`. Appended where the matching element could be the
123
- * host *or anything inside its subtree*: `:has()` arguments, and descendant-combinator
124
- * compounds where the host may be any intermediate ancestor.
125
- *
126
- * Specificity: (0,0,0), for the same reason as the narrow guard.
127
- */
128
- var WIDE_GUARD = ':not(:where([popover], dialog, [popover] *, dialog *))';
129
-
130
- /**
131
- * `S` — the weightless "is a real, non-host element" test used as the `of S` argument to
132
- * `:nth-child()` / `:nth-last-child()`, where it re-bases sibling counting onto real
133
- * elements only.
134
- *
135
- * Unlike `L`, `S` lists the non-rendered elements too, because SSR and dev-loop style
136
- * injection add them as siblings and they shift the count exactly as a host does.
137
- *
138
- * `of S` must stay **narrow**. An `of` argument containing `[popover] *` would filter real
139
- * descendants out of the sibling count, which is the opposite of the intent.
140
- */
141
- var S = ':not(:where([popover], dialog, style, script, template, link, noscript))';
142
-
143
- /**
144
- * `X:first-child` → `X:nth-child(1 of S)`
145
- */
146
- var NTH_FIRST = ':nth-child(1 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
147
-
148
- /**
149
- * `X:last-child` → `X:nth-last-child(1 of S)`
150
- */
151
- var NTH_LAST = ':nth-last-child(1 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
152
-
153
- /**
154
- * `X:not(:first-child)` → `X:nth-child(n+2 of S)`
155
- */
156
- var NTH_NOT_FIRST = ':nth-child(n+2 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
157
-
158
- /**
159
- * `X:not(:last-child)` → `X:nth-last-child(n+2 of S)`
160
- */
161
- var NTH_NOT_LAST = ':nth-last-child(n+2 of :not(:where([popover], dialog, style, script, template, link, noscript)))';
162
-
163
- /**
164
- * `X:only-child` → `X:nth-child(1 of S):not(:where(:nth-last-child(n+2 of S)))`
165
- *
166
- * The naive form — `:nth-child(1 of S):nth-last-child(1 of S)` — is (0,2,0) against
167
- * `:only-child`'s (0,1,0). So is `:nth-child(1 of S):not(:nth-last-child(n+2 of S))`, because
168
- * `:not()` inherits its argument's weight. Wrapping the negation in `:where()` makes it
169
- * weightless and brings the pair back to (0,1,0).
170
- */
171
- var NTH_ONLY = ':nth-child(1 of :not(:where([popover], dialog, style, script, template, link, noscript))):not(:where(:nth-last-child(n+2 of :not(:where([popover], dialog, style, script, template, link, noscript)))))';
172
-
173
- /**
174
- * # The `of S` family is WITHDRAWN — reported, never emitted
175
- *
176
- * Every form above stays in this file, and stays literal, because each is correct CSS and each
177
- * is verified against real Chromium by the harness. None of them is emitted today, because the
178
- * **build** loses them.
179
- *
180
- * `@compiled/react` in `extract: true` mode — platform's `.compiledcssrc`, which every
181
- * Atlaspack build uses, including `gemini-vr` — writes the atomic class names for a rule whose
182
- * selector contains `:nth-child(An+B of S)` or `:nth-last-child(An+B of S)` onto the element
183
- * and **omits the CSS rules themselves**. No warning, no build error: the class is on the
184
- * element and there is no rule behind it, so the declarations are silently gone.
185
- *
186
- * Measured on `@atlaskit/breadcrumbs` by a VR run:
187
- *
188
- * | Selector | Rules in page | Matching `::after` rules | `content` |
189
- * | ----------------------------------------------- | ------------- | ------------------------ | --------- |
190
- * | `&:not(:last-child)::after` (control) | 325 | 7 | `"/"` |
191
- * | `&:nth-last-child(n+2 of S)::after` (guard) | 318 | **0** | `none` |
192
- *
193
- * 325 − 318 is exactly the seven dropped atomic rules, and every `/` separator disappeared from
194
- * the page. The trigger is the `of <selector-list>` clause itself, not the guard: `of li` fails
195
- * identically, and a plain `:nth-last-child(n+2)` survives. Ruled out everywhere else — the
196
- * selector survives `@compiled/babel-plugin` in non-extract mode, `@compiled/css`'s `sort()`,
197
- * lightningcss 1.32 at every browser target and with `cssModules` either way, cssnano,
198
- * postcss-minify-selectors and postcss-selector-parser, and Chromium 143 matches it correctly
199
- * against the real class list and the real DOM. Only the extract pipeline loses it.
200
- *
201
- * So for the positional family the guard does not merely fail to help — **it deletes working
202
- * styling**. That is the one outcome worse than leaving the site unguarded, and it is why the
203
- * fix is withheld rather than offered:
204
- *
205
- * - a selector that *would* need an `of` clause is refused as `residue` by
206
- * {@link planPositionals}, so the ESLint rule reports it under `no-guard-form` and offers no
207
- * autofix, and any bulk caller sharing this module inherits the refusal rather than being free
208
- * to mass-apply the rewrite;
209
- * - a selector that *already carries* an `of` clause is refused for the same reason rather than
210
- * merged or extended, before planning starts in {@link rewriteSelector}. Its CSS is already
211
- * being dropped in every extract build, so calling it `excluded` ("nothing to do") would
212
- * assert a safety it does not have.
213
- *
214
- * {@link rewriteSelector} also checks its emitted text for an `of` clause as a backstop. Nothing
215
- * emits one today, so that check firing is a bug in the transform, not a withdrawal.
216
- *
217
- * The other ~75% of the debt is unaffected: `> *`, `> div`, `:has()` and the descendant forms
218
- * emit a plain `:not(:where(…))` with no `of` clause, and those extract normally.
219
- */
220
- var WITHDRAWN_POSITIONAL_FORMS = new Map([[':first-child', NTH_FIRST], [':last-child', NTH_LAST], [':only-child', NTH_ONLY], [':not(:first-child)', NTH_NOT_FIRST], [':not(:last-child)', NTH_NOT_LAST]]);
221
-
222
- /**
223
- * The term list of the narrow guard, in canonical order. Used when merging.
224
- */
225
- var NARROW_TERMS = ['[popover]', 'dialog'];
226
-
227
- /**
228
- * The term list of the wide guard, in canonical order. Used when merging.
229
- */
230
- var WIDE_TERMS = ['[popover]', 'dialog', '[popover] *', 'dialog *'];
231
-
232
- /* -------------------------------------------------------------------------------------- */
233
- /* Public types */
234
- /* -------------------------------------------------------------------------------------- */
235
-
236
- /**
237
- * CSS specificity as `[ids, classes, types]`.
238
- */
239
-
240
- /**
241
- * The rule body belonging to the selector, when the caller has it.
242
- *
243
- * Accepts either raw CSS declaration text — the shape the enumeration schema stores in its
244
- * `declarations` column — or a style object with camelCase or kebab-case keys.
245
- */
246
-
247
- /**
248
- * Where a selector is written, which decides how a branch with no `&` is read.
249
- */
250
-
251
- /**
252
- * Why a selector was skipped rather than decided.
253
- */
254
-
255
- /**
256
- * Why an `excluded` selector still needs a human decision.
257
- */
258
-
259
- /* -------------------------------------------------------------------------------------- */
260
- /* Refusal sets */
261
- /* -------------------------------------------------------------------------------------- */
262
-
263
- /**
264
- * `*-of-type` counts siblings by tag name and accepts no `of S` argument, so its counting
265
- * cannot be re-based onto real elements. Note that the pre-existing ratcheting rule advises
266
- * authors to migrate *towards* these; that advice is wrong for top layer.
267
- */
268
- var OF_TYPE_PSEUDOS = new Set([':first-of-type', ':last-of-type', ':only-of-type', ':nth-of-type', ':nth-last-of-type']);
269
-
270
- /**
271
- * These match an element *and its ancestors*, so the flip exists only while the pointer or
272
- * focus is inside the surface and there is no guard form at any depth. Inside `:has()` the
273
- * subject itself satisfies the argument; on a subject compound the element inherits the state
274
- * from a surface nested inside it.
275
- */
276
- var ANCESTOR_PROPAGATING_PSEUDOS = new Set([':hover', ':active', ':focus-within']);
277
-
278
- /**
279
- * Positional pseudo-classes that count siblings, and so can be re-based with `of S`.
280
- */
281
- var POSITIONAL_PSEUDOS = new Set([':first-child', ':last-child', ':only-child', ':nth-child', ':nth-last-child']);
282
- var LEGACY_PSEUDO_ELEMENTS = new Set([':before', ':after', ':first-line', ':first-letter']);
283
-
284
- /**
285
- * Element types a top layer host can have. The host is either a `<div popover>` or a
286
- * `<dialog>`; nothing else.
287
- */
288
- var HOST_TAGS = new Set(['div', 'dialog']);
289
-
290
- /**
291
- * Tag names that appear as terms of `L` or `S`. Used to recognise a pre-existing guard, so a
292
- * hand-written guard that lists `style` and the rest is still merged into, not doubled.
293
- */
294
- var GUARD_TERM_TAGS = new Set(['dialog', 'style', 'script', 'template', 'link', 'noscript']);
295
-
296
- /**
297
- * Pseudo-classes and pseudo-elements that only a top layer host can satisfy. A compound
298
- * carrying one names a host as surely as `dialog` or `[popover]` does, so it is never guarded:
299
- * every guard form would exclude exactly what the compound selects.
300
- */
301
- var HOST_PSEUDOS = new Set([':popover-open', ':modal', '::backdrop']);
302
-
303
- /**
304
- * The comparison key for a guard term. Tag and attribute names are ASCII case-insensitive in
305
- * HTML, so `[POPOVER]` and `DIALOG` are the terms `[popover]` and `dialog`, and a guard spelled
306
- * in uppercase must be recognised rather than have the lowercase terms merged in beside it.
307
- */
308
- var normalise = function normalise(text) {
309
- return text.replace(/\s+/g, '').toLowerCase();
310
- };
311
- var NARROW_TERM_KEYS = new Set(NARROW_TERMS.map(normalise));
312
- var WIDE_TERM_KEYS = new Set(WIDE_TERMS.map(normalise));
313
-
314
- /* -------------------------------------------------------------------------------------- */
315
- /* Public API */
316
- /* -------------------------------------------------------------------------------------- */
317
-
318
- /**
319
- * Rewrite a selector so a top layer host can neither receive its declarations nor displace
320
- * the real elements it targets.
321
- *
322
- * Pure and idempotent: feeding `after` back in yields `guardCount: 0` and `after: null`.
323
- *
324
- * @param selector A single selector or a comma-separated selector list. May contain the
325
- * nesting selector `&`.
326
- * @param declarations The rule body, if the caller has it. Used for exactly one decision — see
327
- * {@link findResetSignal}. Omitting it never produces a *wrong* answer, only a lossier one.
328
- * @param options See {@link RewriteOptions}.
329
- */
330
- export function rewriteSelector(selector, declarations, options) {
331
- var _options$scope;
332
- var skip = getSkipReason(selector);
333
- if (skip) {
334
- return skipped(selector, skip.reason, skip.cause);
335
- }
336
- var parsed;
337
- try {
338
- parsed = parse(selector);
339
- } catch (_unused) {
340
- return skipped(selector, 'The selector could not be parsed, so it cannot be rewritten safely. This is most likely an authoring mistake.', 'malformed');
341
- }
342
- if (parsed.length === 0) {
343
- return excluded(selector, [0, 0, 0], 'The selector is empty.');
344
- }
345
-
346
- /**
347
- * In a nested context a branch with no `&` is scoped to the component's own element. It is
348
- * rewritten under its explicit `&` spelling, so it reaches the same verdict, and the prefix is
349
- * stripped again on the way out so the author's spelling is preserved.
350
- */
351
- var scope = (_options$scope = options === null || options === void 0 ? void 0 : options.scope) !== null && _options$scope !== void 0 ? _options$scope : 'global';
352
- var scoped = applyScope(parsed, scope);
353
- if (scoped === null) {
354
- return skipped(selector, 'The selector could not be re-parsed under its nesting scope, so it cannot be rewritten safely.', 'malformed');
355
- }
356
- var branches = scoped.branches,
357
- prefixes = scoped.prefixes;
358
- var specificityBranchesBefore = branches.map(specificityOfSelector);
359
- var specificityBefore = maxSpecificity(specificityBranchesBefore);
360
-
361
- /**
362
- * A bare universal at global scope. **The one class where guarding is actively harmful rather
363
- * than merely useless**, so it is decided before anything else.
364
- *
365
- * `* { box-sizing: inherit }` is a reset. Guarding it excludes the host from the reset and
366
- * makes it the only element in the document with a different box model — a layout bug
367
- * introduced by the fix, with nothing to compensate, because the host surface reset covers
368
- * text-layout properties and not the box model.
369
- *
370
- * `* { cursor: col-resize }` is an override with identical selector text, and it does need the
371
- * guard. The selector cannot tell them apart, so this is a judgement call about the rule body.
372
- *
373
- * Note this is *not* the property-effect filter. That filter is about declarations that are
374
- * inert on a `position: fixed` host (`flex`, `order`, `z-index`, …). Here the declaration is
375
- * live on the host and *wanted* there.
376
- */
377
- if (branches.some(isBareGlobalUniversal)) {
378
- var reset = findResetSignal(declarations);
379
- if (reset) {
380
- return excluded(selector, specificityBefore, "A bare universal selector at global scope carrying '".concat(reset, "', which is reset-shaped rather than an override. Guarding it would exclude the top layer host from the reset and leave it the only element in the document with different inherited defaults \u2014 a layout bug introduced by the fix. Left alone deliberately."));
381
- }
382
- return residue(selector, specificityBefore, "A bare universal selector at global scope. Whether this needs the guard depends on the rule body, which the selector cannot reveal: `* { box-sizing: inherit }` is a reset and guarding it would exclude the host from the reset — a layout bug introduced by the fix — while `* { cursor: col-resize }` is an override and does need it. Decide from the declarations. A *scoped* universal ('& > *', '.foo > *') is unaffected and is rewritten normally.");
383
- }
384
-
385
- /**
386
- * **Input gate for the `of S` withdrawal** — see {@link WITHDRAWN_POSITIONAL_FORMS}.
387
- *
388
- * A selector that already carries an `of` argument is emitting no CSS at all in an extract
389
- * build, whichever list it carries and whoever wrote it. Refusing it here reports it for
390
- * triage instead of merging its terms up to the canonical seven — a merge would leave the
391
- * site exactly as dead as it was, while reading in review as a fix.
392
- *
393
- * This covers both a partial guard in the `of` list and an unrelated `of` list; neither is
394
- * merged.
395
- */
396
- var _iterator = _createForOfIteratorHelper(branches),
397
- _step;
398
- try {
399
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
400
- var branch = _step.value;
401
- var existing = findOfClause(branch);
402
- if (existing) {
403
- return residue(selector, specificityBefore, ofClausePresentReason(existing));
404
- }
405
- }
406
- } catch (err) {
407
- _iterator.e(err);
408
- } finally {
409
- _iterator.f();
410
- }
411
- var plan = createPlan();
412
- var _iterator2 = _createForOfIteratorHelper(branches),
413
- _step2;
414
- try {
415
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
416
- var _branch = _step2.value;
417
- planBranch(_branch, plan, scope);
418
- }
419
-
420
- /**
421
- * A hard refusal stands whether or not anything else in the selector is guardable.
422
- * Refusing the whole selector — rather than rewriting the parts that do have a guard form
423
- * — is deliberate. A partially rewritten selector reads as fixed and is not, which is the
424
- * worst outcome available here.
425
- */
426
- } catch (err) {
427
- _iterator2.e(err);
428
- } finally {
429
- _iterator2.f();
430
- }
431
- if (plan.hardRefusals.length > 0) {
432
- return residue(selector, specificityBefore, plan.hardRefusals[0]);
433
- }
434
-
435
- /**
436
- * A compound the transform declined to decide hands the whole selector to a human. Guards
437
- * that would have been written on its other compounds are withheld too: a partially
438
- * rewritten selector next to a review comment would read as fixed.
439
- */
440
- if (plan.reviews.length > 0) {
441
- return review(selector, specificityBefore, plan.reviews[0]);
442
- }
443
- if (plan.guardCount === 0) {
444
- var _ref, _plan$softRefusals$;
445
- /**
446
- * Nothing needed writing. A soft refusal only matters when a guard would otherwise have
447
- * been written next to it, because that is the case where the result would read as
448
- * fixed. On its own it is reported but not queued for triage.
449
- */
450
- var why = (_ref = (_plan$softRefusals$ = plan.softRefusals[0]) !== null && _plan$softRefusals$ !== void 0 ? _plan$softRefusals$ : plan.reachSuppressions[0]) !== null && _ref !== void 0 ? _ref : plan.sawGeneralSibling ? 'The general sibling combinator is insensitive to insertion — a host inserted between siblings removes no real match — and no compound this selector matches can be a host. Already safe.' : 'No top layer host can be, contain, or displace any element this selector matches.';
451
- if (plan.sawGeneralSibling && plan.softRefusals.length === 0 && plan.reachSuppressions.length === 0) {
452
- return {
453
- before: selector,
454
- after: null,
455
- population: 'guardable',
456
- damageModes: [],
457
- guardCount: 0,
458
- reason: why,
459
- specificityBefore: specificityBefore,
460
- specificityAfter: specificityBefore
461
- };
462
- }
463
- return excluded(selector, specificityBefore, why);
464
- }
465
- if (plan.softRefusals.length > 0) {
466
- return residue(selector, specificityBefore, plan.softRefusals[0]);
467
- }
468
- var emitted = branches.map(function (branch, index) {
469
- return stripScopePrefix(emitSelector(branch, plan), prefixes[index]);
470
- });
471
- if (emitted.some(function (branch) {
472
- return branch === null;
473
- })) {
474
- return residue(selector, specificityBefore, 'The rewritten selector lost its implicit nesting prefix, so it was not emitted. This is a bug in the transform — please report it.');
475
- }
476
- var after = emitted.join(', ');
477
-
478
- /**
479
- * A bracket-level sanity check on the emitted text before anything downstream writes it to
480
- * a file. `postcss-selector-parser` is lenient, so this catches a class of malformed output
481
- * that would otherwise round-trip.
482
- */
483
- if (!isBalanced(after)) {
484
- return residue(selector, specificityBefore, 'The rewritten selector does not have balanced brackets, so it was not emitted. This is a bug in the transform — please report it.');
485
- }
486
-
487
- /**
488
- * Chromium rejects an entire selector containing a `:has()` inside a `:has()` argument,
489
- * which silently stops the rule applying at all. Nothing in the guard forms contains a
490
- * `:has()`, but verify rather than assume — this failure mode looks like a fix and
491
- * disables the rule.
492
- */
493
- var afterBranches;
494
- try {
495
- afterBranches = parse(after);
496
- } catch (_unused2) {
497
- return residue(selector, specificityBefore, 'The rewritten selector could not be re-parsed, so it could not be verified.');
498
- }
499
-
500
- /**
501
- * Backstop for the `of S` withdrawal — see {@link WITHDRAWN_POSITIONAL_FORMS}. The planner
502
- * refuses every positional pseudo in {@link planPositionals}, so nothing reaching this point
503
- * should carry an `of` clause. Checked on the emitted text so a future emit site cannot
504
- * slip one past the planner.
505
- */
506
- var _iterator3 = _createForOfIteratorHelper(afterBranches),
507
- _step3;
508
- try {
509
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
510
- var _branch2 = _step3.value;
511
- if (findOfClause(_branch2)) {
512
- return residue(selector, specificityBefore, "The rewrite would emit an `of` clause, which is withdrawn. ".concat(EXTRACT_DEFECT, " This is a bug in the transform \u2014 please report it."));
513
- }
514
- }
515
- } catch (err) {
516
- _iterator3.e(err);
517
- } finally {
518
- _iterator3.f();
519
- }
520
- var _iterator4 = _createForOfIteratorHelper(afterBranches),
521
- _step4;
522
- try {
523
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
524
- var _branch3 = _step4.value;
525
- if (hasNestedHas(_branch3)) {
526
- return residue(selector, specificityBefore, 'The rewrite would produce a `:has()` nested inside a `:has()` argument, which Chromium rejects outright — the whole rule would silently stop applying.');
527
- }
528
- }
529
-
530
- /**
531
- * Structural specificity check. `:where()` being weightless, `:not()` inheriting its
532
- * argument's weight, and `of S` contributing only the pseudo-class are all load-bearing —
533
- * so verify, branch by branch, on the emitted text.
534
- */
535
- } catch (err) {
536
- _iterator4.e(err);
537
- } finally {
538
- _iterator4.f();
539
- }
540
- var specificityBranchesAfter = afterBranches.map(specificityOfSelector);
541
- if (specificityBranchesAfter.length !== specificityBranchesBefore.length) {
542
- return residue(selector, specificityBefore, 'The rewrite changed the number of selectors in the list, so it could not be verified.');
543
- }
544
- for (var index = 0; index < specificityBranchesBefore.length; index++) {
545
- var from = specificityBranchesBefore[index];
546
- var to = specificityBranchesAfter[index];
547
- if (!sameSpecificity(from, to)) {
548
- return residue(selector, specificityBefore, "The rewrite would change specificity from (".concat(from.join(','), ") to (").concat(to.join(','), ") for '").concat(branches[index].toString().trim(), "'. Every guard form must be specificity-neutral."));
549
- }
550
- }
551
- var damageModes = [];
552
- if (plan.receives) {
553
- damageModes.push('popover-receives');
554
- }
555
- var result = {
556
- before: selector,
557
- after: after,
558
- population: 'guardable',
559
- damageModes: damageModes,
560
- guardCount: plan.guardCount,
561
- specificityBefore: specificityBefore,
562
- specificityAfter: maxSpecificity(specificityBranchesAfter)
563
- };
564
- if (plan.residualNotes.length > 0) {
565
- result.reason = plan.residualNotes[0];
566
- }
567
- return result;
568
- }
569
-
570
- /* -------------------------------------------------------------------------------------- */
571
- /* Result constructors */
572
- /* -------------------------------------------------------------------------------------- */
573
-
574
- function skipped(before, reason, cause) {
575
- return {
576
- before: before,
577
- after: null,
578
- population: 'skipped',
579
- damageModes: [],
580
- guardCount: 0,
581
- reason: reason,
582
- skipCause: cause,
583
- specificityBefore: [0, 0, 0],
584
- specificityAfter: [0, 0, 0]
585
- };
586
- }
587
- function residue(before, specificity, reason) {
588
- return {
589
- before: before,
590
- after: null,
591
- population: 'residue',
592
- damageModes: [],
593
- guardCount: 0,
594
- reason: reason,
595
- specificityBefore: specificity,
596
- specificityAfter: specificity
597
- };
598
- }
599
- function excluded(before, specificity, reason) {
600
- return {
601
- before: before,
602
- after: null,
603
- population: 'excluded',
604
- damageModes: [],
605
- guardCount: 0,
606
- reason: reason,
607
- specificityBefore: specificity,
608
- specificityAfter: specificity
609
- };
610
- }
611
- function review(before, specificity, reason) {
612
- return _objectSpread(_objectSpread({}, excluded(before, specificity, reason)), {}, {
613
- reviewCause: 'div-ancestor'
614
- });
615
- }
616
-
617
- /* -------------------------------------------------------------------------------------- */
618
- /* Nesting scope */
619
- /* -------------------------------------------------------------------------------------- */
620
-
621
- /**
622
- * Under `nested` scope, spell out the `&` the authoring API implies for every branch that has
623
- * none, then re-parse. Under `global` scope the branches are returned untouched.
624
- *
625
- * The prefix is text rather than a synthetic AST node so the branch takes exactly the code path
626
- * its explicit `&` spelling takes; nothing downstream needs to know the `&` was implied.
627
- */
628
- function applyScope(branches, scope) {
629
- if (scope === 'global') {
630
- return {
631
- branches: branches,
632
- prefixes: branches.map(function () {
633
- return null;
634
- })
635
- };
636
- }
637
- var prefixes = branches.map(implicitNestingPrefix);
638
- if (prefixes.every(function (prefix) {
639
- return prefix === null;
640
- })) {
641
- return {
642
- branches: branches,
643
- prefixes: prefixes
644
- };
645
- }
646
- var text = branches.map(function (branch, index) {
647
- var _prefixes$index;
648
- return "".concat((_prefixes$index = prefixes[index]) !== null && _prefixes$index !== void 0 ? _prefixes$index : '').concat(branch.toString().trim());
649
- }).join(', ');
650
- try {
651
- var reparsed = parse(text);
652
- if (reparsed.length !== branches.length) {
653
- return null;
654
- }
655
- return {
656
- branches: reparsed,
657
- prefixes: prefixes
658
- };
659
- } catch (_unused3) {
660
- return null;
661
- }
662
- }
663
-
664
- /**
665
- * The `&` a nested authoring API prepends to a branch with no `&` of its own. A branch that
666
- * opens with a pseudo attaches to the parent compound (`:hover` is `&:hover`); anything else is
667
- * a descendant (`span` is `& span`, `> *` is `& > *`).
668
- */
669
- function implicitNestingPrefix(branch) {
670
- var hasNesting = false;
671
- branch.walk(function (node) {
672
- if (node.type === 'nesting') {
673
- hasNesting = true;
674
- }
675
- });
676
- if (hasNesting) {
677
- return null;
678
- }
679
- var first = nonEmptyNodes(branch)[0];
680
- if (!first) {
681
- return null;
682
- }
683
- if (first.type === 'pseudo') {
684
- return '&';
685
- }
686
- return '& ';
687
- }
688
-
689
- /**
690
- * Remove the prefix {@link applyScope} added. The `&` compound is never guarded or replaced, so
691
- * the emitted branch always opens with it; `null` if it does not, which is a transform bug.
692
- */
693
- function stripScopePrefix(emitted, prefix) {
694
- if (prefix === null) {
695
- return emitted;
696
- }
697
- if (!emitted.startsWith(prefix)) {
698
- return null;
699
- }
700
- return emitted.slice(prefix.length);
701
- }
702
-
703
- /* -------------------------------------------------------------------------------------- */
704
- /* The `of S` withdrawal — see WITHDRAWN_POSITIONAL_FORMS */
705
- /* -------------------------------------------------------------------------------------- */
706
-
707
- /**
708
- * The defect, stated once for the refusal reasons, so a developer reading the squiggle learns
709
- * why the fix is missing rather than only that it is. The measurement behind it lives in the
710
- * {@link WITHDRAWN_POSITIONAL_FORMS} docblock.
711
- */
712
- var EXTRACT_DEFECT = '`@compiled/react` in `extract: true` mode, which every Atlaspack build uses, emits the atomic class names for a rule whose selector carries an `of` argument but omits the CSS rules themselves. There is no warning and no build error, so the declarations are silently lost.';
713
-
714
- /**
715
- * Lowercased pseudo-class name. CSS pseudo-class names are ASCII case-insensitive, so every
716
- * decision keyed on a name must normalise first: `:NTH-CHILD(1 of .foo)` is the same selector
717
- * as `:nth-child(1 of .foo)` and must reach the same verdict.
718
- */
719
- function pseudoName(node) {
720
- var _node$value;
721
- return ((_node$value = node.value) !== null && _node$value !== void 0 ? _node$value : '').toLowerCase();
722
- }
723
-
724
- /**
725
- * Find a `:nth-child()` / `:nth-last-child()` carrying an `of` argument, at any depth —
726
- * including inside a `:has()`, `:is()`, `:where()` or `:not()` argument.
727
- */
728
- function findOfClause(branch) {
729
- var _found$;
730
- var found = [];
731
- branch.walkPseudos(function (pseudo) {
732
- var name = pseudoName(pseudo);
733
- if (name !== ':nth-child' && name !== ':nth-last-child') {
734
- return;
735
- }
736
- if (findOfKeyword(nthArgumentText(pseudo)) === -1) {
737
- return;
738
- }
739
- found.push(pseudo);
740
- });
741
- return (_found$ = found[0]) !== null && _found$ !== void 0 ? _found$ : null;
742
- }
743
-
744
- /**
745
- * The guard form that would have been emitted for a positional pseudo-class, spelled with `S`
746
- * rather than the seven terms so the report stays readable. `null` when this pseudo is not one
747
- * of the positional family.
748
- */
749
- function withdrawnFormFor(pseudo) {
750
- var name = pseudoName(pseudo);
751
- if (name === ':nth-child' || name === ':nth-last-child') {
752
- return "".concat(name, "(").concat(nthArgumentText(pseudo).trim(), " of S)");
753
- }
754
- if (name === ':not') {
755
- var sole = solePseudoInside(pseudo);
756
- var _form = sole ? WITHDRAWN_POSITIONAL_FORMS.get(":not(".concat(pseudoName(sole), ")")) : undefined;
757
- return _form ? abbreviate(_form) : null;
758
- }
759
- var form = WITHDRAWN_POSITIONAL_FORMS.get(name);
760
- return form ? abbreviate(form) : null;
761
- }
762
-
763
- /**
764
- * Collapse the seven-term list back to `S`. The literal is what gets *written*; `S` is what
765
- * gets *read*.
766
- */
767
- function abbreviate(form) {
768
- return form.split(S).join('S');
769
- }
770
-
771
- /**
772
- * Why a rewrite that needs an `of` clause is withheld. Names the pseudo-class and the form that
773
- * would have been emitted for it, so the report is specific about what was withdrawn.
774
- */
775
- function ofClauseWithheldReason(pseudo) {
776
- var form = withdrawnFormFor(pseudo);
777
- var name = pseudoName(pseudo) === ':not' ? pseudo.toString().trim() : pseudo.value;
778
- var subject = form ? "'".concat(name, "' can only be re-based onto real elements as `").concat(form, "`") : "'".concat(name, "' can only be re-based onto real elements with an `of S` clause");
779
- return "".concat(subject, ", and that form is currently withdrawn. ").concat(EXTRACT_DEFECT, " Applying the guard here would therefore delete this rule's styling rather than protect it \u2014 the one outcome worse than leaving the selector unguarded \u2014 so it is reported without a fix. Close the site another way: give the elements you actually mean a class or a `data-` attribute and select them directly. `S = :not(:where([popover], dialog, style, script, template, link, noscript))`.");
780
- }
781
-
782
- /**
783
- * Why a selector that *already* carries an `of` clause is refused rather than merged into the
784
- * canonical list, or reported as already safe.
785
- */
786
- function ofClausePresentReason(pseudo) {
787
- return "'".concat(pseudo.value, "' already carries an `of` argument, and any `of` argument is currently unsafe to ship. ").concat(EXTRACT_DEFECT, " This rule is therefore already dead in every extract build, whatever the `of` list contains \u2014 so the list is neither merged up to the canonical seven terms nor reported as safe. Revert it to a plain selector and close the site another way, or leave it for the owning team; two unrelated `of` lists could not have been combined into one specificity-neutral term anyway.");
788
- }
789
-
790
- /* -------------------------------------------------------------------------------------- */
791
- /* Skip detection — skip, never guess */
792
- /* -------------------------------------------------------------------------------------- */
793
-
794
- /**
795
- * Statically detect a selector whose text is not fully known, or which is not a complete
796
- * selector at all. Guessing at these is strictly worse than reporting them, because a guard
797
- * inserted at the wrong end of an interpolation silently changes what the rule matches.
798
- */
799
- function getSkipReason(selector) {
800
- if (selector.trim() === '') {
801
- return {
802
- cause: 'malformed',
803
- reason: 'The selector is empty.'
804
- };
805
- }
806
- if (/:has\([^)]*\$\{/.test(selector)) {
807
- return {
808
- cause: 'dynamic',
809
- reason: 'The `:has()` argument contains a template-literal interpolation, so the branch structure inside it is not statically known. Skipped rather than guessed at.'
810
- };
811
- }
812
- if (selector.includes('${')) {
813
- return {
814
- cause: 'dynamic',
815
- reason: 'The selector contains a template-literal interpolation, so its full text is not statically known. Skipped rather than guessed at.'
816
- };
817
- }
818
- if (selector.includes('#{')) {
819
- return {
820
- cause: 'dynamic',
821
- reason: 'The selector contains a preprocessor interpolation, so its full text is not statically known. Skipped rather than guessed at.'
822
- };
823
- }
824
- if (!isBalanced(selector)) {
825
- return {
826
- cause: 'malformed',
827
- reason: 'The selector has an unterminated argument — its brackets or parentheses do not balance, so it spans more than the text given and cannot be parsed in isolation.'
828
- };
829
- }
830
- return null;
831
- }
832
- function isBalanced(selector) {
833
- var parens = 0;
834
- var brackets = 0;
835
- var quote = null;
836
- for (var index = 0; index < selector.length; index++) {
837
- var character = selector[index];
838
- if (quote) {
839
- if (character === '\\') {
840
- index++;
841
- } else if (character === quote) {
842
- quote = null;
843
- }
844
- continue;
845
- }
846
- switch (character) {
847
- case '"':
848
- case "'":
849
- quote = character;
850
- break;
851
- case '(':
852
- parens++;
853
- break;
854
- case ')':
855
- parens--;
856
- break;
857
- case '[':
858
- brackets++;
859
- break;
860
- case ']':
861
- brackets--;
862
- break;
863
- default:
864
- break;
865
- }
866
- if (parens < 0 || brackets < 0) {
867
- return false;
868
- }
869
- }
870
- return parens === 0 && brackets === 0 && quote === null;
871
- }
872
-
873
- /* -------------------------------------------------------------------------------------- */
874
- /* Parsing and compounds */
875
- /* -------------------------------------------------------------------------------------- */
876
-
877
- function parse(selector) {
878
- var root = selectorParser().astSync(selector);
879
- return root.nodes.filter(function (branch) {
880
- return nonEmptyNodes(branch).length > 0;
881
- });
882
- }
883
- function nonEmptyNodes(container) {
884
- return container.nodes.filter(function (node) {
885
- return !(node.type === 'string' && node.value.trim() === '');
886
- });
887
- }
888
- function positionOf(combinator) {
889
- if (combinator === null) {
890
- return 'first';
891
- }
892
- switch (combinator.value.trim()) {
893
- case '':
894
- return 'descendant';
895
- case '>':
896
- return 'child';
897
- case '+':
898
- return 'adjacent';
899
- case '~':
900
- return 'general';
901
- default:
902
- return 'descendant';
903
- }
904
- }
905
- function splitCompounds(branch) {
906
- var raw = [];
907
- var current = {
908
- nodes: [],
909
- combinatorBefore: null
910
- };
911
- var _iterator5 = _createForOfIteratorHelper(branch.nodes),
912
- _step5;
913
- try {
914
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
915
- var node = _step5.value;
916
- if (node.type === 'combinator') {
917
- raw.push(current);
918
- current = {
919
- nodes: [],
920
- combinatorBefore: node
921
- };
922
- } else {
923
- current.nodes.push(node);
924
- }
925
- }
926
- } catch (err) {
927
- _iterator5.e(err);
928
- } finally {
929
- _iterator5.f();
930
- }
931
- raw.push(current);
932
- var kept = raw.filter(function (compound) {
933
- return compound.nodes.length > 0;
934
- });
935
- return kept.map(function (compound, index) {
936
- return {
937
- nodes: compound.nodes,
938
- combinatorBefore: compound.combinatorBefore,
939
- position: positionOf(compound.combinatorBefore),
940
- isSubject: index === kept.length - 1
941
- };
942
- });
943
- }
944
-
945
- /* -------------------------------------------------------------------------------------- */
946
- /* Trap 2 — the host-satisfiability predicate */
947
- /* -------------------------------------------------------------------------------------- */
948
-
949
- /**
950
- * **This is the single predicate behind trap 2.** `& > div > div` needs two guards because
951
- * both compounds satisfy it; `& > div > span` needs exactly one because `span` does not. The
952
- * rule "guard every compound this returns true for, not just the rightmost" lives here and
953
- * nowhere else, so it can be swapped wholesale if the Chromium verification of trap 2 comes
954
- * back negative.
955
- *
956
- * Could a top layer host *be* the element this compound matches?
957
- *
958
- * A host is a `<div popover>` or a `<dialog>` rendered by Design System. So:
959
- * - an explicit tag other than `div` / `dialog` proves it cannot — no host is a `<span>`;
960
- * - a class or an id proves it cannot, because those are the consumer's own hooks and are not
961
- * on the host. A consumer who deliberately puts their own class on a surface — via
962
- * `className` / `xcss` — has targeted it on purpose, which the decision doc treats as the
963
- * consumer's call rather than something to guard;
964
- * - the nesting selector `&` proves it cannot, because `&` is the author's own element — and so
965
- * does an `:is()` / `:where()` that resolves the same way, see {@link nestedMatchVerdict};
966
- * - everything else — `*`, attribute-only, pseudo-only — could, so it is guarded.
967
- */
968
- function couldHostMatch(nodes) {
969
- var _iterator6 = _createForOfIteratorHelper(nodes),
970
- _step6;
971
- try {
972
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
973
- var node = _step6.value;
974
- switch (node.type) {
975
- case 'nesting':
976
- case 'class':
977
- case 'id':
978
- return false;
979
- default:
980
- break;
981
- }
982
- }
983
- } catch (err) {
984
- _iterator6.e(err);
985
- } finally {
986
- _iterator6.f();
987
- }
988
- if (nestedMatchVerdictOf(nodes) === 'none') {
989
- return false;
990
- }
991
- var tag = tagOf(nodes);
992
- return tag === null || HOST_TAGS.has(tag);
993
- }
994
-
995
- /**
996
- * Pseudo-classes that match an element when any one of their arguments does, so the element is
997
- * whatever the arguments' subjects are. `:not()` is deliberately absent: `:not(&)` matches every
998
- * element *except* the author's own, which is the opposite of ownership, so a `:not()` carrying
999
- * `&` is read like any other pseudo-only compound and guarded.
1000
- */
1001
- var MATCHES_ANY_PSEUDOS = new Set([':is', ':where', ':matches', ':-webkit-any', ':-moz-any']);
1002
-
1003
- /**
1004
- * What a compound's `:is(…&…)` / `:where(…&…)` argument says about the element it matches.
1005
- *
1006
- * `:is(&) > div` is `& > div` spelled differently, and `:is(& > span)` is `& > span`. Without
1007
- * this the `&` sits one level down, where {@link couldHostMatch} cannot see it, and the compound
1008
- * is guarded as if it were a bare pseudo: the author's own element picks up a wide guard and the
1009
- * rule stops applying inside every surface.
1010
- *
1011
- * - `none` — no argument's subject can be a host or sit inside somebody else's surface: every
1012
- * argument is a lone `&`, class or id compound, or `& > X` where no host can be `X`;
1013
- * - `narrow` — some argument is `& > X` where a host can be `X`, as `& > div` is;
1014
- * - `wide` — some argument is `& X`, whose `X` is always guarded, as in descendant position;
1015
- * - `null` — no such argument, or one shaped otherwise, which keeps the ordinary reading.
1016
- */
1017
-
1018
- function nestedMatchVerdictOf(nodes) {
1019
- var verdict = null;
1020
- var _iterator7 = _createForOfIteratorHelper(nodes),
1021
- _step7;
1022
- try {
1023
- for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
1024
- var node = _step7.value;
1025
- var next = nestedMatchVerdict(node);
1026
- if (next !== null && (verdict === null || rankOf(next) > rankOf(verdict))) {
1027
- verdict = next;
1028
- }
1029
- }
1030
- } catch (err) {
1031
- _iterator7.e(err);
1032
- } finally {
1033
- _iterator7.f();
1034
- }
1035
- return verdict;
1036
- }
1037
- function nestedMatchVerdict(node) {
1038
- if (node.type !== 'pseudo' || !MATCHES_ANY_PSEUDOS.has(pseudoName(node))) {
1039
- return null;
1040
- }
1041
- var hasNesting = false;
1042
- node.walk(function (inner) {
1043
- if (inner.type === 'nesting') {
1044
- hasNesting = true;
1045
- }
1046
- });
1047
- if (!hasNesting) {
1048
- return null;
1049
- }
1050
- var verdict = 'none';
1051
- var _iterator8 = _createForOfIteratorHelper(node.nodes),
1052
- _step8;
1053
- try {
1054
- for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
1055
- var argument = _step8.value;
1056
- var next = argumentVerdict(argument);
1057
- if (next === null) {
1058
- return null;
1059
- }
1060
- if (rankOf(next) > rankOf(verdict)) {
1061
- verdict = next;
1062
- }
1063
- }
1064
- } catch (err) {
1065
- _iterator8.e(err);
1066
- } finally {
1067
- _iterator8.f();
1068
- }
1069
- return verdict;
1070
- }
1071
- function argumentVerdict(argument) {
1072
- var compounds = splitCompounds(argument);
1073
- if (compounds.length === 1) {
1074
- return couldMatchForeignElement(compounds[0].nodes) ? null : 'none';
1075
- }
1076
- var _compounds = _slicedToArray(compounds, 2),
1077
- owner = _compounds[0],
1078
- subject = _compounds[1];
1079
- var ownerIsNesting = owner.nodes.some(function (node) {
1080
- return node.type === 'nesting';
1081
- });
1082
- if (compounds.length !== 2 || !ownerIsNesting) {
1083
- return null;
1084
- }
1085
- switch (subject.position) {
1086
- case 'child':
1087
- return couldHostMatch(subject.nodes) ? 'narrow' : 'none';
1088
- case 'descendant':
1089
- return 'wide';
1090
- default:
1091
- return null;
1092
- }
1093
- }
1094
- function rankOf(verdict) {
1095
- return verdict === 'none' ? 0 : verdict === 'narrow' ? 1 : 2;
1096
- }
1097
-
1098
- /**
1099
- * There used to be a `couldHostShareType` predicate here, gating the of-type refusal on whether a
1100
- * host could carry the compound's tag — so `& > span:nth-of-type(2)` was treated as safe.
1101
- *
1102
- * It is gone deliberately. The of-type family has no guard form at all, and the gate meant that in
1103
- * descendant position, where guards are unconditional, of-type selectors were being guarded anyway:
1104
- * 18 measured pairs across 8 selectors. The family is now refused outright by
1105
- * {@link planWholeBranchRefusals}, whatever its tag.
1106
- */
1107
-
1108
- /**
1109
- * Could this compound match an element that is not the author's own — that is, Design System
1110
- * internals, or content belonging to somebody else?
1111
- *
1112
- * This is the **ownership question**, and it is the real discriminator between the two guard
1113
- * forms. A class or an id answers "no": those only ever match elements the author wrote, so if
1114
- * such an element is inside a surface it is inside *the author's own* surface content.
1115
- * `[popover] *` and `dialog *` would then remove a style the author put there on purpose.
1116
- *
1117
- * `*`, a bare tag, and an attribute-only compound answer "yes": each can match a DS-internal
1118
- * element rendered inside somebody else's surface.
1119
- */
1120
- function couldMatchForeignElement(nodes) {
1121
- var _iterator9 = _createForOfIteratorHelper(nodes),
1122
- _step9;
1123
- try {
1124
- for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
1125
- var node = _step9.value;
1126
- switch (node.type) {
1127
- case 'nesting':
1128
- case 'class':
1129
- case 'id':
1130
- return false;
1131
- default:
1132
- break;
1133
- }
1134
- }
1135
- } catch (err) {
1136
- _iterator9.e(err);
1137
- } finally {
1138
- _iterator9.f();
1139
- }
1140
- var nested = nestedMatchVerdictOf(nodes);
1141
- return nested === null || nested === 'wide';
1142
- }
1143
-
1144
- /**
1145
- * Narrow or wide, for one compound. **The single place this choice is made.**
1146
- *
1147
- * The subtree terms `[popover] <universal>` and `dialog <universal>` do not mean "not the host's
1148
- * subtree". They mean **"not inside ANY surface"** — so a wide guard disables its own rule for
1149
- * any subject that legitimately lives inside a popover, dialog or drawer. Consumer content
1150
- * inside a surface is the common case, not an edge case, which is why wide is NOT the safe
1151
- * default.
1152
- *
1153
- * The governing rule, from the decision doc:
1154
- *
1155
- * > Wide when the matched element could be inside someone *else's* surface. Narrow when it
1156
- * > could be inside the subject's *own* surface. Where both are possible, the site is residue.
1157
- *
1158
- * Operationally that turns on whether a surface can sit **strictly between** the previous
1159
- * compound and this one:
1160
- *
1161
- * - **descendant** — the gap is unbounded, so a surface can sit inside the previous compound
1162
- * and above this one. That surface is somebody else's, and its internals match here. Wide.
1163
- * - **child, adjacent, general** — there is no gap. The only exposure is "this element *is*
1164
- * the host", which narrow already closes. Wide would buy nothing and would additionally
1165
- * break the case where the whole selector is rendered inside a surface — then the previous
1166
- * compound's own real child *is* `[popover] *`. Narrow, always. This is what
1167
- * `.x:has(> div)` measured.
1168
- * - **first** — there is no previous compound, so the gap question does not arise and the
1169
- * ownership question is asked directly, via {@link couldMatchForeignElement}. At global
1170
- * scope a first compound is never given a *fresh* guard, because with nothing above it the
1171
- * rule reached the portalled surface before the flag (see {@link isDocumentLevelCompound});
1172
- * the form still decides which list a pre-existing partial guard is merged up to.
1173
- */
1174
- function guardFormFor(compound) {
1175
- switch (compound.position) {
1176
- case 'descendant':
1177
- return 'wide';
1178
- case 'first':
1179
- return couldMatchForeignElement(compound.nodes) ? 'wide' : 'narrow';
1180
- default:
1181
- return 'narrow';
1182
- }
1183
- }
1184
-
1185
- /**
1186
- * Is this branch a bare universal selector at global scope — `*`, `*::before`, `*::after`?
1187
- *
1188
- * "Bare" means the compound is nothing but the universal selector, optionally with a
1189
- * pseudo-element. "Global scope" means there is no ancestor constraint at all, so the rule reaches
1190
- * every element in the document including a top layer host.
1191
- *
1192
- * Deliberately narrow, so it cannot over-fire:
1193
- * - `& > *`, `.foo > *`, `& *`, `& > *:first-child` all have an ancestor constraint and are
1194
- * rewritten normally;
1195
- * - `*:first-child` is not bare — the pseudo-class makes it a positional rule, not a reset — and is
1196
- * rewritten normally;
1197
- * - `> *` is the nested spelling of `& > *`, so it is scoped too.
1198
- *
1199
- * ## Why this is not wider — the question every reader asks
1200
- *
1201
- * A *scoped* reset looks like it shares the mechanism: guarding `& > div { box-sizing: inherit }`
1202
- * also excludes the host from a reset. It does not, and the reason is **reach**, not the property:
1203
- *
1204
- * - global `* { box-sizing: inherit }` matched the host **before** the flag too, because `*`
1205
- * reaches surface content sitting in a portal at `body` level. Guarding it *removes* something
1206
- * the host already had — a behaviour change, and the layout bug;
1207
- * - scoped `& > * { box-sizing: inherit }` did **not** match the host pre-flag, because the host
1208
- * was portalled away and was not a child of `&`. Post-flag it does. That is exactly the
1209
- * `popover-receives` damage, and guarding *restores* the pre-flag rendering.
1210
- *
1211
- * Same declaration, opposite dispositions. This is also why no browser measurement can settle it:
1212
- * a browser can say what `box-sizing` does, but not what the DOM looked like before the flag.
1213
- */
1214
- function isBareGlobalUniversal(branch) {
1215
- var compounds = splitCompounds(branch);
1216
- if (compounds.length !== 1) {
1217
- return false;
1218
- }
1219
- var _compounds2 = _slicedToArray(compounds, 1),
1220
- compound = _compounds2[0];
1221
- if (compound.position !== 'first') {
1222
- return false;
1223
- }
1224
- var sawUniversal = false;
1225
- var _iterator0 = _createForOfIteratorHelper(compound.nodes),
1226
- _step0;
1227
- try {
1228
- for (_iterator0.s(); !(_step0 = _iterator0.n()).done;) {
1229
- var node = _step0.value;
1230
- if (node.type === 'universal') {
1231
- sawUniversal = true;
1232
- continue;
1233
- }
1234
- if (isPseudoElement(node)) {
1235
- continue;
1236
- }
1237
- return false;
1238
- }
1239
- } catch (err) {
1240
- _iterator0.e(err);
1241
- } finally {
1242
- _iterator0.f();
1243
- }
1244
- return sawUniversal;
1245
- }
1246
-
1247
- /**
1248
- * Declarations that mark a rule as a **reset** rather than an override, meaning a guard would take
1249
- * the declaration away from the host and break it.
1250
- *
1251
- * Deliberately minimal — only signals that are unambiguous on their face:
1252
- * - `box-sizing`, the canonical global reset and the measured case;
1253
- * - any of the cascade keywords, whose whole purpose is to normalise inherited values.
1254
- *
1255
- * The asymmetry here is the point, and it is why this is safe to act on automatically. Wrongly
1256
- * calling an override a reset leaves a `popover-receives` exposure on a bare `*` rule, which is
1257
- * cheap. Wrongly calling a reset an override *introduces* a layout bug, which is not. So this
1258
- * function only ever moves a row **out** of the guarded set, and a row it does not recognise stays
1259
- * `residue` for a human rather than being guarded on a guess.
1260
- */
1261
- function findResetSignal(declarations) {
1262
- if (!declarations) {
1263
- return null;
1264
- }
1265
- var pairs = typeof declarations === 'string' ? parseDeclarationText(declarations) : Object.entries(declarations).map(function (_ref2) {
1266
- var _ref3 = _slicedToArray(_ref2, 2),
1267
- property = _ref3[0],
1268
- value = _ref3[1];
1269
- return [property, String(value !== null && value !== void 0 ? value : '')];
1270
- });
1271
- var _iterator1 = _createForOfIteratorHelper(pairs),
1272
- _step1;
1273
- try {
1274
- for (_iterator1.s(); !(_step1 = _iterator1.n()).done;) {
1275
- var _step1$value = _slicedToArray(_step1.value, 2),
1276
- rawProperty = _step1$value[0],
1277
- rawValue = _step1$value[1];
1278
- var property = kebabCase(rawProperty).toLowerCase();
1279
- var value = rawValue.trim().toLowerCase();
1280
- if (property === 'box-sizing') {
1281
- return "".concat(property, ": ").concat(value);
1282
- }
1283
- if (CASCADE_KEYWORDS.has(value)) {
1284
- return "".concat(property, ": ").concat(value);
1285
- }
1286
- }
1287
- } catch (err) {
1288
- _iterator1.e(err);
1289
- } finally {
1290
- _iterator1.f();
1291
- }
1292
- return null;
1293
- }
1294
- var CASCADE_KEYWORDS = new Set(['inherit', 'initial', 'unset', 'revert', 'revert-layer']);
1295
- function parseDeclarationText(text) {
1296
- var pairs = [];
1297
- var _iterator10 = _createForOfIteratorHelper(text.split(';')),
1298
- _step10;
1299
- try {
1300
- for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
1301
- var part = _step10.value;
1302
- var colon = part.indexOf(':');
1303
- if (colon === -1) {
1304
- continue;
1305
- }
1306
- var property = part.slice(0, colon).trim();
1307
- var value = part.slice(colon + 1).trim();
1308
- if (property !== '') {
1309
- pairs.push([property, value]);
1310
- }
1311
- }
1312
- } catch (err) {
1313
- _iterator10.e(err);
1314
- } finally {
1315
- _iterator10.f();
1316
- }
1317
- return pairs;
1318
- }
1319
- function kebabCase(property) {
1320
- return property.replace(/[A-Z]/g, function (character) {
1321
- return "-".concat(character.toLowerCase());
1322
- });
1323
- }
1324
-
1325
- /**
1326
- * Does this compound name a top layer host or a non-rendered tag outright, such as `dialog`?
1327
- *
1328
- * Then the author is targeting that element deliberately. For a host, **both** guard forms
1329
- * would make the rule match nothing at all, because the guard's own term list excludes exactly
1330
- * what the compound selects. A non-rendered tag is `display: none`, so a guard would protect
1331
- * nothing. Either way the compound is left alone.
1332
- */
1333
- function compoundNamesHost(nodes) {
1334
- return nodes.some(isGuardTermNode);
1335
- }
1336
- function tagOf(nodes) {
1337
- var _iterator11 = _createForOfIteratorHelper(nodes),
1338
- _step11;
1339
- try {
1340
- for (_iterator11.s(); !(_step11 = _iterator11.n()).done;) {
1341
- var node = _step11.value;
1342
- if (node.type === 'tag') {
1343
- return node.value.toLowerCase();
1344
- }
1345
- }
1346
- } catch (err) {
1347
- _iterator11.e(err);
1348
- } finally {
1349
- _iterator11.f();
1350
- }
1351
- return null;
1352
- }
1353
- function isPseudoElement(node) {
1354
- if (node.type !== 'pseudo') {
1355
- return false;
1356
- }
1357
- return node.value.startsWith('::') || LEGACY_PSEUDO_ELEMENTS.has(pseudoName(node));
1358
- }
1359
-
1360
- /**
1361
- * Guards must be inserted before any pseudo-element — `div:not(…)::before`, never after.
1362
- */
1363
- function guardInsertIndex(nodes) {
1364
- var index = nodes.findIndex(isPseudoElement);
1365
- return index === -1 ? nodes.length : index;
1366
- }
1367
-
1368
- /* -------------------------------------------------------------------------------------- */
1369
- /* Plan */
1370
- /* -------------------------------------------------------------------------------------- */
1371
-
1372
- function createPlan() {
1373
- return {
1374
- replace: new Map(),
1375
- appendAfter: new Map(),
1376
- prependBefore: new Map(),
1377
- touched: new Set(),
1378
- guardCount: 0,
1379
- receives: false,
1380
- hardRefusals: [],
1381
- softRefusals: [],
1382
- residualNotes: [],
1383
- reachSuppressions: [],
1384
- reviews: [],
1385
- sawGeneralSibling: false
1386
- };
1387
- }
1388
- function setReplace(plan, node, text) {
1389
- plan.replace.set(node, text);
1390
- plan.touched.add(node);
1391
- }
1392
- function setAppendAfter(plan, node, text) {
1393
- var _plan$appendAfter$get;
1394
- plan.appendAfter.set(node, ((_plan$appendAfter$get = plan.appendAfter.get(node)) !== null && _plan$appendAfter$get !== void 0 ? _plan$appendAfter$get : '') + text);
1395
- plan.touched.add(node);
1396
- }
1397
- function setPrependBefore(plan, node, text) {
1398
- var _plan$prependBefore$g;
1399
- plan.prependBefore.set(node, text + ((_plan$prependBefore$g = plan.prependBefore.get(node)) !== null && _plan$prependBefore$g !== void 0 ? _plan$prependBefore$g : ''));
1400
- plan.touched.add(node);
1401
- }
1402
-
1403
- /* -------------------------------------------------------------------------------------- */
1404
- /* Planning */
1405
- /* -------------------------------------------------------------------------------------- */
1406
-
1407
- function planBranch(branch, plan, scope) {
1408
- var _compounds$;
1409
- /**
1410
- * Refusals that hold **wherever** the pseudo appears, at any nesting depth, before anything
1411
- * is planned. These families have no guard form at all, so no part of a selector containing
1412
- * one may be rewritten — a guard elsewhere in it would be a partial fix on a rule that stays
1413
- * broken, and in a selector list it would leave the list partially guarded.
1414
- */
1415
- planWholeBranchRefusals(branch, plan);
1416
-
1417
- /**
1418
- * `:has()` next, wherever it appears. It may be nested inside `:not()` / `:is()` /
1419
- * `:where()`, and in that case the guard is pushed *inside* the `:has()` argument rather
1420
- * than onto the wrapping `:not()` — trap 5.
1421
- */
1422
- planHasArguments(branch, plan);
1423
- var compounds = splitCompounds(branch);
1424
-
1425
- /**
1426
- * A branch that opens with a combinator (`> *`, `> :not([data-layout-slot])`) is the nested
1427
- * spelling of `& > …` whatever scope the caller named: the parent it hangs off is implied,
1428
- * and that parent is the consumer's own element, so nothing in the branch is document-level.
1429
- */
1430
- var opensWithCombinator = ((_compounds$ = compounds[0]) === null || _compounds$ === void 0 ? void 0 : _compounds$.combinatorBefore) !== null;
1431
- compounds.forEach(function (compound, index) {
1432
- var ancestors = compounds.slice(0, index);
1433
- var isGlobalRule = scope === 'global' && !opensWithCombinator;
1434
-
1435
- /**
1436
- * At global scope, a compound with nothing but the document itself above it reached the
1437
- * portalled surface before the flag. Under `nested` scope every branch carries `&`, which
1438
- * is never document-level, so the question does not arise.
1439
- */
1440
- var reachedPreFlag = isGlobalRule && ancestors.every(isDocumentLevelCompound);
1441
-
1442
- /**
1443
- * A bare `div` among otherwise document-level ancestors is the one case the transform
1444
- * cannot settle. Any other consumer-owned ancestor (`.sidebar`, `div.x`, `[data-foo]`)
1445
- * decides the question the usual way, so the review outcome needs every ancestor to be
1446
- * document-level or a bare `div`.
1447
- */
1448
- var behindBareDivAncestor = isGlobalRule && !reachedPreFlag && ancestors.every(function (ancestor) {
1449
- return isDocumentLevelCompound(ancestor) || isBareDivCompound(ancestor);
1450
- });
1451
- planCompound(compound, plan, {
1452
- reachedPreFlag: reachedPreFlag,
1453
- behindBareDivAncestor: behindBareDivAncestor
1454
- });
1455
- });
1456
- }
1457
-
1458
- /**
1459
- * Is this compound exactly the tag `div`, with no class, id, attribute or pseudo qualifier?
1460
- *
1461
- * Pre-flag, a surface portalled to `body` sat inside `@atlaskit/portal`'s container div, and
1462
- * every surface wrapper is a div too, so a bare `div` ancestor was satisfied on the way down to
1463
- * the surface's content. A qualified div (`div.x`, `div[data-foo]`) names the consumer's own
1464
- * element and is not ambiguous.
1465
- */
1466
- function isBareDivCompound(compound) {
1467
- var nodes = compound.nodes;
1468
- return nodes.length === 1 && nodes[0].type === 'tag' && nodes[0].value.toLowerCase() === 'div';
1469
- }
1470
- function bareDivAncestorReason(nodes) {
1471
- var compound = nodes.map(function (node) {
1472
- return node.toString().trim();
1473
- }).join('');
1474
- return "'".concat(compound, "' is at global scope below a bare div ancestor. The portal container and every surface wrapper were divs, so this rule may already have reached the surface's content when it was portalled to body, and a guard here could remove styling the surface had before the flag rather than restore any. Nothing is written; review by hand. Guard it if the div stands for your own wrapper, leave it if it stands for any div, and anchor the selector to your own element (a class, an id, or `&` in a style object) if you mean only your own content.");
1475
- }
1476
-
1477
- /**
1478
- * Is this compound satisfied by the document itself, rather than by anything the consumer
1479
- * rendered — `html`, `body`, `:root`, each with any qualifiers, or a lone `*`?
1480
- *
1481
- * These are the ancestors every element has, including a surface portalled to `body`. A chain
1482
- * of them above a compound constrains nothing, so the rule reached the portalled surface's
1483
- * content before the flag and a guard would take away what that content already had. A
1484
- * consumer-owned ancestor (`.sidebar`, `#app`, `&`) or any other tag did **not** contain the
1485
- * portal, so below one of those the host is a new match and the guard restores.
1486
- */
1487
- function isDocumentLevelCompound(compound) {
1488
- var nodes = compound.nodes;
1489
- if (isDocumentRootCompound(nodes)) {
1490
- return true;
1491
- }
1492
- return nodes.length === 1 && nodes[0].type === 'universal';
1493
- }
1494
-
1495
- /**
1496
- * `html`, `body` or `:root`, with any qualifiers — an element of the document itself, which is
1497
- * never a host and never inside one.
1498
- */
1499
- function isDocumentRootCompound(nodes) {
1500
- var tag = tagOf(nodes);
1501
- if (tag === 'html' || tag === 'body') {
1502
- return true;
1503
- }
1504
- return nodes.some(function (node) {
1505
- return node.type === 'pseudo' && pseudoName(node) === ':root';
1506
- });
1507
- }
1508
- function reachedPreFlagReason(nodes) {
1509
- var compound = nodes.map(function (node) {
1510
- return node.toString().trim();
1511
- }).join('');
1512
- return "'".concat(compound, "' is at global scope with nothing but the document itself above it (html, body, :root or *), so this rule already reached the surface's content when it was portalled to body. Guarding it would remove styling the surface had before the flag rather than restore any, so it is left alone. Anchor the selector to your own element (a class, an id, or `&` in a style object) if you mean only your own content.");
1513
- }
1514
-
1515
- /**
1516
- * The two families with no guard form at any depth.
1517
- *
1518
- * Both are matched against the **full** pseudo-class name via a set, never by substring. Four of
1519
- * the five of-type pseudos do not contain the text `nth-of-type`, and `:first-of-type` alone is 926
1520
- * occurrences in the monorepo, so a substring test would silently miss almost the whole family.
1521
- */
1522
- function planWholeBranchRefusals(branch, plan) {
1523
- branch.walkPseudos(function (pseudo) {
1524
- if (OF_TYPE_PSEUDOS.has(pseudoName(pseudo))) {
1525
- /**
1526
- * The of-type family is type-scoped by definition: it counts siblings by tag name and
1527
- * accepts no `of S` selector argument, so its counting cannot be re-based onto real
1528
- * elements. A guard anywhere in such a selector cannot fix the counting and changes
1529
- * behaviour inside surfaces for nothing.
1530
- */
1531
- plan.hardRefusals.push("'".concat(pseudo.value, "' has no guard form: the of-type family counts siblings by tag name and accepts no `of S` selector argument, so its counting cannot be re-based onto real elements. Nothing in this selector is rewritten, because a guard elsewhere in it could not fix the counting."));
1532
- return;
1533
- }
1534
- if (pseudoName(pseudo) === ':empty') {
1535
- /**
1536
- * `:empty` is true of an element with no children *of any kind* and takes no selector
1537
- * argument, so a host rendered inside the element cannot be excluded from it. A compound
1538
- * carrying both `:empty` and a positional pseudo must refuse rather than take the
1539
- * positional rewrite — `& > div:has(> div:only-child:empty)` is the measured case.
1540
- */
1541
- plan.hardRefusals.push("':empty' has no guard form: it is true of an element with no children of any kind and takes no selector argument, so a host rendered inside the element cannot be excluded from it. Nothing in this selector is rewritten, including any positional pseudo compounded with it.");
1542
- }
1543
- });
1544
- }
1545
- function planCompound(compound, plan, options) {
1546
- var nodes = compound.nodes,
1547
- position = compound.position,
1548
- isSubject = compound.isSubject;
1549
- if (position === 'general') {
1550
- plan.sawGeneralSibling = true;
1551
- }
1552
-
1553
- /* --- Refusals local to this compound ------------------------------------------------ */
1554
- var _iterator12 = _createForOfIteratorHelper(nodes),
1555
- _step12;
1556
- try {
1557
- for (_iterator12.s(); !(_step12 = _iterator12.n()).done;) {
1558
- var node = _step12.value;
1559
- if (node.type !== 'pseudo') {
1560
- continue;
1561
- }
1562
- if (isSubject && ANCESTOR_PROPAGATING_PSEUDOS.has(pseudoName(node))) {
1563
- plan.softRefusals.push("'".concat(node.value, "' on the subject compound has no guard form: it matches an element *and its ancestors*, so a surface rendered inside this element hands it the state while the pointer or focus is in the surface. No guard expresses \"not originating inside a top layer surface\", at any depth."));
1564
- }
1565
- }
1566
- } catch (err) {
1567
- _iterator12.e(err);
1568
- } finally {
1569
- _iterator12.f();
1570
- }
1571
- var merges = planPreExistingGuards(compound, plan);
1572
-
1573
- /* --- Sibling combinators ------------------------------------------------------------ */
1574
-
1575
- /**
1576
- * The two damage modes split cleanly on a sibling combinator:
1577
- *
1578
- * - if a host could match the right-hand compound, the damage is that the host receives
1579
- * the declaration — `popover-receives` — and the guard goes on that compound. This is
1580
- * what shipped code does for `* + *` and `div + div`;
1581
- * - if it could not, the only remaining damage is a host inserted *between* A and B,
1582
- * which breaks `A + B` and which no guard restores. That is `real-element-loses` and it
1583
- * is refused.
1584
- *
1585
- * `~` has no `real-element-loses` mode at all: it matches every following sibling, so an
1586
- * inserted host removes no real match.
1587
- */
1588
- if (position === 'adjacent' && !couldHostMatch(nodes)) {
1589
- plan.hardRefusals.push('The adjacent sibling combinator has no guard form here: no host can match the right-hand compound, so the only exposure left is a host inserted *between* the two siblings, which breaks the adjacency and which no guard restores.');
1590
- return;
1591
- }
1592
- if (position === 'adjacent' && couldHostMatch(nodes)) {
1593
- plan.residualNotes.push('The guard closes `popover-receives` on this adjacent sibling combinator, but a host inserted *between* the two siblings still breaks the adjacency for real elements. No guard form restores that; review the site.');
1594
- }
1595
-
1596
- /* --- Positional pseudo-classes ------------------------------------------------------ */
1597
-
1598
- /**
1599
- * A positional pseudo refuses the whole selector while the `of S` family is withdrawn, so
1600
- * there is nothing left to plan for this compound.
1601
- */
1602
- if (planPositionals(compound, plan)) {
1603
- return;
1604
- }
1605
-
1606
- /* --- Compound guard ---------------------------------------------------------------- */
1607
-
1608
- /* A merged or pre-existing guard already satisfies this compound — never add a second. */
1609
- var formName = guardFormFor(compound);
1610
- var alreadyGuarded = merges > 0 || isCompoundGuarded(nodes, formName);
1611
- var form = formName === 'wide' ? WIDE_GUARD : NARROW_GUARD;
1612
- var guard = null;
1613
- if (alreadyGuarded) {
1614
- guard = null;
1615
- } else if (nodes.some(function (node) {
1616
- return node.type === 'nesting';
1617
- }) || nestedMatchVerdictOf(nodes) === 'none') {
1618
- /**
1619
- * **Never guard the `&` compound, in any position.** `&` is the enclosing rule's own
1620
- * subject, and the host is created *inside* `&`, never *as* `&`. So `&` can never be the
1621
- * host, and a guard on it can only ever subtract legitimate matches.
1622
- *
1623
- * Measured: `html:not([data-color-mode=dark]) &` rewritten with a guard on `&` matches
1624
- * outside a surface and matches **nothing** inside a popover or a dialog — so a theme rule
1625
- * stops applying to every component rendered inside any surface.
1626
- *
1627
- * This is the mirror image of the host-naming case below. There a compound *names* a host
1628
- * and the guard destroys it; here a compound provably *cannot be* a host and the guard
1629
- * destroys it. Both are guarding something that is not the enemy, and both look like
1630
- * diligence.
1631
- *
1632
- * `:is(&)` and `:is(& > span)` resolve to the same verdict, see {@link nestedMatchVerdict}.
1633
- */
1634
- guard = null;
1635
- } else if (isDocumentRootCompound(nodes)) {
1636
- /**
1637
- * `html`, `body` and `:root` are the document's own elements. No surface can contain them
1638
- * and no host can be one, so a guard on them excludes nothing and is only noise.
1639
- */
1640
- guard = null;
1641
- } else if (compoundNamesHost(nodes)) {
1642
- /**
1643
- * `& dialog`, `& > [popover]`, `& style`: the author is targeting a surface or a
1644
- * non-rendered element on purpose. For a host, every guard form excludes exactly what the
1645
- * compound selects, so guarding would leave a rule that matches nothing. For a
1646
- * non-rendered tag, a guard would protect nothing.
1647
- */
1648
- plan.softRefusals.push("'".concat(nodes.map(function (node) {
1649
- return node.toString().trim();
1650
- }).join(''), "' names a top layer host or a non-rendered tag directly, so it targets that element deliberately. A guard would either exclude exactly what it selects or protect nothing, so it is left alone."));
1651
- } else if (options.reachedPreFlag) {
1652
- /**
1653
- * The reach principle from the module docblock, applied. `div`, `body div` and `* + *` at
1654
- * global scope all matched the surface's content in its portal before the flag, so the
1655
- * guard that would otherwise be written here would remove something the surface had.
1656
- * Recorded only where a guard would have been written, so the reason is never attached
1657
- * to a compound that needed nothing.
1658
- */
1659
- if (position === 'descendant' || couldHostMatch(nodes)) {
1660
- plan.reachSuppressions.push(reachedPreFlagReason(nodes));
1661
- }
1662
- } else if (options.behindBareDivAncestor) {
1663
- /**
1664
- * The ambiguous ancestor from the module docblock. Recorded only where a guard would have
1665
- * been written, exactly as the reach suppression above, so a compound that needed nothing
1666
- * never asks for a review.
1667
- */
1668
- if (position === 'descendant' || couldHostMatch(nodes)) {
1669
- plan.reviews.push(bareDivAncestorReason(nodes));
1670
- }
1671
- } else if (position === 'descendant') {
1672
- /**
1673
- * Always guarded: a surface can sit anywhere in the unbounded gap above this compound, and
1674
- * its internals match here. That is somebody else's surface, so the wide form applies.
1675
- */
1676
- guard = form;
1677
- } else if (couldHostMatch(nodes)) {
1678
- /**
1679
- * Everywhere else, guard when a host could *be* this element.
1680
- */
1681
- guard = form;
1682
- }
1683
- if (guard) {
1684
- var at = guardInsertIndex(nodes);
1685
- if (at === 0) {
1686
- setPrependBefore(plan, nodes[0], guard);
1687
- } else {
1688
- setAppendAfter(plan, nodes[at - 1], guard);
1689
- }
1690
- plan.receives = true;
1691
- plan.guardCount += 1;
1692
- }
1693
- }
1694
-
1695
- /**
1696
- * Handle a guard that is already present.
1697
- *
1698
- * Earlier hand fixes carry partial or longer guards, such as `:not(:where(dialog))` or one that
1699
- * also lists `style` and the rest. Missing terms are **merged into** that list, never replaced,
1700
- * and never joined by a second guard. Extra terms are kept.
1701
- * Merging keeps idempotency across the boundary: once the list is canonical, running again
1702
- * changes nothing.
1703
- *
1704
- * A host-term `:not()` with no `:where()` around it is refused instead of merged, because it
1705
- * carries real weight and unifying it would change the rule's specificity — this covers the
1706
- * editor's `:not(style, .ProseMirror-gapcursor, .ProseMirror-widget, span)`, which is the same
1707
- * shape and additionally lists genuinely rendered elements.
1708
- *
1709
- * A partial guard inside an `of` argument is not handled here. Any selector carrying an `of`
1710
- * argument is refused by `rewriteSelector` before planning starts, because Compiled's extract
1711
- * mode drops such a rule outright (see {@link WITHDRAWN_POSITIONAL_FORMS}).
1712
- *
1713
- * The merged list is written in canonical order: the required terms as `L` lists them, then
1714
- * any extra terms the author added. {@link isCompoundGuarded} recognises the result as complete
1715
- * on the next pass. A list that already has every required term is left as written, in any
1716
- * order and with or without a `*`: the two spellings match the same elements, and the ratchet
1717
- * counts only positional pseudo-classes, so rewriting them would be churn.
1718
- */
1719
- function planPreExistingGuards(compound, plan) {
1720
- var wide = guardFormFor(compound) === 'wide';
1721
- var merges = 0;
1722
- var _iterator13 = _createForOfIteratorHelper(compound.nodes),
1723
- _step13;
1724
- try {
1725
- var _loop = function _loop() {
1726
- var node = _step13.value;
1727
- if (node.type !== 'pseudo') {
1728
- return 0; // continue
1729
- }
1730
- if (pseudoName(node) !== ':not') {
1731
- return 0; // continue
1732
- }
1733
-
1734
- /**
1735
- * Classify from the `:not()`'s *direct* content only. Looking deeper would misread any
1736
- * `:not()` that merely contains a guard somewhere inside it — including
1737
- * `:not(:has(button:not(:where(L))))` and the `:not(:where(:nth-last-child(n+2 of S)))`
1738
- * tail of the `:only-child` form, both of which this transform emits itself.
1739
- */
1740
- var direct = node.nodes;
1741
-
1742
- /**
1743
- * Trap 1. `S` is itself a `:not()`, so `X:not(S)` is a double negative that matches
1744
- * only* hosts. Appending a guard to it would make it match nothing at all.
1745
- */
1746
- var soleNot = soleNotInside(node);
1747
- if (soleNot && mentionsGuardTerm(soleNot)) {
1748
- plan.hardRefusals.push("'".concat(node.toString().trim(), "' is a double negative: the guard `S` is itself a `:not()`, so this matches *only* top layer hosts and nothing else. Appending another guard would make it match nothing. The intended form appends `:not(:where(L))` directly."));
1749
- return 0; // continue
1750
- }
1751
- var where = soleWhereInside(node);
1752
- if (!where) {
1753
- /**
1754
- * Not wrapped in `:where()`. Only a refusal if it is actually an element exclusion
1755
- * list that mentions a guard term — otherwise it is an ordinary `:not()`.
1756
- */
1757
- if (direct.every(isSimpleTerm) && direct.some(termIsGuardTerm)) {
1758
- plan.hardRefusals.push("'".concat(node.toString().trim(), "' is an existing top layer guard with no `:where()` around it, so it carries real specificity. Unifying it would change the rule's weight, and in the editor's case would also drop genuinely rendered elements from the exclusion list. This needs a hand edit and routing to the owning team."));
1759
- }
1760
- return 0; // continue
1761
- }
1762
- var terms = where.nodes;
1763
-
1764
- /**
1765
- * Every term must be a simple selector, and at least one must be a guard term.
1766
- * A `:where()` holding a functional pseudo is not an element exclusion list, and a
1767
- * `:where()` of unrelated selectors is not a top layer guard to merge into.
1768
- */
1769
- if (!terms.every(isSimpleTerm) || !terms.some(termIsGuardTerm)) {
1770
- return 0; // continue
1771
- }
1772
- var existing = terms.map(function (term) {
1773
- return term.toString().trim();
1774
- }).filter(Boolean);
1775
- var existingKeys = new Set(existing.map(normalise));
1776
- var required = wide ? WIDE_TERMS : NARROW_TERMS;
1777
- var requiredKeys = wide ? WIDE_TERM_KEYS : NARROW_TERM_KEYS;
1778
- var missing = required.filter(function (term) {
1779
- return !existingKeys.has(normalise(term));
1780
- });
1781
- if (missing.length === 0) {
1782
- return 0; // continue
1783
- }
1784
-
1785
- /**
1786
- * Canonical order: the required terms as `L` lists them, then any term the author added
1787
- * that is not part of the list. A canonical term the author already had (in any order,
1788
- * or as a wide term on a narrow position) is kept but re-ordered.
1789
- */
1790
- var extras = existing.filter(function (term) {
1791
- return !requiredKeys.has(normalise(term));
1792
- });
1793
- var merged = [].concat(_toConsumableArray(required), _toConsumableArray(extras));
1794
- setReplace(plan, node, ":not(:where(".concat(merged.join(', '), "))"));
1795
-
1796
- /**
1797
- * When a merge rewrites the guard, **add an explicit `*`** if the guard is all the
1798
- * compound has. `& > *:not(:where(…))` and `& > :not(:where(…))` are semantically
1799
- * identical. `*` is the form the guard-form table and the `child-universal` pair use.
1800
- */
1801
- if (compound.nodes.length === 1) {
1802
- setPrependBefore(plan, node, '*');
1803
- }
1804
- merges += 1;
1805
- plan.guardCount += 1;
1806
- plan.receives = true;
1807
- },
1808
- _ret;
1809
- for (_iterator13.s(); !(_step13 = _iterator13.n()).done;) {
1810
- _ret = _loop();
1811
- if (_ret === 0) continue;
1812
- }
1813
- } catch (err) {
1814
- _iterator13.e(err);
1815
- } finally {
1816
- _iterator13.f();
1817
- }
1818
- return merges;
1819
- }
1820
-
1821
- /**
1822
- * A term of a guard's `:where()` list: simple selectors only, no functional pseudos.
1823
- */
1824
- function isSimpleTerm(term) {
1825
- return !term.nodes.some(function (node) {
1826
- return node.type === 'pseudo';
1827
- });
1828
- }
1829
-
1830
- /**
1831
- * Guard every top-level comma branch of every `:has()`, at any depth.
1832
- *
1833
- * `:has()` matches if *any* branch matches, so a guard on one branch leaves the others open.
1834
- * The parser has already split on top-level commas, so nested commas inside `:where()` /
1835
- * `:is()` / `:not()` cannot be split by accident.
1836
- *
1837
- * Within a branch, every compound is planned by {@link planCompound}, exactly as a top-level
1838
- * compound is. The branch's leftmost compound is a descendant of the subject, so it takes the
1839
- * wide list whatever its tag: `.x:has(button, a)` gets two guards even though no host is a
1840
- * `<button>`, because the button can be inside a surface that is inside `.x`. A compound after
1841
- * `>` takes the narrow list only if a host could be that element: `:has(> div > span)` guards
1842
- * the `div` and leaves the `span` alone.
1843
- */
1844
- function planHasArguments(branch, plan) {
1845
- branch.walkPseudos(function (pseudo) {
1846
- if (pseudoName(pseudo) !== ':has') {
1847
- return;
1848
- }
1849
-
1850
- /**
1851
- * Chromium rejects the entire selector when a `:has()` appears inside a `:has()`
1852
- * argument, so the rule has already stopped applying. Never emit one, and never
1853
- * pretend to fix one.
1854
- */
1855
- if (hasAncestorPseudo(pseudo, ':has')) {
1856
- plan.hardRefusals.push('A `:has()` nested inside another `:has()` argument is rejected outright by Chromium, so the whole rule already does not apply. This cannot be guarded — it has to be restructured by hand.');
1857
- return;
1858
- }
1859
- var selfReferential = false;
1860
- pseudo.walk(function (inner) {
1861
- if (inner.type === 'nesting') {
1862
- selfReferential = true;
1863
- }
1864
- });
1865
- if (selfReferential) {
1866
- plan.hardRefusals.push('A self-referential `:has()` — `:has(&)` or `:has(> &)` — has no guard form: the argument resolves to the subject itself, so there is no descendant compound to place a guard on.');
1867
- return;
1868
- }
1869
-
1870
- /**
1871
- * `:has(+ X)` and `:has(X + Y)` are adjacency inside the argument, with no selector
1872
- * argument to re-base it onto real elements. `:has(~ X)` reaches the subject's siblings
1873
- * rather than its descendants, so neither the wide form nor the narrow one is the right
1874
- * guard there. Both are refused.
1875
- */
1876
- var sibling = null;
1877
- pseudo.each(function (argument) {
1878
- var _iterator14 = _createForOfIteratorHelper(argument.nodes),
1879
- _step14;
1880
- try {
1881
- for (_iterator14.s(); !(_step14 = _iterator14.n()).done;) {
1882
- var inner = _step14.value;
1883
- if (inner.type !== 'combinator') {
1884
- continue;
1885
- }
1886
- var value = inner.value.trim();
1887
- if (!sibling && (value === '+' || value === '~')) {
1888
- sibling = value;
1889
- }
1890
- }
1891
- } catch (err) {
1892
- _iterator14.e(err);
1893
- } finally {
1894
- _iterator14.f();
1895
- }
1896
- });
1897
- if (sibling) {
1898
- plan.hardRefusals.push("`:has()` with a sibling combinator ('".concat(sibling, "') has no guard form: adjacency inside the argument takes no selector argument to re-base onto real elements, and the argument reaches the subject's siblings rather than its descendants, so neither guard form applies."));
1899
- return;
1900
- }
1901
- var propagating = null;
1902
- pseudo.walkPseudos(function (inner) {
1903
- if (!propagating && ANCESTOR_PROPAGATING_PSEUDOS.has(pseudoName(inner))) {
1904
- propagating = inner.value;
1905
- }
1906
- });
1907
- if (propagating) {
1908
- plan.hardRefusals.push("`:has()` containing '".concat(propagating, "' has no guard form: '").concat(propagating, "' matches an element *and its ancestors*, so the subject itself satisfies the argument whenever the pointer or focus is inside the surface. No guard on the argument can help, at any depth."));
1909
- return;
1910
- }
1911
- var _iterator15 = _createForOfIteratorHelper(pseudo.nodes),
1912
- _step15;
1913
- try {
1914
- for (_iterator15.s(); !(_step15 = _iterator15.n()).done;) {
1915
- var argument = _step15.value;
1916
- var compounds = splitCompounds(argument);
1917
- if (compounds.length === 0) {
1918
- continue;
1919
- }
1920
-
1921
- /**
1922
- * A positional pseudo inside the argument refuses the whole selector while the `of S`
1923
- * family is withdrawn, at any depth, so there is nothing left to plan for this branch.
1924
- */
1925
- if (compounds.some(function (compound) {
1926
- return planPositionals(compound, plan);
1927
- })) {
1928
- continue;
1929
- }
1930
-
1931
- /**
1932
- * Every compound of the argument is checked, not only the last. `:has(dialog button)`
1933
- * matches only buttons inside a dialog, so a wide guard on `button` would exclude
1934
- * every element the argument can match and leave the `:has()` unsatisfiable.
1935
- */
1936
- if (compounds.some(function (compound) {
1937
- return compoundNamesHost(compound.nodes);
1938
- })) {
1939
- plan.softRefusals.push('A `:has()` argument that names a top layer host or a non-rendered tag directly targets that element deliberately. A guard would either exclude exactly what it selects or protect nothing, so it is left alone.');
1940
- continue;
1941
- }
1942
-
1943
- /**
1944
- * Every compound of the argument is planned exactly as a top-level compound is, by the
1945
- * same code. `:has(> div > span)` therefore guards the host-capable `div` and skips
1946
- * the `span`, as `& > div > span` does; a guard on the `span` alone would be inert,
1947
- * because no host is a span, and the argument would still match popup content through
1948
- * the unguarded `div`.
1949
- *
1950
- * The argument's leftmost compound carries no combinator of its own, but it is a
1951
- * descendant of the subject: `:has(button)` is "a button anywhere inside", so it is
1952
- * planned in descendant position and takes the wide list. A leading combinator is kept
1953
- * as written, so `:has(> div)` is a child and takes the narrow list.
1954
- */
1955
- var _iterator16 = _createForOfIteratorHelper(compounds),
1956
- _step16;
1957
- try {
1958
- for (_iterator16.s(); !(_step16 = _iterator16.n()).done;) {
1959
- var compound = _step16.value;
1960
- var position = compound.position === 'first' ? 'descendant' : compound.position;
1961
- planCompound(_objectSpread(_objectSpread({}, compound), {}, {
1962
- position: position
1963
- }), plan, {
1964
- reachedPreFlag: false,
1965
- behindBareDivAncestor: false
1966
- });
1967
- }
1968
- } catch (err) {
1969
- _iterator16.e(err);
1970
- } finally {
1971
- _iterator16.f();
1972
- }
1973
- }
1974
- } catch (err) {
1975
- _iterator15.e(err);
1976
- } finally {
1977
- _iterator15.f();
1978
- }
1979
- });
1980
- }
1981
-
1982
- /**
1983
- * Refuse every positional pseudo-class on this compound. Returns true if one was found.
1984
- *
1985
- * Each of these has a verified guard form in the decision doc's table, and every one of those
1986
- * forms needs an `of S` clause, which is **withdrawn**: Compiled's extract mode drops the rule
1987
- * outright, so the guard would delete styling rather than protect it — see
1988
- * {@link WITHDRAWN_POSITIONAL_FORMS}. The refusal reason names the form that was withheld, so
1989
- * it can be restored from the report once Compiled is fixed.
1990
- *
1991
- * A positional pseudo nested inside `:is()`, `:where()` or `:not()` has no form even in the
1992
- * table: sibling counting there is relative to a different subject. Inside `:has()` the
1993
- * argument's compounds are handed back to this function by `planHasArguments`, so that case is
1994
- * refused with the same reason as a top-level compound.
1995
- */
1996
- function planPositionals(compound, plan) {
1997
- var found = false;
1998
- var _iterator17 = _createForOfIteratorHelper(compound.nodes),
1999
- _step17;
2000
- try {
2001
- var _loop2 = function _loop2() {
2002
- var node = _step17.value;
2003
- if (node.type !== 'pseudo') {
2004
- return 0; // continue
2005
- }
2006
- var name = pseudoName(node);
2007
- if (POSITIONAL_PSEUDOS.has(name)) {
2008
- plan.hardRefusals.push(ofClauseWithheldReason(node));
2009
- found = true;
2010
- return 0; // continue
2011
- }
2012
- if (name === ':not') {
2013
- var sole = solePseudoInside(node);
2014
- var soleName = sole ? pseudoName(sole) : null;
2015
- if (soleName === ':first-child' || soleName === ':last-child') {
2016
- plan.hardRefusals.push(ofClauseWithheldReason(node));
2017
- found = true;
2018
- return 0; // continue
2019
- }
2020
- if (sole && soleName !== null && POSITIONAL_PSEUDOS.has(soleName)) {
2021
- plan.hardRefusals.push("`:not(".concat(sole.value, "\u2026)` has no guard form. Only `:not(:first-child)` and `:not(:last-child)` can be expressed as a single specificity-neutral term, and even those are withdrawn while Compiled's extract mode drops any selector carrying an `of` clause. Close the site by giving the elements you mean a class or a `data-` attribute and selecting them directly."));
2022
- found = true;
2023
- return 0; // continue
2024
- }
2025
- /* Any other `:not()` falls through to the nested check below. */
2026
- }
2027
- if (name === ':has') {
2028
- return 0; // continue
2029
- }
2030
- node.walkPseudos(function (inner) {
2031
- if (!POSITIONAL_PSEUDOS.has(pseudoName(inner)) || hasAncestorPseudo(inner, ':has')) {
2032
- return;
2033
- }
2034
- plan.hardRefusals.push("The positional pseudo '".concat(inner.value, "' is nested inside '").concat(node.value, "()', where sibling counting is relative to a different subject. The decision doc's `of S` forms do not apply, so this needs triage."));
2035
- found = true;
2036
- });
2037
- },
2038
- _ret2;
2039
- for (_iterator17.s(); !(_step17 = _iterator17.n()).done;) {
2040
- _ret2 = _loop2();
2041
- if (_ret2 === 0) continue;
2042
- }
2043
- } catch (err) {
2044
- _iterator17.e(err);
2045
- } finally {
2046
- _iterator17.f();
2047
- }
2048
- return found;
2049
- }
2050
-
2051
- /* -------------------------------------------------------------------------------------- */
2052
- /* Emission */
2053
- /* -------------------------------------------------------------------------------------- */
2054
-
2055
- function emitSelector(branch, plan) {
2056
- var parts = [];
2057
- var _iterator18 = _createForOfIteratorHelper(branch.nodes),
2058
- _step18;
2059
- try {
2060
- for (_iterator18.s(); !(_step18 = _iterator18.n()).done;) {
2061
- var node = _step18.value;
2062
- if (node.type === 'combinator') {
2063
- var value = node.value.trim();
2064
- parts.push(value === '' ? ' ' : " ".concat(value, " "));
2065
- continue;
2066
- }
2067
- var before = plan.prependBefore.get(node);
2068
- if (before) {
2069
- parts.push(before);
2070
- }
2071
- parts.push(emitNode(node, plan));
2072
- var after = plan.appendAfter.get(node);
2073
- if (after) {
2074
- parts.push(after);
2075
- }
2076
- }
2077
- } catch (err) {
2078
- _iterator18.e(err);
2079
- } finally {
2080
- _iterator18.f();
2081
- }
2082
- return parts.join('').trim();
2083
- }
2084
- function emitNode(node, plan) {
2085
- var replacement = plan.replace.get(node);
2086
- if (replacement !== undefined) {
2087
- return replacement;
2088
- }
2089
-
2090
- /**
2091
- * Only re-emit a functional pseudo from its parsed parts when something inside it changed.
2092
- * Anything untouched is passed through verbatim, which keeps micro-syntaxes such as
2093
- * `:nth-child(2n+1)` byte-exact.
2094
- */
2095
- if (node.type === 'pseudo' && node.nodes.length > 0 && subtreeTouched(node, plan)) {
2096
- var inner = node.nodes.map(function (argument) {
2097
- return emitSelector(argument, plan);
2098
- }).join(', ');
2099
- return "".concat(node.value, "(").concat(inner, ")");
2100
- }
2101
- return node.toString().trim();
2102
- }
2103
- function subtreeTouched(node, plan) {
2104
- var found = false;
2105
- if (node.type !== 'pseudo') {
2106
- return false;
2107
- }
2108
- node.walk(function (inner) {
2109
- if (plan.touched.has(inner)) {
2110
- found = true;
2111
- }
2112
- });
2113
- return found;
2114
- }
2115
-
2116
- /* -------------------------------------------------------------------------------------- */
2117
- /* Guard recognition */
2118
- /* -------------------------------------------------------------------------------------- */
2119
-
2120
- /**
2121
- * Already carries a guard that covers this compound: a `:not(:where(…))` whose term list is a
2122
- * superset of the terms the compound's position needs, in any order and with any extra terms
2123
- * the author added. Byte-exact matching is not enough here, because the merge in
2124
- * {@link planPreExistingGuards} preserves author terms, and a guard the transform itself wrote
2125
- * must be recognised as complete on the next pass.
2126
- */
2127
- function isCompoundGuarded(nodes, form) {
2128
- var required = form === 'wide' ? WIDE_TERM_KEYS : NARROW_TERM_KEYS;
2129
- return nodes.some(function (node) {
2130
- var terms = guardTermKeysOf(node);
2131
- if (terms === null) {
2132
- return false;
2133
- }
2134
- var _iterator19 = _createForOfIteratorHelper(required),
2135
- _step19;
2136
- try {
2137
- for (_iterator19.s(); !(_step19 = _iterator19.n()).done;) {
2138
- var key = _step19.value;
2139
- if (!terms.has(key)) {
2140
- return false;
2141
- }
2142
- }
2143
- } catch (err) {
2144
- _iterator19.e(err);
2145
- } finally {
2146
- _iterator19.f();
2147
- }
2148
- return true;
2149
- });
2150
- }
2151
-
2152
- /**
2153
- * The normalised term keys of a `:not(:where(<simple terms>))` that mentions at least one term
2154
- * of `L`, or `null` when the node is not such a guard.
2155
- */
2156
- function guardTermKeysOf(node) {
2157
- if (node.type !== 'pseudo' || pseudoName(node) !== ':not') {
2158
- return null;
2159
- }
2160
- var where = soleWhereInside(node);
2161
- if (!where) {
2162
- return null;
2163
- }
2164
- var terms = where.nodes;
2165
- if (!terms.every(isSimpleTerm) || !terms.some(termIsGuardTerm)) {
2166
- return null;
2167
- }
2168
- return new Set(terms.map(function (term) {
2169
- return normalise(term.toString());
2170
- }));
2171
- }
2172
-
2173
- /**
2174
- * Does this pseudo mention any term of `L` anywhere inside it?
2175
- */
2176
- function mentionsGuardTerm(pseudo) {
2177
- var found = false;
2178
- pseudo.walk(function (node) {
2179
- if (isGuardTermNode(node)) {
2180
- found = true;
2181
- }
2182
- });
2183
- return found;
2184
- }
2185
-
2186
- /**
2187
- * Is this one term of an exclusion list a term of `L` or `S`, such as `dialog` or `style`?
2188
- */
2189
- function termIsGuardTerm(term) {
2190
- return term.nodes.some(isGuardTermNode);
2191
- }
2192
-
2193
- /**
2194
- * Does this node name a top layer host, or an element `L` lists, outright?
2195
- */
2196
- function isGuardTermNode(node) {
2197
- if (node.type === 'attribute') {
2198
- return node.attribute.toLowerCase() === 'popover';
2199
- }
2200
- if (node.type === 'tag') {
2201
- return GUARD_TERM_TAGS.has(node.value.toLowerCase());
2202
- }
2203
- if (node.type === 'pseudo') {
2204
- return HOST_PSEUDOS.has(pseudoName(node));
2205
- }
2206
- return false;
2207
- }
2208
-
2209
- /**
2210
- * The single `:where()` inside `:not(…)` when that is all it contains, otherwise `null`.
2211
- */
2212
- function soleWhereInside(pseudo) {
2213
- var only = solePseudoInside(pseudo);
2214
- return only && pseudoName(only) === ':where' ? only : null;
2215
- }
2216
-
2217
- /**
2218
- * The single `:not()` inside `:not(…)` when that is all it contains, otherwise `null`.
2219
- */
2220
- function soleNotInside(pseudo) {
2221
- var only = solePseudoInside(pseudo);
2222
- return only && pseudoName(only) === ':not' ? only : null;
2223
- }
2224
-
2225
- /**
2226
- * The single pseudo inside `:not(…)` when that is all it contains, otherwise `null`.
2227
- */
2228
- function solePseudoInside(pseudo) {
2229
- if (pseudo.nodes.length !== 1) {
2230
- return null;
2231
- }
2232
- var inner = nonEmptyNodes(pseudo.nodes[0]);
2233
- if (inner.length !== 1) {
2234
- return null;
2235
- }
2236
- var only = inner[0];
2237
- return only.type === 'pseudo' ? only : null;
2238
- }
2239
-
2240
- /* -------------------------------------------------------------------------------------- */
2241
- /* Specificity */
2242
- /* -------------------------------------------------------------------------------------- */
2243
-
2244
- /**
2245
- * Compute (a,b,c) for one selector.
2246
- *
2247
- * - an id is (1,0,0); a class, attribute or pseudo-class is (0,1,0); a type or pseudo-element
2248
- * is (0,0,1); the universal selector is (0,0,0);
2249
- * - `:where()` is always (0,0,0), whatever it contains;
2250
- * - `:not()`, `:is()` and `:has()` take the specificity of their most specific argument and
2251
- * add nothing of their own;
2252
- * - `:nth-child()` / `:nth-last-child()` count as one pseudo-class *plus* the specificity of
2253
- * the most specific selector in an `of S` argument. With `S` weightless that is (0,1,0),
2254
- * which is what makes the positional rewrites neutral;
2255
- * - the nesting selector `&` is treated as (0,0,0). It is never modified by this transform,
2256
- * so whatever its real value is, it is the same before and after.
2257
- */
2258
- function specificityOfSelector(branch) {
2259
- var a = 0;
2260
- var b = 0;
2261
- var c = 0;
2262
- var _iterator20 = _createForOfIteratorHelper(branch.nodes),
2263
- _step20;
2264
- try {
2265
- for (_iterator20.s(); !(_step20 = _iterator20.n()).done;) {
2266
- var node = _step20.value;
2267
- var _specificityOfNode = specificityOfNode(node),
2268
- _specificityOfNode2 = _slicedToArray(_specificityOfNode, 3),
2269
- na = _specificityOfNode2[0],
2270
- nb = _specificityOfNode2[1],
2271
- nc = _specificityOfNode2[2];
2272
- a += na;
2273
- b += nb;
2274
- c += nc;
2275
- }
2276
- } catch (err) {
2277
- _iterator20.e(err);
2278
- } finally {
2279
- _iterator20.f();
2280
- }
2281
- return [a, b, c];
2282
- }
2283
- function specificityOfNode(node) {
2284
- switch (node.type) {
2285
- case 'id':
2286
- return [1, 0, 0];
2287
- case 'class':
2288
- case 'attribute':
2289
- return [0, 1, 0];
2290
- case 'tag':
2291
- return [0, 0, 1];
2292
- case 'pseudo':
2293
- return specificityOfPseudo(node);
2294
- default:
2295
- return [0, 0, 0];
2296
- }
2297
- }
2298
- function specificityOfPseudo(pseudo) {
2299
- if (isPseudoElement(pseudo)) {
2300
- return [0, 0, 1];
2301
- }
2302
- switch (pseudoName(pseudo)) {
2303
- case ':where':
2304
- return [0, 0, 0];
2305
- case ':not':
2306
- case ':is':
2307
- case ':has':
2308
- case ':matches':
2309
- case ':-moz-any':
2310
- case ':-webkit-any':
2311
- return maxSpecificity(pseudo.nodes.map(specificityOfSelector));
2312
- case ':nth-child':
2313
- case ':nth-last-child':
2314
- {
2315
- var inner = nthArgumentText(pseudo);
2316
- var ofIndex = findOfKeyword(inner);
2317
- if (ofIndex === -1) {
2318
- return [0, 1, 0];
2319
- }
2320
- var argument = [0, 0, 0];
2321
- try {
2322
- argument = maxSpecificity(parse(inner.slice(ofIndex + 2)).map(specificityOfSelector));
2323
- } catch (_unused4) {
2324
- argument = [0, 0, 0];
2325
- }
2326
- return [argument[0], argument[1] + 1, argument[2]];
2327
- }
2328
- default:
2329
- return [0, 1, 0];
2330
- }
2331
- }
2332
- function maxSpecificity(list) {
2333
- var best = [0, 0, 0];
2334
- var _iterator21 = _createForOfIteratorHelper(list),
2335
- _step21;
2336
- try {
2337
- for (_iterator21.s(); !(_step21 = _iterator21.n()).done;) {
2338
- var candidate = _step21.value;
2339
- if (compareSpecificity(candidate, best) > 0) {
2340
- best = candidate;
2341
- }
2342
- }
2343
- } catch (err) {
2344
- _iterator21.e(err);
2345
- } finally {
2346
- _iterator21.f();
2347
- }
2348
- return best;
2349
- }
2350
- function compareSpecificity(left, right) {
2351
- for (var index = 0; index < 3; index++) {
2352
- if (left[index] !== right[index]) {
2353
- return left[index] - right[index];
2354
- }
2355
- }
2356
- return 0;
2357
- }
2358
- function sameSpecificity(left, right) {
2359
- return compareSpecificity(left, right) === 0;
2360
- }
2361
-
2362
- /* -------------------------------------------------------------------------------------- */
2363
- /* Small AST helpers */
2364
- /* -------------------------------------------------------------------------------------- */
2365
-
2366
- /**
2367
- * The raw text between the parentheses of a functional pseudo.
2368
- */
2369
- function nthArgumentText(pseudo) {
2370
- var text = pseudo.toString().trim();
2371
- var open = text.indexOf('(');
2372
- if (open === -1 || !text.endsWith(')')) {
2373
- return '';
2374
- }
2375
- return text.slice(open + 1, -1);
2376
- }
2377
-
2378
- /**
2379
- * Index of the `of` keyword in an `An+B [of S]` argument, or -1. The `An+B` part can only
2380
- * contain digits, `n`, `+`, `-` and whitespace, so the first `of` word is the separator. The
2381
- * selector list may follow it with no whitespace at all, as in `2 of:not(…)`, so only the
2382
- * boundary after the word is required, not a space.
2383
- */
2384
- function findOfKeyword(inner) {
2385
- var match = /(^|\s)of\b/i.exec(inner);
2386
- if (!match) {
2387
- return -1;
2388
- }
2389
- return match.index + match[1].length;
2390
- }
2391
- function hasAncestorPseudo(node, value) {
2392
- var current = node.parent;
2393
- while (current) {
2394
- if (current.type === 'pseudo' && pseudoName(current) === value) {
2395
- return true;
2396
- }
2397
- current = current.parent;
2398
- }
2399
- return false;
2400
- }
2401
- function hasNestedHas(branch) {
2402
- var found = false;
2403
- branch.walkPseudos(function (pseudo) {
2404
- if (pseudoName(pseudo) === ':has' && hasAncestorPseudo(pseudo, ':has')) {
2405
- found = true;
2406
- }
2407
- });
2408
- return found;
2409
- }