feat(workflow): add docs domain and unlicensed powerCode diagnostics, webhook sample injector, and snapshot sanitizer
This commit is contained in:
1 parent
60d0b8ffc1
commit
6e40faccff
14 files changed
+640
-10
No files matched your search
@@ -38,7 +38,29 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
// 离线或受限网络环境下忽略探针失败
|
||||
}
|
||||
|
||||
const result = analyzeWorkflow(detail, { specifications, availableNodeTypes });
|
||||
let openedPowerCodes: Set<string> | undefined;
|
||||
try {
|
||||
const { fetchClientGoods } = await import("../../../domains/store/tools.js");
|
||||
const goods = await fetchClientGoods(runtime.selectedCorp!, { isAll: true });
|
||||
const codes = new Set<string>();
|
||||
for (const item of goods) {
|
||||
const isOpened = item.status?.toUpperCase() === "OPENED" || item.onLineStatus?.toUpperCase() === "ONLINE";
|
||||
if (isOpened && Array.isArray(item.powers)) {
|
||||
for (const power of item.powers) {
|
||||
if (typeof power === "string") {
|
||||
codes.add(power.toLowerCase());
|
||||
} else if (power && typeof power === "object" && power.powerCode) {
|
||||
codes.add(power.powerCode.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
openedPowerCodes = codes;
|
||||
} catch {
|
||||
// 离线或无商店应用查询权限时忽略
|
||||
}
|
||||
|
||||
const result = analyzeWorkflow(detail, { specifications, availableNodeTypes, openedPowerCodes });
|
||||
const failOnAlert = booleanOption(parsed.options, ["fail", "fail-on-alert", "failOnAlert"]);
|
||||
const exitCode = failOnAlert && !result.summary.passed ? 2 : 0;
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import { handleNodeCommand } from "./node.js";
|
||||
import { handleWorkflowTailCommand } from "./tail.js";
|
||||
import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js";
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -114,10 +115,14 @@ export async function handleWorkflowCommand(
|
||||
case "dictionary":
|
||||
case "dict":
|
||||
return handleWorkflowEnum(parsed, runtime);
|
||||
case "webhook":
|
||||
case "webhook-send":
|
||||
case "webhooks":
|
||||
return handleWebhookCommand(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,14 +71,21 @@ export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const isDraft = detail.state === 0;
|
||||
const tasksVersion = (detail as Record<string, unknown>).tasksVersion;
|
||||
const summary = printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"工作流名称": detail.label,
|
||||
"状态": detail.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
"版本号": detail.version || "-",
|
||||
"当前状态": detail.state === 1 ? "🟢 线上启用 (state=1)" : "⚪ 停用/未发布草稿 (state=0)",
|
||||
"发布版本 (version)": detail.version || "-",
|
||||
...(tasksVersion !== undefined ? { "草稿版本 (tasksVersion)": String(tasksVersion) } : {}),
|
||||
"节点总数": detail.tasks?.length ?? 0,
|
||||
});
|
||||
|
||||
const draftNotice = isDraft
|
||||
? `\n💡 提示: 该工作流当前处于未发布草稿态 (state=0)。草稿与生产流程共享同一实例 ID 和历史记录;直接修改草稿将在发布后覆盖线上逻辑。如需安全隔离测试,请先执行: hose-use workflow copy ${detail.id}\n`
|
||||
: "";
|
||||
|
||||
let taskList = "";
|
||||
if (detail.tasks && detail.tasks.length > 0) {
|
||||
const taskRows = detail.tasks.map((t, i) => [
|
||||
@@ -92,7 +99,7 @@ export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Pro
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 工作流详情 ======\n${summary}\n${taskList}\n`,
|
||||
stdout: `====== 工作流详情 ======\n${summary}\n${draftNotice}${taskList}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
import * as shared from "./shared.js";
|
||||
import * as services from "../../../domains/platform/services.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
function createMockRuntime(overrides: Partial<CliRuntime> = {}): CliRuntime {
|
||||
const corp: any = {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
corpId: "corp-1",
|
||||
env: "test",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: {
|
||||
corpId: "corp-1",
|
||||
accessToken: "token-1",
|
||||
staffId: "user-1",
|
||||
},
|
||||
};
|
||||
return {
|
||||
corpContext: {
|
||||
listCorps: () => [corp],
|
||||
getCurrent: () => corp,
|
||||
switchCorp: () => true,
|
||||
resolve: () => corp,
|
||||
} as any,
|
||||
selectedCorp: corp,
|
||||
jsonMode: false,
|
||||
outputOptions: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workflow webhook command", () => {
|
||||
let spies: ReturnType<typeof spyOn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const spy of spies) {
|
||||
spy.mockRestore();
|
||||
}
|
||||
spies = [];
|
||||
});
|
||||
|
||||
it("prints usage when pipelineId is not provided", async () => {
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "workflow",
|
||||
action: "webhook",
|
||||
args: [],
|
||||
options: {},
|
||||
raw: ["webhook"],
|
||||
};
|
||||
const runtime = createMockRuntime();
|
||||
const result = await handleWebhookCommand(parsed, runtime);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("用法: hose-use workflow webhook");
|
||||
});
|
||||
|
||||
it("previews webhook payload in dry-run mode", async () => {
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "workflow",
|
||||
action: "webhook",
|
||||
args: ["send", "881196955148578838"],
|
||||
options: { "dry-run": true, body: '{"foo":"bar"}' },
|
||||
raw: ["send", "881196955148578838", "--dry-run"],
|
||||
};
|
||||
const runtime = createMockRuntime();
|
||||
|
||||
const mockDetail = {
|
||||
id: "881196955148578838",
|
||||
label: "测试 Webhook 工作流",
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_webhook",
|
||||
type: "webhook",
|
||||
label: "Webhook 触发器",
|
||||
urlPath: "test-token-12345",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({
|
||||
client: {} as any,
|
||||
clients: { ekbClient: {} as any } as any,
|
||||
}),
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValue(mockDetail as any)
|
||||
);
|
||||
|
||||
const result = await handleWebhookCommand(parsed, runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("[DRY-RUN]");
|
||||
expect(result.stdout).toContain("881196955148578838");
|
||||
expect(result.stdout).toContain("https://piper.ekuaibao.com/api/webhook/test-token-12345");
|
||||
});
|
||||
|
||||
it("rejects non-webhook workflows with clear error", async () => {
|
||||
const parsed: CliParsedArgs = {
|
||||
area: "workflow",
|
||||
action: "webhook",
|
||||
args: ["881196955148578838"],
|
||||
options: { yes: true },
|
||||
raw: ["881196955148578838", "--yes"],
|
||||
};
|
||||
const runtime = createMockRuntime();
|
||||
|
||||
const mockDetail = {
|
||||
id: "881196955148578838",
|
||||
label: "定时触发流程",
|
||||
tasks: [
|
||||
{
|
||||
name: "trigger_clock",
|
||||
type: "clock",
|
||||
label: "定时触发器",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
spies.push(
|
||||
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({
|
||||
client: {} as any,
|
||||
clients: { ekbClient: {} as any } as any,
|
||||
}),
|
||||
spyOn(services, "getWorkflowDetail").mockResolvedValue(mockDetail as any)
|
||||
);
|
||||
|
||||
const result = await handleWebhookCommand(parsed, runtime);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("首节点不是 Webhook 触发器");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import ky from "ky";
|
||||
import { getWorkflowDetail } from "../../../domains/platform/services.js";
|
||||
import { getBillByCodeOrId } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleWebhookCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const firstArg = parsed.args[0]?.toLowerCase();
|
||||
const isActionVerb = firstArg === "send" || firstArg === "trigger" || firstArg === "post";
|
||||
const pipelineId =
|
||||
(isActionVerb ? parsed.args[1] : parsed.args[0]) ||
|
||||
stringOption(parsed.options, ["id", "pipelineId", "source"]);
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"用法: hose-use workflow webhook [send] <pipelineId> [选项]",
|
||||
"",
|
||||
"说明:",
|
||||
" 向工作流的 Webhook 触发器地址发送测试数据,生成新的数据样本。",
|
||||
" 可彻底解决 Web 控制台复制或新建工作流后【获取更多数据样本】收不到事件的问题。",
|
||||
"",
|
||||
"选项:",
|
||||
" --body='{...}' 指定自定义 JSON 请求体",
|
||||
" --file=<path.json> 从 JSON 文件读取请求体",
|
||||
" --bill=<单号|单据ID> 抓取真实单据数据作为测试载荷发送",
|
||||
" --dry-run 仅预览目标 Webhook 地址与载荷,不实际发送",
|
||||
" --yes 确认发送网络请求",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow webhook send 881196955148578838 --bill=spWC2AmbRbovsQ --yes",
|
||||
" hose-use workflow webhook 881196955148578838 --body='{\"event\":\"test\"}' --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
const triggerNode =
|
||||
detail.tasks?.find(
|
||||
(t) => t.type === "webhook" || t.type === "datalink-button-trigger"
|
||||
) || detail.tasks?.[0];
|
||||
|
||||
const triggerType = triggerNode?.type || "unknown";
|
||||
if (triggerType !== "webhook" && triggerType !== "datalink-button-trigger") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 工作流 [${detail.label || pipelineId}] 的首节点不是 Webhook 触发器 (当前类型: ${triggerType})。\n该命令仅适用于以 Webhook 或外部事件为触发源的工作流。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const rawNode = triggerNode as Record<string, unknown>;
|
||||
const rawPath =
|
||||
(typeof rawNode.urlPath === "string" && rawNode.urlPath) ||
|
||||
(typeof rawNode.url === "string" && rawNode.url) ||
|
||||
(typeof rawNode.path === "string" && rawNode.path);
|
||||
|
||||
if (!rawPath) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 未能在 Webhook 触发器节点 [${triggerNode?.name || "-"}] 中找到有效的调用路径 (urlPath)。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const webhookUrl = rawPath.startsWith("http")
|
||||
? rawPath
|
||||
: `https://piper.ekuaibao.com/api/webhook/${rawPath.replace(/^\/+/, "")}`;
|
||||
|
||||
let payload: Record<string, unknown> = {};
|
||||
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
|
||||
const filePath = stringOption(parsed.options, ["file", "path"]);
|
||||
const billId = stringOption(parsed.options, ["bill", "flow", "code"]);
|
||||
|
||||
if (billId) {
|
||||
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
|
||||
try {
|
||||
const bills = await getBillByCodeOrId(clients.ekbClient, corpId, billId);
|
||||
if (!bills.length) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 未找到单号/ID 为 [${billId}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
const bill = bills[0];
|
||||
payload = {
|
||||
event: "flow.submit",
|
||||
action: "flow.submit",
|
||||
flowId: bill.billId,
|
||||
code: bill.billCode,
|
||||
title: bill.title,
|
||||
data: bill,
|
||||
mockTimestamp: Date.now(),
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 抓取单据 [${billId}] 失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (rawBody) {
|
||||
try {
|
||||
payload = JSON.parse(rawBody);
|
||||
} catch (e: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ --body 参数不是合法的 JSON 格式: ${e instanceof Error ? e.message : String(e)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else if (filePath) {
|
||||
if (!existsSync(filePath)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 指定的 Payload 文件不存在: ${filePath}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
try {
|
||||
payload = JSON.parse(readFileSync(filePath, "utf-8"));
|
||||
} catch (e: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 读取并解析文件 [${filePath}] 失败: ${e instanceof Error ? e.message : String(e)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
payload = {
|
||||
event: "manual_sample_test",
|
||||
pipelineId,
|
||||
triggerType,
|
||||
timestamp: Date.now(),
|
||||
message: "Sample event injected via hose-use workflow webhook send",
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "发送 Webhook 测试事件", pipelineId, {
|
||||
pipelineId,
|
||||
pipelineName: detail.label,
|
||||
targetUrl: webhookUrl,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"发送 Webhook 测试事件",
|
||||
`hose-use workflow webhook send ${pipelineId}${billId ? ` --bill=${billId}` : ""} --yes`
|
||||
);
|
||||
|
||||
let responseText = "";
|
||||
let responseStatus = 200;
|
||||
try {
|
||||
const res = await ky.post(webhookUrl, {
|
||||
json: payload,
|
||||
timeout: 15000,
|
||||
throwHttpErrors: false,
|
||||
});
|
||||
responseStatus = res.status;
|
||||
responseText = await res.text();
|
||||
} catch (err: unknown) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `❌ 发送 Webhook 请求失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const isSuccess = responseStatus >= 200 && responseStatus < 300;
|
||||
const resultData = {
|
||||
pipelineId,
|
||||
pipelineName: detail.label,
|
||||
webhookUrl,
|
||||
statusCode: responseStatus,
|
||||
payloadSize: JSON.stringify(payload).length,
|
||||
response: responseText,
|
||||
success: isSuccess,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(resultData, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: isSuccess ? 0 : 2,
|
||||
};
|
||||
}
|
||||
|
||||
const out = [
|
||||
isSuccess ? "✅ Webhook 测试样本已成功发送!" : "⚠️ Webhook 请求已发送但服务端返回非 2xx 状态码:",
|
||||
printKeyValue({
|
||||
"工作流 ID": pipelineId,
|
||||
"工作流名称": detail.label,
|
||||
"Webhook 目标地址": webhookUrl,
|
||||
"HTTP 状态码": String(responseStatus),
|
||||
"载荷字节大小": `${resultData.payloadSize} bytes`,
|
||||
}),
|
||||
"",
|
||||
"服务端响应体:",
|
||||
responseText || "(空响应体)",
|
||||
"",
|
||||
"下一步操作建议:",
|
||||
" 1. Web 控制台: 在工作流首节点触发器中点击【获取更多数据样本】,直接选取刚刚注入的样本;",
|
||||
` 2. 命令行调试: 执行 hose-use workflow test ${pipelineId} --sample=1 进行沙箱运行。`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: `${out}\n`,
|
||||
stderr: "",
|
||||
exitCode: isSuccess ? 0 : 2,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user