const fs = require('fs'); const path = require('path'); const readline = require('readline'); const logger = require('./logger'); function isEnabled(options = {}) { return options.debugTask === true || process.env.DEBUG_TASK === 'true'; } function shouldKeepOpen(options = {}) { return options.keepOpen === true || process.env.DEBUG_KEEP_OPEN === 'true'; } function shouldPauseEachStep(options = {}) { return options.pauseEachStep === true || process.env.DEBUG_PAUSE_EACH_STEP === 'true'; } function isDryRun(options = {}) { return options.dryRun === true || process.env.DEBUG_DRY_RUN === 'true'; } function createDebugRunDir(taskName) { const stamp = new Date().toISOString() .replace(/[:.]/g, '-') .replace('T', '_') .slice(0, 19); const safeName = String(taskName).replace(/[^\w.-]+/g, '_'); const dir = path.resolve('debug-runs', `${stamp}_${safeName}`); fs.mkdirSync(dir, { recursive: true }); return dir; } async function pageInfo(page) { if (!page || page.isClosed()) { return { title: '', url: '(page closed)' }; } const title = await page.title().catch(() => ''); const url = page.url(); return { title, url }; } async function saveFailureArtifacts(page, dir, index, stepName, err) { if (!dir || !page || page.isClosed()) return; const safeStep = String(stepName).replace(/[^\w.-]+/g, '_').slice(0, 80); const prefix = `${String(index).padStart(2, '0')}_${safeStep}`; await page.screenshot({ path: path.join(dir, `${prefix}_fail.png`), fullPage: true, }).catch((screenshotErr) => { logger.warn(` → 失败截图保存失败: ${screenshotErr.message}`); }); const html = await page.content().catch(() => ''); if (html) { fs.writeFileSync(path.join(dir, `${prefix}_fail.html`), html, 'utf-8'); } fs.writeFileSync( path.join(dir, `${prefix}_error.txt`), err.stack || err.message, 'utf-8' ); } function formatInspectValue(value) { if (value === null || typeof value === 'undefined') return String(value); if (typeof value === 'string') return value; return JSON.stringify(value); } async function runInspect(step, ctx) { if (typeof step.inspect !== 'function') return; logger.info('元素检查:'); try { const result = await step.inspect(ctx); if (!result || typeof result !== 'object') { logger.info(` ${formatInspectValue(result)}`); return; } for (const [key, value] of Object.entries(result)) { logger.info(` ${key}: ${formatInspectValue(value)}`); } } catch (err) { logger.warn(` inspect 执行失败: ${err.message}`); } } function waitForEnter(message) { return new Promise((resolve) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question(message, () => { rl.close(); resolve(); }); }); } async function runDebugSteps(taskName, steps, ctx = {}, options = {}) { const enabled = isEnabled(options); const debugOptions = { enabled, keepOpen: shouldKeepOpen(options), pauseEachStep: shouldPauseEachStep(options), dryRun: isDryRun(options), runDir: enabled ? createDebugRunDir(taskName) : '', }; ctx.debug = debugOptions; if (enabled) { logger.divider(); logger.info(`[DEBUG] 单任务调试: ${taskName}`); logger.info(`[DEBUG] 产物目录: ${debugOptions.runDir}`); logger.info(`[DEBUG] keepOpen=${debugOptions.keepOpen}, pauseEachStep=${debugOptions.pauseEachStep}, dryRun=${debugOptions.dryRun}`); } for (let i = 0; i < steps.length; i++) { const step = steps[i]; const stepNo = i + 1; const label = `Step ${stepNo}/${steps.length}: ${step.name}`; if (enabled) { logger.info(`[DEBUG] ${label} 开始`); } else { logger.info(` → ${step.name}`); } try { await step.run(ctx); if (enabled) { const info = await pageInfo(step.page ? step.page(ctx) : ctx.page); logger.info(`[DEBUG] ${label} ✅`); logger.info(`[DEBUG] 当前页面: ${info.url}`); } if (enabled && debugOptions.pauseEachStep) { await waitForEnter(`[DEBUG] ${label} 已完成,按 Enter 继续...`); } } catch (err) { logger.error(enabled ? `[DEBUG] ${label} ❌` : `${label} ❌`); logger.error(`错误: ${err.message}`); const activePage = step.page ? step.page(ctx) : (ctx.currentPage || ctx.page); const info = await pageInfo(activePage); logger.error(`当前页面: ${info.url}`); logger.error(`页面标题: ${info.title}`); await runInspect(step, ctx); await saveFailureArtifacts(activePage, debugOptions.runDir, stepNo, step.name, err); if (enabled && debugOptions.keepOpen) { logger.warn('浏览器已保留,请检查页面元素。'); await waitForEnter('按 Enter 关闭浏览器并退出...'); } throw err; } } } module.exports = { runDebugSteps, isDryRun, };