chrome-devtools-mcp 1.10.1 → 1.12.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 (103) hide show
  1. package/README.md +72 -20
  2. package/build/src/BrowserManager.js +155 -27
  3. package/build/src/McpContext.js +598 -200
  4. package/build/src/McpPage.js +513 -131
  5. package/build/src/McpResponse.js +291 -116
  6. package/build/src/McpWorker.js +66 -0
  7. package/build/src/SlimMcpResponse.js +5 -1
  8. package/build/src/TextSnapshot.js +40 -20
  9. package/build/src/ToolHandler.js +306 -147
  10. package/build/src/bin/chrome-devtools-mcp-main.js +13 -10
  11. package/build/src/bin/chrome-devtools-mcp.js +1 -1
  12. package/build/src/bin/chrome-devtools.js +34 -44
  13. package/build/src/collectors/PageCollector.js +13 -9
  14. package/build/src/collectors/ServiceWorkerCollector.js +20 -13
  15. package/build/src/collectors/constants.js +7 -0
  16. package/build/src/config/ConfigLocator.js +70 -0
  17. package/build/src/config/ConfigParser.js +159 -0
  18. package/build/src/config/ConfigWatcher.js +94 -0
  19. package/build/src/config/ServerConfig.js +251 -0
  20. package/build/src/config/browser-options.js +15 -17
  21. package/build/src/config/category-options.js +15 -30
  22. package/build/src/config/cli-commands.js +165 -5
  23. package/build/src/config/cli-options.js +441 -58
  24. package/build/src/config/mcp-options.js +212 -264
  25. package/build/src/config/puppeteer-options.js +67 -0
  26. package/build/src/config/tool-options.js +60 -0
  27. package/build/src/daemon/client.js +84 -44
  28. package/build/src/daemon/daemon.js +59 -45
  29. package/build/src/daemon/utils.js +46 -12
  30. package/build/src/devtools/DevToolsCommentBridge.js +71 -11
  31. package/build/src/devtools/DevtoolsUtils.js +52 -15
  32. package/build/src/devtools/McpHostBindingAdapter.js +0 -1
  33. package/build/src/formatters/CommentFormatter.js +4 -13
  34. package/build/src/formatters/ConsoleFormatter.js +29 -2
  35. package/build/src/formatters/CssFormatter.js +3 -2
  36. package/build/src/formatters/HeapSnapshotFormatter.js +111 -57
  37. package/build/src/formatters/IssueFormatter.js +33 -32
  38. package/build/src/formatters/NetworkFormatter.js +62 -22
  39. package/build/src/formatters/RemoteObjectFormatter.js +231 -0
  40. package/build/src/formatters/SnapshotFormatter.js +44 -7
  41. package/build/src/index.js +285 -88
  42. package/build/src/processors/ChunkedTraceParser.js +11 -11
  43. package/build/src/processors/HeapSnapshotManager.js +455 -156
  44. package/build/src/processors/PerformanceTrace.js +9 -9
  45. package/build/src/telemetry/ClearcutLogger.js +1 -1
  46. package/build/src/telemetry/transformation.js +7 -11
  47. package/build/src/telemetry/watchdog/main.js +1 -1
  48. package/build/src/third_party/THIRD_PARTY_NOTICES +399 -689
  49. package/build/src/third_party/bundled-packages.json +7 -8
  50. package/build/src/third_party/cli.js +9239 -0
  51. package/build/src/third_party/devtools-formatter-worker.js +4299 -2517
  52. package/build/src/third_party/devtools-heap-snapshot-worker.js +1298 -22
  53. package/build/src/third_party/index.js +132003 -146852
  54. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
  55. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
  56. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
  57. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
  58. package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
  59. package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
  60. package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
  61. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
  62. package/build/src/tools/ToolDefinition.js +102 -12
  63. package/build/src/tools/comments.js +62 -4
  64. package/build/src/tools/console.js +6 -4
  65. package/build/src/tools/css.js +5 -2
  66. package/build/src/tools/emulation.js +22 -8
  67. package/build/src/tools/extensions.js +5 -0
  68. package/build/src/tools/input.js +29 -9
  69. package/build/src/tools/lighthouse.js +136 -12
  70. package/build/src/tools/memory.js +166 -59
  71. package/build/src/tools/network.js +5 -4
  72. package/build/src/tools/pages.js +52 -7
  73. package/build/src/tools/performance.js +28 -7
  74. package/build/src/tools/pwa.js +7 -0
  75. package/build/src/tools/screencast.js +74 -33
  76. package/build/src/tools/screenshot.js +52 -21
  77. package/build/src/tools/script.js +125 -40
  78. package/build/src/tools/slim/tools.js +27 -13
  79. package/build/src/tools/snapshot.js +13 -3
  80. package/build/src/tools/thirdPartyDeveloper.js +9 -5
  81. package/build/src/tools/tools.js +35 -22
  82. package/build/src/tools/webmcp.js +11 -6
  83. package/build/src/types.js +11 -0
  84. package/build/src/utils/TaskRunner.js +136 -0
  85. package/build/src/utils/WaitForHelper.js +15 -2
  86. package/build/src/utils/bytes.js +2 -12
  87. package/build/src/utils/check-for-updates.js +2 -2
  88. package/build/src/utils/disclaimers.js +27 -0
  89. package/build/src/utils/errorHandling.js +20 -0
  90. package/build/src/utils/keyboard.js +14 -2
  91. package/build/src/utils/logger.js +84 -5
  92. package/build/src/utils/resourceType.js +27 -0
  93. package/build/src/utils/text.js +44 -0
  94. package/build/src/utils/timeout.js +14 -0
  95. package/build/src/utils/url.js +140 -3
  96. package/build/src/version.js +1 -1
  97. package/package.json +16 -11
  98. package/skills/a11y-debugging/SKILL.md +7 -12
  99. package/skills/chrome-devtools/SKILL.md +2 -2
  100. package/skills/chrome-devtools-cli/SKILL.md +18 -15
  101. package/skills/cookie-debugging/SKILL.md +8 -5
  102. package/skills/debug-optimize-lcp/SKILL.md +1 -1
  103. package/skills/troubleshooting/SKILL.md +5 -6
@@ -0,0 +1,251 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { yargs } from '../third_party/cli.js';
8
+ import { CONFLICTING_ARGS, DEFAULT_FILESYSTEM_ROOT, IMPLICATIONS, isReloadableOption, mcpOptions, mcpOptionsForViaCli, stripYargsPositionalArgs, } from './mcp-options.js';
9
+ function isMcpOptionKey(key) {
10
+ return key in mcpOptions;
11
+ }
12
+ function copyOption(target, source, key) {
13
+ if (key in source) {
14
+ target[key] = source[key];
15
+ }
16
+ else {
17
+ delete target[key];
18
+ }
19
+ }
20
+ function filterExplicitArgs(args, baseOptions) {
21
+ const filtered = {};
22
+ for (const key of Object.keys(args)) {
23
+ if (!isMcpOptionKey(key)) {
24
+ continue;
25
+ }
26
+ if (args[key] === undefined && 'default' in baseOptions[key]) {
27
+ continue;
28
+ }
29
+ copyOption(filtered, args, key);
30
+ }
31
+ return filtered;
32
+ }
33
+ function mergeLayer(previous, next) {
34
+ const merged = { ...previous };
35
+ for (const name of Object.keys(mcpOptions)) {
36
+ if (isMcpOptionKey(name) && isReloadableOption(name)) {
37
+ copyOption(merged, next, name);
38
+ }
39
+ }
40
+ return merged;
41
+ }
42
+ function parseDefaultArgs(options) {
43
+ const parsed = yargs([])
44
+ .parserConfiguration({
45
+ 'strip-aliased': true,
46
+ 'camel-case-expansion': false,
47
+ })
48
+ .options(options)
49
+ .parseSync([]);
50
+ return {
51
+ ...stripYargsPositionalArgs(parsed),
52
+ // yargs copies array defaults, so restore the shared reference that the
53
+ // `viaCli` check in `applyDefaults()` compares with `===`.
54
+ filesystemRoot: DEFAULT_FILESYSTEM_ROOT,
55
+ };
56
+ }
57
+ /**
58
+ * Holds explicit CLI and config-file layers alongside the resolved arguments.
59
+ *
60
+ * Components read live configuration through {@link ReadonlyServerConfig}.
61
+ * Only the owning server updates the config in place via {@link commit} after
62
+ * computing and validating a candidate reload via {@link mergeReloadable}.
63
+ */
64
+ export class ServerConfig {
65
+ #cliArgs;
66
+ #fileArgs;
67
+ #configPath;
68
+ #env;
69
+ #resolved;
70
+ constructor(init) {
71
+ this.#cliArgs = { ...init.cliArgs };
72
+ this.#fileArgs = { ...init.fileArgs };
73
+ this.#configPath = init.configPath;
74
+ this.#env = init.env ?? process.env;
75
+ this.#resolved = { ...init.resolved };
76
+ }
77
+ /**
78
+ * Step 4: rejects mutually exclusive inputs. Only explicit inputs are
79
+ * checked, so defaults never conflict.
80
+ */
81
+ static validateConflicts(explicitArgs) {
82
+ const activeArgs = new Set();
83
+ for (const [key, val] of Object.entries(explicitArgs)) {
84
+ if (val !== undefined && val !== false) {
85
+ activeArgs.add(key);
86
+ }
87
+ }
88
+ for (const group of CONFLICTING_ARGS) {
89
+ const activeInGroup = group.filter(arg => activeArgs.has(arg));
90
+ if (activeInGroup.length > 1) {
91
+ const [arg1, arg2] = activeInGroup;
92
+ throw new Error(`Arguments ${String(arg1)} and ${String(arg2)} are mutually exclusive`);
93
+ }
94
+ }
95
+ }
96
+ static validateImplications(explicitArgs) {
97
+ for (const [key, implied] of IMPLICATIONS) {
98
+ const isKeySet = explicitArgs[key] !== undefined && explicitArgs[key] !== false;
99
+ const isImpliedSet = explicitArgs[implied] !== undefined && explicitArgs[implied] !== false;
100
+ if (isKeySet && !isImpliedSet) {
101
+ throw new Error(`Implications failed:\n ${String(key)} -> ${String(implied)}`);
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ * Step 5: fills in defaults for everything that was not set explicitly.
107
+ * `viaCli` is an explicit input like any other; it selects which defaults
108
+ * apply.
109
+ */
110
+ static applyDefaults(explicitArgs, options) {
111
+ const env = options?.env ?? process.env;
112
+ const isViaCli = explicitArgs.viaCli === true;
113
+ const baseOptions = isViaCli ? mcpOptionsForViaCli : mcpOptions;
114
+ const resolvedArgs = {
115
+ ...parseDefaultArgs(baseOptions),
116
+ ...filterExplicitArgs(explicitArgs, baseOptions),
117
+ };
118
+ // `channel` only applies when Chrome is launched by channel. Leaving it
119
+ // unset otherwise keeps it out of telemetry (computeFlagUsage).
120
+ const launchesByChannel = !resolvedArgs.browserUrl &&
121
+ !resolvedArgs.wsEndpoint &&
122
+ !resolvedArgs.executablePath;
123
+ if (!launchesByChannel && explicitArgs.channel === undefined) {
124
+ delete resolvedArgs.channel;
125
+ }
126
+ if (isViaCli) {
127
+ resolvedArgs.slim = false;
128
+ resolvedArgs.pageIdRouting = true;
129
+ if (resolvedArgs.filesystemRoot === DEFAULT_FILESYSTEM_ROOT &&
130
+ explicitArgs.allowUnrestrictedPaths !== false) {
131
+ resolvedArgs.allowUnrestrictedPaths = true;
132
+ resolvedArgs.filesystemRoot = undefined;
133
+ }
134
+ const connectsToExistingBrowser = resolvedArgs.autoConnect ||
135
+ resolvedArgs.browserUrl ||
136
+ resolvedArgs.wsEndpoint;
137
+ if (explicitArgs.isolated === undefined &&
138
+ resolvedArgs.userDataDir === undefined &&
139
+ !connectsToExistingBrowser) {
140
+ resolvedArgs.isolated = true;
141
+ }
142
+ if (resolvedArgs.categoryExtensions === undefined &&
143
+ !connectsToExistingBrowser) {
144
+ resolvedArgs.categoryExtensions = true;
145
+ }
146
+ }
147
+ if (env['CI'] || env['CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS']) {
148
+ if (!options?.suppressUsageStatisticsNotice) {
149
+ console.error("turning off usage statistics. process.env['CI'] || process.env['CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS'] is set.");
150
+ }
151
+ resolvedArgs.usageStatistics = false;
152
+ }
153
+ if (resolvedArgs.categoryExperimentalThirdParty === undefined &&
154
+ env['CHROME_DEVTOOLS_MCP_CATEGORY_EXPERIMENTAL_THIRD_PARTY']) {
155
+ resolvedArgs.categoryExperimentalThirdParty = true;
156
+ }
157
+ return resolvedArgs;
158
+ }
159
+ /**
160
+ * Step 3–5: merges CLI and config-file layers (`CLI > config file`),
161
+ * validates conflicts and implications, and applies defaults.
162
+ */
163
+ static create(options) {
164
+ const explicitArgs = {
165
+ ...options.fileArgs,
166
+ ...options.cliArgs,
167
+ ...(options.configPath ? { config: options.configPath } : {}),
168
+ };
169
+ ServerConfig.validateConflicts(explicitArgs);
170
+ ServerConfig.validateImplications(explicitArgs);
171
+ const resolved = ServerConfig.applyDefaults(explicitArgs, {
172
+ env: options.env,
173
+ suppressUsageStatisticsNotice: options.suppressUsageStatisticsNotice,
174
+ });
175
+ return new ServerConfig({
176
+ cliArgs: options.cliArgs,
177
+ fileArgs: options.fileArgs,
178
+ configPath: options.configPath,
179
+ env: options.env,
180
+ resolved,
181
+ });
182
+ }
183
+ get cliArgs() {
184
+ return this.#cliArgs;
185
+ }
186
+ get fileArgs() {
187
+ return this.#fileArgs;
188
+ }
189
+ get configPath() {
190
+ return this.#configPath;
191
+ }
192
+ get resolved() {
193
+ return this.#resolved;
194
+ }
195
+ /**
196
+ * Produces a new {@link ServerConfig} with updated config-file arguments,
197
+ * preserving this config's CLI arguments, config path, and environment.
198
+ */
199
+ withFileArgs(fileArgs) {
200
+ return ServerConfig.create({
201
+ cliArgs: { ...this.#cliArgs },
202
+ fileArgs,
203
+ configPath: this.#configPath,
204
+ env: this.#env,
205
+ suppressUsageStatisticsNotice: true,
206
+ });
207
+ }
208
+ /**
209
+ * Produces a new {@link ServerConfig} that takes reloadable options from
210
+ * `next` and keeps restart-required options from this config, preserving
211
+ * `CLI > config file > defaults` precedence.
212
+ */
213
+ mergeReloadable(next, options) {
214
+ const mergedFileArgs = mergeLayer(this.#fileArgs, next.#fileArgs);
215
+ const mergedCliArgs = mergeLayer(this.#cliArgs, next.#cliArgs);
216
+ return ServerConfig.create({
217
+ cliArgs: mergedCliArgs,
218
+ fileArgs: mergedFileArgs,
219
+ configPath: this.#configPath,
220
+ env: options?.env ?? this.#env,
221
+ suppressUsageStatisticsNotice: true,
222
+ });
223
+ }
224
+ /**
225
+ * Returns the restart-required options whose resolved values differ between
226
+ * this config and `next`.
227
+ */
228
+ getRestartRequiredChanges(next) {
229
+ const changed = [];
230
+ for (const name of Object.keys(mcpOptions)) {
231
+ if (isMcpOptionKey(name) &&
232
+ !isReloadableOption(name) &&
233
+ (!isDeepStrictEqual(this.#fileArgs[name], next.#fileArgs[name]) ||
234
+ !isDeepStrictEqual(this.#cliArgs[name], next.#cliArgs[name])) &&
235
+ !isDeepStrictEqual(this.#resolved[name], next.#resolved[name])) {
236
+ changed.push(name);
237
+ }
238
+ }
239
+ return changed;
240
+ }
241
+ /**
242
+ * Commits a previously validated {@link ServerConfig} snapshot in place so
243
+ * all shared {@link ReadonlyServerConfig} readers observe the new values.
244
+ */
245
+ commit(next) {
246
+ this.#cliArgs = next.#cliArgs;
247
+ this.#fileArgs = next.#fileArgs;
248
+ this.#resolved = next.#resolved;
249
+ }
250
+ }
251
+ //# sourceMappingURL=ServerConfig.js.map
@@ -7,20 +7,12 @@ export const browserOptions = {
7
7
  autoConnect: {
8
8
  type: 'boolean',
9
9
  description: 'If specified, automatically connects to a browser (Chrome 144+) running locally from the user data directory identified by the channel param (default channel is stable). Requires the remote debugging server to be started in the Chrome instance via chrome://inspect/#remote-debugging.',
10
- conflicts: ['isolated', 'executablePath'],
11
10
  default: false,
12
- coerce: (value) => {
13
- if (!value) {
14
- return;
15
- }
16
- return value;
17
- },
18
11
  },
19
12
  browserUrl: {
20
13
  type: 'string',
21
14
  description: 'Connect to a running, debuggable Chrome instance (e.g. `http://127.0.0.1:9222`). For more details see: https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/advanced-usage.md#connecting-to-a-running-chrome-instance.',
22
15
  alias: 'u',
23
- conflicts: ['wsEndpoint'],
24
16
  coerce: (url) => {
25
17
  if (!url) {
26
18
  return;
@@ -38,7 +30,6 @@ export const browserOptions = {
38
30
  type: 'string',
39
31
  description: 'WebSocket endpoint to connect to a running Chrome instance (e.g., ws://127.0.0.1:9222/devtools/browser/<id>). Alternative to --browserUrl.',
40
32
  alias: 'w',
41
- conflicts: ['browserUrl'],
42
33
  coerce: (url) => {
43
34
  if (!url) {
44
35
  return;
@@ -61,20 +52,28 @@ export const browserOptions = {
61
52
  wsHeaders: {
62
53
  type: 'string',
63
54
  description: 'Custom headers for WebSocket connection in JSON format (e.g., \'{"Authorization":"Bearer token"}\'). Only works with --wsEndpoint.',
64
- implies: 'wsEndpoint',
65
55
  coerce: (val) => {
66
56
  if (!val) {
67
57
  return;
68
58
  }
69
59
  try {
70
- const parsed = JSON.parse(val);
71
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
60
+ const parsed = typeof val === 'string' ? JSON.parse(val) : val;
61
+ if (typeof parsed !== 'object' ||
62
+ parsed === null ||
63
+ Array.isArray(parsed)) {
72
64
  throw new Error('Headers must be a JSON object');
73
65
  }
74
- return parsed;
66
+ const headers = {};
67
+ for (const [key, value] of Object.entries(parsed)) {
68
+ if (typeof value !== 'string') {
69
+ throw new Error(`Header "${key}" must have a string value`);
70
+ }
71
+ headers[key] = value;
72
+ }
73
+ return headers;
75
74
  }
76
75
  catch (error) {
77
- throw new Error(`Invalid JSON for wsHeaders: ${error.message}`);
76
+ throw new Error(`Invalid JSON for wsHeaders: ${error instanceof Error ? error.message : String(error)}`);
78
77
  }
79
78
  },
80
79
  },
@@ -86,23 +85,22 @@ export const browserOptions = {
86
85
  executablePath: {
87
86
  type: 'string',
88
87
  description: 'Path to custom Chrome executable.',
89
- conflicts: ['browserUrl', 'wsEndpoint'],
90
88
  alias: 'e',
91
89
  },
92
90
  isolated: {
93
91
  type: 'boolean',
94
92
  description: 'If specified, creates a temporary user-data-dir that is automatically cleaned up after the browser is closed. Defaults to false.',
93
+ default: false,
95
94
  },
96
95
  userDataDir: {
97
96
  type: 'string',
98
97
  description: 'Path to the user data directory for Chrome. Default is $HOME/.cache/chrome-devtools-mcp/chrome-profile$CHANNEL_SUFFIX_IF_NON_STABLE',
99
- conflicts: ['browserUrl', 'wsEndpoint', 'isolated'],
100
98
  },
101
99
  channel: {
102
100
  type: 'string',
103
101
  description: 'Specify a different Chrome channel that should be used. The default is the stable channel version.',
104
102
  choices: ['canary', 'dev', 'beta', 'stable'],
105
- conflicts: ['browserUrl', 'wsEndpoint', 'executablePath'],
103
+ default: 'stable',
106
104
  },
107
105
  proxyServer: {
108
106
  type: 'string',
@@ -5,46 +5,28 @@
5
5
  */
6
6
  import { ToolCategory } from '../tools/categories.js';
7
7
  const categoryOverrides = {
8
- [ToolCategory.INPUT]: {
9
- hidden: false,
10
- },
11
- [ToolCategory.NAVIGATION]: {
12
- hidden: false,
13
- },
14
- [ToolCategory.EMULATION]: {
15
- hidden: false,
16
- },
17
- [ToolCategory.PERFORMANCE]: {
18
- hidden: false,
19
- },
20
- [ToolCategory.NETWORK]: {
21
- hidden: false,
22
- },
23
- [ToolCategory.DEBUGGING]: {
24
- hidden: false,
25
- },
26
- [ToolCategory.MEMORY]: {
27
- hidden: false,
28
- },
8
+ [ToolCategory.INPUT]: {},
9
+ [ToolCategory.NAVIGATION]: {},
10
+ [ToolCategory.EMULATION]: {},
11
+ [ToolCategory.PERFORMANCE]: {},
12
+ [ToolCategory.NETWORK]: {},
13
+ [ToolCategory.DEBUGGING]: {},
14
+ [ToolCategory.MEMORY]: {},
29
15
  [ToolCategory.WEBMCP]: {
30
- describe: 'Set to true to enable debugging WebMCP tools. Requires Chrome 150+ with the following flag: `--enable-features=WebMCP`',
16
+ describe: 'Set to true to enable WebMCP tools (excluding debugging tools, which are exposed under the third-party developer tools category). Requires Chrome 150+ with the following flag: `--enable-features=WebMCP`',
31
17
  offByDefault: true,
32
- hidden: false,
33
18
  },
34
19
  [ToolCategory.EXTENSIONS]: {
35
- describe: 'Set to true to include tools related to extensions. Note: This feature is currently only supported with a pipe connection. autoConnect, browserUrl, and wsEndpoint are not supported with this feature until 149 will be released.',
36
- hidden: false,
20
+ describe: 'Set to true to include tools related to extensions.',
37
21
  offByDefault: true,
22
+ reloadable: false,
38
23
  },
39
24
  [ToolCategory.THIRD_PARTY]: {
40
- describe: 'Set to true to enable third-party developer tools exposed by the inspected page itself',
41
- hidden: false,
25
+ describe: 'Set to true to enable third-party developer tools exposed by the inspected page itself (via WebMCP or devtoolstooldiscovery)',
42
26
  offByDefault: true,
43
27
  },
44
28
  [ToolCategory.PWA]: {
45
29
  describe: 'Set to true to include tools for automating Progressive Web Apps (install, launch, uninstall, and OS state). This feature is only supported with a pipe connection; autoConnect, browserUrl, and wsEndpoint are not supported.',
46
- conflicts: ['autoConnect', 'browserUrl', 'wsEndpoint'],
47
- hidden: false,
48
30
  offByDefault: true,
49
31
  },
50
32
  };
@@ -56,8 +38,11 @@ function createOption(category) {
56
38
  return {
57
39
  type: 'boolean',
58
40
  describe,
59
- hidden: true,
41
+ reloadable: true,
60
42
  ...overrides,
43
+ // Off-by-default categories have no default so that they stay unset unless
44
+ // passed explicitly. This keeps them out of conflict checks and lets
45
+ // --viaCli apply its own categoryExtensions default.
61
46
  ...(overrides.offByDefault ? {} : { default: true }),
62
47
  };
63
48
  }
@@ -6,21 +6,181 @@
6
6
  /**
7
7
  * Builds the yargs command string and usage line for a CLI command.
8
8
  *
9
- * Optional args are rendered as `[--flag]` in the usage line only: as part of
10
- * the command string yargs parses each one as a trailing positional, and a
11
- * variadic positional has to be the last one.
9
+ * Optional flag args are rendered as `[--flag]` in the usage line only: as
10
+ * part of the command string yargs parses each one as a trailing positional,
11
+ * and a variadic positional has to be the last one. Which args are positional
12
+ * is decided at build time by `scripts/generate-cli.ts`.
12
13
  */
13
14
  export function buildCommand(commandName, args) {
14
15
  let command = commandName;
15
16
  let flags = '';
16
17
  for (const [name, arg] of Object.entries(args)) {
17
- if (arg.required) {
18
+ if (!arg.positional) {
19
+ flags += ` [--${name}]`;
20
+ }
21
+ else if (arg.required) {
18
22
  command += arg.type === 'array' ? ` <${name}..>` : ` <${name}>`;
19
23
  }
20
24
  else {
21
- flags += ` [--${name}]`;
25
+ command += arg.type === 'array' ? ` [${name}..]` : ` [${name}]`;
22
26
  }
23
27
  }
24
28
  return { command, usage: `$0 ${command}${flags}` };
25
29
  }
30
+ /**
31
+ * Options that are available on every tool command and are consumed by yargs
32
+ * rather than forwarded to the tool.
33
+ */
34
+ export const GLOBAL_CLI_OPTIONS = new Map([
35
+ ['sessionId', 'value'],
36
+ ['outputFormat', 'value'],
37
+ ['help', 'boolean'],
38
+ ['version', 'boolean'],
39
+ ]);
40
+ /**
41
+ * Builds a `CommandArgSpec` for a tool command from its generated arg
42
+ * definitions and the options available on every command.
43
+ */
44
+ export function getCommandArgSpec(args, globalOptions = GLOBAL_CLI_OPTIONS) {
45
+ const options = new Map(globalOptions);
46
+ let positionalCount = 0;
47
+ let variadic = false;
48
+ for (const [name, arg] of Object.entries(args)) {
49
+ if (arg.positional) {
50
+ positionalCount++;
51
+ variadic = arg.type === 'array';
52
+ }
53
+ else {
54
+ options.set(name, toOptionKind(arg.type));
55
+ }
56
+ }
57
+ return { options, positionalCount, variadic };
58
+ }
59
+ export function toOptionKind(type) {
60
+ if (type === 'boolean') {
61
+ return 'boolean';
62
+ }
63
+ if (type === 'array') {
64
+ return 'array';
65
+ }
66
+ return 'value';
67
+ }
68
+ const LITERAL_ARG_PREFIX = '\0literal:';
69
+ // Mirrors yargs-parser's negative number detection.
70
+ const NEGATIVE_NUMBER = /^-\d+(\.\d*)?(e-?\d+)?$/;
71
+ function optionName(token) {
72
+ let name = token.replace(/^-+/, '');
73
+ const eq = name.indexOf('=');
74
+ if (eq !== -1) {
75
+ name = name.slice(0, eq);
76
+ }
77
+ if (name.startsWith('no-')) {
78
+ name = name.slice(3);
79
+ }
80
+ return name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
81
+ }
82
+ /**
83
+ * Shields positional values that yargs cannot carry through its parsing.
84
+ *
85
+ * yargs re-parses command positionals as `--name value` pairs, and in that
86
+ * pass yargs-parser treats any value starting with `-` (other than a negative
87
+ * number) as the next flag, replacing the value with `''`. It also never fills
88
+ * positionals from the tokens after `--`. See
89
+ * https://github.com/yargs/yargs/issues/1312 and
90
+ * https://github.com/yargs/yargs/issues/1821.
91
+ *
92
+ * Shielded tokens are replaced by opaque placeholders that `restore` maps back
93
+ * to the original values. A token is shielded when:
94
+ *
95
+ * - it is a lone `-`, which can never be an option;
96
+ * - it follows the first `--`, which is dropped so the tokens populate
97
+ * positionals;
98
+ * - it starts with `-`, is not a known option of the command, and the command
99
+ * still has an unfilled positional. Known options and their values are
100
+ * skipped the way yargs consumes them, so a dash-prefixed value such as
101
+ * `--flag` in a positional slot is passed through as text, while an unknown
102
+ * flag after all positionals are filled is still rejected by yargs.
103
+ *
104
+ * `getSpec` resolves the spec of a command by name and returns `undefined`
105
+ * for tokens that are not a command.
106
+ */
107
+ export function shieldLiteralArgs(argv, getSpec) {
108
+ const literals = new Map();
109
+ const result = [];
110
+ const shield = (token) => {
111
+ const placeholder = `${LITERAL_ARG_PREFIX}${literals.size}`;
112
+ literals.set(placeholder, token);
113
+ result.push(placeholder);
114
+ };
115
+ let spec;
116
+ let filled = 0;
117
+ let afterDoubleDash = false;
118
+ for (let i = 0; i < argv.length; i++) {
119
+ const token = argv[i];
120
+ if (afterDoubleDash) {
121
+ shield(token);
122
+ continue;
123
+ }
124
+ if (token === '--') {
125
+ afterDoubleDash = true;
126
+ continue;
127
+ }
128
+ if (token === '-') {
129
+ shield(token);
130
+ filled++;
131
+ continue;
132
+ }
133
+ if (!token.startsWith('-') || NEGATIVE_NUMBER.test(token)) {
134
+ result.push(token);
135
+ if (!spec) {
136
+ spec = getSpec(token);
137
+ }
138
+ else {
139
+ filled++;
140
+ }
141
+ continue;
142
+ }
143
+ const kind = spec?.options.get(optionName(token));
144
+ if (kind !== undefined) {
145
+ result.push(token);
146
+ if (token.includes('=')) {
147
+ continue;
148
+ }
149
+ if (kind === 'boolean') {
150
+ if (/^(true|false)$/.test(argv[i + 1] ?? '')) {
151
+ result.push(argv[++i]);
152
+ }
153
+ }
154
+ else if (kind === 'array') {
155
+ while (i + 1 < argv.length && !argv[i + 1].startsWith('-')) {
156
+ result.push(argv[++i]);
157
+ }
158
+ }
159
+ else if (i + 1 < argv.length) {
160
+ result.push(argv[++i]);
161
+ }
162
+ continue;
163
+ }
164
+ const hasUnfilledPositional = spec !== undefined &&
165
+ (filled < spec.positionalCount ||
166
+ (spec.variadic && spec.positionalCount > 0));
167
+ if (hasUnfilledPositional) {
168
+ shield(token);
169
+ filled++;
170
+ }
171
+ else {
172
+ result.push(token);
173
+ }
174
+ }
175
+ const restore = (value) => {
176
+ if (typeof value === 'string') {
177
+ return literals.get(value) ?? value;
178
+ }
179
+ if (Array.isArray(value)) {
180
+ return value.map(restore);
181
+ }
182
+ return value;
183
+ };
184
+ return { argv: result, restore };
185
+ }
26
186
  //# sourceMappingURL=cli-commands.js.map