@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
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DaemonConnection = exports.DaemonMsgType = exports.DEFAULT_PORT = exports.MOBILE_PORT = exports.STANDALONE_PORT = void 0;
3
+ exports.DaemonConnection = exports.MAX_DAEMON_TRACE_PAYLOAD_BYTES = exports.MAX_DAEMON_PACKET_PAYLOAD_BYTES = exports.MAX_DAEMON_INNER_PAYLOAD_BYTES = exports.DaemonProtocolError = exports.DaemonMsgType = exports.DEFAULT_PORT = exports.MOBILE_PORT = exports.STANDALONE_PORT = void 0;
4
4
  exports.loadInspectConfig = loadInspectConfig;
5
5
  exports.saveInspectConfig = saveInspectConfig;
6
6
  exports.connectToDaemon = connectToDaemon;
@@ -18,6 +18,7 @@ exports.MOBILE_PORT = 13592;
18
18
  exports.DEFAULT_PORT = exports.MOBILE_PORT;
19
19
  var DaemonMsgType;
20
20
  (function (DaemonMsgType) {
21
+ DaemonMsgType[DaemonMsgType["ERROR_RESPONSE"] = -1] = "ERROR_RESPONSE";
21
22
  DaemonMsgType[DaemonMsgType["LIST_CONTEXTS_REQUEST"] = 2] = "LIST_CONTEXTS_REQUEST";
22
23
  DaemonMsgType[DaemonMsgType["LIST_CONTEXTS_RESPONSE"] = -2] = "LIST_CONTEXTS_RESPONSE";
23
24
  DaemonMsgType[DaemonMsgType["GET_CONTEXT_TREE_REQUEST"] = 3] = "GET_CONTEXT_TREE_REQUEST";
@@ -26,6 +27,14 @@ var DaemonMsgType;
26
27
  DaemonMsgType[DaemonMsgType["TAKE_ELEMENT_SNAPSHOT_RESPONSE"] = -4] = "TAKE_ELEMENT_SNAPSHOT_RESPONSE";
27
28
  DaemonMsgType[DaemonMsgType["DUMP_HEAP_REQUEST"] = 5] = "DUMP_HEAP_REQUEST";
28
29
  DaemonMsgType[DaemonMsgType["DUMP_HEAP_RESPONSE"] = -5] = "DUMP_HEAP_RESPONSE";
30
+ DaemonMsgType[DaemonMsgType["PERFORMANCE_TRACE_STATUS_REQUEST"] = 6] = "PERFORMANCE_TRACE_STATUS_REQUEST";
31
+ DaemonMsgType[DaemonMsgType["PERFORMANCE_TRACE_STATUS_RESPONSE"] = -6] = "PERFORMANCE_TRACE_STATUS_RESPONSE";
32
+ DaemonMsgType[DaemonMsgType["PERFORMANCE_TRACE_START_REQUEST"] = 7] = "PERFORMANCE_TRACE_START_REQUEST";
33
+ DaemonMsgType[DaemonMsgType["PERFORMANCE_TRACE_START_RESPONSE"] = -7] = "PERFORMANCE_TRACE_START_RESPONSE";
34
+ DaemonMsgType[DaemonMsgType["PERFORMANCE_TRACE_STOP_REQUEST"] = 8] = "PERFORMANCE_TRACE_STOP_REQUEST";
35
+ DaemonMsgType[DaemonMsgType["PERFORMANCE_TRACE_STOP_RESPONSE"] = -8] = "PERFORMANCE_TRACE_STOP_RESPONSE";
36
+ DaemonMsgType[DaemonMsgType["CUSTOM_REQUEST"] = 1000] = "CUSTOM_REQUEST";
37
+ DaemonMsgType[DaemonMsgType["CUSTOM_RESPONSE"] = -1000] = "CUSTOM_RESPONSE";
29
38
  })(DaemonMsgType || (exports.DaemonMsgType = DaemonMsgType = {}));
30
39
  const CONFIG_PATH = path.join(os.homedir(), '.valdi-inspect.json');
31
40
  function loadInspectConfig() {
@@ -39,21 +48,135 @@ function loadInspectConfig() {
39
48
  function saveInspectConfig(config) {
40
49
  fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
41
50
  }
51
+ class DaemonProtocolError extends Error {
52
+ constructor(message) {
53
+ super(message);
54
+ this.name = 'DaemonProtocolError';
55
+ }
56
+ }
57
+ exports.DaemonProtocolError = DaemonProtocolError;
42
58
  const MAGIC = Buffer.from([0x33, 0xc6, 0x00, 0x01]);
43
59
  const HEADER_SIZE = 8;
60
+ exports.MAX_DAEMON_INNER_PAYLOAD_BYTES = 64 * 1024 * 1024;
61
+ exports.MAX_DAEMON_PACKET_PAYLOAD_BYTES = 128 * 1024 * 1024;
62
+ exports.MAX_DAEMON_TRACE_PAYLOAD_BYTES = 4 * 1024 * 1024;
63
+ const MAX_DAEMON_BUFFERED_BYTES = HEADER_SIZE + exports.MAX_DAEMON_PACKET_PAYLOAD_BYTES;
44
64
  function encodePacket(json) {
45
- const payload = Buffer.from(JSON.stringify(json), 'utf8');
65
+ const serialized = JSON.stringify(json);
66
+ const payloadLength = Buffer.byteLength(serialized, 'utf8');
67
+ if (payloadLength > exports.MAX_DAEMON_PACKET_PAYLOAD_BYTES) {
68
+ throw new Error(`ValdiPacket payload exceeds the ${exports.MAX_DAEMON_PACKET_PAYLOAD_BYTES}-byte limit.`);
69
+ }
70
+ const payload = Buffer.from(serialized, 'utf8');
46
71
  const header = Buffer.alloc(8);
47
72
  MAGIC.copy(header, 0);
48
73
  header.writeUInt32LE(payload.length, 4);
49
74
  return Buffer.concat([header, payload]);
50
75
  }
51
76
  const DIRECT_CLIENT_ID = 1;
77
+ const ADB_FORWARD_REFRESH_INTERVAL_MS = 5000;
78
+ const adbForwardedAtByEndpoint = new Map();
79
+ const adbForwardRefreshByEndpoint = new Map();
80
+ const MAX_DAEMON_TRACE_EVENT_COUNT = 10_000;
81
+ const MAX_DAEMON_TRACE_NAME_BYTES = 2048;
82
+ const MAX_DAEMON_TRACE_CONTEXT_ID_BYTES = 4096;
83
+ const MAX_DAEMON_TRACE_ERROR_BYTES = 64 * 1024;
84
+ function isRecord(value) {
85
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
86
+ }
87
+ function isPerformanceTraceMessageType(value) {
88
+ return (value === DaemonMsgType.PERFORMANCE_TRACE_STATUS_REQUEST ||
89
+ value === DaemonMsgType.PERFORMANCE_TRACE_STATUS_RESPONSE ||
90
+ value === DaemonMsgType.PERFORMANCE_TRACE_START_REQUEST ||
91
+ value === DaemonMsgType.PERFORMANCE_TRACE_START_RESPONSE ||
92
+ value === DaemonMsgType.PERFORMANCE_TRACE_STOP_REQUEST ||
93
+ value === DaemonMsgType.PERFORMANCE_TRACE_STOP_RESPONSE);
94
+ }
95
+ function isPerformanceTraceRequestType(value) {
96
+ return (value === DaemonMsgType.PERFORMANCE_TRACE_STATUS_REQUEST ||
97
+ value === DaemonMsgType.PERFORMANCE_TRACE_START_REQUEST ||
98
+ value === DaemonMsgType.PERFORMANCE_TRACE_STOP_REQUEST);
99
+ }
100
+ function assertOptionalFiniteNumber(body, key) {
101
+ const value = body[key];
102
+ if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value))) {
103
+ throw new TypeError(`Valdi runtime trace response has an invalid ${key}.`);
104
+ }
105
+ }
106
+ function assertOptionalBoundedString(body, key, maximumBytes, allowEmpty) {
107
+ const value = body[key];
108
+ if (value !== undefined &&
109
+ (typeof value !== 'string' ||
110
+ (!allowEmpty && value.length === 0) ||
111
+ Buffer.byteLength(value, 'utf8') > maximumBytes)) {
112
+ throw new TypeError(`Valdi runtime trace response has an invalid ${key}.`);
113
+ }
114
+ }
115
+ function validatePerformanceTraceStatusBody(value) {
116
+ if (!isRecord(value)) {
117
+ throw new TypeError('Valdi runtime trace response body must be an object.');
118
+ }
119
+ for (const key of ['recording', 'completedRecordingAvailable', 'rendererTracingEnabled', 'tracingSupported']) {
120
+ if (typeof value[key] !== 'boolean') {
121
+ throw new TypeError(`Valdi runtime trace response has an invalid ${key}.`);
122
+ }
123
+ }
124
+ assertOptionalBoundedString(value, 'contextId', MAX_DAEMON_TRACE_CONTEXT_ID_BYTES, false);
125
+ assertOptionalBoundedString(value, 'completedContextId', MAX_DAEMON_TRACE_CONTEXT_ID_BYTES, false);
126
+ assertOptionalBoundedString(value, 'completionError', MAX_DAEMON_TRACE_ERROR_BYTES, true);
127
+ assertOptionalFiniteNumber(value, 'startedAtEpochMs');
128
+ assertOptionalFiniteNumber(value, 'elapsedMs');
129
+ if (value['recording'] && (typeof value['contextId'] !== 'string' || value['contextId'].length === 0)) {
130
+ throw new Error('Valdi runtime trace response is recording without a contextId.');
131
+ }
132
+ if (value['completedRecordingAvailable'] &&
133
+ (typeof value['completedContextId'] !== 'string' || value['completedContextId'].length === 0)) {
134
+ throw new Error('Valdi runtime trace response has a completed recording without a completedContextId.');
135
+ }
136
+ return value;
137
+ }
138
+ function validatePerformanceTraceStopBody(value) {
139
+ const status = validatePerformanceTraceStatusBody(value);
140
+ const body = status;
141
+ const traces = body['traces'];
142
+ if (!Array.isArray(traces) || traces.length > MAX_DAEMON_TRACE_EVENT_COUNT) {
143
+ throw new TypeError('Valdi runtime trace stop response has an invalid traces array.');
144
+ }
145
+ for (const trace of traces) {
146
+ if (!isRecord(trace) ||
147
+ typeof trace['trace'] !== 'string' ||
148
+ trace['trace'].length === 0 ||
149
+ Buffer.byteLength(trace['trace'], 'utf8') > MAX_DAEMON_TRACE_NAME_BYTES ||
150
+ typeof trace['startMicros'] !== 'number' ||
151
+ !Number.isSafeInteger(trace['startMicros']) ||
152
+ trace['startMicros'] < 0 ||
153
+ typeof trace['endMicros'] !== 'number' ||
154
+ !Number.isSafeInteger(trace['endMicros']) ||
155
+ trace['endMicros'] < trace['startMicros'] ||
156
+ typeof trace['threadId'] !== 'number' ||
157
+ !Number.isSafeInteger(trace['threadId']) ||
158
+ trace['threadId'] < 0) {
159
+ throw new TypeError('Valdi runtime trace stop response contains a malformed trace event.');
160
+ }
161
+ }
162
+ if (typeof body['traceEventCount'] !== 'number' ||
163
+ !Number.isSafeInteger(body['traceEventCount']) ||
164
+ body['traceEventCount'] < 0 ||
165
+ body['traceEventCount'] !== traces.length ||
166
+ typeof body['droppedTraceEventCount'] !== 'number' ||
167
+ !Number.isSafeInteger(body['droppedTraceEventCount']) ||
168
+ body['droppedTraceEventCount'] < 0 ||
169
+ typeof body['timedOut'] !== 'boolean') {
170
+ throw new TypeError('Valdi runtime trace stop response has invalid completion metadata.');
171
+ }
172
+ if (typeof body['contextId'] !== 'string' || body['contextId'].length === 0) {
173
+ throw new TypeError('Valdi runtime trace stop response has an invalid contextId.');
174
+ }
175
+ return value;
176
+ }
52
177
  class DaemonConnection {
53
178
  socket;
54
179
  recvBuf = Buffer.alloc(0);
55
- recvChunks = [];
56
- recvLen = 0;
57
180
  reqCounter = 0;
58
181
  msgCounter = 0;
59
182
  pendingRequests = new Map();
@@ -64,7 +187,7 @@ class DaemonConnection {
64
187
  this.socket = socket;
65
188
  socket.on('data', (data) => this.onData(data));
66
189
  socket.on('close', () => this.rejectAllPending(new Error('Connection closed unexpectedly')));
67
- socket.on('error', (err) => this.rejectAllPending(err));
190
+ socket.on('error', err => this.rejectAllPending(err));
68
191
  }
69
192
  rejectAllPending(err) {
70
193
  this.configureReady?.reject(err);
@@ -77,45 +200,59 @@ class DaemonConnection {
77
200
  this.payloadListeners.clear();
78
201
  }
79
202
  onData(chunk) {
80
- this.recvChunks.push(chunk);
81
- this.recvLen += chunk.length;
203
+ const bufferedLength = this.recvBuf.length + chunk.length;
204
+ if (bufferedLength > MAX_DAEMON_BUFFERED_BYTES) {
205
+ this.failProtocol(`ValdiPacket buffered data exceeds the ${MAX_DAEMON_BUFFERED_BYTES}-byte limit.`);
206
+ return;
207
+ }
208
+ this.recvBuf = this.recvBuf.length === 0 ? chunk : Buffer.concat([this.recvBuf, chunk], bufferedLength);
82
209
  this.drainBuffer();
83
210
  }
84
211
  drainBuffer() {
85
212
  for (;;) {
86
- if (this.recvLen < HEADER_SIZE)
213
+ if (this.recvBuf.length < HEADER_SIZE)
87
214
  break;
88
- if (this.recvBuf.length < this.recvLen) {
89
- this.recvBuf = Buffer.concat(this.recvChunks, this.recvLen);
90
- this.recvChunks = [this.recvBuf];
91
- }
92
215
  if (this.recvBuf[0] !== 0x33 ||
93
216
  this.recvBuf[1] !== 0xc6 ||
94
217
  this.recvBuf[2] !== 0x00 ||
95
218
  this.recvBuf[3] !== 0x01) {
96
- this.socket.destroy(new Error('ValdiPacket: bad magic'));
219
+ this.failProtocol('ValdiPacket: bad magic');
97
220
  break;
98
221
  }
99
222
  const payloadLen = this.recvBuf.readUInt32LE(4);
100
- if (this.recvLen < HEADER_SIZE + payloadLen)
223
+ if (payloadLen > exports.MAX_DAEMON_PACKET_PAYLOAD_BYTES) {
224
+ this.failProtocol(`ValdiPacket payload exceeds the ${exports.MAX_DAEMON_PACKET_PAYLOAD_BYTES}-byte limit.`);
225
+ break;
226
+ }
227
+ if (this.recvBuf.length < HEADER_SIZE + payloadLen)
101
228
  break;
102
229
  const raw = this.recvBuf.subarray(HEADER_SIZE, HEADER_SIZE + payloadLen).toString('utf8');
103
230
  const consumed = HEADER_SIZE + payloadLen;
104
231
  this.recvBuf = this.recvBuf.subarray(consumed);
105
- this.recvLen -= consumed;
106
- this.recvChunks = this.recvLen > 0 ? [this.recvBuf] : [];
107
232
  try {
108
- this.dispatchMessage(JSON.parse(raw));
233
+ const parsed = JSON.parse(raw);
234
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
235
+ throw new Error('ValdiPacket payload must be a JSON object.');
236
+ }
237
+ this.dispatchMessage(parsed);
109
238
  }
110
239
  catch {
240
+ this.failProtocol('ValdiPacket payload contains malformed JSON.');
241
+ break;
111
242
  }
112
243
  }
113
244
  }
245
+ failProtocol(message) {
246
+ const error = new Error(message);
247
+ this.recvBuf = Buffer.alloc(0);
248
+ this.rejectAllPending(error);
249
+ this.socket.destroy(error);
250
+ }
114
251
  dispatchMessage(msg) {
115
252
  if (msg['request']) {
116
253
  const req = msg['request'];
117
254
  const reqId = req['request_id'];
118
- const respKey = Object.keys(req).find((k) => k !== 'request_id');
255
+ const respKey = Object.keys(req).find(k => k !== 'request_id');
119
256
  if (respKey) {
120
257
  this.socket.write(encodePacket({ response: { [respKey]: {}, request_id: reqId } }));
121
258
  if (respKey === 'configure') {
@@ -130,15 +267,40 @@ class DaemonConnection {
130
267
  const fcp = req['forward_client_payload'];
131
268
  if (fcp) {
132
269
  try {
133
- const inner = JSON.parse(fcp['payload_string']);
134
- const msgId = String(inner['requestId']);
270
+ const payloadString = fcp['payload_string'];
271
+ if (typeof payloadString !== 'string') {
272
+ throw new TypeError('Valdi debugger inner payload must be a string.');
273
+ }
274
+ const payloadBytes = Buffer.byteLength(payloadString, 'utf8');
275
+ if (payloadBytes > exports.MAX_DAEMON_INNER_PAYLOAD_BYTES) {
276
+ this.failProtocol(`Valdi debugger inner payload exceeds the ${exports.MAX_DAEMON_INNER_PAYLOAD_BYTES}-byte limit.`);
277
+ return;
278
+ }
279
+ const parsed = JSON.parse(payloadString);
280
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
281
+ throw new Error('Valdi debugger inner payload must be a JSON object.');
282
+ }
283
+ const inner = parsed;
284
+ const requestId = inner['requestId'];
285
+ if (typeof requestId !== 'string' || requestId.length === 0) {
286
+ throw new TypeError('Valdi debugger inner payload must have a requestId.');
287
+ }
288
+ const msgId = requestId;
135
289
  const listener = this.payloadListeners.get(msgId);
290
+ const payloadLimit = listener?.maxPayloadBytes ?? exports.MAX_DAEMON_INNER_PAYLOAD_BYTES;
291
+ if (payloadBytes > payloadLimit ||
292
+ (isPerformanceTraceMessageType(inner['type']) && payloadBytes > exports.MAX_DAEMON_TRACE_PAYLOAD_BYTES)) {
293
+ this.failProtocol(`Valdi debugger performance trace payload exceeds the ${exports.MAX_DAEMON_TRACE_PAYLOAD_BYTES}-byte limit.`);
294
+ return;
295
+ }
136
296
  if (listener) {
137
297
  this.payloadListeners.delete(msgId);
138
298
  listener.resolve(inner);
139
299
  }
140
300
  }
141
301
  catch {
302
+ this.failProtocol('Valdi debugger inner payload is malformed.');
303
+ return;
142
304
  }
143
305
  }
144
306
  }
@@ -166,14 +328,20 @@ class DaemonConnection {
166
328
  return new Promise((resolve, reject) => {
167
329
  const timer = setTimeout(() => {
168
330
  this.pendingRequests.delete(reqId);
169
- reject(new errors_1.CliError(`Valdi daemon did not respond (port ${(this.socket.remotePort ?? '?')}).\n` +
331
+ reject(new errors_1.CliError(`Valdi daemon did not respond (port ${this.socket.remotePort ?? '?'}).\n` +
170
332
  `Is the hot-reloader actually running and connected?`));
171
333
  }, timeoutMs);
172
334
  this.pendingRequests.set(reqId, {
173
- resolve: (v) => { clearTimeout(timer); resolve(v); },
174
- reject: (e) => { clearTimeout(timer); reject(e); },
335
+ resolve: v => {
336
+ clearTimeout(timer);
337
+ resolve(v);
338
+ },
339
+ reject: e => {
340
+ clearTimeout(timer);
341
+ reject(e);
342
+ },
175
343
  });
176
- this.socket.write(encodePacket(envelope), (err) => {
344
+ this.socket.write(encodePacket(envelope), err => {
177
345
  if (err) {
178
346
  clearTimeout(timer);
179
347
  this.pendingRequests.delete(reqId);
@@ -186,6 +354,12 @@ class DaemonConnection {
186
354
  return String(++this.msgCounter);
187
355
  }
188
356
  configure() {
357
+ return this.configureWithTimeout(5000);
358
+ }
359
+ configureWithTimeout(timeoutMs) {
360
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 5000) {
361
+ return Promise.reject(new Error('Valdi daemon configure timeout must be between 1 and 5000 milliseconds.'));
362
+ }
189
363
  if (this.configureData)
190
364
  return Promise.resolve();
191
365
  return new Promise((resolve, reject) => {
@@ -193,10 +367,16 @@ class DaemonConnection {
193
367
  this.configureReady = null;
194
368
  reject(new errors_1.CliError(`Valdi daemon did not respond (port ${this.socket.remotePort ?? '?'}).\n` +
195
369
  `Is the hot-reloader actually running and connected?`));
196
- }, 5_000);
370
+ }, timeoutMs);
197
371
  this.configureReady = {
198
- resolve: () => { clearTimeout(timer); resolve(); },
199
- reject: (e) => { clearTimeout(timer); reject(e); },
372
+ resolve: () => {
373
+ clearTimeout(timer);
374
+ resolve();
375
+ },
376
+ reject: e => {
377
+ clearTimeout(timer);
378
+ reject(e);
379
+ },
200
380
  };
201
381
  });
202
382
  }
@@ -214,14 +394,27 @@ class DaemonConnection {
214
394
  async forwardAndWait(_clientId, msgType, body, timeoutMs = 15_000) {
215
395
  const msgId = this.nextMsgId();
216
396
  const payloadString = JSON.stringify({ type: msgType, requestId: msgId, body });
397
+ const maxPayloadBytes = isPerformanceTraceRequestType(msgType)
398
+ ? exports.MAX_DAEMON_TRACE_PAYLOAD_BYTES
399
+ : exports.MAX_DAEMON_INNER_PAYLOAD_BYTES;
400
+ if (Buffer.byteLength(payloadString, 'utf8') > maxPayloadBytes) {
401
+ throw new Error(`Valdi debugger request payload exceeds the ${maxPayloadBytes}-byte limit.`);
402
+ }
217
403
  const resultPromise = new Promise((resolve, reject) => {
218
404
  const timer = setTimeout(() => {
219
405
  this.payloadListeners.delete(msgId);
220
406
  reject(new Error('Timeout waiting for device response. Is the app running?'));
221
407
  }, timeoutMs);
222
408
  this.payloadListeners.set(msgId, {
223
- resolve: (v) => { clearTimeout(timer); resolve(v); },
224
- reject: (e) => { clearTimeout(timer); reject(e); },
409
+ maxPayloadBytes,
410
+ resolve: v => {
411
+ clearTimeout(timer);
412
+ resolve(v);
413
+ },
414
+ reject: e => {
415
+ clearTimeout(timer);
416
+ reject(e);
417
+ },
225
418
  });
226
419
  });
227
420
  this.socket.write(encodePacket({
@@ -231,7 +424,7 @@ class DaemonConnection {
231
424
  payload_string: payloadString,
232
425
  },
233
426
  },
234
- }), (err) => {
427
+ }), err => {
235
428
  if (err) {
236
429
  const listener = this.payloadListeners.get(msgId);
237
430
  if (listener) {
@@ -240,14 +433,38 @@ class DaemonConnection {
240
433
  }
241
434
  }
242
435
  });
243
- return resultPromise;
436
+ const response = await resultPromise;
437
+ if (response['requestId'] !== msgId) {
438
+ throw new Error('The Valdi runtime returned a debugger response with a mismatched requestId.');
439
+ }
440
+ if (response['type'] === DaemonMsgType.ERROR_RESPONSE) {
441
+ const body = response['body'];
442
+ const message = body !== null && typeof body === 'object' && !Array.isArray(body)
443
+ ? body['message']
444
+ : undefined;
445
+ throw new Error(message === undefined ? 'The Valdi runtime rejected the debugger request.' : String(message));
446
+ }
447
+ if (response['type'] !== -msgType) {
448
+ const message = `The Valdi runtime returned debugger response type ${String(response['type'])}; expected ${-msgType}.`;
449
+ if (msgType === DaemonMsgType.CUSTOM_REQUEST) {
450
+ throw new DaemonProtocolError(message);
451
+ }
452
+ throw new Error(message);
453
+ }
454
+ return response;
244
455
  }
245
456
  async listContexts(clientId) {
246
- const resp = await this.forwardAndWait(clientId, DaemonMsgType.LIST_CONTEXTS_REQUEST, {});
457
+ return await this.listContextsWithTimeout(clientId, 15_000);
458
+ }
459
+ async listContextsWithTimeout(clientId, timeoutMs) {
460
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.LIST_CONTEXTS_REQUEST, {}, timeoutMs);
247
461
  return (resp['body'] ?? []);
248
462
  }
249
- async getContextTree(clientId, contextId) {
250
- const resp = await this.forwardAndWait(clientId, DaemonMsgType.GET_CONTEXT_TREE_REQUEST, { id: contextId });
463
+ async getContextTree(clientId, contextId, includeComponentData) {
464
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.GET_CONTEXT_TREE_REQUEST, {
465
+ id: contextId,
466
+ includeComponentData,
467
+ });
251
468
  return resp['body'];
252
469
  }
253
470
  async takeSnapshot(clientId, elementId, contextId) {
@@ -261,21 +478,124 @@ class DaemonConnection {
261
478
  const resp = await this.forwardAndWait(clientId, DaemonMsgType.DUMP_HEAP_REQUEST, { performGC }, 60_000);
262
479
  return resp['body'];
263
480
  }
481
+ async performanceTraceStatus(clientId, body, timeoutMs) {
482
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.PERFORMANCE_TRACE_STATUS_REQUEST, body, timeoutMs);
483
+ return validatePerformanceTraceStatusBody(resp['body']);
484
+ }
485
+ async performanceTraceStart(clientId, body, timeoutMs) {
486
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.PERFORMANCE_TRACE_START_REQUEST, body, timeoutMs);
487
+ return validatePerformanceTraceStatusBody(resp['body']);
488
+ }
489
+ async performanceTraceStop(clientId, body, timeoutMs) {
490
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.PERFORMANCE_TRACE_STOP_REQUEST, body, timeoutMs);
491
+ return validatePerformanceTraceStopBody(resp['body']);
492
+ }
493
+ async customRequest(clientId, identifier, data, timeoutMs = 15_000) {
494
+ if (typeof identifier !== 'string' || identifier.trim().length === 0 || identifier.length > 128) {
495
+ throw new DaemonProtocolError('Custom debugger request identifiers must contain 1 to 128 characters.');
496
+ }
497
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
498
+ throw new DaemonProtocolError('Custom debugger request data must be an object.');
499
+ }
500
+ let serializedData;
501
+ try {
502
+ serializedData = JSON.stringify(data);
503
+ }
504
+ catch {
505
+ throw new DaemonProtocolError('Custom debugger request data must be JSON serializable.');
506
+ }
507
+ if (typeof serializedData !== 'string') {
508
+ throw new DaemonProtocolError('Custom debugger request data must be JSON serializable.');
509
+ }
510
+ if (Buffer.byteLength(serializedData, 'utf8') > 128 * 1024) {
511
+ throw new DaemonProtocolError('Custom debugger request data exceeds 128 KiB.');
512
+ }
513
+ const resp = await this.forwardAndWait(clientId, DaemonMsgType.CUSTOM_REQUEST, { identifier, data }, timeoutMs);
514
+ const body = resp['body'];
515
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
516
+ throw new DaemonProtocolError('The Valdi runtime returned a non-object custom debugger response body.');
517
+ }
518
+ const response = body;
519
+ if (typeof response['handled'] !== 'boolean') {
520
+ throw new DaemonProtocolError('The Valdi runtime custom debugger response requires a boolean handled field.');
521
+ }
522
+ const responseData = response['data'];
523
+ if (response['handled'] === true &&
524
+ (typeof responseData !== 'object' || responseData === null || Array.isArray(responseData))) {
525
+ throw new DaemonProtocolError('Handled custom debugger responses require object data.');
526
+ }
527
+ if (responseData !== undefined &&
528
+ (typeof responseData !== 'object' || responseData === null || Array.isArray(responseData))) {
529
+ throw new DaemonProtocolError('Custom debugger response data must be an object when present.');
530
+ }
531
+ if (responseData !== undefined) {
532
+ let serializedResponseData;
533
+ try {
534
+ serializedResponseData = JSON.stringify(responseData);
535
+ }
536
+ catch {
537
+ throw new DaemonProtocolError('Custom debugger response data must be JSON serializable.');
538
+ }
539
+ if (typeof serializedResponseData !== 'string') {
540
+ throw new DaemonProtocolError('Custom debugger response data must be JSON serializable.');
541
+ }
542
+ if (Buffer.byteLength(serializedResponseData, 'utf8') > 128 * 1024) {
543
+ throw new DaemonProtocolError('Custom debugger response data exceeds 128 KiB.');
544
+ }
545
+ }
546
+ return {
547
+ handled: response['handled'],
548
+ ...(responseData === undefined ? {} : { data: responseData }),
549
+ };
550
+ }
264
551
  close() {
265
552
  this.socket.destroy();
266
553
  }
267
554
  }
268
555
  exports.DaemonConnection = DaemonConnection;
269
- async function tryAdbForward(port) {
556
+ function adbForwardKey(endpoint) {
557
+ return `${endpoint.deviceId ?? ''}\0${endpoint.port.toString()}`;
558
+ }
559
+ async function tryAdbForward(endpoint) {
560
+ if (endpoint.deviceId !== undefined && !/^[\w.:-]{1,128}$/.test(endpoint.deviceId)) {
561
+ throw new errors_1.CliError('Android device serial contains unsupported characters.');
562
+ }
563
+ const key = adbForwardKey(endpoint);
564
+ const lastForwardedAt = adbForwardedAtByEndpoint.get(key);
565
+ if (lastForwardedAt !== undefined && Date.now() - lastForwardedAt < ADB_FORWARD_REFRESH_INTERVAL_MS)
566
+ return;
567
+ const pendingRefresh = adbForwardRefreshByEndpoint.get(key);
568
+ if (pendingRefresh) {
569
+ await pendingRefresh;
570
+ return;
571
+ }
572
+ const refresh = refreshAdbForward(endpoint, key);
573
+ adbForwardRefreshByEndpoint.set(key, refresh);
574
+ try {
575
+ await refresh;
576
+ }
577
+ finally {
578
+ if (adbForwardRefreshByEndpoint.get(key) === refresh)
579
+ adbForwardRefreshByEndpoint.delete(key);
580
+ }
581
+ }
582
+ async function refreshAdbForward(endpoint, key) {
270
583
  try {
271
- await (0, cliUtils_1.runCliCommand)(`adb forward tcp:${port} tcp:${port}`);
584
+ const deviceSelector = endpoint.deviceId === undefined ? '' : `-s ${endpoint.deviceId} `;
585
+ await (0, cliUtils_1.runCliCommand)(`adb ${deviceSelector}forward tcp:${endpoint.port} tcp:${endpoint.port}`);
586
+ adbForwardedAtByEndpoint.set(key, Date.now());
272
587
  }
273
588
  catch {
274
589
  }
275
590
  }
276
- async function connectToDaemon(port = exports.DEFAULT_PORT) {
277
- if (port !== exports.STANDALONE_PORT) {
278
- await tryAdbForward(port);
591
+ async function connectToDaemon(target) {
592
+ const resolvedTarget = target ?? exports.DEFAULT_PORT;
593
+ const endpoint = typeof resolvedTarget === 'number'
594
+ ? { autoForward: resolvedTarget !== exports.STANDALONE_PORT, port: resolvedTarget }
595
+ : resolvedTarget;
596
+ const port = endpoint.port;
597
+ if (endpoint.autoForward && port !== exports.STANDALONE_PORT) {
598
+ await tryAdbForward(endpoint);
279
599
  }
280
600
  return new Promise((resolve, reject) => {
281
601
  const socket = net.createConnection({ port, host: '127.0.0.1' });
@@ -305,7 +625,7 @@ async function resolveContextId(conn, clientId, contextIdOverride) {
305
625
  throw new errors_1.CliError('No contexts found on the connected device.');
306
626
  }
307
627
  if (contextIdOverride) {
308
- if (!contexts.some((c) => c.id === contextIdOverride)) {
628
+ if (!contexts.some(c => c.id === contextIdOverride)) {
309
629
  throw new errors_1.CliError(`Context "${contextIdOverride}" not found. Run "valdi inspect contexts" to see available contexts.`);
310
630
  }
311
631
  return contextIdOverride;
@@ -313,7 +633,7 @@ async function resolveContextId(conn, clientId, contextIdOverride) {
313
633
  if (contexts.length === 1) {
314
634
  return contexts[0].id;
315
635
  }
316
- return (0, cliUtils_1.getUserChoice)(contexts.map((c) => ({
636
+ return (0, cliUtils_1.getUserChoice)(contexts.map(c => ({
317
637
  name: `${c.rootComponentName} [${c.id}]`,
318
638
  value: c.id,
319
639
  })), 'Multiple contexts found. Select one:');
@@ -325,19 +645,19 @@ async function resolveClientId(conn, clientIdOverride) {
325
645
  'Make sure the Valdi app is running and connected to the hot-reloader.');
326
646
  }
327
647
  if (clientIdOverride) {
328
- if (!clients.some((c) => c.client_id === clientIdOverride)) {
648
+ if (!clients.some(c => c.client_id === clientIdOverride)) {
329
649
  throw new errors_1.CliError(`Client "${clientIdOverride}" not found. Run "valdi inspect devices" to see connected clients.`);
330
650
  }
331
651
  return clientIdOverride;
332
652
  }
333
653
  const config = loadInspectConfig();
334
- if (config.selectedClientId && clients.some((c) => c.client_id === config.selectedClientId)) {
654
+ if (config.selectedClientId && clients.some(c => c.client_id === config.selectedClientId)) {
335
655
  return config.selectedClientId;
336
656
  }
337
657
  if (clients.length === 1) {
338
658
  return clients[0].client_id;
339
659
  }
340
- return (0, cliUtils_1.getUserChoice)(clients.map((c) => ({
660
+ return (0, cliUtils_1.getUserChoice)(clients.map(c => ({
341
661
  name: `${c.application_id} (${c.platform}) [${c.client_id}]`,
342
662
  value: c.client_id,
343
663
  })), 'Multiple devices connected. Select one:');