server.mjs 11.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
import { createServer } from 'node:http';
import { networkInterfaces } from 'node:os';
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { dirname, extname, join, normalize, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const startPort = Number(process.env.E2E_PANEL_PORT || 5200);
const reportDir = resolve(process.cwd(), 'playwright-report');
const appProjects = new Map([
  ['dj-carlife-web', { label: 'D+智享车生活PC', suites: new Set(['all', 'basic', 'saas-v5.8.6']) }],
]);
const envs = new Set(['local', 'dev', 'test']);
const browsers = new Set(['edge', 'all', 'firefox', 'webkit']);
let running = false;
const reportChineseScript = String.raw`
<script>
(() => {
  const textMap = new Map([
    ['Search tests', '搜索用例'],
    ['All', '全部'],
    ['Passed', '通过'],
    ['Failed', '失败'],
    ['Flaky', '不稳定'],
    ['Skipped', '跳过'],
    ['Total time:', '总耗时:'],
    ['Filtered:', '筛选结果:'],
    ['Errors', '错误'],
    ['Test Steps', '测试步骤'],
    ['Filter steps', '搜索步骤'],
    ['Screenshots', '截图'],
    ['Traces', '调试轨迹'],
    ['Videos', '视频'],
    ['Attachments', '附件'],
    ['Copy prompt', '复制提示'],
    ['Copied', '已复制'],
  ]);

  function translateText(value) {
    if (!value) return value;
    let next = value;
    for (const [english, chinese] of textMap) {
      next = next.replaceAll(english, chinese);
    }
    return next;
  }

  function translateNode(node) {
    if (node.nodeType === Node.TEXT_NODE) {
      const next = translateText(node.nodeValue);
      if (next !== node.nodeValue) node.nodeValue = next;
      return;
    }

    if (node.nodeType !== Node.ELEMENT_NODE) return;

    for (const attr of ['placeholder', 'aria-label', 'title']) {
      if (node.hasAttribute(attr)) {
        const value = node.getAttribute(attr);
        const next = translateText(value);
        if (next !== value) node.setAttribute(attr, next);
      }
    }

    for (const child of node.childNodes) translateNode(child);
  }

  function translateReport() {
    document.title = 'Playwright 测试报告';
    translateNode(document.body);
  }

  translateReport();
  new MutationObserver(translateReport).observe(document.body, {
    childList: true,
    subtree: true,
    characterData: true,
    attributes: true,
    attributeFilter: ['placeholder', 'aria-label', 'title'],
  });
})();
</script>`;

const contentTypes = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'text/javascript; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.json': 'application/json; charset=utf-8',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.svg': 'image/svg+xml',
  '.webp': 'image/webp',
  '.zip': 'application/zip',
  '.md': 'text/markdown; charset=utf-8',
};

function readBody(req) {
  return new Promise((resolve, reject) => {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk;
      if (body.length > 10000) {
        reject(new Error('请求内容太大'));
        req.destroy();
      }
    });
    req.on('end', () => resolve(body));
    req.on('error', reject);
  });
}

function sendJson(res, status, value) {
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
  res.end(JSON.stringify(value));
}

function reportExists() {
  return existsSync(join(reportDir, 'index.html'));
}

async function serveReport(req, res) {
  if (!reportExists()) {
    res.writeHead(404, { 'content-type': 'text/html; charset=utf-8' });
    res.end('<!doctype html><meta charset="utf-8"><body>还没有生成测试报告,请先运行一次测试。</body>');
    return;
  }

  const url = new URL(req.url || '/', 'http://localhost');
  const relativePath = decodeURIComponent(url.pathname.replace(/^\/report\/?/, '')) || 'index.html';
  const filePath = resolve(reportDir, normalize(relativePath));

  if (!filePath.startsWith(reportDir)) {
    res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
    res.end('不能访问报告目录外的文件。');
    return;
  }

  let file = await readFile(filePath);
  if (filePath.endsWith('index.html')) {
    file = Buffer.from(file.toString('utf8').replace('</body>', reportChineseScript + '</body>'), 'utf8');
  }
  res.writeHead(200, { 'content-type': contentTypes[extname(filePath)] || 'application/octet-stream' });
  res.end(file);
}

function buildPlaywrightArgs(env, appProject, browser, suite) {
  const args = ['scripts/run-e2e.mjs', env, '--app-project=' + appProject];
  if (browser === 'all') {
    args.push('--project=edge', '--project=firefox', '--project=webkit');
  } else {
    args.push(`--project=${browser}`);
  }
  if (suite !== 'all') {
    args.push(`--suite=${suite}`);
  }

  return args;
}

function runPlaywright({ env, appProject, browser, suite }) {
  return new Promise((resolve) => {
    const args = buildPlaywrightArgs(env, appProject, browser, suite);

    const child = spawn('node', args, {
      cwd: process.cwd(),
      shell: true,
      env: process.env,
    });

    let output = '';
    child.stdout.on('data', (chunk) => {
      output += chunk.toString();
    });
    child.stderr.on('data', (chunk) => {
      output += chunk.toString();
    });
    child.on('close', (code) => {
      resolve({ code, output });
    });
    child.on('error', (error) => {
      resolve({ code: 1, output: error.message });
    });
  });
}

function streamPlaywright({ env, appProject, browser, suite, req, res }) {
  return new Promise((resolve) => {
    const args = buildPlaywrightArgs(env, appProject, browser, suite);

    const send = (value) => {
      if (!res.destroyed) {
        res.write(`${JSON.stringify(value)}\n`);
      }
    };

    const child = spawn('node', args, {
      cwd: process.cwd(),
      shell: true,
      env: process.env,
    });
    let finished = false;
    const stopChild = () => {
      if (!finished && !child.killed) {
        child.kill();
      }
    };
    const cleanup = () => {
      req.off('aborted', stopChild);
      res.off('close', stopChild);
    };
    req.on('aborted', stopChild);
    res.on('close', stopChild);

    child.stdout.on('data', (chunk) => {
      send({ type: 'output', output: chunk.toString() });
    });
    child.stderr.on('data', (chunk) => {
      send({ type: 'output', output: chunk.toString() });
    });
    child.on('close', (code) => {
      finished = true;
      cleanup();
      const result = {
        type: 'done',
        ok: code === 0,
        code,
        reportExists: reportExists(),
        reportUrl: '/report/',
      };
      send(result);
      resolve(result);
    });
    child.on('error', (error) => {
      finished = true;
      cleanup();
      const result = {
        type: 'done',
        ok: false,
        code: 1,
        reportExists: reportExists(),
        reportUrl: '/report/',
      };
      send({ type: 'output', output: error.message });
      send(result);
      resolve(result);
    });
  });
}
function validateRunParams(env, project, browser, suite) {
  const projectConfig = appProjects.get(project);
  if (!envs.has(env) || !projectConfig || !browsers.has(browser) || !projectConfig.suites.has(suite)) {
    return '参数不正确。请检查项目、环境、浏览器和用例范围。';
  }

  return '';
}

function createPanelServer() {
  return createServer(async (req, res) => {
    try {
      if (req.method === 'GET' && req.url === '/panel-config.js') {
        const file = await readFile(join(__dirname, 'panel-config.js'));
        res.writeHead(200, { 'content-type': contentTypes['.js'] });
        res.end(file);
        return;
      }
      if (req.method === 'GET' && req.url === '/') {
        const html = await readFile(join(__dirname, 'index.html'), 'utf8');
        res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
        res.end(html);
        return;
      }

      if (req.method === 'GET' && req.url === '/report-status') {
        sendJson(res, 200, { exists: reportExists(), url: '/report/' });
        return;
      }

      if (req.method === 'GET' && req.url?.startsWith('/report/')) {
        await serveReport(req, res);
        return;
      }

      if (req.method === 'POST' && req.url === '/run') {
        if (running) {
          sendJson(res, 409, { ok: false, reportExists: reportExists(), output: '已有测试正在运行,请等待它结束。' });
          return;
        }

        const body = JSON.parse((await readBody(req)) || '{}');
        const env = body.env;
        const project = body.project || 'dj-carlife-web';
        const browser = body.browser || 'edge';
        const suite = body.suite || 'all';
        const error = validateRunParams(env, project, browser, suite);

        if (error) {
          sendJson(res, 400, { ok: false, reportExists: reportExists(), output: error });
          return;
        }

        running = true;
        const result = await runPlaywright({ env, appProject: project, browser, suite });
        running = false;
        sendJson(res, 200, { ok: result.code === 0, reportExists: reportExists(), reportUrl: '/report/', ...result });
        return;
      }

      if (req.method === 'POST' && req.url === '/run-stream') {
        if (running) {
          sendJson(res, 409, { ok: false, reportExists: reportExists(), output: '已有测试正在运行,请等待它结束。' });
          return;
        }

        const body = JSON.parse((await readBody(req)) || '{}');
        const env = body.env;
        const project = body.project || 'dj-carlife-web';
        const browser = body.browser || 'edge';
        const suite = body.suite || 'all';
        const error = validateRunParams(env, project, browser, suite);

        if (error) {
          sendJson(res, 400, { ok: false, reportExists: reportExists(), output: error });
          return;
        }

        running = true;
        res.writeHead(200, {
          'content-type': 'application/x-ndjson; charset=utf-8',
          'cache-control': 'no-cache',
          connection: 'keep-alive',
        });

        try {
          await streamPlaywright({ env, appProject: project, browser, suite, req, res });
        } finally {
          running = false;
          res.end();
        }
        return;
      }

      sendJson(res, 404, { ok: false, output: '没有找到这个页面。' });
    } catch (error) {
      running = false;
      sendJson(res, 500, { ok: false, reportExists: reportExists(), output: error.message });
    }
  });
}

function getLocalIp() {
  for (const addresses of Object.values(networkInterfaces())) {
    for (const address of addresses || []) {
      if (address.family === 'IPv4' && !address.internal) {
        return address.address;
      }
    }
  }

  return '127.0.0.1';
}

function listen(port) {
  const host = getLocalIp();
  const server = createPanelServer();

  server.once('error', (error) => {
    if (error.code === 'EADDRINUSE') {
      console.log(`端口 ${port} 已被占用,正在尝试端口 ${port + 1}...`);
      listen(port + 1);
      return;
    }

    throw error;
  });

  server.listen(port, host, () => {
    console.log(`E2E 测试面板已启动:http://${host}:${port}`);
  });
}

listen(startPort);