refactor(platform): organize workflow capabilities into structured submodules
This commit is contained in:
1 parent
c917df13cc
commit
5aef332026
36 files changed
+2539
-2472
No files matched your search
@@ -0,0 +1,5 @@
|
||||
export * from "./types.js";
|
||||
export * from "./lint-js.js";
|
||||
export * from "./lint-mvel.js";
|
||||
export * from "./scanner.js";
|
||||
export * from "./sandbox.js";
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
|
||||
/**
|
||||
* 检查代码中是否存在 return 关键字(排除纯注释中的 return)
|
||||
*/
|
||||
export function hasReturnStatement(code: string): boolean {
|
||||
const lines = code.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
||||
continue;
|
||||
}
|
||||
if (/\breturn\b/.test(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态检查 JavaScript (code-js2) 语法与规范
|
||||
*/
|
||||
export function lintJavaScriptCode(
|
||||
code: string,
|
||||
boundVariables: string[] = []
|
||||
): { issues: ScriptIssue[]; hasReturn: boolean } {
|
||||
const issues: ScriptIssue[] = [];
|
||||
const trimmed = code.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: "代码节点脚本内容为空,合思调度时将报错",
|
||||
rule: "empty-script",
|
||||
});
|
||||
return { issues, hasReturn: false };
|
||||
}
|
||||
|
||||
const hasRet = hasReturnStatement(code);
|
||||
if (!hasRet) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "脚本中缺少显式 return 语句,可能导致下游节点接收到 null 或 undefined",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
// 语法验证:通过 Function 构造器做 AST 编译期语法解析
|
||||
try {
|
||||
// 注入声明的参数名以验证语法合法性
|
||||
new Function(...boundVariables, code);
|
||||
} catch (err: any) {
|
||||
let line: number | undefined;
|
||||
let column: number | undefined;
|
||||
|
||||
const msg = err?.message || String(err);
|
||||
// 尝试从堆栈或错误描述提取行号
|
||||
const match = err?.stack?.match(/<anonymous>:(\d+):(\d+)/) || msg.match(/line (\d+)/i);
|
||||
if (match) {
|
||||
line = Number(match[1]);
|
||||
if (match[2]) column = Number(match[2]);
|
||||
}
|
||||
|
||||
issues.push({
|
||||
level: "error",
|
||||
line,
|
||||
column,
|
||||
message: `JavaScript 语法错误: ${msg}`,
|
||||
rule: "syntax-error",
|
||||
});
|
||||
}
|
||||
|
||||
return { issues, hasReturn: hasRet };
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { WorkflowTask } from "../../types.js";
|
||||
import type { ScriptIssue } from "./types.js";
|
||||
import { hasReturnStatement } from "./lint-js.js";
|
||||
|
||||
/**
|
||||
* 静态检查 MVEL (code) 括号闭合与上游节点引用有效性
|
||||
*/
|
||||
export function lintMvelCode(
|
||||
code: string,
|
||||
existingNodeNames?: Set<string>
|
||||
): {
|
||||
issues: ScriptIssue[];
|
||||
referencedNodes: Array<{ name: string; exists: boolean }>;
|
||||
hasReturn: boolean;
|
||||
} {
|
||||
const issues: ScriptIssue[] = [];
|
||||
const referencedNodes: Array<{ name: string; exists: boolean }> = [];
|
||||
const trimmed = code.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: "MVEL 代码内容为空,合思调度时将报错",
|
||||
rule: "empty-script",
|
||||
});
|
||||
return { issues, referencedNodes, hasReturn: false };
|
||||
}
|
||||
|
||||
const hasRet = hasReturnStatement(code);
|
||||
if (!hasRet) {
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象",
|
||||
rule: "missing-return",
|
||||
});
|
||||
}
|
||||
|
||||
// 1. 括号与引号对称性平衡检查
|
||||
const stack: Array<{ char: string; line: number }> = [];
|
||||
const lines = code.split(/\r?\n/);
|
||||
|
||||
for (let l = 0; l < lines.length; l++) {
|
||||
const lineText = lines[l];
|
||||
// 忽略单行注释
|
||||
const cleanLine = lineText.replace(/\/\/.*$/, "");
|
||||
|
||||
for (let c = 0; c < cleanLine.length; c++) {
|
||||
const ch = cleanLine[c];
|
||||
if (ch === "{" || ch === "(" || ch === "[") {
|
||||
stack.push({ char: ch, line: l + 1 });
|
||||
} else if (ch === "}" || ch === ")" || ch === "]") {
|
||||
const top = stack.pop();
|
||||
const expected = ch === "}" ? "{" : ch === ")" ? "(" : "[";
|
||||
if (!top || top.char !== expected) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: l + 1,
|
||||
column: c + 1,
|
||||
message: `括号不匹配: 遇到闭合 '${ch}',但预期匹配 '${expected}'`,
|
||||
rule: "unmatched-brackets",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (stack.length > 0) {
|
||||
const unclosed = stack.pop()!;
|
||||
issues.push({
|
||||
level: "error",
|
||||
line: unclosed.line,
|
||||
message: `未闭合的括号: '${unclosed.char}' 缺少对应的闭合括号`,
|
||||
rule: "unclosed-bracket",
|
||||
});
|
||||
}
|
||||
|
||||
// 2. 提取引用的上游节点标识并比对有效性
|
||||
// 合思节点命名规范形如 action_xxx, control_xxx, trigger_xxx
|
||||
const nodeRefRegex = /\b(action_[a-zA-Z0-9_]+|control_[a-zA-Z0-9_]+|trigger_[a-zA-Z0-9_]+)\b/g;
|
||||
const foundRefs = new Set<string>();
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = nodeRefRegex.exec(code)) !== null) {
|
||||
foundRefs.add(match[1]);
|
||||
}
|
||||
|
||||
for (const ref of foundRefs) {
|
||||
const exists = existingNodeNames ? existingNodeNames.has(ref) : true;
|
||||
referencedNodes.push({ name: ref, exists });
|
||||
if (!exists) {
|
||||
issues.push({
|
||||
level: "error",
|
||||
message: `引用的上游节点 [${ref}] 在工作流中不存在(可能已被重命名或移除)`,
|
||||
rule: "dangling-node-reference",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { issues, referencedNodes, hasReturn: hasRet };
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归收集工作流任务树中所有节点标识
|
||||
*/
|
||||
export function collectAllWorkflowNodeNames(tasks: WorkflowTask[]): Set<string> {
|
||||
const names = new Set<string>();
|
||||
|
||||
function walk(list: WorkflowTask[]) {
|
||||
for (const t of list) {
|
||||
if (!t) continue;
|
||||
if (t.name) names.add(t.name);
|
||||
if (Array.isArray(t.tasks) && t.tasks.length > 0) {
|
||||
walk(t.tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(tasks);
|
||||
return names;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import vm from "node:vm";
|
||||
import type { ScriptEvalResult, ScriptEvalLog } from "./types.js";
|
||||
|
||||
/**
|
||||
* 在隔离沙箱中执行 JavaScript 代码节点,仿真合思云端运行时并捕获输出与异常
|
||||
*/
|
||||
export async function executeJavaScriptSandbox(
|
||||
code: string,
|
||||
inputs: Record<string, unknown> = {},
|
||||
options: { timeoutMs?: number } = {}
|
||||
): Promise<ScriptEvalResult> {
|
||||
const timeoutMs = options.timeoutMs ?? 3000;
|
||||
const logs: ScriptEvalLog[] = [];
|
||||
const start = performance.now();
|
||||
|
||||
const recordLog = (level: "log" | "warn" | "error", ...args: unknown[]) => {
|
||||
const message = args
|
||||
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
|
||||
.join(" ");
|
||||
logs.push({ level, message, timestamp: Date.now() });
|
||||
};
|
||||
|
||||
const sandboxConsole = {
|
||||
log: (...args: unknown[]) => recordLog("log", ...args),
|
||||
info: (...args: unknown[]) => recordLog("log", ...args),
|
||||
warn: (...args: unknown[]) => recordLog("warn", ...args),
|
||||
error: (...args: unknown[]) => recordLog("error", ...args),
|
||||
};
|
||||
|
||||
// 创建安全的执行沙箱上下文
|
||||
const sandboxContext = vm.createContext({
|
||||
...inputs,
|
||||
console: sandboxConsole,
|
||||
Date,
|
||||
Math,
|
||||
JSON,
|
||||
RegExp,
|
||||
Array,
|
||||
Object,
|
||||
Number,
|
||||
String,
|
||||
Boolean,
|
||||
parseInt,
|
||||
parseFloat,
|
||||
isNaN,
|
||||
isFinite,
|
||||
encodeURI,
|
||||
decodeURI,
|
||||
encodeURIComponent,
|
||||
decodeURIComponent,
|
||||
});
|
||||
|
||||
// 包裹立即执行函数体 (IIFE),既允许顶层 return 语句,又能直接受 vm timeout 保护
|
||||
const wrappedCode = `(function() {\n${code}\n})()`;
|
||||
|
||||
try {
|
||||
const returnValue = vm.runInContext(wrappedCode, sandboxContext, {
|
||||
timeout: timeoutMs,
|
||||
displayErrors: true,
|
||||
});
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
durationMs,
|
||||
returnValue,
|
||||
logs,
|
||||
inputs,
|
||||
};
|
||||
} catch (err: any) {
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
const msg = err?.message || String(err);
|
||||
let line: number | undefined;
|
||||
let column: number | undefined;
|
||||
|
||||
const stack = err?.stack || "";
|
||||
// 匹配包裹函数内的行号(第 1 行是包裹头,因此需要 -1)
|
||||
const match = stack.match(/evalmachine\.<anonymous>:(\d+):(\d+)/);
|
||||
if (match) {
|
||||
const rawLine = Number(match[1]);
|
||||
line = Math.max(1, rawLine - 1);
|
||||
column = Number(match[2]);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
durationMs,
|
||||
returnValue: undefined,
|
||||
logs,
|
||||
error: {
|
||||
name: err?.name || "ExecutionError",
|
||||
message: msg,
|
||||
stack,
|
||||
line,
|
||||
column,
|
||||
},
|
||||
inputs,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
|
||||
import type { NodeScriptLintReport, WorkflowScriptLintReport, ScriptIssue } from "./types.js";
|
||||
import { lintJavaScriptCode } from "./lint-js.js";
|
||||
import { lintMvelCode, collectAllWorkflowNodeNames } from "./lint-mvel.js";
|
||||
|
||||
/**
|
||||
* 扫描并全面静态校验工作流中的全部代码节点(JS 与 MVEL)
|
||||
*/
|
||||
export function lintWorkflowScripts(
|
||||
workflow: WorkflowDetail,
|
||||
targetNodeQuery?: string
|
||||
): WorkflowScriptLintReport {
|
||||
const tasks = workflow.tasks || [];
|
||||
const allNodeNames = collectAllWorkflowNodeNames(tasks);
|
||||
const reports: NodeScriptLintReport[] = [];
|
||||
|
||||
function traverse(list: WorkflowTask[]) {
|
||||
for (const task of list) {
|
||||
if (!task) continue;
|
||||
|
||||
if (task.type === "code" || task.type === "code-js2") {
|
||||
if (!targetNodeQuery || task.name === targetNodeQuery || task.label === targetNodeQuery || task.displayName === targetNodeQuery) {
|
||||
const rawCode = (task as any).code || "";
|
||||
const lineCount = rawCode ? rawCode.split(/\r?\n/).length : 0;
|
||||
const mappings = Array.isArray((task as any).mapping) ? (task as any).mapping : [];
|
||||
const boundVariables: Array<{ key: string; upstreamTarget?: string }> = mappings.map((m: any) => ({
|
||||
key: m.key,
|
||||
upstreamTarget: m.value,
|
||||
}));
|
||||
|
||||
let issues: ScriptIssue[] = [];
|
||||
let hasReturn = false;
|
||||
let referencedNodes: Array<{ name: string; exists: boolean }> = [];
|
||||
|
||||
if (task.type === "code-js2") {
|
||||
const paramNames = boundVariables.map((b) => b.key);
|
||||
const res = lintJavaScriptCode(rawCode, paramNames);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
} else {
|
||||
const res = lintMvelCode(rawCode, allNodeNames);
|
||||
issues = res.issues;
|
||||
hasReturn = res.hasReturn;
|
||||
referencedNodes = res.referencedNodes;
|
||||
}
|
||||
|
||||
const hasErrors = issues.some((i) => i.level === "error");
|
||||
|
||||
reports.push({
|
||||
nodeName: task.name,
|
||||
displayName: task.displayName || undefined,
|
||||
label: task.label || undefined,
|
||||
type: task.type,
|
||||
codeLength: rawCode.length,
|
||||
lineCount,
|
||||
hasReturn,
|
||||
boundVariables,
|
||||
referencedNodes,
|
||||
issues,
|
||||
valid: !hasErrors,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
traverse(task.tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(tasks);
|
||||
|
||||
const validCount = reports.filter((r) => r.valid).length;
|
||||
const invalidCount = reports.length - validCount;
|
||||
|
||||
return {
|
||||
pipelineId: workflow.id,
|
||||
label: workflow.label,
|
||||
totalCodeNodes: reports.length,
|
||||
validCount,
|
||||
invalidCount,
|
||||
reports,
|
||||
allValid: invalidCount === 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export interface ScriptIssue {
|
||||
level: "error" | "warning";
|
||||
line?: number;
|
||||
column?: number;
|
||||
message: string;
|
||||
rule: string;
|
||||
}
|
||||
|
||||
export interface NodeScriptLintReport {
|
||||
nodeName: string;
|
||||
displayName?: string;
|
||||
label?: string;
|
||||
type: "code-js2" | "code";
|
||||
codeLength: number;
|
||||
lineCount: number;
|
||||
hasReturn: boolean;
|
||||
boundVariables: Array<{ key: string; upstreamTarget?: string }>;
|
||||
referencedNodes: Array<{ name: string; exists: boolean }>;
|
||||
issues: ScriptIssue[];
|
||||
valid: boolean;
|
||||
}
|
||||
|
||||
export interface WorkflowScriptLintReport {
|
||||
pipelineId?: string;
|
||||
label?: string;
|
||||
totalCodeNodes: number;
|
||||
validCount: number;
|
||||
invalidCount: number;
|
||||
reports: NodeScriptLintReport[];
|
||||
allValid: boolean;
|
||||
}
|
||||
|
||||
export interface ScriptEvalLog {
|
||||
level: "log" | "warn" | "error";
|
||||
message: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface ScriptEvalResult {
|
||||
success: boolean;
|
||||
durationMs: number;
|
||||
returnValue: unknown;
|
||||
logs: ScriptEvalLog[];
|
||||
error?: {
|
||||
name: string;
|
||||
message: string;
|
||||
stack?: string;
|
||||
line?: number;
|
||||
column?: number;
|
||||
};
|
||||
inputs: Record<string, unknown>;
|
||||
}
|
||||
Reference in new issue
Block a user