import fs from "node:fs"; import { getWorkflowDetail, getWorkflowSampleData, findWorkflowTask, lintWorkflowScripts, lintJavaScriptCode, lintMvelCode, executeJavaScriptSandbox, } from "../../../domains/platform/services.js"; import { stringOption, booleanOption } from "../../parser.js"; import { printJson, printKeyValue } from "../../printer.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import { createWorkflowDetailClient } from "./shared.js"; /** * 校验工作流脚本 (JavaScript / MVEL) 语法、上游引用与代码规范 */ export async function handleWorkflowLintScript( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]); const filePath = stringOption(parsed.options, ["file", "path"]); const codeInline = stringOption(parsed.options, ["code"]); const explicitType = (stringOption(parsed.options, ["type"]) || "code-js2").toLowerCase(); // 1. 本地代码文件或行内脚本校验 if (filePath || codeInline) { let rawCode = codeInline || ""; if (filePath) { if (!fs.existsSync(filePath)) { return { stdout: "", stderr: `指定的脚本文件不存在: ${filePath}\n`, exitCode: 1, }; } rawCode = fs.readFileSync(filePath, "utf-8"); } const type = explicitType === "code" || explicitType === "mvel" ? "code" : "code-js2"; let issues: Array<{ level: string; line?: number; column?: number; message: string; rule: string }> = []; let hasReturn = false; let referencedNodes: Array<{ name: string; exists: boolean }> = []; if (type === "code-js2") { const res = lintJavaScriptCode(rawCode); issues = res.issues; hasReturn = res.hasReturn; } else { const res = lintMvelCode(rawCode); issues = res.issues; hasReturn = res.hasReturn; referencedNodes = res.referencedNodes; } const hasErrors = issues.some((i) => i.level === "error"); const report = { source: filePath ? `file: ${filePath}` : "inline-code", type: type === "code-js2" ? "JavaScript (code-js2)" : "MVEL (code)", codeLength: rawCode.length, lineCount: rawCode ? rawCode.split(/\r?\n/).length : 0, hasReturn, referencedNodes, issues, valid: !hasErrors, }; if (isJson) { return { stdout: printJson(report, runtime.outputOptions), stderr: "", exitCode: hasErrors ? 1 : 0 }; } const lines: string[] = []; lines.push(`脚本静态校验: ${report.source}`); lines.push(`引擎类型: ${report.type} | 代码行数: ${report.lineCount} | 字符数: ${report.codeLength}`); lines.push(`return 语句: ${hasReturn ? "✅ 存在" : "⚠️ 缺失"}`); if (referencedNodes.length > 0) { lines.push(`引用上游节点: ${referencedNodes.map((n) => n.name).join(", ")}`); } if (issues.length === 0) { lines.push("校验结果: ✅ 语法完全合规,无任何错误或警告\n"); } else { lines.push(`\n发现 ${issues.length} 个潜在问题:`); for (const iss of issues) { const icon = iss.level === "error" ? "❌ [错误]" : "⚠️ [警告]"; const loc = iss.line ? ` L${iss.line}${iss.column ? `:${iss.column}` : ""}` : ""; lines.push(` ${icon}${loc} [${iss.rule}] ${iss.message}`); } lines.push(hasErrors ? "\n校验未通过 ❌ 请根据上述提示修复语法错误。\n" : "\n校验通过 (含告警提示) ⚠️\n"); } return { stdout: lines.join("\n"), stderr: "", exitCode: hasErrors ? 1 : 0, }; } // 2. 线上工作流整条流水线或指定节点校验 const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]); const targetNode = parsed.args[1] || stringOption(parsed.options, ["node", "target"]); if (!pipelineId) { return { stdout: "", stderr: [ "用法: hose-use workflow lint-script [节点标识] [选项]", " 或: hose-use workflow lint-script --file= [--type=code-js2|code] [选项]", " 或: hose-use workflow lint-script --code=\"\" [--type=code-js2|code] [选项]", "", "选项:", " --node= 仅校验流水线中指定的某个代码节点", " --file= 静态检查本地脚本文件", " --code= 静态检查行内传入的代码片段", " --type=code-js2|code 指定脚本类型(默认 code-js2 JavaScript)", " --json 输出结构化 JSON 格式结果", "", "示例:", " hose-use workflow lint-script 896398895352487950", " hose-use workflow lint-script 896398895352487950 action_dx9cci", " hose-use workflow lint-script --file=./scripts/clean.js", ].join("\n") + "\n", exitCode: 1, }; } const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const workflow = await getWorkflowDetail(client, pipelineId); const report = lintWorkflowScripts(workflow, targetNode); if (isJson) { return { stdout: printJson(report, runtime.outputOptions), stderr: "", exitCode: report.allValid ? 0 : 1 }; } const lines: string[] = []; lines.push(`工作流脚本静态校验: ${report.label || pipelineId} (${pipelineId})`); lines.push(`共检测 ${report.totalCodeNodes} 个代码节点 (JS/MVEL): ${report.validCount} 个合规, ${report.invalidCount} 个异常\n`); if (report.reports.length === 0) { lines.push("未找到任何代码节点 (code / code-js2)。"); return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 }; } for (const node of report.reports) { const statusIcon = node.valid ? (node.issues.length > 0 ? "⚠️" : "✅") : "❌"; const typeLabel = node.type === "code-js2" ? "JavaScript" : "MVEL"; lines.push(`${statusIcon} 节点 [${node.nodeName}] ${node.label || node.displayName || ""} (${typeLabel})`); lines.push(` 代码行数: ${node.lineCount} | 字符数: ${node.codeLength} | return 语句: ${node.hasReturn ? "有" : "无"}`); if (node.boundVariables.length > 0) { lines.push(` 绑定变量: ${node.boundVariables.map((v) => `${v.key} -> ${v.upstreamTarget || "无"}`).join(", ")}`); } if (node.referencedNodes.length > 0) { lines.push( ` 引用节点: ${node.referencedNodes.map((r) => `${r.name}${r.exists ? "" : " (❌不存在)"}`).join(", ")}` ); } if (node.issues.length === 0) { lines.push(" 结果: 语法合规"); } else { for (const iss of node.issues) { const flag = iss.level === "error" ? "❌" : "⚠️"; const loc = iss.line ? ` L${iss.line}${iss.column ? `:${iss.column}` : ""}` : ""; lines.push(` ${flag}${loc} [${iss.rule}] ${iss.message}`); } } lines.push(""); } if (report.allValid) { lines.push("总体验证结果: 全部代码节点均通过语法与引用校验 ✅"); } else { lines.push(`总体验证结果: 发现 ${report.invalidCount} 个代码节点存在语法错误或悬空引用 ❌`); } return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: report.allValid ? 0 : 1, }; } /** * 在隔离沙箱中离线仿真运行工作流代码节点 */ export async function handleWorkflowEvalScript( parsed: CliParsedArgs, runtime: CliRuntime ): Promise { const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]); const filePath = stringOption(parsed.options, ["file", "path"]); const codeInline = stringOption(parsed.options, ["code"]); const timeoutStr = stringOption(parsed.options, ["timeout"]); const timeoutMs = timeoutStr ? parseInt(timeoutStr, 10) : 3000; // 1. 获取输入参数 inputs let inputs: Record = {}; const rawInput = stringOption(parsed.options, ["input", "data"]); const inputFile = stringOption(parsed.options, ["input-file"]); if (rawInput) { try { inputs = JSON.parse(rawInput); } catch (e: any) { return { stdout: "", stderr: `解析 --input JSON 参数失败: ${e.message}\n`, exitCode: 1, }; } } else if (inputFile) { if (!fs.existsSync(inputFile)) { return { stdout: "", stderr: `指定的 --input-file 不存在: ${inputFile}\n`, exitCode: 1, }; } try { inputs = JSON.parse(fs.readFileSync(inputFile, "utf-8")); } catch (e: any) { return { stdout: "", stderr: `解析 --input-file JSON 失败: ${e.message}\n`, exitCode: 1, }; } } // 2. 本地文件或行内代码沙箱运行 if (filePath || codeInline) { let code = codeInline || ""; if (filePath) { if (!fs.existsSync(filePath)) { return { stdout: "", stderr: `指定的脚本文件不存在: ${filePath}\n`, exitCode: 1, }; } code = fs.readFileSync(filePath, "utf-8"); } const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs }); if (isJson) { return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 }; } return formatEvalCliResult(evalResult, filePath ? `file: ${filePath}` : "inline-code"); } // 3. 从工作流节点加载脚本并运行 const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]); const targetNode = parsed.args[1] || stringOption(parsed.options, ["node", "target"]); if (!pipelineId || !targetNode) { return { stdout: "", stderr: [ "用法: hose-use workflow eval-script <节点标识> [选项]", " 或: hose-use workflow eval-script --file= [--input='{...}'] [选项]", " 或: hose-use workflow eval-script --code=\"\" [--input='{...}'] [选项]", "", "选项:", " --input= 传递给脚本的入参 JSON 字符串", " --input-file= 从本地 JSON 文件读取入参", " --sample= 自动从工作流历史测试样本中提取输入(如 1、2)", " --timeout= 沙箱执行超时时间(毫秒,默认 3000)", " --json 输出结构化 JSON 格式结果", "", "示例:", " hose-use workflow eval-script 896398895352487950 action_dx9cci", " hose-use workflow eval-script 896398895352487950 action_dx9cci --sample=1", " hose-use workflow eval-script 896398895352487950 action_dx9cci --input='{\"info\":{\"money\":100}}'", " hose-use workflow eval-script --code=\"return { total: a + b };\" --input='{\"a\":10,\"b\":20}'", ].join("\n") + "\n", exitCode: 1, }; } const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId); const workflow = await getWorkflowDetail(client, pipelineId); const located = findWorkflowTask(workflow, targetNode); if (!located) { return { stdout: "", stderr: `在工作流 [${pipelineId}] 中未找到节点: ${targetNode}\n`, exitCode: 1, }; } const task = located.task; if (task.type !== "code-js2") { if (task.type === "code") { return { stdout: "", stderr: [ `节点 [${task.name}] 是 MVEL (code) 节点。`, "当前本地离线沙箱仅支持 JavaScript (code-js2) 运行时仿真。", "提示: 您可以使用 hose-use workflow lint-script 检查其括号与上游引用,或使用 hose-use workflow test 进行全链路调试。", ].join("\n") + "\n", exitCode: 1, }; } return { stdout: "", stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`, exitCode: 1, }; } const code: string = (task as any).code || ""; // 如果没有显式传 input,尝试提取工作流样本数据 if (Object.keys(inputs).length === 0) { const sampleIdxStr = stringOption(parsed.options, ["sample"]); try { const sampleResult = await getWorkflowSampleData(client, pipelineId, "webhook"); const list = sampleResult?.records || []; if (list.length > 0) { const idx = sampleIdxStr ? Math.max(0, parseInt(sampleIdxStr, 10) - 1) : 0; const chosen = list[idx] || list[0]; let samplePayload: any = chosen; if (chosen?.dataJson) { try { samplePayload = JSON.parse(chosen.dataJson); } catch { samplePayload = chosen.dataJson; } } // 根据 code-js2 mapping 配置进行参数绑定 const mappings = Array.isArray((task as any).mapping) ? (task as any).mapping : []; if (mappings.length > 0) { for (const m of mappings) { if (m.key) { inputs[m.key] = samplePayload; } } } else { inputs = typeof samplePayload === "object" && samplePayload !== null ? samplePayload : { sample: samplePayload }; } } } catch { // 忽略样例拉取失败,继续空入参执行 } } const evalResult = await executeJavaScriptSandbox(code, inputs, { timeoutMs }); if (isJson) { return { stdout: printJson(evalResult, runtime.outputOptions), stderr: "", exitCode: evalResult.success ? 0 : 1 }; } const targetDesc = `节点 [${task.name}] ${task.label || task.displayName || ""} (${pipelineId})`; return formatEvalCliResult(evalResult, targetDesc); } function formatEvalCliResult( evalResult: import("../../../domains/platform/workflow/script/index.js").ScriptEvalResult, targetDesc: string ): CliResult { const lines: string[] = []; const statusStr = evalResult.success ? "执行成功 ✅" : "执行失败 ❌"; lines.push(`代码节点沙箱仿真: ${targetDesc}`); lines.push(`状态: ${statusStr} | 耗时: ${evalResult.durationMs}ms`); lines.push("\n入参 (Inputs):"); lines.push(JSON.stringify(evalResult.inputs, null, 2)); if (evalResult.logs.length > 0) { lines.push("\n控制台日志 (Console Logs):"); for (const log of evalResult.logs) { const icon = log.level === "error" ? "🔴" : log.level === "warn" ? "🟡" : "⚪"; lines.push(` ${icon} [${log.level}] ${log.message}`); } } if (evalResult.success) { lines.push("\n返回值 (Return Value):"); if (typeof evalResult.returnValue === "object" && evalResult.returnValue !== null) { lines.push(JSON.stringify(evalResult.returnValue, null, 2)); } else { lines.push(String(evalResult.returnValue)); } lines.push(""); } else if (evalResult.error) { lines.push("\n异常信息 (Error Details):"); const loc = evalResult.error.line ? ` (第 ${evalResult.error.line} 行)` : ""; lines.push(` ${evalResult.error.name}: ${evalResult.error.message}${loc}`); if (evalResult.error.stack) { lines.push(`\n堆栈详情:\n${evalResult.error.stack}`); } lines.push(""); } return { stdout: lines.join("\n"), stderr: "", exitCode: evalResult.success ? 0 : 1, }; }