Files
hose-use/src/cli/commands/workflow/script.ts
T
gitea 4e03c9bcd7 refactor: 将应用数据与工作流统一归入应用平台子模块
建立 applications 的应用模型和查询出口,保留基础及详情投影差异。
下沉 DataLink,将工作流模型、API、编排及执行上下文归回 workflow。
同步 CLI、SDK、生成脚本、测试和活跃文档引用,公开命令与 SDK 名称保持兼容。

验证:943 项测试、类型和版本检查通过;三份生成规范字节一致,README 审计通过。
2026-10-30 16:56:09 +08:00

407 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from "node:fs";
import {
getWorkflowDetail,
getWorkflowSampleData,
findWorkflowTask,
lintWorkflowScripts,
lintJavaScriptCode,
lintMvelCode,
executeJavaScriptSandbox,
executeMvelSandbox,
} from "../../../domains/platform/workflow/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<CliResult> {
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 <pipelineId> [节点标识] [选项]",
" 或: hose-use workflow lint-script --file=<path> [--type=code-js2|code] [选项]",
" 或: hose-use workflow lint-script --code=\"<code>\" [--type=code-js2|code] [选项]",
"",
"选项:",
" --node=<name|index> 仅校验流水线中指定的某个代码节点",
" --file=<path> 静态检查本地脚本文件",
" --code=<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<CliResult> {
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;
const explicitType = (stringOption(parsed.options, ["type"]) || "").toLowerCase();
const isMvel = explicitType === "code" || explicitType === "mvel" || (filePath ? filePath.endsWith(".mvel") : false);
// 1. 获取输入参数 inputs
let inputs: Record<string, unknown> = {};
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 = isMvel
? await executeMvelSandbox(code, inputs, { timeoutMs })
: 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 <pipelineId> <节点标识> [选项]",
" 或: hose-use workflow eval-script --file=<path> [--input='{...}'] [选项]",
" 或: hose-use workflow eval-script --code=\"<code>\" [--input='{...}'] [选项]",
"",
"选项:",
" --input=<json> 传递给脚本的入参 JSON 字符串",
" --input-file=<path> 从本地 JSON 文件读取入参",
" --sample=<index> 自动从工作流历史测试样本中提取输入(如 1、2)",
" --timeout=<ms> 沙箱执行超时时间(毫秒,默认 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" && task.type !== "code") {
return {
stdout: "",
stderr: `节点 [${task.name}] 不是代码节点,类型为: ${task.type}\n`,
exitCode: 1,
};
}
const code: string = (task as any).code || "";
const isNodeMvel = task.type === "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 = isNodeMvel
? await executeMvelSandbox(code, inputs, { timeoutMs })
: 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,
};
}