@snap/valdi 1.1.7 → 1.2.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 (96) hide show
  1. package/.metadata/.bazelrc.template +9 -7
  2. package/.metadata/AGENTS.md.template +7 -0
  3. package/.metadata/MODULE.bazel.template +47 -3
  4. package/.metadata/README.md.template +2 -2
  5. package/.metadata/bzl/patches/rules_python/1.9.0/BUILD.bazel.template +1 -0
  6. package/.metadata/bzl/patches/rules_python/1.9.0/remove_setuptools_spaces.patch.template +96 -0
  7. package/.metadata/skill-tests-README.md.template +1 -1
  8. package/README.md +47 -14
  9. package/bundled-skills/registry.json +2 -1
  10. package/bundled-skills/skills/valdi-animations/skill.md +49 -0
  11. package/bundled-skills/skills/valdi-async/skill.md +3 -2
  12. package/bundled-skills/skills/valdi-async/tests/README.md +1 -1
  13. package/bundled-skills/skills/valdi-bazel/skill.md +2 -6
  14. package/bundled-skills/skills/valdi-component-tests/tests/README.md +1 -1
  15. package/bundled-skills/skills/valdi-cpp-runtime/skill.md +18 -0
  16. package/bundled-skills/skills/valdi-custom-view/skill.md +1 -1
  17. package/bundled-skills/skills/valdi-error-handling/skill.md +1 -1
  18. package/bundled-skills/skills/valdi-gestures/skill.md +3 -3
  19. package/bundled-skills/skills/valdi-migrate/skill.md +2 -1
  20. package/bundled-skills/skills/valdi-migrate/tests/README.md +2 -2
  21. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +4 -4
  22. package/bundled-skills/skills/valdi-mock-to-module/skill.md +9 -6
  23. package/bundled-skills/skills/valdi-overview/skill.md +2 -1
  24. package/bundled-skills/skills/valdi-perf/skill.md +121 -5
  25. package/bundled-skills/skills/valdi-perf/tests/README.md +1 -1
  26. package/bundled-skills/skills/valdi-pr-review/skill.md +189 -0
  27. package/bundled-skills/skills/valdi-profile/skill.md +5 -3
  28. package/bundled-skills/skills/valdi-setup/skill.md +3 -6
  29. package/bundled-skills/skills/valdi-testing/skill.md +1 -1
  30. package/bundled-skills/skills/valdi-tsx/skill.md +47 -11
  31. package/bundled-skills/skills/valdi-tsx/tests/README.md +1 -1
  32. package/debugger/README.md +356 -0
  33. package/debugger/debugger-actions.js +373 -0
  34. package/debugger/debugger-api.js +225 -0
  35. package/debugger/debugger-bootstrap.js +295 -0
  36. package/debugger/debugger-model.js +790 -0
  37. package/debugger/debugger-performance.js +573 -0
  38. package/debugger/debugger-preview-html.js +676 -0
  39. package/debugger/debugger-providers.js +389 -0
  40. package/debugger/debugger-render.js +529 -0
  41. package/debugger/debugger-runtime.js +387 -0
  42. package/debugger/debugger-session.js +188 -0
  43. package/debugger/debugger-settings.js +209 -0
  44. package/debugger/debugger-state.js +221 -0
  45. package/debugger/debugger-tree-model.js +539 -0
  46. package/debugger/debugger.css +1865 -0
  47. package/debugger/devtools-panel.css +1318 -0
  48. package/debugger/devtools-panel.html +273 -0
  49. package/debugger/devtools-panel.js +3329 -0
  50. package/debugger/index.html +279 -0
  51. package/dist/commands/bootstrap.js +7 -6
  52. package/dist/commands/build.js +7 -1
  53. package/dist/commands/debugger.js +163 -0
  54. package/dist/commands/doctor.js +3 -62
  55. package/dist/commands/export.js +47 -16
  56. package/dist/commands/hotreload.js +247 -27
  57. package/dist/commands/inspect.js +5 -2
  58. package/dist/commands/inspect_commands/input.js +176 -0
  59. package/dist/commands/inspect_commands/snapshot.js +1 -1
  60. package/dist/commands/inspect_commands/tree.js +1 -1
  61. package/dist/commands/install.js +79 -2
  62. package/dist/commands/projectsync.js +15 -0
  63. package/dist/commands/webHotreload.js +31 -0
  64. package/dist/core/constants.js +34 -7
  65. package/dist/debugger/chromiumConsole.js +279 -0
  66. package/dist/debugger/inputClient.js +473 -0
  67. package/dist/debugger/server.js +3801 -0
  68. package/dist/debugger/targetRegistry.js +436 -0
  69. package/dist/debugger/webPreviewPerformance.js +864 -0
  70. package/dist/index.js +0 -0
  71. package/dist/utils/BazelClient.js +34 -5
  72. package/dist/utils/applicationUtils.js +20 -2
  73. package/dist/utils/buildInfo.js +5 -1
  74. package/dist/utils/chromiumDevToolsClient.js +350 -0
  75. package/dist/utils/cliUtils.js +2 -2
  76. package/dist/utils/daemonClient.js +364 -44
  77. package/dist/utils/directorySync.js +153 -0
  78. package/dist/utils/githubUtils.js +1 -1
  79. package/dist/utils/hermesClient.js +82 -176
  80. package/dist/utils/loopbackHost.js +14 -0
  81. package/dist/utils/owlCdpClient.js +282 -0
  82. package/dist/utils/owlDevToolsExtension.js +142 -0
  83. package/dist/utils/processUtils.js +14 -0
  84. package/dist/utils/stringUtils.js +13 -1
  85. package/dist/utils/webApplicationSession.js +58 -0
  86. package/dist/utils/webHotReloadSession.js +212 -0
  87. package/dist/utils/webServerUtils.js +195 -0
  88. package/dist/utils/zipUtils.js +20 -2
  89. package/package.json +4 -2
  90. package/dist/commands/inspect_commands/snapshot.spec.js +0 -105
  91. package/dist/core/packageFiles.spec.js +0 -29
  92. package/dist/preview/previewGenerator.spec.js +0 -203
  93. package/dist/preview/viewModelParser.spec.js +0 -171
  94. package/dist/utils/linuxDistro.spec.js +0 -122
  95. package/dist/utils/skillsAdapters.spec.js +0 -141
  96. package/dist/utils/stringUtils.spec.js +0 -81
package/dist/index.js CHANGED
File without changes
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BazelClient = exports.BazelLabel = void 0;
4
+ exports.bazelrcDefinesStableExec = bazelrcDefinesStableExec;
4
5
  const tslib_1 = require("tslib");
6
+ const fs = tslib_1.__importStar(require("fs"));
5
7
  const path_1 = tslib_1.__importDefault(require("path"));
6
8
  const constants_1 = require("../core/constants");
7
9
  const errors_1 = require("../core/errors");
@@ -13,6 +15,26 @@ const BAZEL_QUIET_OPTIONS = '--noshow_progress --noshow_loading_progress --ui_ev
13
15
  const BAZEL_PREFIXED_OPTIONS = '--max_idle_secs=5';
14
16
  const BAZEL_POSTFIXED_OPTIONS = '--color=yes';
15
17
  const DEFAULT_STDIO_MODE = ['pipe', 'pipe', 'inherit'];
18
+ const WORKSPACE_MARKERS = ['MODULE.bazel', 'MODULE.bazel.bzlmod', 'WORKSPACE', 'WORKSPACE.bazel'];
19
+ function bazelrcDefinesStableExec(startDir = process.cwd()) {
20
+ let dir = startDir;
21
+ for (;;) {
22
+ if (WORKSPACE_MARKERS.some(marker => fs.existsSync(path_1.default.join(dir, marker)))) {
23
+ const bazelrc = path_1.default.join(dir, '.bazelrc');
24
+ try {
25
+ return fs.existsSync(bazelrc) && /(^|\n)[^\n#]*:stable_exec\b/.test(fs.readFileSync(bazelrc, 'utf8'));
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ const parent = path_1.default.dirname(dir);
32
+ if (parent === dir) {
33
+ return false;
34
+ }
35
+ dir = parent;
36
+ }
37
+ }
16
38
  let cached_bazel_executable;
17
39
  function getBazelCli() {
18
40
  if (!cached_bazel_executable) {
@@ -112,6 +134,7 @@ class BazelCommandCache {
112
134
  class BazelClient {
113
135
  workspaceRootCache;
114
136
  executionRootCache;
137
+ stableExecArgsCache;
115
138
  constructor() {
116
139
  this.workspaceRootCache = new BazelCommandCache(async () => {
117
140
  return this.runCommandAndGetTrimmedStdOut('info workspace');
@@ -157,25 +180,25 @@ class BazelClient {
157
180
  return Digraph_1.Digraph.parse(stdout.trim());
158
181
  }
159
182
  async queryBuildOutputs(targets, extraArgs = '') {
160
- const command = `cquery 'set(${targets.join(' ')})' --output files ${extraArgs}`;
183
+ const command = `cquery 'set(${targets.join(' ')})' --output files ${this.stableExecArgs()} ${extraArgs}`;
161
184
  const lines = await this.runCommandWithLinesOutput(command);
162
185
  return lines.sort();
163
186
  }
164
187
  async buildTarget(target, extraArgs = '') {
165
- const commandBuildTarget = `build ${target} ${extraArgs}`;
188
+ const commandBuildTarget = `build ${target} ${this.stableExecArgs()} ${extraArgs}`;
166
189
  return await this.spawnCommand(commandBuildTarget, 'inherit').catch(() => {
167
190
  throw new errors_1.CliError(`Failed to build target: ${target}`);
168
191
  });
169
192
  }
170
193
  async buildTargets(targets) {
171
194
  const allTargets = targets.join(' ');
172
- const commandBuildTarget = `build ${allTargets} --show_result=${targets.length}`;
195
+ const commandBuildTarget = `build ${allTargets} ${this.stableExecArgs()} --show_result=${targets.length}`;
173
196
  return await this.spawnCommand(commandBuildTarget, 'inherit').catch(() => {
174
197
  throw new errors_1.CliError(`Failed to build targets: ${targets.join(' ')}`);
175
198
  });
176
199
  }
177
200
  async runTarget(target, extraArgs = '') {
178
- const commandBuildTarget = `run ${target} ${extraArgs}`;
201
+ const commandBuildTarget = `run ${target} ${this.stableExecArgs()} ${extraArgs}`;
179
202
  return await this.spawnCommand(commandBuildTarget, 'inherit').catch(() => {
180
203
  throw new errors_1.CliError(`Failed to run target: ${target}`);
181
204
  });
@@ -193,7 +216,7 @@ class BazelClient {
193
216
  }
194
217
  async testTargets(targets, extraArgs = '') {
195
218
  const targetsString = targets.join(' ');
196
- const commandTestTarget = `test ${targetsString} ${extraArgs}`;
219
+ const commandTestTarget = `test ${targetsString} ${this.stableExecArgs()} ${extraArgs}`;
197
220
  return await this.spawnCommand(commandTestTarget, 'inherit', extraArgs).catch(() => {
198
221
  throw new errors_1.CliError(`Failed to test targets: ${targetsString}`);
199
222
  });
@@ -203,6 +226,12 @@ class BazelClient {
203
226
  const { returnCode: returnCode, stdout: versionInfo, stderr: error, } = await this.runCommand(commandBazelInfoVersion);
204
227
  return [returnCode, versionInfo.trim(), String(error)];
205
228
  }
229
+ stableExecArgs() {
230
+ if (this.stableExecArgsCache === undefined) {
231
+ this.stableExecArgsCache = bazelrcDefinesStableExec() ? constants_1.STABLE_EXEC_BUILD_FLAGS.join(' ') : '';
232
+ }
233
+ return this.stableExecArgsCache;
234
+ }
206
235
  async runCommandWithLinesOutput(command) {
207
236
  const { stdout: outputStrings } = await this.runCommand(command);
208
237
  return outputStrings.split('\n').filter(output => output.length > 0);
@@ -18,7 +18,7 @@ function makeArgsBuilder(nestedBuilder) {
18
18
  return yargs => {
19
19
  yargs
20
20
  .positional('platform', {
21
- describe: 'Platform to build the library or application for: <ios|android>',
21
+ describe: 'Platform to build for: <ios|android|macos|cli|web>',
22
22
  type: 'string',
23
23
  choices: constants_1.VALID_PLATFORMS,
24
24
  coerce: arg => {
@@ -26,7 +26,7 @@ function makeArgsBuilder(nestedBuilder) {
26
26
  },
27
27
  })
28
28
  .option('build_config', {
29
- describe: 'Specifiy whether the application or library should be built in release or debug mode',
29
+ describe: 'Specifiy whether the target should be built in release or debug mode',
30
30
  type: 'string',
31
31
  choices: ['debug', 'release'],
32
32
  default: 'debug',
@@ -83,6 +83,9 @@ function getApplicationTargetTagForPlatform(platform) {
83
83
  case constants_1.PLATFORM.CLI: {
84
84
  return constants_1.CLI_BAZEL_APPLICATION_TAG;
85
85
  }
86
+ case constants_1.PLATFORM.WEB: {
87
+ return constants_1.WEB_BAZEL_APPLICATION_TAG;
88
+ }
86
89
  }
87
90
  }
88
91
  function getExportedLibraryTargetTagForPlatform(platform) {
@@ -102,6 +105,9 @@ function getExportedLibraryTargetTagForPlatform(platform) {
102
105
  case constants_1.PLATFORM.CLI: {
103
106
  throw new errors_1.CliError('Exported library is not supported for CLI platform');
104
107
  }
108
+ case constants_1.PLATFORM.WEB: {
109
+ return constants_1.WEB_EXPORTED_LIBRARY_TAG;
110
+ }
105
111
  }
106
112
  }
107
113
  function applicationExtensionForPlatform(platform) {
@@ -121,6 +127,9 @@ function applicationExtensionForPlatform(platform) {
121
127
  case constants_1.PLATFORM.CLI: {
122
128
  return '';
123
129
  }
130
+ case constants_1.PLATFORM.WEB: {
131
+ return '.zip';
132
+ }
124
133
  }
125
134
  }
126
135
  function exportedLibraryExtensionForPlatform(platform) {
@@ -140,6 +149,9 @@ function exportedLibraryExtensionForPlatform(platform) {
140
149
  case constants_1.PLATFORM.CLI: {
141
150
  return '.zip';
142
151
  }
152
+ case constants_1.PLATFORM.WEB: {
153
+ return '.zip';
154
+ }
143
155
  }
144
156
  }
145
157
  async function getOutputFilePath(bazel, expectedExtension, target, bazelArgs = '') {
@@ -203,11 +215,17 @@ function resolveBazelBuildArgs(platform, buildConfig, architectures, forDevice,
203
215
  else if (platform === constants_1.PLATFORM.LINUX) {
204
216
  allArgs.push(...constants_1.LINUX_BUILD_FLAGS);
205
217
  }
218
+ else if (platform === constants_1.PLATFORM.WEB) {
219
+ allArgs.push(...constants_1.WEB_BUILD_FLAGS);
220
+ }
206
221
  if (platform === constants_1.PLATFORM.ANDROID) {
207
222
  allArgs.push(...constants_1.ANDROID_BUILD_FLAGS);
208
223
  for (const architecture of architectures) {
209
224
  allArgs.push(...androidBuildFlagsForArchitecture(architecture));
210
225
  }
226
+ if (architectures.length > 0) {
227
+ allArgs.push((0, constants_1.androidPlatformsFlag)(architectures));
228
+ }
211
229
  }
212
230
  if (additionalBazelArgs) {
213
231
  allArgs.push(additionalBazelArgs);
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isDeviceBuild = isDeviceBuild;
3
4
  exports.getBuildInfo = getBuildInfo;
4
5
  const tslib_1 = require("tslib");
5
6
  const separator_1 = tslib_1.__importDefault(require("inquirer/lib/objects/separator"));
@@ -29,9 +30,12 @@ async function getDeviceChoice(platform) {
29
30
  choices.push(...availableDevices.map(device => ({ name: device, value: device })));
30
31
  return await (0, cliUtils_1.getUserChoice)(choices, 'Please select a device to perform the install:');
31
32
  }
33
+ function isDeviceBuild(simulator) {
34
+ return simulator === false;
35
+ }
32
36
  async function getBuildInfo(argv, bazel, checkDevice) {
33
37
  const platform = argv.getArgument('platform');
34
- const forDevice = !!argv.getArgument('simulator');
38
+ const forDevice = isDeviceBuild(argv.getArgument('simulator'));
35
39
  let selectedDevice;
36
40
  let architectures = constants_1.ALL_ARCHITECTURES;
37
41
  if (platform === constants_1.PLATFORM.ANDROID) {
@@ -0,0 +1,350 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChromiumDevToolsConnection = exports.ChromiumDevToolsProtocolError = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const node_crypto_1 = tslib_1.__importDefault(require("node:crypto"));
6
+ const node_http_1 = tslib_1.__importDefault(require("node:http"));
7
+ const node_util_1 = require("node:util");
8
+ const loopbackHost_1 = require("./loopbackHost");
9
+ const WEBSOCKET_ACCEPT_SUFFIX = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
10
+ const MAX_WEBSOCKET_FRAME_BYTES = 16 * 1024 * 1024;
11
+ const MAX_WEBSOCKET_RECEIVE_BYTES = MAX_WEBSOCKET_FRAME_BYTES + 10;
12
+ const FATAL_UTF8_DECODER = new node_util_1.TextDecoder('utf8', { fatal: true });
13
+ class ChromiumDevToolsProtocolError extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = 'ChromiumDevToolsProtocolError';
17
+ }
18
+ }
19
+ exports.ChromiumDevToolsProtocolError = ChromiumDevToolsProtocolError;
20
+ function encodeWebSocketFrame(opcode, payload) {
21
+ const mask = node_crypto_1.default.randomBytes(4);
22
+ let header;
23
+ if (payload.length < 126) {
24
+ header = Buffer.alloc(6);
25
+ header[1] = 0x80 | payload.length;
26
+ mask.copy(header, 2);
27
+ }
28
+ else if (payload.length <= 0xff_ff) {
29
+ header = Buffer.alloc(8);
30
+ header[1] = 0x80 | 126;
31
+ header.writeUInt16BE(payload.length, 2);
32
+ mask.copy(header, 4);
33
+ }
34
+ else {
35
+ header = Buffer.alloc(14);
36
+ header[1] = 0x80 | 127;
37
+ header.writeBigUInt64BE(BigInt(payload.length), 2);
38
+ mask.copy(header, 10);
39
+ }
40
+ header[0] = 0x80 | opcode;
41
+ const maskedPayload = Buffer.from(payload);
42
+ for (let index = 0; index < maskedPayload.length; index += 1) {
43
+ maskedPayload[index] = (maskedPayload[index] ?? 0) ^ (mask[index % mask.length] ?? 0);
44
+ }
45
+ return Buffer.concat([header, maskedPayload]);
46
+ }
47
+ function encodeWebSocketTextFrame(text) {
48
+ return encodeWebSocketFrame(0x01, Buffer.from(text, 'utf8'));
49
+ }
50
+ class ChromiumDevToolsConnection {
51
+ socket;
52
+ closeListeners = new Set();
53
+ eventListeners = new Set();
54
+ pending = new Map();
55
+ closedError = null;
56
+ nextCommandId = 0;
57
+ receiveBuffer = Buffer.alloc(0);
58
+ constructor(socket, initialData) {
59
+ this.socket = socket;
60
+ socket.on('data', this.handleData);
61
+ socket.on('close', this.handleClose);
62
+ socket.on('error', this.handleError);
63
+ if (initialData.length > 0) {
64
+ this.handleData(initialData);
65
+ }
66
+ }
67
+ static async connect(webSocketUrl, timeoutMs) {
68
+ const url = new URL(webSocketUrl);
69
+ if (url.protocol !== 'ws:' || !(0, loopbackHost_1.isLoopbackHost)(url.hostname) || url.username || url.password) {
70
+ throw new Error('Chromium DevTools inspection only allows unauthenticated loopback WebSocket targets.');
71
+ }
72
+ const key = node_crypto_1.default.randomBytes(16).toString('base64');
73
+ const expectedAccept = node_crypto_1.default.createHash('sha1').update(`${key}${WEBSOCKET_ACCEPT_SUFFIX}`).digest('base64');
74
+ const hostname = url.hostname === '[::1]' ? '::1' : url.hostname;
75
+ return await new Promise((resolve, reject) => {
76
+ let settled = false;
77
+ const request = node_http_1.default.request({
78
+ headers: {
79
+ Connection: 'Upgrade',
80
+ Host: url.host,
81
+ 'Sec-WebSocket-Key': key,
82
+ 'Sec-WebSocket-Version': '13',
83
+ Upgrade: 'websocket',
84
+ },
85
+ hostname,
86
+ method: 'GET',
87
+ path: `${url.pathname}${url.search}`,
88
+ port: url.port ? Number.parseInt(url.port, 10) : 80,
89
+ });
90
+ const timer = setTimeout(() => {
91
+ fail(new Error('Timed out connecting to the Chromium DevTools target.'));
92
+ }, timeoutMs);
93
+ function finish() {
94
+ if (settled)
95
+ return false;
96
+ settled = true;
97
+ clearTimeout(timer);
98
+ return true;
99
+ }
100
+ function fail(error) {
101
+ if (!finish())
102
+ return;
103
+ request.destroy();
104
+ reject(error);
105
+ }
106
+ request.once('upgrade', (response, socket, head) => {
107
+ if (response.headers['sec-websocket-accept'] !== expectedAccept) {
108
+ socket.destroy();
109
+ fail(new Error('The Chromium DevTools WebSocket handshake returned an invalid accept key.'));
110
+ return;
111
+ }
112
+ if (finish()) {
113
+ resolve(new ChromiumDevToolsConnection(socket, head));
114
+ }
115
+ else {
116
+ socket.destroy();
117
+ }
118
+ });
119
+ request.once('response', response => {
120
+ response.resume();
121
+ fail(new Error(`Chromium DevTools WebSocket upgrade returned HTTP ${String(response.statusCode)}.`));
122
+ });
123
+ request.once('error', fail);
124
+ request.end();
125
+ });
126
+ }
127
+ async call(method, params, timeoutMs) {
128
+ if (this.closedError)
129
+ throw this.closedError;
130
+ const id = ++this.nextCommandId;
131
+ return await new Promise((resolve, reject) => {
132
+ const timer = setTimeout(() => {
133
+ this.pending.delete(id);
134
+ reject(new Error(`Timeout waiting for the Chromium DevTools ${method} response.`));
135
+ }, timeoutMs);
136
+ this.pending.set(id, { reject, resolve, timer });
137
+ try {
138
+ this.socket.write(encodeWebSocketTextFrame(JSON.stringify({ id, method, params })));
139
+ }
140
+ catch (error) {
141
+ clearTimeout(timer);
142
+ this.pending.delete(id);
143
+ reject(error instanceof Error ? error : new Error(`Could not send the Chromium DevTools ${method} request.`));
144
+ }
145
+ });
146
+ }
147
+ onClose(listener) {
148
+ if (this.closedError) {
149
+ listener(this.closedError);
150
+ return () => { };
151
+ }
152
+ this.closeListeners.add(listener);
153
+ return () => {
154
+ this.closeListeners.delete(listener);
155
+ };
156
+ }
157
+ onEvent(listener) {
158
+ if (this.closedError)
159
+ throw this.closedError;
160
+ this.eventListeners.add(listener);
161
+ return () => {
162
+ this.eventListeners.delete(listener);
163
+ };
164
+ }
165
+ close() {
166
+ this.failConnection(new Error('The Chromium DevTools WebSocket closed.'));
167
+ }
168
+ handleData = (chunk) => {
169
+ if (this.closedError)
170
+ return;
171
+ if (chunk.length > MAX_WEBSOCKET_RECEIVE_BYTES - this.receiveBuffer.length) {
172
+ this.failConnection(new Error(`Chromium DevTools exceeded the ${MAX_WEBSOCKET_RECEIVE_BYTES} byte receive buffer limit.`));
173
+ return;
174
+ }
175
+ this.receiveBuffer = Buffer.concat([this.receiveBuffer, chunk]);
176
+ while (this.receiveBuffer.length >= 2) {
177
+ const firstByte = this.receiveBuffer.readUInt8(0);
178
+ const secondByte = this.receiveBuffer.readUInt8(1);
179
+ const finalFrame = (firstByte & 0x80) !== 0;
180
+ const opcode = firstByte & 0x0f;
181
+ if ((firstByte & 0x70) !== 0) {
182
+ this.failConnection(new Error('Chromium DevTools returned a WebSocket frame with reserved bits set.'));
183
+ return;
184
+ }
185
+ if ((secondByte & 0x80) !== 0) {
186
+ this.failConnection(new Error('Chromium DevTools servers must not mask WebSocket frames.'));
187
+ return;
188
+ }
189
+ let payloadLength = secondByte & 0x7f;
190
+ let offset = 2;
191
+ if (payloadLength === 126) {
192
+ if (this.receiveBuffer.length < 4)
193
+ return;
194
+ payloadLength = this.receiveBuffer.readUInt16BE(2);
195
+ offset = 4;
196
+ }
197
+ else if (payloadLength === 127) {
198
+ if (this.receiveBuffer.length < 10)
199
+ return;
200
+ const length = this.receiveBuffer.readBigUInt64BE(2);
201
+ if (length > BigInt(MAX_WEBSOCKET_FRAME_BYTES)) {
202
+ this.failConnection(new Error(`Chromium DevTools announced a frame larger than ${MAX_WEBSOCKET_FRAME_BYTES} bytes.`));
203
+ return;
204
+ }
205
+ payloadLength = Number(length);
206
+ offset = 10;
207
+ }
208
+ if (payloadLength > MAX_WEBSOCKET_FRAME_BYTES) {
209
+ this.failConnection(new Error(`Chromium DevTools announced a frame larger than ${MAX_WEBSOCKET_FRAME_BYTES} bytes.`));
210
+ return;
211
+ }
212
+ const controlFrame = opcode >= 0x08;
213
+ if (controlFrame && payloadLength > 125) {
214
+ this.failConnection(new Error('Chromium DevTools returned an oversized WebSocket control frame.'));
215
+ return;
216
+ }
217
+ if (!finalFrame) {
218
+ this.failConnection(new Error('Chromium DevTools fragmented WebSocket frames are not supported.'));
219
+ return;
220
+ }
221
+ const totalLength = offset + payloadLength;
222
+ if (this.receiveBuffer.length < totalLength)
223
+ return;
224
+ const payload = this.receiveBuffer.subarray(offset, totalLength);
225
+ this.receiveBuffer = this.receiveBuffer.subarray(totalLength);
226
+ switch (opcode) {
227
+ case 0x01:
228
+ case 0x02: {
229
+ this.handleMessage(payload);
230
+ break;
231
+ }
232
+ case 0x08: {
233
+ this.failConnection(new Error('The Chromium DevTools WebSocket closed by the target.'));
234
+ return;
235
+ }
236
+ case 0x09: {
237
+ try {
238
+ this.socket.write(encodeWebSocketFrame(0x0a, payload));
239
+ }
240
+ catch (error) {
241
+ this.failConnection(error instanceof Error ? error : new Error('Could not answer the Chromium DevTools WebSocket ping.'));
242
+ return;
243
+ }
244
+ break;
245
+ }
246
+ case 0x0a: {
247
+ break;
248
+ }
249
+ default: {
250
+ this.failConnection(new Error(`Chromium DevTools returned unsupported WebSocket opcode ${opcode}.`));
251
+ return;
252
+ }
253
+ }
254
+ }
255
+ };
256
+ handleMessage(payload) {
257
+ let text;
258
+ try {
259
+ text = FATAL_UTF8_DECODER.decode(payload);
260
+ }
261
+ catch {
262
+ this.failConnection(new Error('Chromium DevTools returned malformed UTF-8.'));
263
+ return;
264
+ }
265
+ let parsed;
266
+ try {
267
+ parsed = JSON.parse(text);
268
+ }
269
+ catch {
270
+ this.failConnection(new Error('Chromium DevTools returned malformed JSON.'));
271
+ return;
272
+ }
273
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
274
+ this.failConnection(new Error('Chromium DevTools returned a non-object protocol message.'));
275
+ return;
276
+ }
277
+ const response = parsed;
278
+ if (response.id === undefined) {
279
+ if (typeof response.method !== 'string' || response.method.length === 0 || response.method.length > 256) {
280
+ this.failConnection(new Error('Chromium DevTools returned a malformed protocol event.'));
281
+ return;
282
+ }
283
+ const params = response.params;
284
+ if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) {
285
+ this.failConnection(new Error('Chromium DevTools returned an event with invalid parameters.'));
286
+ return;
287
+ }
288
+ const event = {
289
+ method: response.method,
290
+ params: params ?? {},
291
+ };
292
+ for (const listener of Array.from(this.eventListeners)) {
293
+ try {
294
+ listener(event);
295
+ }
296
+ catch (error) {
297
+ console.warn(`[Valdi DevTools] A Chromium ${response.method} event listener failed.`, error);
298
+ }
299
+ }
300
+ return;
301
+ }
302
+ if (!Number.isInteger(response.id)) {
303
+ this.failConnection(new Error('Chromium DevTools returned a response with a non-numeric command id.'));
304
+ return;
305
+ }
306
+ const command = this.pending.get(response.id);
307
+ if (!command)
308
+ return;
309
+ this.pending.delete(response.id);
310
+ clearTimeout(command.timer);
311
+ if (response.error) {
312
+ command.reject(new ChromiumDevToolsProtocolError(response.error.message ?? 'The Chromium DevTools target rejected the request.'));
313
+ return;
314
+ }
315
+ command.resolve(response.result);
316
+ }
317
+ handleClose = () => {
318
+ this.failConnection(new Error('The Chromium DevTools WebSocket closed.'));
319
+ };
320
+ handleError = (error) => {
321
+ this.failConnection(error);
322
+ };
323
+ failConnection(error) {
324
+ if (this.closedError)
325
+ return;
326
+ this.closedError = error;
327
+ this.receiveBuffer = Buffer.alloc(0);
328
+ this.rejectPending(error);
329
+ this.eventListeners.clear();
330
+ for (const listener of Array.from(this.closeListeners)) {
331
+ try {
332
+ listener(error);
333
+ }
334
+ catch (listenerError) {
335
+ console.warn('[Valdi DevTools] A Chromium close listener failed.', listenerError);
336
+ }
337
+ }
338
+ this.closeListeners.clear();
339
+ if (!this.socket.destroyed)
340
+ this.socket.destroy();
341
+ }
342
+ rejectPending(error) {
343
+ for (const command of this.pending.values()) {
344
+ clearTimeout(command.timer);
345
+ command.reject(error);
346
+ }
347
+ this.pending.clear();
348
+ }
349
+ }
350
+ exports.ChromiumDevToolsConnection = ChromiumDevToolsConnection;
@@ -35,13 +35,13 @@ function spawnCliCommand(command, cwd, stdioMode, quiet, rejectOnFailure) {
35
35
  child.stdout?.on('data', (data) => {
36
36
  stdout += data.toString();
37
37
  if (!quiet) {
38
- process.stdout.write(stdout);
38
+ process.stdout.write(data);
39
39
  }
40
40
  });
41
41
  child.stderr?.on('data', (data) => {
42
42
  stderr += data.toString();
43
43
  if (!quiet) {
44
- process.stderr.write(stderr);
44
+ process.stderr.write(data);
45
45
  }
46
46
  });
47
47
  child.on('close', code => {