Files
hose-use/src/cli/commands/workflow/draft.ts
T
gitea e00adbe5a8 feat(workflow): 增强 MVEL 脚本条件块变量首次赋值与 break 静态拦截
- 在 `lintMvelCode` 中新增 `mvel-unscoped-block-assignment` 规则,检测在 if/else/switch/catch 等条件分支块内首次赋值但未在外部预先初始化的变量,提前防范 MVEL2 优化编译模式下的 `unresolvable property or identifier` 运行时反射异常
- 新增 `mvel-unsupported-break` 规则,拦截 MVEL2 循环中不支持的 `break` 控制流关键字,引导改用条件标志位控制终止
- 在 `workflow save` 草稿保存前自动注入工作流全节点脚本静态健康度扫描,及时透出代码告警
- 补充对应的单元测试用例,覆盖块内未声明赋值、预声明/三元表达式放行及 break 拦截场景
2026-11-13 17:49:06 +08:00

240 lines
11 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 { readFileSync, writeFileSync } from "node:fs";
import { EkbError } from "../../../core/errors.js";
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow, lintWorkflowScripts } from "../../../domains/platform/workflow/services.js";
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js";
import {
applyWorkflowPathPatch,
beginWorkflowSave,
commitWorkflowSave,
createWorkflowDraft,
failWorkflowSave,
hasWorkflowVersionConflict,
} from "../../../domains/platform/workflow/state/index.js";
import { stringOption, booleanOption } from "../../parser.js";
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
import { printJson } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { PLATFORM_ID_OPTION_KEYS, formatWorkflowVersion } from "./shared.js";
export async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
const file = stringOption(parsed.options, ["file", "input", "from"]);
const path = stringOption(parsed.options, ["path", "field"]);
const rawValue = parsed.options.value;
const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]);
const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]);
if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) {
return {
stdout: "",
stderr: "用法: hose-use workflow patch <pipelineId> --file=<workflow.json> --path=<tasks.0.code> --value=<值> (--output=<patched.json>|--in-place) [--value-json]\n",
exitCode: 1,
};
}
let source: unknown;
try {
source = JSON.parse(readFileSync(file, "utf8"));
} catch (error) {
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
}
const sourceWorkflow = WorkflowDetailSchema.parse(source);
if (sourceWorkflow.id !== pipelineId) {
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`);
}
let value: unknown = rawValue;
if (booleanOption(parsed.options, ["value-json", "valueJson"])) {
try {
value = JSON.parse(rawValue);
} catch (error) {
throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`);
}
}
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
const target = inPlace ? file : output!;
requireMutationConfirmation(
parsed,
runtime,
"写入工作流草稿文件",
`hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, {
pipelineId,
path,
value,
tasksVersion: patched.tasksVersion,
});
}
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 };
}
export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
const file = stringOption(parsed.options, ["file", "input", "from"]);
if (!pipelineId || !file) {
return {
stdout: "",
stderr: "用法: hose-use workflow save <pipelineId> --file=<workflow.json> [--force-write] [--in-place]\n",
exitCode: 1,
};
}
let draftWorkflow: unknown;
try {
draftWorkflow = JSON.parse(readFileSync(file, "utf8"));
} catch (error) {
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
}
const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow);
if (parsedWorkflow.id !== pipelineId) {
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
}
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]);
// 保存前静态代码健康度检查
const scriptLintReport = lintWorkflowScripts(parsedWorkflow as any);
const scriptWarnings: string[] = [];
if (scriptLintReport.totalCodeNodes > 0) {
for (const node of scriptLintReport.reports) {
if (node.issues.length > 0) {
for (const iss of node.issues) {
const icon = iss.level === "error" ? "❌" : "⚠️";
const loc = iss.line ? `(L${iss.line})` : "";
scriptWarnings.push(`${icon} 节点 [${node.nodeName}] ${loc}: [${iss.rule}] ${iss.message}`);
}
}
}
}
requireMutationConfirmation(
parsed,
runtime,
"保存工作流草稿到远端",
`hose-use workflow save ${pipelineId} --file=${file} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, {
file,
version: parsedWorkflow.version,
tasksVersion: parsedWorkflow.tasksVersion,
forceWrite,
syncFile,
...(scriptWarnings.length > 0 ? { scriptWarnings } : {}),
});
}
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
const remote = await getWorkflowDetail(piperClient, pipelineId);
let state = createWorkflowDraft(parsedWorkflow);
state = {
...state,
revision: 1,
status: "dirty",
dirtyPaths: ["*"],
};
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
throw new Error(
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。请重新导出最新工作流后再改;后续保存可加 --in-place 自动同步本地文件版本。确认要覆盖时使用 --force-write。`
);
}
state = beginWorkflowSave(state);
const localWorkflowForSync = state.workflow;
try {
const payload = state.workflow.inputs?.length
? state.workflow
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
let partialError: WorkflowSavePartialError | undefined;
const saved = await updateWorkflow(piperClient, payload).catch((error: unknown) => {
if (!(error instanceof WorkflowSavePartialError)) throw error;
partialError = error;
return error.savedWorkflow;
});
state = commitWorkflowSave(state, saved);
if (partialError) state = { ...state, status: "partial", error: partialError.message };
let fileSynced = false;
let fileSyncWarning = "";
if (syncFile) {
try {
const syncedWorkflow = {
...localWorkflowForSync,
version: saved.version,
tasksVersion: saved.tasksVersion,
updateTime: saved.updateTime,
};
writeFileSync(file, `${JSON.stringify(syncedWorkflow, null, 2)}\n`, "utf8");
fileSynced = true;
} catch (error) {
fileSyncWarning = `本地文件同步失败: ${error instanceof Error ? error.message : String(error)}`;
}
}
const quoteArg = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
const nextAction = `hose-use workflow refresh-chooses ${quoteArg(pipelineId)} --platform-id=${quoteArg(platformId)} --corp=${quoteArg(runtime.selectedCorp!.id)} --yes`;
const result = {
success: !partialError,
...(partialError ? { remoteSaved: true, failedStep: "chooses", nextAction, message: partialError.message } : {}),
pipelineId,
status: state.status,
version: saved.version,
tasksVersion: saved.tasksVersion,
updateTime: saved.updateTime,
fileSynced,
...(fileSyncWarning ? { fileSyncWarning } : {}),
};
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: partialError ? 1 : 0 };
if (partialError) return {
stdout: `⚠️ ${partialError.message}\n${fileSynced ? "已同步本地文件版本。\n" : ""}恢复命令: ${nextAction}\n`,
stderr: fileSyncWarning,
exitCode: 1,
};
return {
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功:${formatWorkflowVersion(saved)}。${fileSynced ? "\n📝 已同步更新本地文件。" : ""}${fileSyncWarning ? `\n⚠️ ${fileSyncWarning}` : ""}\n`,
stderr: fileSyncWarning,
exitCode: 0,
};
} catch (error) {
state = failWorkflowSave(state, error);
if (error instanceof EkbError) throw error;
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
}
}
export async function handleRefreshChooses(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) throw new Error("请提供工作流 ID: hose-use workflow refresh-chooses <pipelineId> --yes");
requireMutationConfirmation(parsed, runtime, "刷新工作流元数据", `hose-use workflow refresh-chooses ${pipelineId} --yes`);
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "刷新工作流元数据", pipelineId, { retryStep: "chooses", saveWorkflow: false });
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
const client = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
await refreshWorkflowChooses(client, pipelineId);
return { stdout: runtime.jsonMode ? printJson({ success: true, pipelineId, metadataRefreshed: true }, runtime.outputOptions) : `工作流 [${pipelineId}] 元数据刷新成功,未重新提交快照。\n`, stderr: "", exitCode: 0 };
}
async function resolveWorkflowPlatformId(
parsed: CliParsedArgs,
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
pipelineId: string
): Promise<string> {
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
if (explicit) return explicit;
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
if (!match?.platformId) {
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId> 或 --app-id=<appId>`);
}
return match.platformId;
}