-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathprogram.ts
More file actions
438 lines (390 loc) · 14.2 KB
/
program.ts
File metadata and controls
438 lines (390 loc) · 14.2 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
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable no-console */
/* eslint-disable no-restricted-properties */
import { execSync, spawn } from 'child_process';
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { createClientInfo, explicitSessionName, Registry, resolveSessionName } from './registry';
import { Session, renderResolvedConfig } from './session';
import { serverRegistry } from '../../serverRegistry';
import { minimist } from './minimist';
import type { Config } from '../mcp/config.d';
import type { ClientInfo, SessionFile } from './registry';
import type { BrowserDescriptor } from '../../serverRegistry';
import type { MinimistArgs } from './minimist';
type GlobalOptions = {
help?: boolean;
session?: string;
version?: boolean;
};
type OpenOptions = {
attach?: string;
browser?: string;
config?: string;
extension?: boolean;
headed?: boolean;
persistent?: boolean;
profile?: string;
};
const globalOptions: (keyof (GlobalOptions & OpenOptions))[] = [
'attach',
'browser',
'config',
'extension',
'headed',
'help',
'persistent',
'profile',
'session',
'version',
];
const booleanOptions: (keyof (GlobalOptions & OpenOptions & { all?: boolean }))[] = [
'all',
'help',
'version',
];
export async function program(options?: { embedderVersion?: string}) {
const clientInfo = createClientInfo();
const help = require('./help.json');
const argv = process.argv.slice(2);
const boolean = [...help.booleanOptions, ...booleanOptions];
const args: MinimistArgs = minimist(argv, { boolean, string: ['_'] });
// Normalize -s alias to --session
if (args.s) {
args.session = args.s;
delete args.s;
}
const commandName = args._?.[0];
if (args.version || args.v) {
console.log(options?.embedderVersion ?? clientInfo.version);
process.exit(0);
}
const command = commandName && help.commands[commandName];
if (args.help || args.h) {
if (command) {
console.log(command);
} else {
console.log('playwright-cli - run playwright mcp commands from terminal\n');
console.log(help.global);
}
process.exit(0);
}
if (!command) {
console.error(`Unknown command: ${commandName}\n`);
console.log(help.global);
process.exit(1);
}
const registry = await Registry.load();
const sessionName = resolveSessionName(args.session as string);
switch (commandName) {
case 'list': {
await listSessions(registry, clientInfo, !!args.all);
return;
}
case 'close-all': {
const entries = registry.entries(clientInfo);
for (const entry of entries)
await new Session(entry).stop(true);
return;
}
case 'delete-data': {
const entry = registry.entry(clientInfo, sessionName);
if (!entry) {
console.log(`No user data found for browser '${sessionName}'.`);
return;
}
await new Session(entry).deleteData();
return;
}
case 'kill-all': {
await killAllDaemons();
return;
}
case 'open': {
await startSession(sessionName, registry, clientInfo, args);
return;
}
case 'attach': {
const attachTarget = args._[1];
const attachSessionName = explicitSessionName(args.session as string) ?? attachTarget;
args.attach = attachTarget;
args.session = attachSessionName;
await startSession(attachSessionName, registry, clientInfo, args);
return;
}
case 'close':
const closeEntry = registry.entry(clientInfo, sessionName);
const session = closeEntry ? new Session(closeEntry) : undefined;
if (!session || !await session.canConnect()) {
console.log(`Browser '${sessionName}' is not open.`);
return;
}
await session.stop();
return;
case 'install':
await install(args);
return;
case 'install-browser':
await installBrowser();
return;
case 'show': {
const daemonScript = require.resolve('../dashboard/dashboardApp.js');
const child = spawn(process.execPath, [daemonScript], {
detached: true,
stdio: 'ignore',
});
child.unref();
return;
}
default: {
const entry = registry.entry(clientInfo, sessionName);
if (!entry) {
console.log(`The browser '${sessionName}' is not open, please run open first`);
console.log('');
console.log(` playwright-cli${sessionName !== 'default' ? ` -s=${sessionName}` : ''} open [params]`);
process.exit(1);
}
await runInSession(entry, clientInfo, args);
}
}
}
async function startSession(sessionName: string, registry: Registry, clientInfo: ClientInfo, args: MinimistArgs) {
const entry = registry.entry(clientInfo, sessionName);
if (entry)
await new Session(entry).stop(true);
await Session.startDaemon(clientInfo, args);
const newEntry = await registry.loadEntry(clientInfo, sessionName);
await runInSession(newEntry, clientInfo, args);
}
async function runInSession(entry: SessionFile, clientInfo: ClientInfo, args: MinimistArgs) {
for (const globalOption of globalOptions)
delete args[globalOption];
const session = new Session(entry);
const result = await session.run(clientInfo, args);
console.log(result.text);
}
async function install(args: MinimistArgs) {
const cwd = process.cwd();
// Create .playwright folder to mark workspace root
const playwrightDir = path.join(cwd, '.playwright');
await fs.promises.mkdir(playwrightDir, { recursive: true });
console.log(`✅ Workspace initialized at \`${cwd}\`.`);
if (args.skills) {
const skillSourceDir = path.join(__dirname, 'skill');
const skillDestDir = path.join(cwd, '.claude', 'skills', 'playwright-cli');
if (!fs.existsSync(skillSourceDir)) {
console.error('❌ Skills source directory not found:', skillSourceDir);
process.exit(1);
}
await fs.promises.cp(skillSourceDir, skillDestDir, { recursive: true });
console.log(`✅ Skills installed to \`${path.relative(cwd, skillDestDir)}\`.`);
}
await ensureConfiguredBrowserInstalled();
}
async function ensureConfiguredBrowserInstalled() {
if (fs.existsSync(defaultConfigFile())) {
const { registry } = await import('playwright-core/lib/server/registry/index');
// Config exists, ensure configured browser is installed
const data = await fs.promises.readFile(defaultConfigFile(), 'utf-8');
const config = JSON.parse(data.charCodeAt(0) === 0xFEFF ? data.slice(1) : data) as Config;
const browserName = config.browser?.browserName ?? 'chromium';
const channel = config.browser?.launchOptions?.channel;
if (!channel || channel.startsWith('chromium')) {
const executable = registry.findExecutable(channel ?? browserName);
if (executable && !fs.existsSync(executable?.executablePath()!))
await registry.install([executable]);
}
} else {
// No config exists, detect or install a browser and create config
const channel = await findOrInstallDefaultBrowser();
if (channel !== 'chrome')
await createDefaultConfig(channel);
}
}
async function installBrowser() {
const { program } = require('../../cli/program');
const argv = process.argv.map(arg => arg === 'install-browser' ? 'install' : arg);
program.parse(argv);
}
async function createDefaultConfig(channel: string) {
const config: Config = {
browser: {
browserName: 'chromium',
launchOptions: {
channel,
},
},
};
await fs.promises.writeFile(defaultConfigFile(), JSON.stringify(config, null, 2));
console.log(`✅ Created default config for ${channel} at ${path.relative(process.cwd(), defaultConfigFile())}.`);
}
async function findOrInstallDefaultBrowser() {
const { registry } = await import('playwright-core/lib/server/registry/index');
const channels = ['chrome', 'msedge'];
for (const channel of channels) {
const executable = registry.findExecutable(channel);
if (!executable?.executablePath())
continue;
console.log(`✅ Found ${channel}, will use it as the default browser.`);
return channel;
}
const chromiumExecutable = registry.findExecutable('chromium');
// Unlike channels, chromium executable path is always valid, even if the browser is not installed.
if (!fs.existsSync(chromiumExecutable?.executablePath()!))
await registry.install([chromiumExecutable]);
return 'chromium';
}
function defaultConfigFile(): string {
return path.resolve('.playwright', 'cli.config.json');
}
async function killAllDaemons(): Promise<void> {
const platform = os.platform();
let killed = 0;
try {
if (platform === 'win32') {
const result = execSync(
`powershell -NoProfile -NonInteractive -Command `
+ `"Get-CimInstance Win32_Process `
+ `| Where-Object { $_.CommandLine -like '*run-mcp-server*' -or $_.CommandLine -like '*run-cli-server*' -or $_.CommandLine -like '*cli-daemon*' } `
+ `| ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; $_.ProcessId }"`,
{ encoding: 'utf-8' }
);
const pids = result.split('\n')
.map(line => line.trim())
.filter(line => /^\d+$/.test(line));
for (const pid of pids)
console.log(`Killed daemon process ${pid}`);
killed = pids.length;
} else {
const result = execSync('ps aux', { encoding: 'utf-8' });
const lines = result.split('\n');
for (const line of lines) {
if (line.includes('run-mcp-server') || line.includes('run-cli-server') || line.includes('cli-daemon')) {
const parts = line.trim().split(/\s+/);
const pid = parts[1];
if (pid && /^\d+$/.test(pid)) {
try {
process.kill(parseInt(pid, 10), 'SIGKILL');
console.log(`Killed daemon process ${pid}`);
killed++;
} catch {
// Process may have already exited
}
}
}
}
}
} catch (e) {
// Silently handle errors - no processes to kill is fine
}
if (killed === 0)
console.log('No daemon processes found.');
else if (killed > 0)
console.log(`Killed ${killed} daemon process${killed === 1 ? '' : 'es'}.`);
}
async function listSessions(registry: Registry, clientInfo: ClientInfo, all: boolean): Promise<void> {
if (all) {
const entries = registry.entryMap();
const serverEntries = await serverRegistry.list();
if (entries.size === 0 && serverEntries.size === 0) {
console.log('No browsers found.');
return;
}
const runningSessions = new Set<string>();
if (entries.size)
console.log('### Browsers');
for (const [workspace, list] of entries)
await gcAndPrintSessions(clientInfo, list.map(entry => new Session(entry)), `${path.relative(process.cwd(), workspace) || '/'}:`, runningSessions);
// Filter out server entries that already have an attached session.
const filteredServerEntries = new Map<string, BrowserDescriptor[]>();
for (const [workspace, list] of serverEntries) {
const unattached = list.filter(d => !runningSessions.has(d.title));
if (unattached.length)
filteredServerEntries.set(workspace, unattached);
}
if (filteredServerEntries.size) {
if (entries.size)
console.log('');
console.log('### Browser servers available for attach');
}
for (const [workspace, list] of filteredServerEntries)
await gcAndPrintBrowserSessions(workspace, list);
} else {
console.log('### Browsers');
const entries = registry.entries(clientInfo);
await gcAndPrintSessions(clientInfo, entries.map(entry => new Session(entry)));
}
}
async function gcAndPrintSessions(clientInfo: ClientInfo, sessions: Session[], header?: string, runningSessions?: Set<string>) {
const running: Session[] = [];
const stopped: Session[] = [];
for (const session of sessions) {
const canConnect = await session.canConnect();
if (canConnect) {
running.push(session);
runningSessions?.add(session.name);
} else {
if (session.config.cli.persistent)
stopped.push(session);
else
await session.deleteSessionConfig();
}
}
if (header && (running.length || stopped.length))
console.log(header);
for (const session of running)
console.log(await renderSessionStatus(clientInfo, session));
for (const session of stopped)
console.log(await renderSessionStatus(clientInfo, session));
if (running.length === 0 && stopped.length === 0)
console.log(' (no browsers)');
}
async function gcAndPrintBrowserSessions(workspace: string, list: BrowserDescriptor[]) {
if (!list.length)
return;
if (workspace)
console.log(`${path.relative(process.cwd(), workspace) || '/'}:`);
for (const descriptor of list) {
const text: string[] = [];
text.push(`- browser "${descriptor.title}":`);
text.push(` - browser: ${descriptor.browser.browserName}`);
text.push(` - version: v${descriptor.playwrightVersion}`);
text.push(` - run \`playwright-cli attach "${descriptor.title}"\` to attach`);
console.log(text.join('\n'));
}
if (!list.length)
console.log(' (no browsers)');
}
async function renderSessionStatus(clientInfo: ClientInfo, session: Session) {
const text: string[] = [];
const config = session.config;
const canConnect = await session.canConnect();
text.push(`- ${session.name}:`);
text.push(` - status: ${canConnect ? 'open' : 'closed'}`);
if (canConnect && !session.isCompatible(clientInfo))
text.push(` - version: v${config.version} [incompatible please re-open]`);
if (config.browser)
text.push(...renderResolvedConfig(config));
return text.join('\n');
}
export function calculateSha1(buffer: Buffer | string): string {
const hash = crypto.createHash('sha1');
hash.update(buffer);
return hash.digest('hex');
}