401 lines
14 KiB
TypeScript
401 lines
14 KiB
TypeScript
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
|
|
|
export interface WorkflowAstNode {
|
|
type: string;
|
|
name: string;
|
|
label: string;
|
|
path: string;
|
|
orderIndex: number;
|
|
levelIndex: number[];
|
|
children: WorkflowAstNode[];
|
|
}
|
|
|
|
export interface WorkflowDependency {
|
|
path: string;
|
|
taskType: string;
|
|
references: string[];
|
|
}
|
|
|
|
export interface WorkflowDiagnostic {
|
|
severity: "warning" | "error";
|
|
code: string;
|
|
path: string;
|
|
message: string;
|
|
}
|
|
|
|
export interface WorkflowAnalysis {
|
|
workflow: { id: string; label: string; state: number; version: string };
|
|
ast: WorkflowAstNode[];
|
|
dependencies: WorkflowDependency[];
|
|
diagnostics: WorkflowDiagnostic[];
|
|
}
|
|
|
|
export interface WorkflowFormSpecComponentLike {
|
|
name?: string;
|
|
field?: string;
|
|
label?: string;
|
|
type?: string;
|
|
isLinkageAssignment?: boolean;
|
|
assignmentRule?: string | null;
|
|
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
|
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
|
}
|
|
|
|
export interface WorkflowFormSpecLike {
|
|
id: string;
|
|
name?: string;
|
|
components?: WorkflowFormSpecComponentLike[];
|
|
}
|
|
|
|
export interface AnalyzeWorkflowOptions {
|
|
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
|
}
|
|
|
|
const KNOWN_TYPES = new Set([
|
|
"webhook",
|
|
"crontab",
|
|
"clock",
|
|
"condition",
|
|
"every",
|
|
"stop",
|
|
"http",
|
|
"flow-detail",
|
|
"code",
|
|
"code-js2",
|
|
"ekuaibao-datalink-filter",
|
|
"ekuaibao-datalink-create",
|
|
"ekuaibao-datalink-edit",
|
|
"ekuaibao-datalink-delete",
|
|
"data-convert",
|
|
"flow-create-task",
|
|
]);
|
|
|
|
function referencesFromTask(task: WorkflowTask): string[] {
|
|
const code = typeof task.code === "string" ? task.code : "";
|
|
const values = [
|
|
...code.matchAll(
|
|
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
|
),
|
|
]
|
|
.map((match) => (match[1] || match[2] || "").trim())
|
|
.filter(Boolean);
|
|
return [...new Set(values)];
|
|
}
|
|
|
|
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
|
return tasks.map((task, index) => {
|
|
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
|
return {
|
|
type: task.type,
|
|
name: task.name,
|
|
label: task.label || task.displayName || "",
|
|
path,
|
|
orderIndex: task.orderIndex,
|
|
levelIndex: task.levelIndex,
|
|
children: toAst(task.tasks || [], path),
|
|
};
|
|
});
|
|
}
|
|
|
|
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
|
const raw = task as Record<string, unknown>;
|
|
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
|
return raw.specificationId.trim();
|
|
}
|
|
if (Array.isArray(task.inputs)) {
|
|
const found = task.inputs.find((item) => item.key === "specificationId");
|
|
if (found && typeof found.value === "string" && found.value.trim()) {
|
|
return found.value.trim();
|
|
}
|
|
} else if (raw.inputs && typeof raw.inputs === "object") {
|
|
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
|
if (typeof specId === "string" && specId.trim()) {
|
|
return specId.trim();
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function getTaskFormEntries(
|
|
task: WorkflowTask
|
|
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
|
const raw = task as Record<string, unknown>;
|
|
if (Array.isArray(raw.form)) {
|
|
return raw.form.filter(
|
|
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
|
Boolean(item && typeof item === "object")
|
|
);
|
|
}
|
|
if (raw.form && typeof raw.form === "object") {
|
|
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
|
key,
|
|
value,
|
|
}));
|
|
}
|
|
if (Array.isArray(task.inputs)) {
|
|
const formInput = task.inputs.find((item) => item.key === "form");
|
|
if (formInput && Array.isArray(formInput.value)) {
|
|
return formInput.value.filter(
|
|
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
|
Boolean(item && typeof item === "object")
|
|
);
|
|
}
|
|
if (formInput && formInput.value && typeof formInput.value === "object") {
|
|
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
|
key,
|
|
value,
|
|
}));
|
|
}
|
|
} else if (raw.inputs && typeof raw.inputs === "object") {
|
|
const formVal = (raw.inputs as Record<string, unknown>).form;
|
|
if (Array.isArray(formVal)) {
|
|
return formVal.filter(
|
|
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
|
Boolean(item && typeof item === "object")
|
|
);
|
|
}
|
|
if (formVal && typeof formVal === "object") {
|
|
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
|
key,
|
|
value,
|
|
}));
|
|
}
|
|
}
|
|
return [];
|
|
}
|
|
|
|
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
|
const ids = new Set<string>();
|
|
const walk = (tasks: WorkflowTask[]) => {
|
|
for (const task of tasks) {
|
|
if (task.type === "flow-create-task") {
|
|
const specId = getTaskSpecificationId(task);
|
|
if (specId) ids.add(specId);
|
|
}
|
|
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
|
walk(task.tasks);
|
|
}
|
|
}
|
|
};
|
|
walk(detail.tasks || []);
|
|
return [...ids];
|
|
}
|
|
|
|
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
|
if (task.type !== "condition") return false;
|
|
const raw = task as Record<string, unknown>;
|
|
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
|
const serialized = JSON.stringify(filterSource);
|
|
if (
|
|
serialized.includes(`${targetTaskName}.$status`) ||
|
|
serialized.includes(`${targetTaskName}.status`) ||
|
|
serialized.includes(`${targetTaskName}.result`) ||
|
|
serialized.includes(`${targetTaskName}.data`)
|
|
) {
|
|
return true;
|
|
}
|
|
return (
|
|
serialized.includes(targetTaskName) &&
|
|
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
|
);
|
|
}
|
|
|
|
function findUnguardedDatalinkEdits(
|
|
tasks: WorkflowTask[],
|
|
basePath: string,
|
|
createTaskName: string
|
|
): Array<{ task: WorkflowTask; path: string }> {
|
|
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
|
tasks.forEach((task, idx) => {
|
|
const path = `${basePath}.${idx}`;
|
|
if (task.type === "ekuaibao-datalink-edit") {
|
|
found.push({ task, path });
|
|
return;
|
|
}
|
|
if (taskGuardsStatusOf(task, createTaskName)) {
|
|
return;
|
|
}
|
|
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
|
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
|
}
|
|
});
|
|
return found;
|
|
}
|
|
|
|
export function analyzeWorkflow(
|
|
detail: WorkflowDetail,
|
|
options: AnalyzeWorkflowOptions = {}
|
|
): WorkflowAnalysis {
|
|
const ast = toAst(detail.tasks);
|
|
const dependencies: WorkflowDependency[] = [];
|
|
const diagnostics: WorkflowDiagnostic[] = [];
|
|
|
|
if (detail.state === 0) {
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "WORKFLOW_DISABLED",
|
|
path: "workflow",
|
|
message:
|
|
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
|
});
|
|
}
|
|
|
|
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
|
tasks.forEach((task, index) => {
|
|
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
|
const refs = referencesFromTask(task);
|
|
if (refs.length) {
|
|
dependencies.push({ path, taskType: task.type, references: refs });
|
|
}
|
|
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
|
diagnostics.push({
|
|
severity: "error",
|
|
code: "EMPTY_CODE",
|
|
path,
|
|
message: "代码节点没有可执行脚本",
|
|
});
|
|
}
|
|
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "EMPTY_BRANCH",
|
|
path,
|
|
message: `${task.type} 控制节点没有子节点`,
|
|
});
|
|
}
|
|
if (!KNOWN_TYPES.has(task.type)) {
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "UNKNOWN_TASK_TYPE",
|
|
path,
|
|
message: `未收录的节点类型: ${task.type}`,
|
|
});
|
|
}
|
|
|
|
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
|
if (insideEvery && task.type === "flow-create-task") {
|
|
const onError = (task as Record<string, unknown>).onError as
|
|
| { defaultAction?: string }
|
|
| undefined;
|
|
if (onError?.defaultAction === "SKIP") {
|
|
const subsequentSiblings = tasks.slice(index + 1);
|
|
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
|
subsequentSiblings.forEach((sibling, relIdx) => {
|
|
const siblingIndex = index + 1 + relIdx;
|
|
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
|
if (sibling.type === "ekuaibao-datalink-edit") {
|
|
unguardedEdits.push({ task: sibling, path: siblingPath });
|
|
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
|
unguardedEdits.push(
|
|
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
|
);
|
|
}
|
|
});
|
|
|
|
for (const edit of unguardedEdits) {
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
|
path: edit.path,
|
|
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
|
if (task.type === "flow-create-task") {
|
|
const specId = getTaskSpecificationId(task);
|
|
const spec = specId ? options.specifications?.[specId] : undefined;
|
|
const formEntries = getTaskFormEntries(task).filter(
|
|
(entry) =>
|
|
entry.value !== undefined &&
|
|
entry.value !== null &&
|
|
String(entry.value).trim() !== ""
|
|
);
|
|
|
|
const specComponents =
|
|
spec?.components ??
|
|
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
|
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
|
: []);
|
|
|
|
if (spec && specComponents.length && formEntries.length > 0) {
|
|
const matchedComponents = specComponents.filter((comp) => {
|
|
const compKey = comp.name || comp.field || "";
|
|
return formEntries.some(
|
|
(entry) =>
|
|
(Boolean(compKey) && entry.key === compKey) ||
|
|
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
|
);
|
|
});
|
|
|
|
const linkageSources = matchedComponents.filter(
|
|
(comp) =>
|
|
Boolean(comp.assignmentRule) ||
|
|
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
|
);
|
|
|
|
for (const src of linkageSources) {
|
|
const srcKey = src.name || src.field || src.label || "";
|
|
const overrideTargets = matchedComponents
|
|
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
|
.map((comp) => {
|
|
const list = comp.priorityList || comp.priority || [];
|
|
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
|
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
|
const linkagePriority = linkage?.priority ?? linkage?.value;
|
|
const manualPriority = manual?.priority ?? manual?.value;
|
|
if (
|
|
linkagePriority !== undefined &&
|
|
manualPriority !== undefined &&
|
|
linkagePriority > manualPriority
|
|
) {
|
|
return {
|
|
comp,
|
|
compKey: comp.name || comp.field || comp.label || "",
|
|
linkagePriority,
|
|
manualPriority,
|
|
};
|
|
}
|
|
return undefined;
|
|
})
|
|
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
|
|
|
if (overrideTargets.length > 0) {
|
|
const affectedDesc = overrideTargets
|
|
.map(
|
|
(t) =>
|
|
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
|
)
|
|
.join("、");
|
|
diagnostics.push({
|
|
severity: "warning",
|
|
code: "LINKAGE_PRIORITY_OVERRIDE",
|
|
path,
|
|
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
|
});
|
|
};
|
|
|
|
visit(detail.tasks);
|
|
return {
|
|
workflow: {
|
|
id: detail.id,
|
|
label: detail.label,
|
|
state: detail.state,
|
|
version: detail.version,
|
|
},
|
|
ast,
|
|
dependencies,
|
|
diagnostics,
|
|
};
|
|
}
|
|
|