@snap/valdi 1.1.5 → 1.2.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 (82) hide show
  1. package/.metadata/.bazelrc.template +9 -3
  2. package/.metadata/MODULE.bazel.template +112 -3
  3. package/.metadata/bzl/patches/rules_python/1.9.0/BUILD.bazel.template +1 -0
  4. package/.metadata/bzl/patches/rules_python/1.9.0/remove_setuptools_spaces.patch.template +96 -0
  5. package/README.md +35 -1
  6. package/bundled-skills/registry.json +2 -1
  7. package/bundled-skills/skills/valdi-animations/skill.md +49 -0
  8. package/bundled-skills/skills/valdi-async/skill.md +3 -2
  9. package/bundled-skills/skills/valdi-bazel/skill.md +2 -6
  10. package/bundled-skills/skills/valdi-compiler/skill.md +4 -4
  11. package/bundled-skills/skills/valdi-cpp-runtime/skill.md +18 -0
  12. package/bundled-skills/skills/valdi-error-handling/skill.md +1 -1
  13. package/bundled-skills/skills/valdi-gestures/skill.md +3 -3
  14. package/bundled-skills/skills/valdi-migrate/skill.md +2 -1
  15. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +4 -4
  16. package/bundled-skills/skills/valdi-mock-to-module/skill.md +9 -6
  17. package/bundled-skills/skills/valdi-overview/skill.md +2 -1
  18. package/bundled-skills/skills/valdi-perf/skill.md +121 -5
  19. package/bundled-skills/skills/valdi-pr-review/skill.md +189 -0
  20. package/bundled-skills/skills/valdi-profile/skill.md +5 -3
  21. package/bundled-skills/skills/valdi-setup/skill.md +3 -6
  22. package/bundled-skills/skills/valdi-testing/skill.md +1 -1
  23. package/bundled-skills/skills/valdi-tsx/skill.md +47 -11
  24. package/debugger/README.md +356 -0
  25. package/debugger/debugger-actions.js +373 -0
  26. package/debugger/debugger-api.js +225 -0
  27. package/debugger/debugger-bootstrap.js +295 -0
  28. package/debugger/debugger-model.js +790 -0
  29. package/debugger/debugger-performance.js +573 -0
  30. package/debugger/debugger-preview-html.js +676 -0
  31. package/debugger/debugger-providers.js +389 -0
  32. package/debugger/debugger-render.js +529 -0
  33. package/debugger/debugger-runtime.js +387 -0
  34. package/debugger/debugger-session.js +188 -0
  35. package/debugger/debugger-settings.js +209 -0
  36. package/debugger/debugger-state.js +221 -0
  37. package/debugger/debugger-tree-model.js +539 -0
  38. package/debugger/debugger.css +1865 -0
  39. package/debugger/devtools-panel.css +1318 -0
  40. package/debugger/devtools-panel.html +273 -0
  41. package/debugger/devtools-panel.js +3329 -0
  42. package/debugger/index.html +279 -0
  43. package/dist/commands/bootstrap.js +6 -5
  44. package/dist/commands/build.js +6 -0
  45. package/dist/commands/debugger.js +163 -0
  46. package/dist/commands/doctor.js +5 -125
  47. package/dist/commands/inspect.js +5 -2
  48. package/dist/commands/inspect_commands/input.js +176 -0
  49. package/dist/commands/inspect_commands/snapshot.js +1 -1
  50. package/dist/commands/inspect_commands/tree.js +1 -1
  51. package/dist/commands/install.js +6 -0
  52. package/dist/commands/projectsync.js +15 -0
  53. package/dist/commands/webHotreload.js +31 -0
  54. package/dist/core/constants.js +26 -7
  55. package/dist/debugger/chromiumConsole.js +279 -0
  56. package/dist/debugger/inputClient.js +473 -0
  57. package/dist/debugger/server.js +3801 -0
  58. package/dist/debugger/targetRegistry.js +436 -0
  59. package/dist/debugger/webPreviewPerformance.js +864 -0
  60. package/dist/index.js +0 -0
  61. package/dist/setup/DevSetupHelper.js +0 -3
  62. package/dist/setup/linuxSetup.js +0 -14
  63. package/dist/setup/macOSSetup.js +1 -2
  64. package/dist/utils/BazelClient.js +34 -5
  65. package/dist/utils/applicationUtils.js +18 -0
  66. package/dist/utils/chromiumDevToolsClient.js +350 -0
  67. package/dist/utils/daemonClient.js +364 -44
  68. package/dist/utils/hermesClient.js +82 -176
  69. package/dist/utils/linuxDistro.js +0 -21
  70. package/dist/utils/loopbackHost.js +14 -0
  71. package/dist/utils/owlCdpClient.js +282 -0
  72. package/dist/utils/owlDevToolsExtension.js +142 -0
  73. package/dist/utils/skillsAdapters.js +40 -14
  74. package/dist/utils/stringUtils.js +13 -1
  75. package/package.json +4 -2
  76. package/dist/commands/inspect_commands/snapshot.spec.js +0 -105
  77. package/dist/core/packageFiles.spec.js +0 -29
  78. package/dist/preview/previewGenerator.spec.js +0 -203
  79. package/dist/preview/viewModelParser.spec.js +0 -171
  80. package/dist/utils/linuxDistro.spec.js +0 -170
  81. package/dist/utils/skillsAdapters.spec.js +0 -60
  82. package/dist/utils/stringUtils.spec.js +0 -81
package/dist/index.js CHANGED
File without changes
@@ -93,9 +93,6 @@ class DevSetupHelper {
93
93
  console.log(' 3. Run `valdi doctor` to verify your setup');
94
94
  console.log(' 4. Create your first project with `valdi bootstrap`');
95
95
  }
96
- async setupGitLfs() {
97
- await this.runShell('Initializing git-lfs', ['git lfs install']);
98
- }
99
96
  async setupShellAutoComplete() {
100
97
  const rcFile = this.getRcFile();
101
98
  if (!rcFile) {
@@ -42,7 +42,6 @@ async function linuxSetup() {
42
42
  console.log((0, logUtils_1.wrapInColor)('Unable to detect Linux distribution.', constants_1.ANSI_COLORS.YELLOW_COLOR));
43
43
  console.log((0, logUtils_1.wrapInColor)('Please manually install the following dependencies and re-run this command:', constants_1.ANSI_COLORS.YELLOW_COLOR));
44
44
  console.log(' - git');
45
- console.log(' - git-lfs');
46
45
  console.log(' - npm (Node.js)');
47
46
  console.log(' - openjdk-17-jdk (or equivalent Java 17 JDK)');
48
47
  console.log(' - watchman');
@@ -54,15 +53,6 @@ async function linuxSetup() {
54
53
  throw new Error('Unable to proceed with automatic setup on unknown Linux distribution');
55
54
  }
56
55
  const packageMappings = (0, linuxDistro_1.getCommonPackageMappings)();
57
- const repoSetupCommand = (0, linuxDistro_1.getGitLfsRepoSetupCommand)(distro);
58
- if (repoSetupCommand && (0, linuxDistro_1.needsGitLfsRepoSetup)(distro)) {
59
- try {
60
- await devSetup.runShell('Setting up git-lfs repository', [repoSetupCommand]);
61
- }
62
- catch {
63
- console.log((0, logUtils_1.wrapInColor)(`Warning: git-lfs repository setup failed. Will try to install git-lfs from standard repositories.`, constants_1.ANSI_COLORS.YELLOW_COLOR));
64
- }
65
- }
66
56
  const packagesToInstall = [];
67
57
  if (!(0, cliUtils_1.checkCommandExists)('npm')) {
68
58
  packagesToInstall.push((0, linuxDistro_1.getPackageName)(packageMappings['npm'], distro));
@@ -70,9 +60,6 @@ async function linuxSetup() {
70
60
  if (!(0, cliUtils_1.checkCommandExists)('java')) {
71
61
  packagesToInstall.push((0, linuxDistro_1.getPackageName)(packageMappings['openjdk-17'], distro));
72
62
  }
73
- if (!(0, cliUtils_1.checkCommandExists)('git-lfs')) {
74
- packagesToInstall.push((0, linuxDistro_1.getPackageName)(packageMappings['git-lfs'], distro));
75
- }
76
63
  if (!(0, cliUtils_1.checkCommandExists)('watchman')) {
77
64
  packagesToInstall.push((0, linuxDistro_1.getPackageName)(packageMappings['watchman'], distro));
78
65
  }
@@ -104,7 +91,6 @@ async function linuxSetup() {
104
91
  else {
105
92
  console.log((0, logUtils_1.wrapInColor)('All required packages are already installed.', constants_1.ANSI_COLORS.GREEN_COLOR));
106
93
  }
107
- await devSetup.setupGitLfs();
108
94
  await devSetup.setupShellAutoComplete();
109
95
  if (distro.type === linuxDistro_1.LinuxDistroType.DEBIAN) {
110
96
  const libtinfoInstalled = (0, cliUtils_1.checkCommandExists)('dpkg') &&
@@ -68,7 +68,7 @@ async function macOSSetup() {
68
68
  console.log('Note: Could not automatically configure Homebrew PATH in .zprofile');
69
69
  }
70
70
  }
71
- const packages = ['npm', 'bazelisk', 'openjdk@17', 'temurin', 'git-lfs', 'watchman', 'ios-webkit-debug-proxy', 'android-platform-tools'];
71
+ const packages = ['npm', 'bazelisk', 'openjdk@17', 'temurin', 'watchman', 'ios-webkit-debug-proxy', 'android-platform-tools'];
72
72
  const packagesToInstall = [];
73
73
  for (const pkg of packages) {
74
74
  try {
@@ -87,7 +87,6 @@ async function macOSSetup() {
87
87
  else {
88
88
  console.log('All Homebrew dependencies are already installed');
89
89
  }
90
- await devSetup.setupGitLfs();
91
90
  await devSetup.setupShellAutoComplete();
92
91
  const jdkSymlinkPath = '/Library/Java/JavaVirtualMachines/openjdk-17.jdk';
93
92
  const jdkSourcePath = '/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk';
@@ -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);
@@ -77,6 +77,9 @@ function getApplicationTargetTagForPlatform(platform) {
77
77
  case constants_1.PLATFORM.MACOS: {
78
78
  return constants_1.MACOS_BAZEL_APPLICATION_TAG;
79
79
  }
80
+ case constants_1.PLATFORM.LINUX: {
81
+ return constants_1.LINUX_BAZEL_APPLICATION_TAG;
82
+ }
80
83
  case constants_1.PLATFORM.CLI: {
81
84
  return constants_1.CLI_BAZEL_APPLICATION_TAG;
82
85
  }
@@ -93,6 +96,9 @@ function getExportedLibraryTargetTagForPlatform(platform) {
93
96
  case constants_1.PLATFORM.MACOS: {
94
97
  throw new errors_1.CliError('Exported library is not yet supported for macOS platform');
95
98
  }
99
+ case constants_1.PLATFORM.LINUX: {
100
+ throw new errors_1.CliError('Exported library is not yet supported for Linux platform');
101
+ }
96
102
  case constants_1.PLATFORM.CLI: {
97
103
  throw new errors_1.CliError('Exported library is not supported for CLI platform');
98
104
  }
@@ -109,6 +115,9 @@ function applicationExtensionForPlatform(platform) {
109
115
  case constants_1.PLATFORM.MACOS: {
110
116
  return '.zip';
111
117
  }
118
+ case constants_1.PLATFORM.LINUX: {
119
+ return '';
120
+ }
112
121
  case constants_1.PLATFORM.CLI: {
113
122
  return '';
114
123
  }
@@ -125,6 +134,9 @@ function exportedLibraryExtensionForPlatform(platform) {
125
134
  case constants_1.PLATFORM.MACOS: {
126
135
  return '.zip';
127
136
  }
137
+ case constants_1.PLATFORM.LINUX: {
138
+ return '.zip';
139
+ }
128
140
  case constants_1.PLATFORM.CLI: {
129
141
  return '.zip';
130
142
  }
@@ -188,11 +200,17 @@ function resolveBazelBuildArgs(platform, buildConfig, architectures, forDevice,
188
200
  else if (platform === constants_1.PLATFORM.MACOS) {
189
201
  allArgs.push(...constants_1.MACOS_BUILD_FLAGS);
190
202
  }
203
+ else if (platform === constants_1.PLATFORM.LINUX) {
204
+ allArgs.push(...constants_1.LINUX_BUILD_FLAGS);
205
+ }
191
206
  if (platform === constants_1.PLATFORM.ANDROID) {
192
207
  allArgs.push(...constants_1.ANDROID_BUILD_FLAGS);
193
208
  for (const architecture of architectures) {
194
209
  allArgs.push(...androidBuildFlagsForArchitecture(architecture));
195
210
  }
211
+ if (architectures.length > 0) {
212
+ allArgs.push((0, constants_1.androidPlatformsFlag)(architectures));
213
+ }
196
214
  }
197
215
  if (additionalBazelArgs) {
198
216
  allArgs.push(additionalBazelArgs);
@@ -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;