-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
924 lines (821 loc) · 29 KB
/
server.js
File metadata and controls
924 lines (821 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import process from "node:process";
import { randomUUID } from "node:crypto";
import { spawnSync } from "node:child_process";
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
import { CliError, normalizeError } from "./errors.js";
import { createRuntimeScript } from "./runtime-script.js";
import {
buildSessionCapabilities,
getSessionEndpoint,
normalizeBrowserName,
normalizeEngine,
normalizeTransport,
resolveTimeoutMs,
} from "./session-model.js";
import { ensureSessionDir, removeSessionFiles, writeMetadata, writeRuntime } from "./session-store.js";
const require = createRequire(import.meta.url);
function resolveLocalPackage(packageName) {
try {
return require.resolve(packageName, { paths: [process.cwd()] });
} catch {
return null;
}
}
function resolveGlobalPackage(packageName) {
const npmExecutable = process.platform === "win32" ? "npm.cmd" : "npm";
const result = spawnSync(npmExecutable, ["root", "-g"], {
encoding: "utf8",
windowsHide: true,
});
if (result.status !== 0) {
return null;
}
const globalRoot = result.stdout.trim();
if (!globalRoot) {
return null;
}
try {
return require.resolve(packageName, { paths: [globalRoot] });
} catch {
return null;
}
}
async function loadPlaywright() {
const envPath = process.env.RDT_PLAYWRIGHT_PATH;
const candidates = [
() => {
const resolved = resolveLocalPackage("playwright");
if (!resolved) {
throw new Error("skip");
}
return import(pathToFileURL(resolved).href).then((loaded) => ({
loaded,
source: "local-playwright",
resolvedPath: resolved,
}));
},
() => {
const resolved = resolveLocalPackage("playwright-core");
if (!resolved) {
throw new Error("skip");
}
return import(pathToFileURL(resolved).href).then((loaded) => ({
loaded,
source: "local-playwright-core",
resolvedPath: resolved,
}));
},
() => {
if (!envPath) {
throw new Error("skip");
}
return import(pathToFileURL(envPath).href).then((loaded) => ({
loaded,
source: "env-path",
resolvedPath: envPath,
}));
},
() => {
const resolved = resolveGlobalPackage("playwright");
if (!resolved) {
throw new Error("skip");
}
return import(pathToFileURL(resolved).href).then((loaded) => ({
loaded,
source: "global-playwright",
resolvedPath: resolved,
}));
},
() => {
const resolved = resolveGlobalPackage("playwright-core");
if (!resolved) {
throw new Error("skip");
}
return import(pathToFileURL(resolved).href).then((loaded) => ({
loaded,
source: "global-playwright-core",
resolvedPath: resolved,
}));
},
];
for (const candidate of candidates) {
try {
const resolved = await candidate();
if (resolved?.loaded?.chromium) {
return resolved;
}
} catch {}
}
try {
const resolved = resolveLocalPackage("playwright");
const loaded = await import("playwright");
return {
loaded,
source: "local-playwright",
resolvedPath: resolved || "playwright",
};
} catch (error) {
throw new CliError(
'Playwright runtime was not found. Install `playwright` locally, install it globally, or set `RDT_PLAYWRIGHT_PATH` to a resolvable module entry.',
{ code: "missing-playwright" },
);
}
}
function buildHelperImportTarget(resolvedPath) {
if (!resolvedPath || resolvedPath === "playwright" || resolvedPath === "playwright-core") {
return null;
}
try {
return pathToFileURL(resolvedPath).href;
} catch {
return null;
}
}
function checkExternalNodePlaywrightImport() {
const scriptPath = path.join(os.tmpdir(), `rdt-playwright-check-${randomUUID()}.mjs`);
const scriptContents = `import("playwright").then(() => {
process.stdout.write(JSON.stringify({ ok: true }) + "\\n");
}).catch((error) => {
process.stderr.write(JSON.stringify({
ok: false,
code: error?.code || null,
message: error?.message || String(error),
}) + "\\n");
process.exit(1);
});\n`;
try {
fs.writeFileSync(scriptPath, scriptContents, "utf8");
const result = spawnSync(process.execPath, [scriptPath], {
encoding: "utf8",
windowsHide: true,
});
if (result.status === 0) {
return {
ok: true,
status: "ok",
mode: "tmp-script",
};
}
let details = null;
try {
details = JSON.parse(result.stderr.trim().split("\n").pop() || "{}");
} catch {}
return {
ok: false,
status: details?.code === "ERR_MODULE_NOT_FOUND" ? "missing-package" : "resolution-mismatch",
mode: "tmp-script",
code: details?.code || null,
message: details?.message || result.stderr.trim() || result.stdout.trim() || null,
};
} finally {
try {
fs.unlinkSync(scriptPath);
} catch {}
}
}
function unwrapRuntimeResult(result) {
if (result?.__rdtError) {
throw new CliError(result.message, {
code: result.code,
details: result.details,
});
}
return result;
}
function parseServerArgv(argv) {
const options = {};
for (let index = 0; index < argv.length; index += 1) {
const token = argv[index];
if (!token.startsWith("--")) {
continue;
}
const [, rawKey, inlineValue] = token.match(/^--([^=]+)(?:=(.*))?$/) ?? [];
const key = rawKey.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
if (inlineValue !== undefined) {
options[key] = inlineValue;
continue;
}
const next = argv[index + 1];
if (!next || next.startsWith("--")) {
options[key] = true;
continue;
}
options[key] = next;
index += 1;
}
return options;
}
async function findTargetPage(browser, targetUrl) {
for (const context of browser.contexts()) {
for (const page of context.pages()) {
if (!targetUrl || page.url().includes(targetUrl)) {
return page;
}
}
}
return null;
}
function resolveBrowserType(playwright, browserName, transport) {
const normalized = normalizeBrowserName(browserName, transport);
const browserType = playwright[normalized];
if (!browserType) {
throw new CliError(`Playwright runtime does not provide browser: ${normalized}`, {
code: "unsupported-browser",
});
}
return { browserName: normalized, browserType };
}
function resolveContextOptions(playwright, options) {
const contextOptions = {};
if (options.device) {
const device = playwright.devices?.[String(options.device)];
if (!device) {
throw new CliError(`Unknown Playwright device: ${options.device}`, {
code: "invalid-device",
});
}
Object.assign(contextOptions, device);
}
if (options.storageState) {
contextOptions.storageState = String(options.storageState);
}
return contextOptions;
}
class SessionServer {
constructor(options) {
this.options = options;
this.sessionName = options.sessionName;
this.secret = options.secret;
this.transport = normalizeTransport(options.transport ?? options.mode);
this.browserName = normalizeBrowserName(options.browser, this.transport);
this.enginePreference = normalizeEngine(options.engine);
this.timeoutMs = resolveTimeoutMs(options);
this.endpoint = getSessionEndpoint(this.transport, options);
this.persistent = false;
this.browser = null;
this.context = null;
this.page = null;
this.server = null;
this.playwrightResolution = {
source: "unresolved",
resolvedPath: null,
};
}
async start() {
await this.initializeBrowser();
await this.ensureReactSettled();
this.server = http.createServer((request, response) => {
this.handleRequest(request, response).catch((error) => {
const normalized = normalizeError(error);
response.writeHead(500, { "content-type": "application/json" });
response.end(
JSON.stringify({
error: {
code: normalized.code,
message: normalized.message,
},
}),
);
});
});
await new Promise((resolve) => {
this.server.listen(0, "127.0.0.1", resolve);
});
const address = this.server.address();
const port = typeof address === "object" && address ? address.port : null;
const runtime = await this.status();
await writeMetadata(this.sessionName, {
sessionName: this.sessionName,
pid: process.pid,
port,
secret: this.secret,
transport: this.transport,
browserName: this.browserName,
enginePreference: this.enginePreference,
endpoint: this.endpoint,
persistent: this.persistent,
createdAt: new Date().toISOString(),
});
await writeRuntime(this.sessionName, runtime);
}
async initializeBrowser() {
const playwrightRuntime = await loadPlaywright();
const playwright = playwrightRuntime.loaded;
this.playwrightResolution = {
source: playwrightRuntime.source,
resolvedPath: playwrightRuntime.resolvedPath,
};
const runtimeScript = createRuntimeScript();
const contextOptions = resolveContextOptions(playwright, this.options);
if (this.transport === "open") {
const { browserType } = resolveBrowserType(playwright, this.browserName, this.transport);
const launchOptions = {
headless: this.options.headless !== "false",
channel: this.options.channel ? String(this.options.channel) : undefined,
};
if (this.options.userDataDir) {
this.context = await browserType.launchPersistentContext(String(this.options.userDataDir), {
...launchOptions,
...contextOptions,
});
this.persistent = true;
this.browser = this.context.browser();
} else {
this.browser = await browserType.launch(launchOptions);
this.context = await this.browser.newContext(contextOptions);
}
this.applyTimeouts(this.context);
await this.context.addInitScript({ content: runtimeScript });
this.page = this.context.pages()[0] ?? await this.context.newPage();
await this.page.goto(this.options.url, {
waitUntil: "load",
timeout: this.timeoutMs,
});
return;
}
if (this.transport === "connect") {
const { browserType } = resolveBrowserType(playwright, this.browserName, this.transport);
try {
this.browser = await browserType.connect(String(this.options.wsEndpoint));
} catch (error) {
throw new CliError(`Failed to connect to Playwright endpoint: ${error.message}`, {
code: "connect-failed",
});
}
this.page = await findTargetPage(this.browser, this.options.targetUrl);
if (!this.page) {
throw new CliError("No matching page found for connect mode.", {
code: "page-not-found",
});
}
this.context = this.page.context();
this.applyTimeouts(this.context);
await this.context.addInitScript({ content: runtimeScript });
await this.page.reload({
waitUntil: "load",
timeout: this.timeoutMs,
});
return;
}
if (this.transport === "attach") {
try {
this.browser = await playwright.chromium.connectOverCDP(String(this.options.cdpUrl));
} catch (error) {
throw new CliError(`Failed to attach to CDP endpoint: ${error.message}`, {
code: "cdp-attach-failed",
});
}
this.page = await findTargetPage(this.browser, this.options.targetUrl);
if (!this.page) {
throw new CliError("No matching page found for attach mode.", {
code: "page-not-found",
});
}
this.context = this.page.context();
this.applyTimeouts(this.context);
await this.context.addInitScript({ content: runtimeScript });
await this.page.reload({
waitUntil: "load",
timeout: this.timeoutMs,
});
return;
}
throw new CliError(`Unsupported transport: ${this.transport}`, { code: "unsupported-transport" });
}
applyTimeouts(context) {
if (!this.timeoutMs) {
return;
}
context.setDefaultTimeout(this.timeoutMs);
context.setDefaultNavigationTimeout(this.timeoutMs);
}
async ensureReactSettled() {
const timeoutMs = 5000;
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
const snapshot = await this.collectTree();
if (snapshot.reactDetected) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
async collectTree() {
return this.page.evaluate((preferredEngine) => window.__RDT_CLI_RUNTIME__.collectTree(preferredEngine), this.enginePreference);
}
async peekTree() {
return this.page.evaluate((preferredEngine) => window.__RDT_CLI_RUNTIME__.peekTree(preferredEngine), this.enginePreference);
}
async getEngineInfo() {
return this.page.evaluate((preferredEngine) => window.__RDT_CLI_RUNTIME__.getEngineInfo(preferredEngine), this.enginePreference);
}
async status() {
const tree = await this.peekTree();
const engineInfo = await this.getEngineInfo();
return {
sessionName: this.sessionName,
transport: this.transport,
browserName: this.browserName,
enginePreference: this.enginePreference,
selectedEngine: engineInfo.selectedEngine,
availableEngines: engineInfo.availableEngines,
recommendedEngine: engineInfo.recommendedEngine,
engineFallback: engineInfo.engineFallback,
endpoint: this.endpoint,
persistent: this.persistent,
target: this.page.url(),
reactDetected: tree.reactDetected,
roots: tree.roots,
nodeCount: tree.nodes.length,
title: await this.page.title(),
capabilities: buildSessionCapabilities({
transport: this.transport,
persistent: this.persistent,
}),
};
}
async doctor() {
const runtimeDoctor = unwrapRuntimeResult(await this.page.evaluate(
(preferredEngine) => window.__RDT_CLI_RUNTIME__.doctor(preferredEngine),
this.enginePreference,
));
const externalImport = checkExternalNodePlaywrightImport();
const runtimeWarnings = runtimeDoctor.runtimeWarnings.slice();
let helperScriptWarning = null;
const helperImportTarget = buildHelperImportTarget(this.playwrightResolution.resolvedPath);
const helperImportExample = helperImportTarget
? `const playwright = await import(${JSON.stringify(helperImportTarget)});`
: null;
if (!externalImport.ok) {
helperScriptWarning = helperImportTarget
? "rdt can resolve Playwright for its own session, but standalone Node helper scripts may fail to import `playwright`. Use helperImportTarget from this doctor response, or set RDT_PLAYWRIGHT_PATH to a resolvable module entry."
: "rdt can resolve Playwright for its own session, but standalone Node helper scripts may fail to import `playwright`. Run helper code from the repo, or set RDT_PLAYWRIGHT_PATH to a resolvable module entry.";
runtimeWarnings.push(helperScriptWarning);
}
const checks = {
...runtimeDoctor.checks,
interaction: {
status: this.page ? "ok" : "failed",
hasPageTarget: Boolean(this.page),
supportsBuiltInInteract: Boolean(this.page),
},
playwrightRuntime: {
status: this.playwrightResolution.source === "unresolved" ? "failed" : "ok",
source: this.playwrightResolution.source,
resolvedPath: this.playwrightResolution.resolvedPath,
},
externalNodeImport: {
status: externalImport.status,
canImportPlaywright: externalImport.ok,
mode: externalImport.mode,
code: externalImport.code || null,
message: externalImport.message || null,
},
};
const statuses = Object.values(checks).map((check) => check.status);
let status = "ok";
if (statuses.includes("failed")) {
status = "failed";
} else if (statuses.includes("partial") || statuses.includes("degraded") || runtimeWarnings.length) {
status = "partial";
}
return {
sessionName: this.sessionName,
transport: this.transport,
browserName: this.browserName,
enginePreference: this.enginePreference,
availableEngines: runtimeDoctor.availableEngines,
selectedEngine: runtimeDoctor.selectedEngine,
recommendedEngine: runtimeDoctor.recommendedEngine,
engineFallback: runtimeDoctor.engineFallback,
engineReasons: runtimeDoctor.engineReasons,
devtoolsCapabilities: runtimeDoctor.devtoolsCapabilities,
sourceCapability: runtimeDoctor.sourceCapability,
target: this.page.url(),
status,
observationLevel: "observed",
limitations: runtimeDoctor.limitations.concat([
"external helper scripts may not resolve Playwright the same way as rdt",
]),
runtimeWarnings,
checks,
rdtPlaywrightResolution: {
source: this.playwrightResolution.source,
resolvedPath: this.playwrightResolution.resolvedPath,
},
helperImportTarget,
helperImportExample,
externalNodeCanImportPlaywright: externalImport.ok,
externalNodeImportCheck: externalImport.status,
helperScriptWarning,
recommendedWorkflow: runtimeDoctor.recommendedWorkflow || [
"run session doctor before profiling or scripted interactions",
"prefer built-in interact commands over ad hoc Playwright helper scripts",
"capture snapshotId with tree get before node search/inspect/highlight/source",
"use profiler commits, commit, ranked, flamegraph, and compare for follow-up analysis",
],
recommendedProfilerWorkflow: runtimeDoctor.recommendedProfilerWorkflow || [],
recommendedCommitSelection: runtimeDoctor.recommendedCommitSelection || [],
unsafeConclusions: runtimeDoctor.unsafeConclusions || [
"all matching nodes rerendered because a commit happened",
"external helper scripts will resolve Playwright exactly like rdt does",
],
helperStrategy: externalImport.ok ? "standalone-helper-or-interact" : "prefer-built-in-interact-or-helperImportTarget",
};
}
async ensureInteractivePage() {
if (!this.page) {
throw new CliError("The current session does not have an interactive page target.", {
code: "page-not-found",
});
}
return this.page;
}
async isProfilerActive() {
const page = await this.ensureInteractivePage();
try {
return await page.evaluate(() => Boolean(window.__RDT_CLI_RUNTIME__?.profilerSummary?.().active));
} catch {
return false;
}
}
async clickLocator(locator, timeoutMs) {
if (!await this.isProfilerActive()) {
await locator.click({ timeout: timeoutMs, noWaitAfter: true });
return "playwright";
}
await locator.waitFor({ state: "visible", timeout: timeoutMs });
await locator.scrollIntoViewIfNeeded({ timeout: timeoutMs });
const clicked = await locator.evaluate((element) => {
const ariaDisabled = element.getAttribute?.("aria-disabled");
const disabled = typeof element.matches === "function" ? element.matches(":disabled") : false;
if (disabled || ariaDisabled === "true") {
return false;
}
if (typeof element.click === "function") {
element.click();
return true;
}
element.dispatchEvent(new MouseEvent("click", {
bubbles: true,
cancelable: true,
composed: true,
view: window,
}));
return true;
});
if (!clicked) {
throw new CliError("Target element is disabled.", { code: "disabled-target" });
}
return "dom-click";
}
async interact(command, payload) {
const page = await this.ensureInteractivePage();
const timeoutMs = payload.timeoutMs ? Number(payload.timeoutMs) : this.timeoutMs;
if (command === "wait") {
const ms = Number(payload.ms);
await page.waitForTimeout(ms);
return {
observationLevel: "observed",
limitations: [],
runtimeWarnings: [],
action: "wait",
ok: true,
waitedMs: ms,
};
}
const selector = payload.selector ? String(payload.selector) : null;
const locator = selector ? page.locator(selector).first() : null;
if (locator) {
await locator.waitFor({ state: "attached", timeout: timeoutMs });
}
const target = selector
? await locator.evaluate((element) => ({
tagName: element.tagName.toLowerCase(),
id: element.id || null,
className: element.className || null,
textPreview: element.textContent ? element.textContent.slice(0, 80) : null,
}))
: null;
let delivery = command;
const runtimeWarnings = [];
if (command === "click") {
delivery = await this.clickLocator(locator, timeoutMs);
} else if (command === "type") {
await locator.focus({ timeout: timeoutMs });
await locator.fill(String(payload.text), { timeout: timeoutMs });
delivery = "fill";
} else if (command === "press") {
if (locator) {
await locator.focus({ timeout: timeoutMs });
}
await page.keyboard.press(String(payload.key));
delivery = "keyboard";
} else {
throw new CliError(`Unsupported interact action: ${command}`, { code: "unsupported-action" });
}
runtimeWarnings.push("Interact actions confirm dispatch only; verify post-action UI state with follow-up commands when profiling or large rerenders are active.");
if (delivery === "dom-click") {
runtimeWarnings.push("Profiler was active, so click used a DOM fallback instead of Playwright pointer input.");
}
return {
observationLevel: "observed",
limitations: ["selector-based interaction targets the first matching element only"],
runtimeWarnings,
action: command,
ok: true,
delivery,
selector,
target,
key: payload.key ? String(payload.key) : null,
textLength: payload.text != null ? String(payload.text).length : null,
};
}
async ensureReactDetected() {
const tree = await this.peekTree();
if (!tree.reactDetected) {
throw new CliError("The current page does not expose a React fiber tree.", {
code: "not-react-app",
});
}
return tree;
}
async handleRequest(request, response) {
if (request.method !== "POST" || request.url !== "/command") {
response.writeHead(404);
response.end();
return;
}
if (request.headers["x-rdt-session-secret"] !== this.secret) {
response.writeHead(403, { "content-type": "application/json" });
response.end(JSON.stringify({ error: { code: "forbidden", message: "Invalid session secret." } }));
return;
}
const body = await new Promise((resolve, reject) => {
let data = "";
request.setEncoding("utf8");
request.on("data", (chunk) => {
data += chunk;
});
request.on("end", () => resolve(data));
request.on("error", reject);
});
const { action, payload } = JSON.parse(body || "{}");
const result = await this.execute(action, payload || {});
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ ok: true, result }));
if (action !== "session.close") {
this.refreshRuntime().catch(() => {});
}
}
async refreshRuntime() {
await writeRuntime(this.sessionName, await this.status());
}
async execute(action, payload) {
switch (action) {
case "session.status":
return this.status();
case "session.doctor":
return this.doctor();
case "session.close":
return this.close();
case "tree.get":
return this.collectTree();
case "node.inspect":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ nodeId, snapshotId, commitId }) => window.__RDT_CLI_RUNTIME__.inspectNode(nodeId, snapshotId, commitId),
{ ...payload, preferredEngine: this.enginePreference },
));
case "node.search":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ query, snapshotId, preferredEngine }) => window.__RDT_CLI_RUNTIME__.searchNodes(query, snapshotId, preferredEngine),
{ ...payload, preferredEngine: this.enginePreference },
));
case "node.highlight":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ nodeId, snapshotId, preferredEngine }) => window.__RDT_CLI_RUNTIME__.highlightNode(nodeId, snapshotId, preferredEngine),
{ ...payload, preferredEngine: this.enginePreference },
));
case "node.pick":
await this.ensureReactDetected();
return this.page.evaluate(
({ timeoutMs, preferredEngine }) => window.__RDT_CLI_RUNTIME__.pickNode(timeoutMs, preferredEngine),
{ timeoutMs: payload.timeoutMs ?? 30000, preferredEngine: this.enginePreference },
);
case "interact.click":
return this.interact("click", payload);
case "interact.type":
return this.interact("type", payload);
case "interact.press":
return this.interact("press", payload);
case "interact.wait":
return this.interact("wait", payload);
case "profiler.start":
await this.ensureReactDetected();
return this.page.evaluate(
({ profileId, preferredEngine }) => window.__RDT_CLI_RUNTIME__.startProfiler(profileId, preferredEngine),
{ profileId: payload.profileId, preferredEngine: this.enginePreference },
);
case "profiler.stop":
await this.ensureReactDetected();
return this.page.evaluate(() => window.__RDT_CLI_RUNTIME__.stopProfiler());
case "profiler.export":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ profileId }) => window.__RDT_CLI_RUNTIME__.exportProfiler(profileId),
payload,
));
case "profiler.profile":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ profileId }) => window.__RDT_CLI_RUNTIME__.profilerProfile(profileId),
payload,
));
case "profiler.summary":
await this.ensureReactDetected();
return this.page.evaluate(() => window.__RDT_CLI_RUNTIME__.profilerSummary());
case "profiler.commits":
await this.ensureReactDetected();
return this.page.evaluate(() => window.__RDT_CLI_RUNTIME__.profilerCommits());
case "profiler.commit":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ commitId }) => window.__RDT_CLI_RUNTIME__.profilerCommit(commitId),
payload,
));
case "profiler.ranked":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ commitId, limit }) => window.__RDT_CLI_RUNTIME__.profilerRanked(commitId, limit),
payload,
));
case "profiler.flamegraph":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(
({ commitId }) => window.__RDT_CLI_RUNTIME__.profilerFlamegraph(commitId),
payload,
));
case "source.reveal":
await this.ensureReactDetected();
return unwrapRuntimeResult(await this.page.evaluate(({ nodeId, snapshotId, commitId, preferredEngine }) => {
const node = window.__RDT_CLI_RUNTIME__.inspectNode(nodeId, snapshotId, commitId, preferredEngine);
return node ? node.source : null;
}, { ...payload, preferredEngine: this.enginePreference }));
default:
throw new CliError(`Unsupported action: ${action}`, { code: "unsupported-action" });
}
}
async close() {
const result = { closed: true, sessionName: this.sessionName };
setTimeout(async () => {
await this.dispose();
process.exit(0);
}, 50);
return result;
}
async dispose() {
await removeSessionFiles(this.sessionName);
if (this.server) {
await new Promise((resolve) => this.server.close(resolve));
}
if (this.browser) {
await this.browser.close();
}
}
}
async function main() {
const options = parseServerArgv(process.argv.slice(2));
const sessionName = options.sessionName;
const secret = options.secret || randomUUID();
if (!sessionName) {
throw new CliError("Missing --session-name for server bootstrap.", { code: "missing-session-name" });
}
await ensureSessionDir(sessionName);
const server = new SessionServer({
...options,
sessionName,
secret,
});
process.on("SIGINT", async () => {
await server.dispose();
process.exit(0);
});
process.on("SIGTERM", async () => {
await server.dispose();
process.exit(0);
});
await server.start();
}
main().catch(async (error) => {
const message = error?.stack ?? error?.message ?? String(error);
process.stderr.write(`${message}\n`);
process.exit(1);
});