chrome-devtools-mcp 1.9.0 → 1.10.1

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 (64) hide show
  1. package/build/src/BrowserManager.js +401 -0
  2. package/build/src/McpContext.js +5 -5
  3. package/build/src/McpPage.js +107 -3
  4. package/build/src/McpResponse.js +68 -3
  5. package/build/src/ToolHandler.js +172 -118
  6. package/build/src/bin/chrome-devtools-mcp-main.js +11 -6
  7. package/build/src/bin/chrome-devtools.js +6 -12
  8. package/build/src/collectors/PageCollector.js +66 -3
  9. package/build/src/config/browser-options.js +2 -0
  10. package/build/src/config/category-options.js +13 -4
  11. package/build/src/config/cli-commands.js +26 -0
  12. package/build/src/config/cli-options.js +32 -0
  13. package/build/src/config/mcp-options.js +40 -1
  14. package/build/src/devtools/DevToolsCommentBridge.js +91 -0
  15. package/build/src/formatters/CommentFormatter.js +82 -0
  16. package/build/src/formatters/CssFormatter.js +812 -0
  17. package/build/src/index.js +53 -72
  18. package/build/src/processors/ChunkedTraceParser.js +361 -0
  19. package/build/src/processors/PerformanceTrace.js +60 -13
  20. package/build/src/telemetry/ClearcutLogger.js +91 -34
  21. package/build/src/telemetry/metricsRegistry.js +3 -0
  22. package/build/src/telemetry/persistence.js +17 -7
  23. package/build/src/telemetry/transformation.js +53 -4
  24. package/build/src/telemetry/types.js +1 -0
  25. package/build/src/third_party/THIRD_PARTY_NOTICES +715 -131
  26. package/build/src/third_party/bundled-packages.json +6 -3
  27. package/build/src/third_party/devtools-formatter-worker.js +136 -5
  28. package/build/src/third_party/devtools-heap-snapshot-worker.js +567 -6
  29. package/build/src/third_party/index.js +54948 -35497
  30. package/build/src/third_party/issue-descriptions/webInstallManifestMissingId.md +3 -0
  31. package/build/src/third_party/issue-descriptions/webInstallManifestMissingNameOrShortName.md +3 -0
  32. package/build/src/third_party/issue-descriptions/webInstallManifestParsingOrNetworkError.md +3 -0
  33. package/build/src/third_party/issue-descriptions/webInstallNoManifest.md +3 -0
  34. package/build/src/third_party/issue-descriptions/webInstallStartUrlInvalid.md +3 -0
  35. package/build/src/tools/ToolDefinition.js +13 -21
  36. package/build/src/tools/comments.js +169 -0
  37. package/build/src/tools/console.js +3 -3
  38. package/build/src/tools/css.js +45 -0
  39. package/build/src/tools/emulation.js +5 -5
  40. package/build/src/tools/extensions.js +10 -10
  41. package/build/src/tools/input.js +159 -87
  42. package/build/src/tools/lighthouse.js +18 -7
  43. package/build/src/tools/memory.js +26 -26
  44. package/build/src/tools/network.js +4 -4
  45. package/build/src/tools/pages.js +14 -14
  46. package/build/src/tools/performance.js +6 -6
  47. package/build/src/tools/pwa.js +8 -8
  48. package/build/src/tools/screencast.js +4 -4
  49. package/build/src/tools/screenshot.js +2 -2
  50. package/build/src/tools/script.js +7 -7
  51. package/build/src/tools/slim/tools.js +5 -5
  52. package/build/src/tools/snapshot.js +4 -4
  53. package/build/src/tools/thirdPartyDeveloper.js +4 -4
  54. package/build/src/tools/tools.js +6 -9
  55. package/build/src/tools/webmcp.js +4 -4
  56. package/build/src/types.js +4 -1
  57. package/build/src/utils/WaitForHelper.js +14 -8
  58. package/build/src/utils/logger.js +7 -6
  59. package/build/src/version.js +1 -1
  60. package/package.json +8 -5
  61. package/skills/chrome-devtools/SKILL.md +2 -1
  62. package/skills/chrome-devtools-cli/SKILL.md +2 -0
  63. package/build/src/browser.js +0 -233
  64. package/build/src/third_party/issue-descriptions/cookieExcludeBlockedWithinRelatedWebsiteSet.md +0 -4
@@ -0,0 +1,812 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { DevTools } from '../third_party/index.js';
7
+ const PROPERTY_STATE_MAP = {
8
+ ["Active" /* DevTools.CSSMatchedStyles.PropertyState.ACTIVE */]: 'active',
9
+ ["Overloaded" /* DevTools.CSSMatchedStyles.PropertyState.OVERLOADED */]: 'overloaded',
10
+ };
11
+ class IndentedWriter {
12
+ #lines = [];
13
+ #indent = 0;
14
+ constructor(baseIndent = 0) {
15
+ this.#indent = baseIndent;
16
+ }
17
+ indent() {
18
+ this.#indent += 2;
19
+ }
20
+ dedent() {
21
+ this.#indent = Math.max(0, this.#indent - 2);
22
+ }
23
+ writeLine(text) {
24
+ this.#lines.push(' '.repeat(this.#indent) + text);
25
+ }
26
+ writeEmptyLine() {
27
+ this.#lines.push('');
28
+ }
29
+ writeComment(comment) {
30
+ this.writeLine(`/* ${comment} */`);
31
+ }
32
+ lines() {
33
+ return this.#lines;
34
+ }
35
+ }
36
+ function getFilenameFromUrl(sheetUrl) {
37
+ const parsed = new DevTools.Common.ParsedURL.ParsedURL(sheetUrl);
38
+ if (parsed.isDataURL()) {
39
+ return 'data-uri';
40
+ }
41
+ if (parsed.isBlobURL()) {
42
+ return 'blob';
43
+ }
44
+ if (parsed.lastPathComponent) {
45
+ return parsed.lastPathComponent;
46
+ }
47
+ return 'index';
48
+ }
49
+ /**
50
+ * Resolves the human-readable source location
51
+ *
52
+ * Checks in precedence order:
53
+ * 1. Special origins: 'user agent stylesheet', 'injected stylesheet', 'via inspector', 'constructed stylesheet'.
54
+ * 2. 1-based line coordinates from rule header or style range.
55
+ * 3. File source: `<style>` for inline sheets, `(index)` for root documents, or filename for external stylesheets.
56
+ */
57
+ function getSourceLocation(rule) {
58
+ if (rule.isUserAgent?.()) {
59
+ return 'user agent stylesheet';
60
+ }
61
+ if (rule.isInjected?.()) {
62
+ return 'injected stylesheet';
63
+ }
64
+ if (rule.isViaInspector?.()) {
65
+ return 'via inspector';
66
+ }
67
+ if (rule.header?.isConstructedByNew?.() && !rule.sourceURL) {
68
+ return 'constructed stylesheet';
69
+ }
70
+ let locSuffix = '';
71
+ if (rule instanceof DevTools.CSSRule.CSSStyleRule) {
72
+ const lineNum = rule.lineNumberInSource(0);
73
+ if (lineNum >= 0) {
74
+ locSuffix = `:${lineNum + 1}`;
75
+ }
76
+ }
77
+ else if (rule.header && rule.style?.range) {
78
+ locSuffix = `:${rule.header.lineNumberInSource(rule.style.range.startLine) + 1}`;
79
+ }
80
+ const sheetUrl = rule.sourceURL;
81
+ if (!sheetUrl) {
82
+ return `<style>${locSuffix}`;
83
+ }
84
+ return `${getFilenameFromUrl(sheetUrl)}${locSuffix}`;
85
+ }
86
+ /**
87
+ * Returns the subset of selectors in a comma-separated selector group that
88
+ * actually matched the target element. Returns undefined if single selector
89
+ * or no filter is available.
90
+ */
91
+ function getMatchingSelectors(matchedStyles, rule) {
92
+ if (!rule.selectors || rule.selectors.length <= 1) {
93
+ return undefined;
94
+ }
95
+ const indexes = matchedStyles.getMatchingSelectors?.(rule);
96
+ if (!indexes || indexes.length === 0) {
97
+ return undefined;
98
+ }
99
+ const indexSet = new Set(indexes);
100
+ const matching = [];
101
+ for (const [idx, sel] of rule.selectors.entries()) {
102
+ if (indexSet.has(idx)) {
103
+ matching.push(sel.text);
104
+ }
105
+ }
106
+ return matching.length > 0 ? matching : undefined;
107
+ }
108
+ function createLayerAncestor(layer) {
109
+ if (!layer) {
110
+ return undefined;
111
+ }
112
+ return { type: 'layer', ...(layer.text ? { name: layer.text } : {}) };
113
+ }
114
+ function createQueryAncestor(type, query) {
115
+ if (!query) {
116
+ return undefined;
117
+ }
118
+ if (type === 'scope') {
119
+ return { type, ...(query.text ? { query: query.text } : {}) };
120
+ }
121
+ return query.text ? { type, query: query.text } : undefined;
122
+ }
123
+ function createContainerQueryAncestor(containerQuery, containerDetails) {
124
+ if (!containerQuery) {
125
+ return undefined;
126
+ }
127
+ const details = containerDetails?.get(containerQuery);
128
+ return {
129
+ type: 'container',
130
+ query: containerQuery.text ?? '',
131
+ ...(containerQuery.name ? { name: containerQuery.name } : {}),
132
+ ...(details?.container ? { container: details.container } : {}),
133
+ };
134
+ }
135
+ /**
136
+ * Collects enclosing ancestor rules (@media, @container, @supports, @layer,
137
+ * @scope, @starting-style, @navigation, and CSS nesting) for a style rule.
138
+ */
139
+ function collectAncestorRules(rule, containerDetails) {
140
+ if (!rule.ruleTypes || rule.ruleTypes.length === 0) {
141
+ return undefined;
142
+ }
143
+ let mediaIndex = 0;
144
+ let containerIndex = 0;
145
+ let scopeIndex = 0;
146
+ let supportsIndex = 0;
147
+ let nestingIndex = 0;
148
+ let layerIndex = 0;
149
+ let navigationsIndex = 0;
150
+ const ancestors = [];
151
+ for (const ruleType of rule.ruleTypes) {
152
+ let item;
153
+ switch (ruleType) {
154
+ case "MediaRule" /* DevTools.Protocol.CSS.CSSRuleType.MediaRule */:
155
+ item = createQueryAncestor('media', rule.media?.[mediaIndex++]);
156
+ break;
157
+ case "ContainerRule" /* DevTools.Protocol.CSS.CSSRuleType.ContainerRule */:
158
+ item = createContainerQueryAncestor(rule.containerQueries?.[containerIndex++], containerDetails);
159
+ break;
160
+ case "LayerRule" /* DevTools.Protocol.CSS.CSSRuleType.LayerRule */:
161
+ item = createLayerAncestor(rule.layers?.[layerIndex++]);
162
+ break;
163
+ case "ScopeRule" /* DevTools.Protocol.CSS.CSSRuleType.ScopeRule */:
164
+ item = createQueryAncestor('scope', rule.scopes?.[scopeIndex++]);
165
+ break;
166
+ case "SupportsRule" /* DevTools.Protocol.CSS.CSSRuleType.SupportsRule */:
167
+ item = createQueryAncestor('supports', rule.supports?.[supportsIndex++]);
168
+ break;
169
+ case "StartingStyleRule" /* DevTools.Protocol.CSS.CSSRuleType.StartingStyleRule */:
170
+ item = { type: 'starting-style' };
171
+ break;
172
+ case "StyleRule" /* DevTools.Protocol.CSS.CSSRuleType.StyleRule */: {
173
+ const selector = rule.nestingSelectors?.[nestingIndex++];
174
+ if (selector) {
175
+ item = { type: 'nesting', selector };
176
+ }
177
+ break;
178
+ }
179
+ case "NavigationRule" /* DevTools.Protocol.CSS.CSSRuleType.NavigationRule */:
180
+ item = createQueryAncestor('navigation', rule.navigations?.[navigationsIndex++]);
181
+ break;
182
+ }
183
+ if (item) {
184
+ ancestors.push(item);
185
+ }
186
+ }
187
+ ancestors.reverse();
188
+ return ancestors.length > 0 ? ancestors : undefined;
189
+ }
190
+ /**
191
+ * Extracts common metadata (`ancestors`, `matchingSelectors`, `source`)
192
+ * uniformly across matched rules, inherited rules, and pseudo-element rules.
193
+ */
194
+ function getCSSStyleRuleMetadata(rule, matchedStyles, containerDetails) {
195
+ if (!rule) {
196
+ return {};
197
+ }
198
+ const matchingSelectors = getMatchingSelectors(matchedStyles, rule);
199
+ const ancestors = collectAncestorRules(rule, containerDetails);
200
+ const source = getSourceLocation(rule);
201
+ return {
202
+ ...(ancestors ? { ancestors } : {}),
203
+ ...(matchingSelectors ? { matchingSelectors } : {}),
204
+ ...(source ? { source } : {}),
205
+ };
206
+ }
207
+ /**
208
+ * Formats a CSS property into standard CSS syntax with optional status tags.
209
+ *
210
+ * Status prefix convention:
211
+ * - 'active': Clean output without tags (e.g. `color: red;`).
212
+ * - 'overloaded' | 'invalid' | 'disabled': Tagged prefix (e.g. `[overloaded] color: blue;`).
213
+ */
214
+ function formatPropertyLine(prop) {
215
+ const stateStr = prop.status === 'active' ? '' : `[${prop.status}] `;
216
+ const imp = prop.important && !/\s*!\s*important$/i.test(prop.value)
217
+ ? ' !important'
218
+ : '';
219
+ return `${stateStr}${prop.name}: ${prop.value}${imp};`;
220
+ }
221
+ /**
222
+ * Filters properties to only those that can be inherited from an ancestor element.
223
+ *
224
+ * For highlight pseudo-elements, custom properties (`--*`) are not inherited.
225
+ * For other CSS custom properties, check registered @property inheritance
226
+ * rules if available.
227
+ * For all remaining properties, use standard CSSMetadata inheritance check.
228
+ */
229
+ function getInheritableProperties(properties, matchedStyles, isHighlight = false) {
230
+ return properties.filter(prop => {
231
+ if (isHighlight) {
232
+ return !DevTools.CSSMetadata.cssMetadata().isCustomProperty(prop.name);
233
+ }
234
+ if (DevTools.CSSMetadata.cssMetadata().isCustomProperty(prop.name)) {
235
+ const registered = matchedStyles.getRegisteredProperty?.(prop.name);
236
+ if (registered) {
237
+ return registered.inherits();
238
+ }
239
+ }
240
+ return DevTools.CSSMetadata.cssMetadata().isPropertyInherited(prop.name);
241
+ });
242
+ }
243
+ /**
244
+ * Resolves DOM ancestor node details when a style declaration is inherited.
245
+ */
246
+ function getParentNodeInfo(style, matchedStyles, resolveUid) {
247
+ if (!matchedStyles.isInherited?.(style)) {
248
+ return undefined;
249
+ }
250
+ const parentNode = matchedStyles.nodeForStyle?.(style);
251
+ if (!parentNode) {
252
+ return undefined;
253
+ }
254
+ const parentUid = resolveUid?.(parentNode.backendNodeId());
255
+ return {
256
+ ...(parentUid ? { uid: parentUid } : {}),
257
+ selector: parentNode.simpleSelector(),
258
+ };
259
+ }
260
+ function getCascadeRuleHeader(rule) {
261
+ let selector;
262
+ switch (rule.type) {
263
+ case 'inline':
264
+ case 'transition':
265
+ case 'animation':
266
+ case 'attributes':
267
+ case 'matched':
268
+ case 'keyframes':
269
+ case 'at-rule':
270
+ case 'property':
271
+ case 'function':
272
+ selector = rule.selector;
273
+ break;
274
+ case 'inherited':
275
+ selector = rule.selector ?? 'element.style';
276
+ break;
277
+ case 'pseudo':
278
+ selector = rule.selector ?? rule.pseudoType;
279
+ break;
280
+ case 'position-try': {
281
+ const statePrefix = rule.active ? '' : '[inactive] ';
282
+ selector = `${statePrefix}${rule.selector}`;
283
+ break;
284
+ }
285
+ }
286
+ const source = 'source' in rule ? rule.source : undefined;
287
+ return source ? `${selector} (${source})` : selector;
288
+ }
289
+ function formatAncestorRuleHeader(ancestor) {
290
+ switch (ancestor.type) {
291
+ case 'layer':
292
+ return { header: ancestor.name ? `@layer ${ancestor.name}` : '@layer' };
293
+ case 'media':
294
+ return { header: `@media ${ancestor.query}` };
295
+ case 'container': {
296
+ let comment;
297
+ if (ancestor.container?.selector) {
298
+ comment = ancestor.container.selector;
299
+ }
300
+ if (ancestor.container?.uid) {
301
+ const uidStr = `(uid: "${ancestor.container.uid}")`;
302
+ comment = comment ? `${comment} ${uidStr}` : uidStr;
303
+ }
304
+ if (comment) {
305
+ comment = `container: ${comment}`;
306
+ }
307
+ const shouldPrependName = ancestor.name && !ancestor.query.startsWith(ancestor.name);
308
+ const nameStr = shouldPrependName ? `${ancestor.name} ` : '';
309
+ return { comment, header: `@container ${nameStr}${ancestor.query}` };
310
+ }
311
+ case 'scope': {
312
+ const queryStr = ancestor.query?.trim();
313
+ return { header: queryStr ? `@scope ${queryStr}` : '@scope' };
314
+ }
315
+ case 'supports':
316
+ return { header: `@supports ${ancestor.query}` };
317
+ case 'starting-style':
318
+ return { header: '@starting-style' };
319
+ case 'nesting':
320
+ return { header: ancestor.selector };
321
+ case 'navigation':
322
+ return { header: `@navigation ${ancestor.query}` };
323
+ case 'at-rule': {
324
+ const nameStr = ancestor.name ? ` ${ancestor.name}` : '';
325
+ return { header: `@${ancestor.atRuleType}${nameStr}` };
326
+ }
327
+ }
328
+ }
329
+ function appendRuleWithAncestors(writer, rule) {
330
+ const ancestors = 'ancestors' in rule ? rule.ancestors : undefined;
331
+ let ancestorCount = 0;
332
+ if (ancestors && ancestors.length > 0) {
333
+ for (const ancestor of ancestors) {
334
+ const { comment, header } = formatAncestorRuleHeader(ancestor);
335
+ if (comment) {
336
+ writer.writeComment(comment);
337
+ }
338
+ writer.writeLine(`${header} {`);
339
+ writer.indent();
340
+ ancestorCount++;
341
+ }
342
+ }
343
+ const header = getCascadeRuleHeader(rule);
344
+ writer.writeLine(`${header} {`);
345
+ writer.indent();
346
+ for (const prop of rule.properties) {
347
+ writer.writeLine(formatPropertyLine(prop));
348
+ }
349
+ writer.dedent();
350
+ writer.writeLine('}');
351
+ for (let i = 0; i < ancestorCount; i++) {
352
+ writer.dedent();
353
+ writer.writeLine('}');
354
+ }
355
+ }
356
+ function appendKeyframesRule(writer, rule) {
357
+ const header = getCascadeRuleHeader(rule);
358
+ writer.writeLine(`${header} {`);
359
+ writer.indent();
360
+ for (const step of rule.keyframes) {
361
+ writer.writeLine(`${step.keyText} {`);
362
+ writer.indent();
363
+ for (const prop of step.properties) {
364
+ writer.writeLine(formatPropertyLine(prop));
365
+ }
366
+ writer.dedent();
367
+ writer.writeLine('}');
368
+ }
369
+ writer.dedent();
370
+ writer.writeLine('}');
371
+ }
372
+ function appendCssSectionsToString(writer, styles) {
373
+ for (const rule of styles.rules) {
374
+ writer.writeEmptyLine();
375
+ if (rule.type === 'inherited') {
376
+ const uidStr = rule.node.uid ? ` (uid: "${rule.node.uid}")` : '';
377
+ writer.writeLine(`Inherited from ${rule.node.selector}${uidStr}:`);
378
+ writer.indent();
379
+ appendRuleWithAncestors(writer, rule);
380
+ writer.dedent();
381
+ }
382
+ else if (rule.type === 'pseudo') {
383
+ let inheritedStr = '';
384
+ if (rule.node) {
385
+ const uidPart = rule.node.uid ? `, uid: "${rule.node.uid}"` : '';
386
+ inheritedStr = ` (inherited from ${rule.node.selector}${uidPart})`;
387
+ }
388
+ writer.writeComment(`Pseudo ${rule.pseudoType} element${inheritedStr}`);
389
+ appendRuleWithAncestors(writer, rule);
390
+ }
391
+ else if (rule.type === 'keyframes') {
392
+ appendKeyframesRule(writer, rule);
393
+ }
394
+ else {
395
+ appendRuleWithAncestors(writer, rule);
396
+ }
397
+ }
398
+ }
399
+ export class CssFormatter {
400
+ static #getStyleProperties(style) {
401
+ return style.leadingProperties?.() ?? style.allProperties();
402
+ }
403
+ /**
404
+ * Aggregates all cascading rules impacting the target node.
405
+ */
406
+ static collectRules(matchedStyles, options) {
407
+ const rules = [];
408
+ CssFormatter.#collectNodeStyles(rules, matchedStyles, options);
409
+ CssFormatter.#collectPseudoStyles(rules, matchedStyles, options);
410
+ CssFormatter.#collectKeyframes(rules, matchedStyles);
411
+ CssFormatter.#collectAtRules(rules, matchedStyles);
412
+ CssFormatter.#collectPositionTryRules(rules, matchedStyles);
413
+ CssFormatter.#collectRegisteredProperties(rules, matchedStyles);
414
+ CssFormatter.#collectFunctionRules(rules, matchedStyles);
415
+ return rules;
416
+ }
417
+ static #collectNodeStyles(rules, matchedStyles, options) {
418
+ for (const style of matchedStyles.nodeStyles?.() ?? []) {
419
+ const properties = CssFormatter.#getStyleProperties(style);
420
+ if (!properties.length) {
421
+ continue;
422
+ }
423
+ if (matchedStyles.isInherited(style)) {
424
+ const inheritedRule = CssFormatter.#createInheritedRule(style, properties, matchedStyles, options);
425
+ if (inheritedRule) {
426
+ rules.push(inheritedRule);
427
+ }
428
+ continue;
429
+ }
430
+ if (style.type === DevTools.CSSStyleDeclaration.Type.Transition) {
431
+ rules.push({
432
+ type: 'transition',
433
+ selector: CssFormatter.#getNodeStyleSelector(style),
434
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
435
+ });
436
+ }
437
+ else if (style.type === DevTools.CSSStyleDeclaration.Type.Animation) {
438
+ const animName = style.animationName();
439
+ rules.push({
440
+ type: 'animation',
441
+ ...(animName ? { name: animName } : {}),
442
+ selector: CssFormatter.#getNodeStyleSelector(style),
443
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
444
+ });
445
+ }
446
+ else if (style.type === DevTools.CSSStyleDeclaration.Type.Attributes) {
447
+ rules.push({
448
+ type: 'attributes',
449
+ selector: CssFormatter.#getNodeStyleSelector(style, matchedStyles),
450
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
451
+ });
452
+ }
453
+ else if (style.type === DevTools.CSSStyleDeclaration.Type.Inline) {
454
+ rules.push({
455
+ type: 'inline',
456
+ selector: CssFormatter.#getNodeStyleSelector(style),
457
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
458
+ });
459
+ }
460
+ else if (style.parentRule instanceof DevTools.CSSRule.CSSStyleRule) {
461
+ rules.push(CssFormatter.#createMatchedRule(style.parentRule, properties, matchedStyles, options));
462
+ }
463
+ }
464
+ }
465
+ static #createMatchedRule(rule, properties, matchedStyles, options) {
466
+ const meta = getCSSStyleRuleMetadata(rule, matchedStyles, options.containerDetails);
467
+ return {
468
+ type: 'matched',
469
+ selector: rule.selectorText(),
470
+ ...meta,
471
+ ...(rule.isUserAgent?.() ? { isUserAgent: true } : {}),
472
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
473
+ };
474
+ }
475
+ static #getNodeStyleSelector(style, matchedStyles) {
476
+ switch (style.type) {
477
+ case DevTools.CSSStyleDeclaration.Type.Transition:
478
+ return 'transitions style';
479
+ case DevTools.CSSStyleDeclaration.Type.Animation: {
480
+ const animName = style.animationName();
481
+ return animName ? `${animName} animation` : 'animation style';
482
+ }
483
+ case DevTools.CSSStyleDeclaration.Type.Attributes: {
484
+ const node = matchedStyles?.nodeForStyle(style);
485
+ const tag = node ? node.nodeNameInCorrectCase() : '';
486
+ return tag ? `${tag}[attributes style]` : '[attributes style]';
487
+ }
488
+ case DevTools.CSSStyleDeclaration.Type.Inline:
489
+ return 'element.style';
490
+ default:
491
+ if (style.parentRule instanceof DevTools.CSSRule.CSSStyleRule) {
492
+ return style.parentRule.selectorText();
493
+ }
494
+ return '';
495
+ }
496
+ }
497
+ static #createInheritedRule(style, properties, matchedStyles, options) {
498
+ const node = getParentNodeInfo(style, matchedStyles, options.resolveUid);
499
+ if (!node) {
500
+ return undefined;
501
+ }
502
+ const inheritableProps = getInheritableProperties(properties, matchedStyles);
503
+ if (!inheritableProps.length) {
504
+ return undefined;
505
+ }
506
+ const rule = style.parentRule instanceof DevTools.CSSRule.CSSStyleRule
507
+ ? style.parentRule
508
+ : undefined;
509
+ const meta = getCSSStyleRuleMetadata(rule, matchedStyles, options.containerDetails);
510
+ const selector = CssFormatter.#getNodeStyleSelector(style, matchedStyles) || undefined;
511
+ return {
512
+ type: 'inherited',
513
+ node,
514
+ ...(selector ? { selector } : {}),
515
+ ...meta,
516
+ properties: CssFormatter.#formatProperties(inheritableProps, matchedStyles),
517
+ };
518
+ }
519
+ static #collectPseudoStyles(rules, matchedStyles, options) {
520
+ const customHighlightNames = matchedStyles.customHighlightPseudoNames?.() ?? [];
521
+ for (const highlightName of customHighlightNames) {
522
+ const pseudoStyles = matchedStyles.customHighlightPseudoStyles?.(highlightName) ?? [];
523
+ CssFormatter.#collectPseudoList(rules, `::highlight(${highlightName})`, pseudoStyles, matchedStyles, options, true);
524
+ }
525
+ // Standard Pseudos (::before, ::after, ::marker, ::selection, etc.)
526
+ const otherPseudoTypes = matchedStyles.pseudoTypes?.() ?? [];
527
+ for (const pseudoType of otherPseudoTypes) {
528
+ const pseudoStyles = matchedStyles.pseudoStyles?.(pseudoType) ?? [];
529
+ CssFormatter.#collectPseudoList(rules, `::${pseudoType}`, pseudoStyles, matchedStyles, options, DevTools.CSSMetadata.cssMetadata().isHighlightPseudoType(pseudoType));
530
+ }
531
+ }
532
+ static #collectPseudoList(rules, pseudoType, pseudoStyles, matchedStyles, options, isHighlight = false) {
533
+ for (const style of pseudoStyles) {
534
+ const allProps = CssFormatter.#getStyleProperties(style);
535
+ if (!allProps.length) {
536
+ continue;
537
+ }
538
+ const node = getParentNodeInfo(style, matchedStyles, options.resolveUid);
539
+ const properties = node
540
+ ? getInheritableProperties(allProps, matchedStyles, isHighlight)
541
+ : allProps;
542
+ if (!properties.length) {
543
+ continue;
544
+ }
545
+ const rule = style.parentRule instanceof DevTools.CSSRule.CSSStyleRule
546
+ ? style.parentRule
547
+ : undefined;
548
+ const meta = getCSSStyleRuleMetadata(rule, matchedStyles, options.containerDetails);
549
+ rules.push({
550
+ type: 'pseudo',
551
+ pseudoType,
552
+ ...(node ? { node } : {}),
553
+ ...(rule ? { selector: rule.selectorText() } : {}),
554
+ ...meta,
555
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
556
+ });
557
+ }
558
+ }
559
+ static #collectKeyframes(rules, matchedStyles) {
560
+ const keyframesRules = matchedStyles.keyframes?.() ?? [];
561
+ for (const keyframesRule of keyframesRules) {
562
+ const name = keyframesRule.name?.()?.text ?? '';
563
+ const rawKeyframes = keyframesRule.keyframes?.() ?? [];
564
+ const steps = [];
565
+ let parentSource;
566
+ for (const keyframe of rawKeyframes) {
567
+ const properties = CssFormatter.#getStyleProperties(keyframe.style);
568
+ if (!properties.length) {
569
+ continue;
570
+ }
571
+ const keyText = keyframe.key?.()?.text ?? '';
572
+ const source = getSourceLocation(keyframe);
573
+ if (!parentSource && source) {
574
+ parentSource = source;
575
+ }
576
+ steps.push({
577
+ keyText,
578
+ ...(source ? { source } : {}),
579
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
580
+ });
581
+ }
582
+ if (!steps.length) {
583
+ continue;
584
+ }
585
+ rules.push({
586
+ type: 'keyframes',
587
+ name,
588
+ selector: `@keyframes ${name}`,
589
+ ...(parentSource ? { source: parentSource } : {}),
590
+ keyframes: steps,
591
+ });
592
+ }
593
+ }
594
+ static #collectAtRules(rules, matchedStyles) {
595
+ const atRules = matchedStyles.atRules?.() ?? [];
596
+ for (const atRule of atRules) {
597
+ const properties = CssFormatter.#getStyleProperties(atRule.style);
598
+ if (!properties.length) {
599
+ continue;
600
+ }
601
+ const subsection = atRule.subsection() ?? undefined;
602
+ const name = atRule.name()?.text;
603
+ const type = atRule.type();
604
+ const selector = subsection
605
+ ? `@${subsection}`
606
+ : name
607
+ ? `@${type} ${name}`
608
+ : `@${type}`;
609
+ const ancestors = [];
610
+ if (subsection) {
611
+ ancestors.push({
612
+ type: 'at-rule',
613
+ atRuleType: type,
614
+ ...(name ? { name } : {}),
615
+ });
616
+ }
617
+ rules.push({
618
+ type: 'at-rule',
619
+ atRuleType: type,
620
+ ...(name ? { name } : {}),
621
+ ...(subsection ? { subsection } : {}),
622
+ selector,
623
+ ...(ancestors.length > 0 ? { ancestors } : {}),
624
+ source: getSourceLocation(atRule),
625
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
626
+ });
627
+ }
628
+ }
629
+ static #collectPositionTryRules(rules, matchedStyles) {
630
+ const positionTryRules = matchedStyles.positionTryRules?.() ?? [];
631
+ for (const positionTryRule of positionTryRules) {
632
+ const properties = CssFormatter.#getStyleProperties(positionTryRule.style);
633
+ if (!properties.length) {
634
+ continue;
635
+ }
636
+ const name = positionTryRule.name?.()?.text ?? '';
637
+ const active = positionTryRule.active?.() ?? false;
638
+ const source = getSourceLocation(positionTryRule);
639
+ rules.push({
640
+ type: 'position-try',
641
+ name,
642
+ active,
643
+ selector: `@position-try ${name}`,
644
+ ...(source ? { source } : {}),
645
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
646
+ });
647
+ }
648
+ }
649
+ static #collectRegisteredProperties(rules, matchedStyles) {
650
+ const registeredProperties = matchedStyles.registeredProperties?.() ?? [];
651
+ for (const propertyRule of registeredProperties) {
652
+ const style = propertyRule.style?.();
653
+ if (!style) {
654
+ continue;
655
+ }
656
+ const properties = CssFormatter.#getStyleProperties(style);
657
+ if (!properties.length) {
658
+ continue;
659
+ }
660
+ const name = propertyRule.propertyName?.() ?? '';
661
+ const parentRule = style.parentRule;
662
+ const source = parentRule
663
+ ? getSourceLocation(parentRule)
664
+ : 'CSS.registerProperty';
665
+ rules.push({
666
+ type: 'property',
667
+ name,
668
+ selector: `@property ${name}`,
669
+ ...(source ? { source } : {}),
670
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
671
+ });
672
+ }
673
+ }
674
+ static #collectFunctionRules(rules, matchedStyles) {
675
+ const functionRules = matchedStyles.functionRules?.() ?? [];
676
+ for (const functionRule of functionRules) {
677
+ const properties = CssFormatter.#getStyleProperties(functionRule.style);
678
+ if (!properties.length) {
679
+ continue;
680
+ }
681
+ const name = functionRule.functionName?.()?.text ?? '';
682
+ const nameWithParameters = functionRule.nameWithParameters?.() || name;
683
+ const source = getSourceLocation(functionRule);
684
+ rules.push({
685
+ type: 'function',
686
+ name,
687
+ selector: `@function ${nameWithParameters}`,
688
+ ...(source ? { source } : {}),
689
+ properties: CssFormatter.#formatProperties(properties, matchedStyles),
690
+ });
691
+ }
692
+ }
693
+ static #formatProperties(props, matchedStyles) {
694
+ return props.map(p => CssFormatter.#formatStructuredProperty(p, matchedStyles));
695
+ }
696
+ static #formatStructuredProperty(prop, matchedStyles) {
697
+ let status = 'active';
698
+ if (prop.parsedOk === false) {
699
+ status = 'invalid';
700
+ }
701
+ else if (prop.disabled) {
702
+ status = 'disabled';
703
+ }
704
+ else {
705
+ const state = matchedStyles.propertyState?.(prop);
706
+ if (state) {
707
+ status = PROPERTY_STATE_MAP[state] ?? 'active';
708
+ }
709
+ }
710
+ let value = prop.value;
711
+ const isImportant = Boolean(prop.important);
712
+ if (isImportant) {
713
+ value = value.replace(/\s*!\s*important$/i, '').trimEnd();
714
+ }
715
+ return {
716
+ name: prop.name,
717
+ value,
718
+ status,
719
+ ...(isImportant ? { important: true } : {}),
720
+ };
721
+ }
722
+ #matchedStyles;
723
+ #options;
724
+ #cascadeRules;
725
+ constructor(matchedStyles, options, cascadeRules) {
726
+ this.#matchedStyles = matchedStyles;
727
+ this.#options = options;
728
+ this.#cascadeRules =
729
+ cascadeRules ?? CssFormatter.collectRules(matchedStyles, options);
730
+ }
731
+ get rules() {
732
+ return this.#cascadeRules;
733
+ }
734
+ toString() {
735
+ const json = this.toJSON();
736
+ const lines = [
737
+ `Styles for ${json.element.selector} (uid: "${json.element.uid}"):`,
738
+ ];
739
+ if (this.#cascadeRules.length === 0) {
740
+ lines.push('', ' (no styles)');
741
+ return lines.join('\n');
742
+ }
743
+ const writer = new IndentedWriter(2);
744
+ appendCssSectionsToString(writer, json);
745
+ lines.push(...writer.lines());
746
+ return lines.join('\n');
747
+ }
748
+ toJSON() {
749
+ return {
750
+ element: {
751
+ uid: this.#options.uid,
752
+ selector: this.#matchedStyles.node?.()?.simpleSelector() ?? '',
753
+ },
754
+ rules: [...this.#cascadeRules],
755
+ };
756
+ }
757
+ }
758
+ /**
759
+ * Resolves container element details for all `@container` queries impacting the node.
760
+ *
761
+ * Container queries evaluate against an ancestor container element in the DOM tree.
762
+ * The DevTools SDK performs an asynchronous CDP request (`CSS.getContainerForNode`)
763
+ * to discover the concrete container node for each query.
764
+ *
765
+ * Resolving these upfront in parallel allows `CssFormatter` methods to remain purely
766
+ * synchronous while providing container selectors and UIDs in headers and comments.
767
+ */
768
+ export async function resolveContainerQueries(matchedStyles, resolveUid) {
769
+ const resolved = new Map();
770
+ const targetNode = matchedStyles.node?.();
771
+ if (!targetNode) {
772
+ return resolved;
773
+ }
774
+ const queries = new Set();
775
+ const allStyles = [...(matchedStyles.nodeStyles?.() ?? [])];
776
+ for (const name of matchedStyles.customHighlightPseudoNames?.() ?? []) {
777
+ allStyles.push(...(matchedStyles.customHighlightPseudoStyles?.(name) ?? []));
778
+ }
779
+ for (const type of matchedStyles.pseudoTypes?.() ?? []) {
780
+ allStyles.push(...(matchedStyles.pseudoStyles?.(type) ?? []));
781
+ }
782
+ for (const style of allStyles) {
783
+ if (style.parentRule instanceof DevTools.CSSRule.CSSStyleRule &&
784
+ style.parentRule.containerQueries) {
785
+ for (const query of style.parentRule.containerQueries) {
786
+ queries.add(query);
787
+ }
788
+ }
789
+ }
790
+ await Promise.all([...queries].map(async (query) => {
791
+ try {
792
+ const container = await query.getContainerForNode?.(targetNode.id);
793
+ if (!container) {
794
+ return;
795
+ }
796
+ const containerNode = container.containerNode;
797
+ const selector = containerNode.simpleSelector();
798
+ const uid = resolveUid?.(containerNode.backendNodeId());
799
+ resolved.set(query, {
800
+ container: {
801
+ ...(uid ? { uid } : {}),
802
+ selector,
803
+ },
804
+ });
805
+ }
806
+ catch {
807
+ // Ignore container query resolution errors
808
+ }
809
+ }));
810
+ return resolved;
811
+ }
812
+ //# sourceMappingURL=CssFormatter.js.map