|
| 1 | +import { spawn } from 'node:child_process' |
| 2 | +import { fileURLToPath } from 'node:url' |
| 3 | +import path from 'node:path' |
| 4 | +import { readFileSync, writeFileSync, rmSync, existsSync } from 'node:fs' |
| 5 | + |
| 6 | +const __filename = fileURLToPath(import.meta.url) |
| 7 | +const __dirname = path.dirname(__filename) |
| 8 | +const rootDir = path.resolve(__dirname, '..', '..', '..') |
| 9 | +const templatePath = path.resolve(__dirname, '..', 'assets', 'config.template.json') |
| 10 | +const configPath = path.resolve(rootDir, 'config.json') |
| 11 | + |
| 12 | +function loadTemplate() { |
| 13 | + const raw = readFileSync(templatePath, 'utf8') |
| 14 | + return JSON.parse(raw) |
| 15 | +} |
| 16 | + |
| 17 | +function buildConfig() { |
| 18 | + const template = loadTemplate() |
| 19 | + const listenPort = Number.parseInt(process.env.WEBSSH2_LISTEN_PORT ?? '', 10) || 4444 |
| 20 | + const sshPort = Number.parseInt(process.env.E2E_SSH_PORT ?? '', 10) || 22 |
| 21 | + |
| 22 | + template.listen.port = listenPort |
| 23 | + template.ssh.port = sshPort |
| 24 | + |
| 25 | + return template |
| 26 | +} |
| 27 | + |
| 28 | +function writeConfig(config) { |
| 29 | + writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8') |
| 30 | +} |
| 31 | + |
| 32 | +function cleanup() { |
| 33 | + if (existsSync(configPath)) { |
| 34 | + try { |
| 35 | + rmSync(configPath) |
| 36 | + } catch (error) { |
| 37 | + console.warn('[playwright:start-server] Failed to remove config.json:', error) |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +const config = buildConfig() |
| 43 | +writeConfig(config) |
| 44 | + |
| 45 | +const childEnv = { |
| 46 | + ...process.env, |
| 47 | + WEBSSH2_LISTEN_PORT: String(config.listen.port) |
| 48 | +} |
| 49 | + |
| 50 | +const child = spawn(process.execPath, ['dist/index.js'], { |
| 51 | + cwd: rootDir, |
| 52 | + stdio: 'inherit', |
| 53 | + env: childEnv |
| 54 | +}) |
| 55 | + |
| 56 | +child.on('error', (error) => { |
| 57 | + console.error('[playwright:start-server] Failed to start WebSSH2 server:', error) |
| 58 | + cleanup() |
| 59 | + process.exit(1) |
| 60 | +}) |
| 61 | + |
| 62 | +const signals = ['SIGINT', 'SIGTERM', 'SIGQUIT'] |
| 63 | + |
| 64 | +for (const signal of signals) { |
| 65 | + process.on(signal, () => { |
| 66 | + if (child.killed) { |
| 67 | + return |
| 68 | + } |
| 69 | + child.kill(signal) |
| 70 | + }) |
| 71 | +} |
| 72 | + |
| 73 | +process.on('exit', () => { |
| 74 | + cleanup() |
| 75 | +}) |
| 76 | + |
| 77 | +child.on('exit', (code, signal) => { |
| 78 | + cleanup() |
| 79 | + const exitCode = code ?? (typeof signal === 'string' ? 1 : 0) |
| 80 | + process.exit(exitCode) |
| 81 | +}) |
0 commit comments