|
| 1 | +/** |
| 2 | + * VS Code Evaluator - HTTP Client |
| 3 | + * |
| 4 | + * Connects to the VS Code test runner HTTP server and allows |
| 5 | + * executing functions with access to the VS Code API. |
| 6 | + * |
| 7 | + * Uses Playwright's internal API to access the Electron process, similar |
| 8 | + * to how vscode-test-playwright does it. |
| 9 | + */ |
| 10 | +import type { ChildProcess } from 'child_process'; |
| 11 | +import type { EventEmitter } from 'events'; |
| 12 | +import readline from 'readline'; |
| 13 | +import type { ElectronApplication } from '@playwright/test'; |
| 14 | +import { _electron } from '@playwright/test'; |
| 15 | + |
| 16 | +// Re-export vscode types for use in evaluate callbacks |
| 17 | +export type VSCode = typeof import('vscode'); |
| 18 | + |
| 19 | +interface InvokeRequest { |
| 20 | + fn: string; |
| 21 | + params?: unknown[]; |
| 22 | +} |
| 23 | + |
| 24 | +interface InvokeResponse { |
| 25 | + result?: unknown; |
| 26 | + error?: { message: string; stack?: string }; |
| 27 | +} |
| 28 | + |
| 29 | +// Internal Playwright API types |
| 30 | +interface ElectronAppImpl { |
| 31 | + _process: ChildProcess; |
| 32 | + _nodeConnection?: { |
| 33 | + _browserLogsCollector?: { |
| 34 | + recentLogs(): string[]; |
| 35 | + }; |
| 36 | + }; |
| 37 | +} |
| 38 | + |
| 39 | +export class VSCodeEvaluator { |
| 40 | + private serverUrl: string; |
| 41 | + |
| 42 | + private constructor(serverUrl: string) { |
| 43 | + this.serverUrl = serverUrl; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Connect to the VS Code test server using Playwright's internal API. |
| 48 | + * Uses the same approach as vscode-test-playwright to access the process. |
| 49 | + * |
| 50 | + * @param electronApp - The ElectronApplication from Playwright |
| 51 | + * @param timeout - Connection timeout in ms |
| 52 | + */ |
| 53 | + static async connect(electronApp: ElectronApplication, timeout = 30000): Promise<VSCodeEvaluator> { |
| 54 | + // Access Playwright's internal implementation to get the process |
| 55 | + // The _electron._connection.toImpl() method converts public API objects to internal implementations |
| 56 | + |
| 57 | + const connection = (_electron as any)._connection; |
| 58 | + const electronAppImpl = connection.toImpl(electronApp) as ElectronAppImpl; |
| 59 | + const process = electronAppImpl._process; |
| 60 | + |
| 61 | + // Check recent logs first (in case server already started) |
| 62 | + const vscodeTestServerRegExp = /VSCodeTestServer listening on (http:\/\/[^\s]+)/; |
| 63 | + const recentLogs = electronAppImpl._nodeConnection?._browserLogsCollector?.recentLogs() ?? []; |
| 64 | + let match = recentLogs.map((s: string) => s.match(vscodeTestServerRegExp)).find(Boolean) as |
| 65 | + | RegExpMatchArray |
| 66 | + | undefined; |
| 67 | + |
| 68 | + // If not found in recent logs, wait for it |
| 69 | + if (!match) { |
| 70 | + match = await this.waitForLine(process, vscodeTestServerRegExp, timeout); |
| 71 | + } |
| 72 | + |
| 73 | + const serverUrl = match[1]; |
| 74 | + return new VSCodeEvaluator(serverUrl); |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Wait for a line matching the regex in the process stderr. |
| 79 | + * Adapted from Playwright's electron.ts |
| 80 | + */ |
| 81 | + private static waitForLine(process: ChildProcess, regex: RegExp, timeout: number): Promise<RegExpMatchArray> { |
| 82 | + type Listener = { emitter: EventEmitter; eventName: string | symbol; handler: (...args: any[]) => void }; |
| 83 | + |
| 84 | + function addEventListener( |
| 85 | + emitter: EventEmitter, |
| 86 | + eventName: string | symbol, |
| 87 | + handler: (...args: any[]) => void, |
| 88 | + ): Listener { |
| 89 | + emitter.on(eventName, handler); |
| 90 | + return { emitter: emitter, eventName: eventName, handler: handler }; |
| 91 | + } |
| 92 | + |
| 93 | + function removeEventListeners(listeners: Listener[]) { |
| 94 | + for (const listener of listeners) { |
| 95 | + listener.emitter.removeListener(listener.eventName, listener.handler); |
| 96 | + } |
| 97 | + listeners.splice(0, listeners.length); |
| 98 | + } |
| 99 | + |
| 100 | + return new Promise((resolve, reject) => { |
| 101 | + const rl = readline.createInterface({ input: process.stderr! }); |
| 102 | + const failError = new Error('Process failed to launch!'); |
| 103 | + const timeoutError = new Error(`Timeout waiting for VSCodeTestServer (${timeout}ms)`); |
| 104 | + |
| 105 | + const listeners = [ |
| 106 | + addEventListener(rl, 'line', onLine), |
| 107 | + addEventListener(rl, 'close', () => reject(failError)), |
| 108 | + addEventListener(process, 'exit', () => reject(failError)), |
| 109 | + addEventListener(process, 'error', () => reject(failError)), |
| 110 | + ]; |
| 111 | + |
| 112 | + const timer = setTimeout(() => { |
| 113 | + cleanup(); |
| 114 | + reject(timeoutError); |
| 115 | + }, timeout); |
| 116 | + |
| 117 | + function onLine(line: string) { |
| 118 | + const match = line.match(regex); |
| 119 | + if (!match) return; |
| 120 | + cleanup(); |
| 121 | + resolve(match); |
| 122 | + } |
| 123 | + |
| 124 | + function cleanup() { |
| 125 | + clearTimeout(timer); |
| 126 | + removeEventListeners(listeners); |
| 127 | + } |
| 128 | + }); |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Evaluate a function in the VS Code Extension Host context. |
| 133 | + * The function receives the `vscode` module as its first argument. |
| 134 | + * |
| 135 | + * @example |
| 136 | + * ```ts |
| 137 | + * await evaluator.evaluate(vscode => { |
| 138 | + * vscode.commands.executeCommand('gitlens.showCommitGraph'); |
| 139 | + * }); |
| 140 | + * |
| 141 | + * const version = await evaluator.evaluate(vscode => vscode.version); |
| 142 | + * ``` |
| 143 | + */ |
| 144 | + evaluate<R>(fn: (vscode: VSCode) => R | Promise<R>): Promise<R>; |
| 145 | + evaluate<R, A>(fn: (vscode: VSCode, arg: A) => R | Promise<R>, arg: A): Promise<R>; |
| 146 | + async evaluate<R, A>(fn: (vscode: VSCode, arg?: A) => R | Promise<R>, arg?: A): Promise<R> { |
| 147 | + const params = arg !== undefined ? [arg] : []; |
| 148 | + |
| 149 | + const request: InvokeRequest = { |
| 150 | + fn: fn.toString(), |
| 151 | + params: params, |
| 152 | + }; |
| 153 | + |
| 154 | + const res = await fetch(`${this.serverUrl}/invoke`, { |
| 155 | + method: 'POST', |
| 156 | + headers: { 'Content-Type': 'application/json' }, |
| 157 | + body: JSON.stringify(request), |
| 158 | + }); |
| 159 | + |
| 160 | + const response = (await res.json()) as InvokeResponse; |
| 161 | + |
| 162 | + if (response.error) { |
| 163 | + const err = new Error(response.error.message); |
| 164 | + err.stack = response.error.stack; |
| 165 | + throw err; |
| 166 | + } |
| 167 | + |
| 168 | + return response.result as R; |
| 169 | + } |
| 170 | + |
| 171 | + /** |
| 172 | + * Close the connection (no-op for HTTP, kept for API compatibility). |
| 173 | + */ |
| 174 | + close(): void { |
| 175 | + // No-op for HTTP - each request is independent |
| 176 | + } |
| 177 | +} |
0 commit comments