merge(main): 合入 main (v0.8.22) 解决 catalog 灰度开通网关冲突
- 解决 src/domains/platform/workflow/transport/catalog/api.ts 中的冲突, 合并 innerData 解析与 interpretGatewayOutcome 判定逻辑; - 执行 bun install 补齐 qrcode-terminal 依赖; - 全部 1021 个单测通过,tsc --noEmit 校验通过。
This commit is contained in:
commit
c3e39fe77a
53 files changed
+20116
-640
No files matched your search
@@ -220,7 +220,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"check": "检查错误管道",
|
||||
"enum": "查询在线枚举字典(不可用时使用内置字典)",
|
||||
"lint-script": "静态检查 JavaScript / MVEL 脚本",
|
||||
"eval-script": "在本地沙箱中模拟执行脚本"
|
||||
"eval-script": "在本地沙箱中模拟执行脚本",
|
||||
"webhook": "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||
"link": "生成工作流设计器 (Piper) 免密直达链接 (包含特权警告)"
|
||||
},
|
||||
"options": [
|
||||
"--flow=<单号> 指定测试单据",
|
||||
@@ -271,9 +273,13 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"run-script": "eval-script",
|
||||
"enums": "enum",
|
||||
"dictionary": "enum",
|
||||
"dict": "enum"
|
||||
"dict": "enum",
|
||||
"webhook-send": "webhook",
|
||||
"webhooks": "webhook",
|
||||
"url": "link",
|
||||
"web": "link"
|
||||
},
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
|
||||
},
|
||||
"bill": {
|
||||
"summary": "单据检索、表单规格诊断与审批动作",
|
||||
@@ -832,8 +838,9 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"forward": "transfer"
|
||||
},
|
||||
flags: {
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff staff-id staffId alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
|
||||
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff staff-id staffId alias corp-name count limit n start offset state corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
|
||||
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates qr check", "boolean"),
|
||||
...flagList("status", "boolean-or-value")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,10 @@ import {
|
||||
clearAssistPlatformSession,
|
||||
} from "../../../core/auth/assist-platform-store.js";
|
||||
import { createAssistPlatformClient } from "../../../core/http/assist-platform-client.js";
|
||||
import { searchCorporations } from "../../../domains/assist-platform/services.js";
|
||||
import {
|
||||
searchCorporations,
|
||||
loginAssistPlatformByQrCode,
|
||||
} from "../../../domains/assist-platform/services.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -66,35 +69,150 @@ export async function handleLogin(
|
||||
};
|
||||
}
|
||||
|
||||
// 查看当前协助平台会话状态
|
||||
const checkStatusOnly = booleanOption(parsed.options, ["status", "check"]);
|
||||
const forceQr = booleanOption(parsed.options, ["qr", "force"]);
|
||||
const isInteractive = Boolean(
|
||||
process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test"
|
||||
);
|
||||
const existing = loadAssistPlatformSession();
|
||||
if (!existing || !existing.token) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
// 如果仅检查状态 (--status)
|
||||
if (checkStatusOnly) {
|
||||
if (!existing || !existing.token) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 未检测到协助平台登录凭证。\n请运行: hose-use assist-platform login 进行扫码登录\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const testClient = createAssistPlatformClient({
|
||||
token: existing.token,
|
||||
baseUrl: existing.baseUrl,
|
||||
hoseAccessToken: existing.hoseAccessToken,
|
||||
});
|
||||
|
||||
try {
|
||||
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
|
||||
} catch {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 协助平台凭证已过期或无效。\n请运行: hose-use assist-platform login 进行扫码登录\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ valid: true, ...existing }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 凭证有效 (已登录)",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: printJson(existing),
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 已登录",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
// 如果已有凭证且未强制发起扫码,先探测有效性
|
||||
if (existing?.token && !forceQr) {
|
||||
let isValid = false;
|
||||
const testClient = createAssistPlatformClient({
|
||||
token: existing.token,
|
||||
baseUrl: existing.baseUrl,
|
||||
hoseAccessToken: existing.hoseAccessToken,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
try {
|
||||
await searchCorporations(testClient, { limit: { start: 0, count: 1 } });
|
||||
isValid = true;
|
||||
} catch {
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(existing),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const pairs: Record<string, string> = {
|
||||
协助平台状态: "🟢 已登录 (凭证有效)",
|
||||
操作员工姓名: existing.userName || "运营实施人员",
|
||||
基础服务地址: existing.baseUrl || "https://unity.ekuaibao.com/api",
|
||||
当前会话凭证: existing.token.replace(/(.{4}).*(.{4})/, "$1****$2"),
|
||||
最后更新时间: new Date(existing.updatedAt).toLocaleString("zh-CN", { hour12: false }),
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: `====== 合思协助平台当前会话 ======\n${printKeyValue(pairs)}\n\n💡 提示: 当前凭证处于有效状态。如需重新扫码登录,请运行: hose-use assist-platform login --qr\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 凭证不存在或已失效:非交互/测试模式下给出指引,交互模式或显式 --qr 下直接自动拉起扫码登录
|
||||
if (!isInteractive && !forceQr) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未检测到协助平台登录凭证。\n用法:\n hose-use assist-platform login [--qr]\n hose-use assist-platform login --token <TOKEN> [--user <姓名>]\n hose-use assist-platform login --logout (清理凭证)\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 自动发起钉钉交互式扫码登录流程 ──────────────────────────
|
||||
try {
|
||||
const loginRes = await loginAssistPlatformByQrCode({
|
||||
timeoutMs: 60000,
|
||||
onQrCode: (qrText, dingUrl) => {
|
||||
if (!runtime.jsonMode) {
|
||||
process.stdout.write(`\n====== 合思协助平台钉钉扫码登录 ======\n`);
|
||||
process.stdout.write(`请使用钉钉 App 扫描下方二维码确认登录(有效期 60 秒):\n\n`);
|
||||
process.stdout.write(`${qrText}\n\n`);
|
||||
process.stdout.write(`🔗 快捷授权链接: ${dingUrl}\n\n`);
|
||||
process.stdout.write(`等待钉钉扫码并确认中... (最长等待 60 秒)\n`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
success: true,
|
||||
token: loginRes.token,
|
||||
userName: loginRes.userName,
|
||||
baseUrl: loginRes.baseUrl,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `\n[SUCCESS] 协助平台凭证已自动更新成功!\n操作人员: ${loginRes.userName}\n会话 Token: ${loginRes.token}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 协助平台扫码登录失败: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2331,5 +2331,90 @@ describe("CLI - workflow list 轻量化与名称搜索", () => {
|
||||
expect(data.workflows[0].pipelineName).toBe("待摊台账拆分计划");
|
||||
expect(data.totalWorkflows).toBe(1);
|
||||
});
|
||||
|
||||
it("workflow link 生成高特权免密直达链接并输出安全警告与自建应用信息", async () => {
|
||||
const mockSessionClient = {
|
||||
get: () => ({
|
||||
json: async () => ({ id: "mock.jwt.token" }),
|
||||
}),
|
||||
};
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
sessionClient: mockSessionClient,
|
||||
} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: [
|
||||
{
|
||||
id: "wf_001",
|
||||
pipelineName: "待摊台账拆分计划",
|
||||
platformId: "app_platform_1",
|
||||
platformName: "商机台账",
|
||||
state: 1,
|
||||
},
|
||||
] as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "link",
|
||||
args: ["wf_001"],
|
||||
options: {},
|
||||
raw: ["workflow", "link", "wf_001"],
|
||||
},
|
||||
mockRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("【高特权免密直达警告】");
|
||||
expect(res.stdout).toContain("所属自建应用 : 商机台账 (app_platform_1)");
|
||||
expect(res.stdout).toContain("目标工作流 : 待摊台账拆分计划 (wf_001)");
|
||||
expect(res.stdout).toContain("https://piper.ekuaibao.com/#/workflow/wf_001?jwtToken=mock.jwt.token&$platformId=app_platform_1");
|
||||
});
|
||||
|
||||
it("workflow link --json 返回结构化授权链接与警告信息", async () => {
|
||||
const mockSessionClient = {
|
||||
get: () => ({
|
||||
json: async () => ({ id: "mock.jwt.token" }),
|
||||
}),
|
||||
};
|
||||
spies.push(
|
||||
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
|
||||
sessionClient: mockSessionClient,
|
||||
} as any),
|
||||
spyOn(platformServices, "listAllWorkflows").mockResolvedValue({
|
||||
workflows: [
|
||||
{
|
||||
id: "wf_001",
|
||||
pipelineName: "待摊台账拆分计划",
|
||||
platformId: "app_platform_1",
|
||||
platformName: "商机台账",
|
||||
state: 1,
|
||||
},
|
||||
] as any,
|
||||
errors: [],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await handleWorkflowCommand(
|
||||
{
|
||||
area: "workflow",
|
||||
action: "link",
|
||||
args: ["wf_001"],
|
||||
options: { json: true },
|
||||
raw: ["workflow", "link", "wf_001", "--json"],
|
||||
},
|
||||
{ ...mockRuntime, jsonMode: true }
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.pipelineId).toBe("wf_001");
|
||||
expect(data.platformName).toBe("商机台账");
|
||||
expect(data.jwtToken).toBe("mock.jwt.token");
|
||||
expect(data.warning).toContain("特权");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
| [analyze.ts](./analyze.ts)、[check.ts](./check.ts)、[diff.ts](./diff.ts) | 静态分析、健康检查与配置/执行差异 |
|
||||
| [script.ts](./script.ts)、[test.ts](./test.ts) | 脚本校验、求值与工作流测试 |
|
||||
| [tail.ts](./tail.ts)、[webhook.ts](./webhook.ts)、[enum.ts](./enum.ts) | 执行监听、Webhook 与业务枚举 |
|
||||
| [link.ts](./link.ts) | 工作流设计器 (Piper) 免密直达链接签发与高特权安全警告 |
|
||||
|
||||
## 保存和执行契约
|
||||
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { runCli } from "../../runner.js";
|
||||
import { renderScopedHelp } from "../../help.js";
|
||||
|
||||
const keys = ["HOSE_ENTERPRISES_DIR", "HOSE_CONFIG_FILE"] as const;
|
||||
const original = keys.map((key) => process.env[key]);
|
||||
let tempDir = "";
|
||||
|
||||
describe("workflow CLI ergonomics & layered help", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-ergonomics-"));
|
||||
const corps = join(tempDir, "corps");
|
||||
mkdirSync(corps, { recursive: true });
|
||||
writeFileSync(
|
||||
join(corps, "corp.json"),
|
||||
JSON.stringify({
|
||||
id: "corp",
|
||||
name: "Fixture",
|
||||
source: "manual",
|
||||
credentials: { accessToken: "fake", corpId: "corp", staffId: "staff" },
|
||||
})
|
||||
);
|
||||
writeFileSync(
|
||||
join(tempDir, "config.json"),
|
||||
JSON.stringify({ defaultCorpId: "corp", stateful: true })
|
||||
);
|
||||
process.env.HOSE_ENTERPRISES_DIR = corps;
|
||||
process.env.HOSE_CONFIG_FILE = join(tempDir, "config.json");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
keys.forEach((key, i) => {
|
||||
if (original[i] === undefined) delete process.env[key];
|
||||
else process.env[key] = original[i];
|
||||
});
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
tempDir = "";
|
||||
}
|
||||
});
|
||||
it("renders specialized layered help for workflow node add", () => {
|
||||
const help = renderScopedHelp(["workflow", "node", "add"]);
|
||||
expect(help).toContain("workflow node add -");
|
||||
expect(help).toContain("--type=<type>");
|
||||
expect(help).toContain("--sleep-time=<秒数>");
|
||||
expect(help).toContain("--set='key=value'");
|
||||
expect(help).toContain("--after=<节点name>");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("renders specialized layered help for workflow node edit", () => {
|
||||
const help = renderScopedHelp(["workflow", "node", "edit"]);
|
||||
expect(help).toContain("workflow node edit -");
|
||||
expect(help).toContain("--sleep-time=<秒数>");
|
||||
expect(help).toContain("--set='key=value'");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("renders specialized layered help for workflow test", () => {
|
||||
const help = renderScopedHelp(["workflow", "test"]);
|
||||
expect(help).toContain("workflow test -");
|
||||
expect(help).toContain("--flow=<单号>");
|
||||
expect(help).toContain("--body='{...}'");
|
||||
expect(help).toContain("--sample=<1|2|3>");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("renders specialized layered help for workflow webhook send", () => {
|
||||
const help = renderScopedHelp(["workflow", "webhook", "send"]);
|
||||
expect(help).toContain("workflow webhook send -");
|
||||
expect(help).toContain("--bill=<单号|单据ID>");
|
||||
expect(help).toContain("--body='{...}'");
|
||||
expect(help).toContain("支持选项:");
|
||||
});
|
||||
|
||||
it("runCli correctly resolves sub-subcommand help via --help flag", async () => {
|
||||
const result = await runCli(["workflow", "node", "add", "--help"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("workflow node add -");
|
||||
expect(result.stdout).toContain("--sleep-time=<秒数>");
|
||||
});
|
||||
|
||||
it("workflow test automatically swaps reversed arguments (billCode and 18-digit pipelineId)", async () => {
|
||||
const result = await runCli(["workflow", "test", "B26000148", "881196955148578838", "--dry-run"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("881196955148578838");
|
||||
expect(result.stdout).toContain("B26000148");
|
||||
});
|
||||
|
||||
it("workflow node add dry-run accepts --sleep-time directly", async () => {
|
||||
const result = await runCli([
|
||||
"workflow",
|
||||
"node",
|
||||
"add",
|
||||
"881196955148578838",
|
||||
"--type=task-dynamic-delay",
|
||||
"--sleep-time=5",
|
||||
"--dry-run",
|
||||
]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("追加工作流节点");
|
||||
expect(result.stdout).toContain("task-dynamic-delay");
|
||||
});
|
||||
|
||||
it("workflow node edit dry-run parses JSON payload in --set", async () => {
|
||||
const result = await runCli([
|
||||
"workflow",
|
||||
"node",
|
||||
"edit",
|
||||
"881196955148578838",
|
||||
"action_agree_normal",
|
||||
'--set={"authId":157,"appId":"4"}',
|
||||
"--dry-run",
|
||||
]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("修改工作流节点");
|
||||
expect(result.stdout).toContain('"authId":157');
|
||||
expect(result.stdout).toContain('"appId":"4"');
|
||||
});
|
||||
|
||||
it("WorkflowTaskSchema preserves authId and appId on http tasks without stripping", async () => {
|
||||
const { WorkflowTaskSchema } = await import("../../../domains/platform/workflow/models/nodes.js");
|
||||
const sample = {
|
||||
name: "action_test",
|
||||
type: "http",
|
||||
label: "http节点",
|
||||
groupName: "action",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0],
|
||||
status: "active",
|
||||
method: "POST",
|
||||
url: "https://example.com",
|
||||
header: [],
|
||||
params: [],
|
||||
successCode: ["200"],
|
||||
authId: 157,
|
||||
appId: "4",
|
||||
};
|
||||
const parsed = WorkflowTaskSchema.parse(sample);
|
||||
expect((parsed as any).authId).toBe(157);
|
||||
expect((parsed as any).appId).toBe("4");
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import { handleWorkflowTailCommand } from "./tail.js";
|
||||
import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js";
|
||||
import { handleWorkflowEnum } from "./enum.js";
|
||||
import { handleWebhookCommand } from "./webhook.js";
|
||||
import { handleWorkflowLink } from "./link.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -121,10 +122,14 @@ export async function handleWorkflowCommand(
|
||||
case "webhook-send":
|
||||
case "webhooks":
|
||||
return handleWebhookCommand(parsed, runtime);
|
||||
case "link":
|
||||
case "url":
|
||||
case "web":
|
||||
return handleWorkflowLink(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook, link\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import { listAllWorkflows } from "../../../domains/platform/workflow/services.js";
|
||||
|
||||
// ── 工作流设计器 (Piper) 免密直达链接签发 ────────────────────────────────────
|
||||
|
||||
export async function handleWorkflowLink(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const pipelineId =
|
||||
parsed.args[0] ||
|
||||
stringOption(parsed.options, ["id", "pipelineId", "workflowId", "pipeline"]);
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请提供工作流 ID: hose-use workflow link <pipelineId> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --corp=<corpId> 指定企业 (默认当前企业)",
|
||||
" --platform-id=<platformId> 指定所属自建应用 ID (可选,默认自动识别)",
|
||||
" --json 输出结构化 JSON 格式",
|
||||
"",
|
||||
"示例:",
|
||||
" hose-use workflow link 881196955148578838",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(corp);
|
||||
|
||||
// 1. 查询工作流元数据及所属自建应用平台信息
|
||||
let platformId = stringOption(parsed.options, ["platform-id", "platformId", "app-id", "appId"]);
|
||||
let platformName = "";
|
||||
let pipelineName = "";
|
||||
let workflowState: number | undefined;
|
||||
|
||||
try {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((w) => w.id === pipelineId);
|
||||
if (match) {
|
||||
pipelineName = match.pipelineName || "";
|
||||
platformId = platformId || match.platformId || "";
|
||||
platformName = match.platformName || "";
|
||||
workflowState = match.state;
|
||||
}
|
||||
} catch {
|
||||
// 容错降级
|
||||
}
|
||||
|
||||
platformId = platformId || corp.corpId || corp.id;
|
||||
|
||||
// 2. 向 EASO Realm 申请专属 3 段式 JWT 授权凭据
|
||||
let jwt = "";
|
||||
try {
|
||||
const jwtRes = await clients.sessionClient.get("api/engine/realm/$EASO/actions/jwt", {
|
||||
searchParams: { corpId: corp.corpId || corp.id },
|
||||
}).json<{ id: string }>();
|
||||
jwt = jwtRes.id;
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `获取 EASO JWT 授权凭据失败: ${errMsg}\n请确认当前会话是否有效或重新登录。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const directUrl = `https://piper.ekuaibao.com/#/workflow/${pipelineId}?jwtToken=${jwt}&$platformId=${encodeURIComponent(platformId)}`;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const output = {
|
||||
pipelineId,
|
||||
pipelineName: pipelineName || pipelineId,
|
||||
corpId: corp.corpId || corp.id,
|
||||
corpName: corp.name,
|
||||
env: corp.env || (corp.isTest ? "test" : "prod"),
|
||||
staffId: corp.staffId,
|
||||
staffName: corp.staffName || corp.staffId,
|
||||
platformId,
|
||||
platformName: platformName || "自建应用",
|
||||
state: workflowState,
|
||||
jwtToken: jwt,
|
||||
url: directUrl,
|
||||
warning: "⚠️ 该直达链接具备以当前员工身份免密直接访问和修改工作流的最高特权,严禁外泄!",
|
||||
};
|
||||
return {
|
||||
stdout: printJson(output, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const envTag = corp.isTest ? "🧪 测试环境" : "🚨 生产环境";
|
||||
const stateText =
|
||||
workflowState === 1
|
||||
? "🟢 启用中 (state=1)"
|
||||
: workflowState === 0
|
||||
? "⚪ 停用/草稿 (state=0)"
|
||||
: "未知";
|
||||
|
||||
const lines = [
|
||||
"⚠️ 【高特权免密直达警告】(HIGH PRIVILEGE DIRECT ACCESS WARNING)",
|
||||
" ----------------------------------------------------------------------",
|
||||
" • 该链接包含有效 3 段式 EASO JWT 授权凭证,在浏览器中打开即直接以当前员工身份进入!",
|
||||
" • 具有对该工作流的所有节点配置、代码脚本、版本发布及运行实例的完全编辑/删除/调试权限!",
|
||||
" • 严禁将该链接发送到群聊、公开工单或不受信渠道;使用完毕后请及时关闭会话标签页。",
|
||||
" ----------------------------------------------------------------------",
|
||||
"",
|
||||
"====== 合思工作流设计器 (Piper) 免密直达链接 ======",
|
||||
` 企业名称 : ${corp.name} (${corp.corpId || corp.id}) [${envTag}]`,
|
||||
` 操作人身份 : ${corp.staffName || "未指定姓名"} (${corp.staffId})`,
|
||||
` 所属自建应用 : ${platformName ? `${platformName} (${platformId})` : platformId}`,
|
||||
` 目标工作流 : ${pipelineName ? `${pipelineName} (${pipelineId})` : pipelineId}`,
|
||||
` 当前流程状态 : ${stateText}`,
|
||||
" 凭证有效时长 : 约 2 小时 (由合思 EASO Realm 动态颁发)",
|
||||
"",
|
||||
" 直达链接:",
|
||||
` ${directUrl}`,
|
||||
"",
|
||||
`Markdown 直达: [打开「${platformName || "工作流"}」设计器 (${pipelineName || pipelineId} - ${corp.staffName || "免密"})](${directUrl})`,
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js";
|
||||
import { ValidationError } from "../../../core/errors.js";
|
||||
import type { WorkflowDetail } from "../../../domains/platform/workflow/types.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { stringOption, numberOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -257,10 +257,12 @@ async function handleAddNode(
|
||||
stdout: "",
|
||||
stderr: [
|
||||
"请指定新增节点类型: --type=<类型>",
|
||||
"常见类型: code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"常见类型: task-dynamic-delay (延迟等待), code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --type=<type> 节点类型 (如 code-js2 / code)",
|
||||
" --type=<type> 节点类型 (如 task-dynamic-delay / code-js2 / http)",
|
||||
" --sleep-time=<秒数> 延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
" --set='key=value' 自定义节点属性注入",
|
||||
" --label=<标题> 节点类型标题",
|
||||
" --display-name=<名称> 设计器节点标题(displayName,最多 20 字符)",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费",
|
||||
@@ -269,7 +271,9 @@ async function handleAddNode(
|
||||
" --after=<前置节点name> 插入指定节点之后",
|
||||
" --yes 确认追加",
|
||||
"",
|
||||
"示例: hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||||
"示例:",
|
||||
" hose-use workflow node add 881196955148578838 --type=task-dynamic-delay --sleep-time=5 --after=action_123 --yes",
|
||||
" hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||||
].join("\n") + "\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
@@ -288,6 +292,33 @@ async function handleAddNode(
|
||||
code = await fs.readFile(codeFile, "utf-8");
|
||||
}
|
||||
|
||||
const rawSleepTime = numberOption(parsed.options, ["sleep-time", "sleepTime", "seconds"]);
|
||||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||||
const extra: Record<string, any> = {};
|
||||
if (rawSleepTime !== undefined) {
|
||||
extra.sleepTime = rawSleepTime;
|
||||
}
|
||||
if (rawSet) {
|
||||
if (rawSet.startsWith("{") && rawSet.endsWith("}")) {
|
||||
try {
|
||||
Object.assign(extra, JSON.parse(rawSet));
|
||||
} catch {
|
||||
// fallback
|
||||
}
|
||||
} else {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
try {
|
||||
extra[k] = JSON.parse(v);
|
||||
} catch {
|
||||
extra[k] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
@@ -295,6 +326,17 @@ async function handleAddNode(
|
||||
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
|
||||
);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
|
||||
pipelineId,
|
||||
type,
|
||||
label: label || "-",
|
||||
displayName: displayName || "-",
|
||||
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
|
||||
extra: Object.keys(extra).length ? extra : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
@@ -306,20 +348,9 @@ async function handleAddNode(
|
||||
code,
|
||||
parent,
|
||||
after,
|
||||
extra: Object.keys(extra).length ? extra : undefined,
|
||||
});
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
|
||||
pipelineId,
|
||||
newNodeName: newTask.name,
|
||||
type: newTask.type,
|
||||
label: newTask.label,
|
||||
displayName: newTask.displayName,
|
||||
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
|
||||
totalTasksCount: updatedWorkflow.tasks?.length || 0,
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -359,12 +390,13 @@ async function handleEditNode(
|
||||
"请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||||
"",
|
||||
"常用选项:",
|
||||
" --sleep-time=<秒数> 更新延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
" --set='key=value' 定向修改节点自定义属性 (如 --set='sleepTime=5')",
|
||||
" --label=<类型标题> 更新节点类型标题(服务端保存时可能重新生成)",
|
||||
" --display-name=<新名称> 更新设计器节点标题(displayName,最多 20 字符)",
|
||||
" --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费",
|
||||
" --code=<行内代码> 直接传入代码片段(短脚本)",
|
||||
" --desc=<描述> 更新节点描述",
|
||||
" --set='key=value' 定向修改节点自定义属性",
|
||||
" --dry-run 只预览变更",
|
||||
" --yes 确认保存修改",
|
||||
"",
|
||||
@@ -388,15 +420,27 @@ async function handleEditNode(
|
||||
|
||||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||||
const customSet: Record<string, any> = {};
|
||||
const rawSleepTime = numberOption(parsed.options, ["sleep-time", "sleepTime", "seconds"]);
|
||||
if (rawSleepTime !== undefined) {
|
||||
customSet.sleepTime = rawSleepTime;
|
||||
}
|
||||
if (rawSet) {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
if (rawSet.startsWith("{") && rawSet.endsWith("}")) {
|
||||
try {
|
||||
customSet[k] = JSON.parse(v);
|
||||
Object.assign(customSet, JSON.parse(rawSet));
|
||||
} catch {
|
||||
customSet[k] = v;
|
||||
// fallback to key=value if json parse fails
|
||||
}
|
||||
} else {
|
||||
const eqIdx = rawSet.indexOf("=");
|
||||
if (eqIdx !== -1) {
|
||||
const k = rawSet.slice(0, eqIdx).trim();
|
||||
const v = rawSet.slice(eqIdx + 1).trim();
|
||||
try {
|
||||
customSet[k] = JSON.parse(v);
|
||||
} catch {
|
||||
customSet[k] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -416,6 +460,22 @@ async function handleEditNode(
|
||||
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""} --yes`
|
||||
);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${nodeTarget}`, {
|
||||
pipelineId,
|
||||
nodeName: nodeTarget,
|
||||
label: label || "-",
|
||||
displayName: displayName || "-",
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(displayName !== undefined ? { displayName } : {}),
|
||||
...(desc ? { desc } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
@@ -428,22 +488,6 @@ async function handleEditNode(
|
||||
});
|
||||
const descManaged = desc !== undefined && isServerManagedDescType(editedTask.type);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${editedTask.name}`, {
|
||||
pipelineId,
|
||||
nodeName: editedTask.name,
|
||||
label: editedTask.label,
|
||||
updatedFields: {
|
||||
...(label ? { label } : {}),
|
||||
...(displayName !== undefined ? { displayName } : {}),
|
||||
...(desc && !descManaged ? { desc } : {}),
|
||||
...(descManaged ? { desc: "服务端托管,已跳过" } : {}),
|
||||
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||||
...customSet,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
|
||||
@@ -18,7 +18,20 @@ export async function handleWorkflowTest(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]);
|
||||
let pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]);
|
||||
let flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
|
||||
|
||||
// 智能参数纠错:如果首参数疑似单号/台账记录(非纯数字长ID),且第二个位置参数为工作流ID(16~20位纯数字)
|
||||
if (
|
||||
parsed.args[0] &&
|
||||
parsed.args[1] &&
|
||||
/^\d{16,20}$/.test(parsed.args[1]) &&
|
||||
!/^\d{16,20}$/.test(parsed.args[0])
|
||||
) {
|
||||
flowCodeOrId = parsed.args[0];
|
||||
pipelineId = parsed.args[1];
|
||||
}
|
||||
|
||||
if (!pipelineId) {
|
||||
return {
|
||||
stdout: "",
|
||||
@@ -44,7 +57,6 @@ export async function handleWorkflowTest(
|
||||
};
|
||||
}
|
||||
|
||||
const flowCodeOrId = stringOption(parsed.options, ["flow", "record", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
|
||||
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
|
||||
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000;
|
||||
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
|
||||
@@ -245,13 +257,16 @@ export async function handleWorkflowTest(
|
||||
...(sampleLines.length > 0
|
||||
? [` --sample=<1|2|3> 直接选用上述服务器最近接收的数据样本发起测试`]
|
||||
: []),
|
||||
` --flow=<单号> 提取指定单据的编码与数据作为 Webhook Payload 发起测试`,
|
||||
` --body='{"key": "value"}' 直接传入自定义 JSON 请求体`,
|
||||
` --file=<payload.json> 从本地 JSON 文件读取请求体`,
|
||||
` --empty 使用空对象 {} 直接发起测试`,
|
||||
"",
|
||||
`示例: hose-use workflow test ${pipelineId} ${
|
||||
sampleLines.length > 0 ? "--sample=1" : `--body='{"code": "TEST-001"}'`
|
||||
`示例:`,
|
||||
` hose-use workflow test ${pipelineId} ${
|
||||
sampleLines.length > 0 ? "--sample=1" : `--flow=B26000148`
|
||||
}`,
|
||||
` hose-use workflow webhook send ${pipelineId} --bill=B26000148 --yes`,
|
||||
].join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
@@ -357,9 +372,13 @@ export async function handleWorkflowTest(
|
||||
].join("\n");
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 1 };
|
||||
} catch (err: any) {
|
||||
const errMsg = err.message || String(err);
|
||||
const notFoundHint = errMsg.includes("expected 1 result. got 0")
|
||||
? `\n💡 提示: 云端未查询到工作流 [${pipelineId}] 的调试数据源,请检查工作流 ID 是否有效,或工作流类型是否需要 --flow / --body 等参数。`
|
||||
: "";
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${err.message || String(err)}\n`,
|
||||
stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${errMsg}${notFoundHint}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -489,6 +508,13 @@ export async function handleWorkflowTest(
|
||||
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
|
||||
}
|
||||
|
||||
if (category === "WEBHOOK" && report.outcome !== "completed") {
|
||||
outLines.push("");
|
||||
outLines.push("💡 [Webhook 流程调试提示]");
|
||||
outLines.push(" 工作流首节点为 Webhook 触发器。若需向合思云端发起真实的 Webhook 事件调度流转,可直接运行:");
|
||||
outLines.push(` hose-use workflow webhook send ${pipelineId}${flowCodeOrId ? ` --bill=${flowCodeOrId}` : ""} --yes`);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
|
||||
+86
-4
@@ -3,6 +3,72 @@ import { usageError } from "./errors.js";
|
||||
export type { HelpTopic } from "./command-metadata.js";
|
||||
export const HELP_REGISTRY = COMMAND_METADATA;
|
||||
|
||||
interface SubActionHelp {
|
||||
summary: string;
|
||||
usage: string;
|
||||
options: string[];
|
||||
}
|
||||
|
||||
const SUB_ACTION_HELP: Record<string, SubActionHelp> = {
|
||||
"workflow:node:add": {
|
||||
summary: "向工作流声明式追加任务节点",
|
||||
usage: "hose-use workflow node add <pipelineId> --type=<类型> [选项]",
|
||||
options: [
|
||||
"--type=<type> 节点类型 (如 task-dynamic-delay / code-js2 / http / stop / every)",
|
||||
"--sleep-time=<秒数> 延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
"--set='key=value' 自定义节点属性注入 (如 --set='sleepTime=5')",
|
||||
"--after=<节点name> 插入在指定节点之后",
|
||||
"--parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)",
|
||||
"--label=<标题> 节点类型标题",
|
||||
"--display-name=<名称> 设计器节点标题(最多 20 字符)",
|
||||
"--code-file=<脚本路径> 从本地文件导入代码 (推荐)",
|
||||
"--code=<代码片段> 传入代码字符串 (仅限简短代码)",
|
||||
"--dry-run 只预览追加变更,不实际写入",
|
||||
"--yes 确认追加新节点",
|
||||
],
|
||||
},
|
||||
"workflow:node:edit": {
|
||||
summary: "定向修改工作流任务节点配置",
|
||||
usage: "hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||||
options: [
|
||||
"--sleep-time=<秒数> 更新延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||||
"--set='key=value' 定向修改节点自定义属性 (如 --set='sleepTime=5')",
|
||||
"--display-name=<新名称> 更新设计器节点标题(displayName,最多 20 字符)",
|
||||
"--code-file=<脚本路径> 从本地文件导入最新脚本 (推荐)",
|
||||
"--code=<行内代码> 直接传入代码片段",
|
||||
"--desc=<描述> 更新节点描述",
|
||||
"--label=<类型标题> 更新节点类型标题",
|
||||
"--dry-run 只预览变更",
|
||||
"--yes 确认保存修改",
|
||||
],
|
||||
},
|
||||
"workflow:test": {
|
||||
summary: "端到端一键调试工作流(替代前端手工调测)",
|
||||
usage: "hose-use workflow test <pipelineId> [选项]",
|
||||
options: [
|
||||
"--flow=<单号> 测试单据编号 (flowCode 或 flowId)",
|
||||
"--body='{...}' 自定义测试请求体 (针对 Webhook 触发器)",
|
||||
"--sample=<1|2|3> 直接选用服务器最近接收的数据样本发起测试",
|
||||
"--timeout=<ms> 轮询超时时间 (毫秒,默认 15000)",
|
||||
"--auto-publish 调试通过后是否自动发布测试快照 (默认 false)",
|
||||
"--force, -f 生产环境安全放行 (正式企业 env: prod 调试必须加)",
|
||||
"--dry-run 只预览测试配置,不发起调用",
|
||||
"--yes/--confirm 确认执行真实调试",
|
||||
],
|
||||
},
|
||||
"workflow:webhook": {
|
||||
summary: "向工作流 Webhook 触发器发送测试数据 (别名: webhook-send)",
|
||||
usage: "hose-use workflow webhook [send] <pipelineId> [选项]",
|
||||
options: [
|
||||
"--bill=<单号|单据ID> 抓取真实单据数据作为测试载荷发送",
|
||||
"--body='{...}' 指定自定义 JSON 请求体",
|
||||
"--file=<path.json> 从 JSON 文件读取请求体",
|
||||
"--dry-run 仅预览目标 Webhook 地址与载荷,不实际发送",
|
||||
"--yes 确认发送网络请求",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export function renderScopedHelp(target: string[]): string {
|
||||
const resolved = resolveCommandMetadata(target[0]);
|
||||
if (!resolved) throw usageError(`未找到命令域帮助: ${target.join(" ") || "<empty>"}。运行 hose-use --help 查看全部命令域。`);
|
||||
@@ -10,10 +76,26 @@ export function renderScopedHelp(target: string[]): string {
|
||||
|
||||
const action = resolveCommandAction(area, target[1]);
|
||||
if (action && !Object.hasOwn(topic.commands, action)) throw usageError(`未找到子命令帮助: ${area} ${target[1]}`);
|
||||
const lines = [`${area} - ${topic.summary}`, "", `用法: ${topic.usage}`, "", "子命令:"];
|
||||
if (action && topic.commands[action]) lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
else for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
if (topic.options?.length) lines.push("", "常用选项:", ...topic.options.map((option) => ` ${option}`));
|
||||
|
||||
const subTarget = target[2]?.toLowerCase();
|
||||
const subKey = subTarget ? `${area}:${action}:${subTarget}` : `${area}:${action}`;
|
||||
const subHelp = SUB_ACTION_HELP[subKey] || SUB_ACTION_HELP[`${area}:${action}`];
|
||||
|
||||
const titlePrefix = subHelp ? `${area} ${action}${subTarget ? ` ${subTarget}` : ""}` : area;
|
||||
const summaryText = subHelp?.summary || topic.summary;
|
||||
const usageText = subHelp?.usage || topic.usage;
|
||||
const commonOpts = subHelp?.options || topic.options;
|
||||
|
||||
const lines = [`${titlePrefix} - ${summaryText}`, "", `用法: ${usageText}`, "", "子命令:"];
|
||||
if (subHelp) {
|
||||
lines.push(` ${action}${subTarget ? ` ${subTarget}` : ""}`.padEnd(16) + ` ${subHelp.summary}`);
|
||||
} else if (action && topic.commands[action]) {
|
||||
lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
} else {
|
||||
for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
}
|
||||
|
||||
if (commonOpts?.length) lines.push("", "常用选项:", ...commonOpts.map((option) => ` ${option}`));
|
||||
lines.push("", "支持选项:", ...Object.entries(commandFlags(area, action)).map(([key, kind]) => ` --${key}${kind === "value" ? "=<值>" : kind === "boolean-or-value" ? "[=<值>]" : ""}`));
|
||||
lines.push("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
|
||||
return lines.join("\n");
|
||||
|
||||
+4
-2
@@ -93,9 +93,11 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
|
||||
function resolveHelpTarget(parsed: CliParsedArgs): string[] {
|
||||
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
|
||||
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
|
||||
return [parsed.action, parsed.args[0], parsed.args[1]].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
return [parsed.area, parsed.action === "help" ? parsed.args[0] : parsed.action].filter((value): value is string => Boolean(value));
|
||||
const primaryAction = parsed.action === "help" ? parsed.args[0] : parsed.action;
|
||||
const subAction = parsed.action === "help" ? parsed.args[1] : parsed.args[0];
|
||||
return [parsed.area, primaryAction, subAction].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
async function dispatchCli(rawArgs: string[], options: CliRunOptions = {}): Promise<CliResult> {
|
||||
|
||||
@@ -37,6 +37,23 @@ export function createAssistPlatformClient(options: AssistPlatformClientOptions)
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new AuthenticationError("协助平台凭证已过期或无效,请重新登录协助平台");
|
||||
}
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
try {
|
||||
const clone = response.clone();
|
||||
const json = (await clone.json()) as any;
|
||||
if (
|
||||
json?.errorCode === 403 ||
|
||||
(typeof json?.errorMessage === "string" && json.errorMessage.includes("token过期"))
|
||||
) {
|
||||
throw new AuthenticationError(
|
||||
"协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录"
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof AuthenticationError) throw err;
|
||||
}
|
||||
}
|
||||
return response;
|
||||
},
|
||||
],
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
getOpenApiHeaders,
|
||||
} from "./openapi-client.js";
|
||||
import { resolveCorpCluster, getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
||||
import { createAssistPlatformClient } from "./assist-platform-client.js";
|
||||
import { getScriptEngineClient } from "./script-engine-client.js";
|
||||
import { setCorpTokens, resetTokenStoreMemory } from "../auth/token-store.js";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
@@ -150,4 +151,23 @@ describe("core/http/unity-client & script-engine-client", () => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("createAssistPlatformClient throws AuthenticationError when response body contains errorCode: 403", async () => {
|
||||
const client = createAssistPlatformClient({
|
||||
token: "fake-token",
|
||||
baseUrl: "https://mock-unity.invalid",
|
||||
});
|
||||
|
||||
const mockFetch = async () =>
|
||||
new Response(JSON.stringify({ errorCode: 403, errorMessage: "token过期请重新登录!" }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
|
||||
const testClient = client.extend({ fetch: mockFetch as any });
|
||||
|
||||
expect(async () => {
|
||||
await testClient.get("test").json();
|
||||
}).toThrow("协助平台凭证已过期或无效,请运行: hose-use assist-platform login 重新扫码登录");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
createSsoClient,
|
||||
getSsoQrCode,
|
||||
pollSsoQrCodeStatus,
|
||||
verifySsoTokenOnUnity,
|
||||
} from "./sso-client.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
|
||||
describe("core/http/sso-client", () => {
|
||||
it("getSsoQrCode 能够正常解析二维码链接与 Session Cookie", async () => {
|
||||
const mockClient = {
|
||||
post: async () => ({
|
||||
headers: new Headers({
|
||||
"set-cookie": "SSO_SESSION_ID=mock-session-1234; Path=/; HttpOnly",
|
||||
}),
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
message: "ok",
|
||||
data: {
|
||||
url: "https://login.dingtalk.com/oauth2/auth?mock=1",
|
||||
appId: "12021",
|
||||
redirect: "https://unity.ekuaibao.com/platform-charge/",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
|
||||
const res = await getSsoQrCode(mockClient as any);
|
||||
expect(res.dingUrl).toContain("login.dingtalk.com");
|
||||
expect(res.ssoSessionId).toBe("mock-session-1234");
|
||||
});
|
||||
|
||||
it("getSsoQrCode 遇到业务错误时抛出 AuthenticationError", async () => {
|
||||
const mockClient = {
|
||||
post: async () => ({
|
||||
headers: new Headers(),
|
||||
json: async () => ({
|
||||
code: 1,
|
||||
message: "类型不支持",
|
||||
}),
|
||||
}),
|
||||
};
|
||||
|
||||
expect(async () => {
|
||||
await getSsoQrCode(mockClient as any);
|
||||
}).toThrow("类型不支持");
|
||||
});
|
||||
|
||||
it("pollSsoQrCodeStatus 能够正确传递 Cookie 并解析确认状态", async () => {
|
||||
let capturedHeaders: any = null;
|
||||
const mockClient = {
|
||||
get: (url: string, opts: any) => {
|
||||
capturedHeaders = opts.headers;
|
||||
return {
|
||||
json: async () => ({
|
||||
code: 0,
|
||||
message: "ok",
|
||||
data: {
|
||||
token: "mock-jwt-token",
|
||||
redirect: "https://unity.ekuaibao.com/platform-charge/?token=mock-token",
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const res = await pollSsoQrCodeStatus(mockClient as any, {
|
||||
sessionId: "session-abc",
|
||||
});
|
||||
|
||||
expect(capturedHeaders.cookie).toBe("SSO_SESSION_ID=session-abc");
|
||||
expect(res.code).toBe(0);
|
||||
expect(typeof res.data).toBe("object");
|
||||
});
|
||||
|
||||
it("verifySsoTokenOnUnity 优先从 redirect 提取 token 并完成换票", async () => {
|
||||
// 拦截全局 fetch 测试 verifySsoTokenOnUnity
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
globalThis.fetch = (async (url: any, opts: any) => {
|
||||
const req = new Request(url, opts);
|
||||
const body = (await req.json()) as any;
|
||||
if (body.token === "extracted-token") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
token: "unity-session-uuid",
|
||||
user: { name: "张三", userId: "zhangsan" },
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ errorCode: 400 }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}) as any;
|
||||
|
||||
const res = await verifySsoTokenOnUnity(
|
||||
"https://unity.ekuaibao.com/platform-charge/?token=extracted-token"
|
||||
);
|
||||
|
||||
expect(res.sessionToken).toBe("unity-session-uuid");
|
||||
expect(res.userName).toBe("张三");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("verifySsoTokenOnUnity 当 token 包含点时自动 base64 处理", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
try {
|
||||
let passedToken = "";
|
||||
globalThis.fetch = (async (url: any, opts: any) => {
|
||||
const req = new Request(url, opts);
|
||||
const body = (await req.json()) as any;
|
||||
passedToken = body.token;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
token: "unity-session-uuid-2",
|
||||
user: { name: "李四" },
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}) as any;
|
||||
|
||||
const res = await verifySsoTokenOnUnity("jwt.with.dots");
|
||||
expect(passedToken).toBe(Buffer.from("jwt.with.dots").toString("base64"));
|
||||
expect(res.sessionToken).toBe("unity-session-uuid-2");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,65 @@ export interface QrCodeStatusResponse {
|
||||
} | string;
|
||||
}
|
||||
|
||||
export interface SsoQrCodeResult {
|
||||
dingUrl: string;
|
||||
ssoSessionId: string;
|
||||
appId: string;
|
||||
redirect: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求 HoseCloudSSO 生成钉钉扫码登录链接与会话 Cookie
|
||||
*/
|
||||
export async function getSsoQrCode(
|
||||
client: KyInstance,
|
||||
options: {
|
||||
appId?: string;
|
||||
redirect?: string;
|
||||
} = {}
|
||||
): Promise<SsoQrCodeResult> {
|
||||
const appId = options.appId || "12021";
|
||||
const redirect = options.redirect || "https://unity.ekuaibao.com/platform-charge/";
|
||||
|
||||
try {
|
||||
const res = await client.post("api/v1/user/login/qrcode", {
|
||||
json: {
|
||||
type: "ding",
|
||||
appId,
|
||||
redirect,
|
||||
},
|
||||
});
|
||||
|
||||
const cookieHeader = res.headers.get("set-cookie");
|
||||
const matchCookie = cookieHeader ? cookieHeader.match(/SSO_SESSION_ID=([^;]+)/) : null;
|
||||
const ssoSessionId = matchCookie ? matchCookie[1] : "";
|
||||
|
||||
const json = (await res.json()) as {
|
||||
code?: number;
|
||||
message?: string;
|
||||
data?: { url?: string; appId?: string; redirect?: string };
|
||||
};
|
||||
|
||||
if (json.code !== 0 || !json.data?.url) {
|
||||
throw new AuthenticationError(
|
||||
`获取钉钉登录二维码失败: ${json.message || "服务端未返回有效二维码链接"}`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
dingUrl: json.data.url,
|
||||
ssoSessionId,
|
||||
appId: json.data.appId || appId,
|
||||
redirect: json.data.redirect || redirect,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof AuthenticationError) throw err;
|
||||
throw new AuthenticationError(
|
||||
`请求 SSO 钉钉二维码接口失败: ${err instanceof Error ? err.message : String(err)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询 HoseCloudSSO 钉钉扫码登录确认状态
|
||||
*/
|
||||
@@ -67,3 +126,67 @@ export async function pollSsoQrCodeStatus(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 SSO 返回的重定向地址或 Token 换取为 Unity 协助平台凭证会话
|
||||
*/
|
||||
export async function verifySsoTokenOnUnity(
|
||||
tokenOrUrl: string,
|
||||
options: {
|
||||
unityBaseUrl?: string;
|
||||
} = {}
|
||||
): Promise<{ sessionToken: string; userName: string }> {
|
||||
const unityBaseUrl = options.unityBaseUrl || "https://unity.ekuaibao.com";
|
||||
|
||||
// 提取候选 Token
|
||||
const candidates: string[] = [];
|
||||
if (tokenOrUrl.includes("://")) {
|
||||
try {
|
||||
const u = new URL(tokenOrUrl);
|
||||
const t = u.searchParams.get("token") || u.searchParams.get("ticket");
|
||||
if (t) candidates.push(t);
|
||||
} catch {}
|
||||
} else {
|
||||
candidates.push(tokenOrUrl);
|
||||
}
|
||||
|
||||
const firstCand = candidates[0] || tokenOrUrl;
|
||||
if (firstCand.includes(".")) {
|
||||
candidates.unshift(Buffer.from(firstCand).toString("base64"));
|
||||
}
|
||||
|
||||
let lastError = "未能完成换票";
|
||||
for (const cand of candidates) {
|
||||
try {
|
||||
const res = await ky
|
||||
.post(`${unityBaseUrl}/api/auth/verify`, {
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
referer: `${unityBaseUrl}/platform-charge/index.html`,
|
||||
},
|
||||
json: { token: cand },
|
||||
timeout: 10000,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
token: string;
|
||||
user?: { name?: string; userId?: string; [key: string]: unknown };
|
||||
};
|
||||
errorCode?: number;
|
||||
errorMessage?: string;
|
||||
}>();
|
||||
|
||||
if (res.value?.token) {
|
||||
return {
|
||||
sessionToken: res.value.token,
|
||||
userName: res.value.user?.name || "运营人员",
|
||||
};
|
||||
}
|
||||
lastError = res.errorMessage || `errorCode: ${res.errorCode}`;
|
||||
} catch (e) {
|
||||
lastError = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
|
||||
throw new AuthenticationError(`换取合思协助平台会话失败: ${lastError}`);
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import qrcode from "qrcode-terminal";
|
||||
import { BusinessError, NotFoundError } from "../../core/errors.js";
|
||||
import { importFromLink, type ImportFromLinkOptions } from "../../core/auth/link-import.js";
|
||||
import { loadCorpConfigs, resolveWritableEnterprisesDir, saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { saveAssistPlatformSession } from "../../core/auth/assist-platform-store.js";
|
||||
import {
|
||||
createSsoClient,
|
||||
getSsoQrCode,
|
||||
pollSsoQrCodeStatus,
|
||||
verifySsoTokenOnUnity,
|
||||
} from "../../core/http/sso-client.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import {
|
||||
approveAssistTicketApi,
|
||||
@@ -351,8 +359,10 @@ export async function importAssistSessionToLocal(
|
||||
}> {
|
||||
const sessionResult = await generateAssistSession(client, params);
|
||||
|
||||
const importBaseUrl = sessionResult.baseUrl || "https://app.ekuaibao.com";
|
||||
const importOptions: ImportFromLinkOptions = {
|
||||
name: params.saveName,
|
||||
baseUrl: importBaseUrl,
|
||||
overwrite: params.overwrite ?? true,
|
||||
enterprisesDir: params.enterprisesDir,
|
||||
ttl: params.ttl,
|
||||
@@ -361,7 +371,7 @@ export async function importAssistSessionToLocal(
|
||||
|
||||
const linkToImport = sessionResult.loginUrl.includes("accessToken=")
|
||||
? sessionResult.loginUrl
|
||||
: `https://app.ekuaibao.com/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
|
||||
: `${importBaseUrl}/web/thirdparty.html?accessToken=${encodeURIComponent(sessionResult.token)}&ekbCorpId=${encodeURIComponent(sessionResult.corporationId)}${sessionResult.staffId ? `&staffId=${encodeURIComponent(sessionResult.staffId)}` : ""}`;
|
||||
|
||||
const previousCorp = loadCorpConfigs(params.enterprisesDir ? [params.enterprisesDir] : undefined)
|
||||
.find((corp) => corp.id === sessionResult.corporationId);
|
||||
@@ -520,3 +530,95 @@ export async function transferAssistTicket(
|
||||
remarks: params.remarks,
|
||||
};
|
||||
}
|
||||
|
||||
export interface AssistQrLoginOptions {
|
||||
timeoutMs?: number;
|
||||
onQrCode?: (qrText: string, dingUrl: string) => void;
|
||||
onProgress?: (elapsedMs: number, remainingMs: number) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export function generateTerminalQrCode(text: string): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
qrcode.generate(text, { small: true }, (qr) => {
|
||||
resolve(qr);
|
||||
});
|
||||
} catch {
|
||||
resolve("");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整固化的钉钉交互式扫码登录合思协助平台闭环
|
||||
*/
|
||||
export async function loginAssistPlatformByQrCode(
|
||||
options: AssistQrLoginOptions = {}
|
||||
): Promise<{ token: string; userName: string; baseUrl: string }> {
|
||||
const timeoutMs = options.timeoutMs ?? 60000;
|
||||
const ssoClient = createSsoClient();
|
||||
const qrRes = await getSsoQrCode(ssoClient);
|
||||
|
||||
const terminalQr = await generateTerminalQrCode(qrRes.dingUrl);
|
||||
|
||||
if (options.onQrCode) {
|
||||
options.onQrCode(terminalQr, qrRes.dingUrl);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
let pollData: any = null;
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
if (options.signal?.aborted) {
|
||||
throw new BusinessError("扫码登录已取消");
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
const remaining = Math.max(0, timeoutMs - elapsed);
|
||||
if (options.onProgress) {
|
||||
options.onProgress(elapsed, remaining);
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await pollSsoQrCodeStatus(ssoClient, {
|
||||
cookie: `SSO_SESSION_ID=${qrRes.ssoSessionId}`,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
if (res.code === 0 && res.data && typeof res.data === "object") {
|
||||
pollData = res.data;
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === "AbortError") throw err;
|
||||
// 容错继续轮询
|
||||
}
|
||||
}
|
||||
|
||||
if (!pollData) {
|
||||
throw new BusinessError("钉钉扫码登录超时(超过 60 秒时间窗口),请重新发起登录");
|
||||
}
|
||||
|
||||
const tokenCandidate = pollData.redirect || pollData.token;
|
||||
if (!tokenCandidate) {
|
||||
throw new BusinessError("SSO 认证响应中未包含有效 Token 或跳转链接");
|
||||
}
|
||||
|
||||
const { sessionToken, userName } = await verifySsoTokenOnUnity(tokenCandidate);
|
||||
|
||||
saveAssistPlatformSession({
|
||||
token: sessionToken,
|
||||
userName,
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
return {
|
||||
token: sessionToken,
|
||||
userName,
|
||||
baseUrl: "https://unity.ekuaibao.com/api",
|
||||
};
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
WorkflowFormSpecComponentLike,
|
||||
AnalyzeWorkflowOptions,
|
||||
} from "./types.js";
|
||||
import { isKnownGrayNodeType } from "../nodes/gray-nodes-catalog.js";
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
@@ -473,7 +474,7 @@ export function analyzeWorkflow(
|
||||
message: `${task.type} 控制节点没有子节点`,
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
if (!KNOWN_TYPES.has(task.type) && !isKnownGrayNodeType(task.type)) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
|
||||
@@ -1,209 +1,5 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 工作流任务节点(递归、按类型区分)─────────────────────────────────────────
|
||||
|
||||
export const BaseTaskSchema = z.object({
|
||||
name: z.string(),
|
||||
type: z.string(),
|
||||
label: z.string(),
|
||||
desc: z.string().optional(),
|
||||
groupName: z.string(),
|
||||
orderIndex: z.number(),
|
||||
levelIndex: z.array(z.number()),
|
||||
status: z.string(),
|
||||
displayName: z.string().optional(),
|
||||
});
|
||||
|
||||
// 任务节点运行时类型(用于递归结构中的类型标注)
|
||||
export interface WorkflowTask {
|
||||
name: string;
|
||||
type: string;
|
||||
label?: string;
|
||||
desc?: string;
|
||||
groupName: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
status: string;
|
||||
displayName?: string;
|
||||
tasks?: WorkflowTask[];
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 条件/过滤的递归结构:condition / combineFilters
|
||||
export const FilterConditionSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.any().optional(),
|
||||
compare: z.string(),
|
||||
});
|
||||
|
||||
export const FilterGroupSchema: z.ZodType<any> = z.lazy(() =>
|
||||
z.object({
|
||||
filters: z.array(z.union([FilterConditionSchema, FilterGroupSchema])),
|
||||
condition: z.string(),
|
||||
})
|
||||
);
|
||||
|
||||
// 字段映射条目的两种形态:只读 key 或 key-value 映射(保留 value 及其余配置项)
|
||||
export const FieldMappingSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.any().optional(),
|
||||
}).passthrough();
|
||||
|
||||
// 错误处理配置
|
||||
export const OnErrorSchema = z.object({
|
||||
defaultAction: z.string(),
|
||||
});
|
||||
|
||||
// ── 控制节点 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const ConditionTaskSchema: z.ZodType<WorkflowTask> = BaseTaskSchema.extend({
|
||||
type: z.literal("condition"),
|
||||
tasksMaxLevel: z.number(),
|
||||
combineFilters: FilterGroupSchema,
|
||||
tasks: z.lazy(() => z.array(WorkflowTaskSchema)),
|
||||
});
|
||||
|
||||
export const EveryTaskSchema: z.ZodType<WorkflowTask> = BaseTaskSchema.extend({
|
||||
type: z.literal("every"),
|
||||
batch: z.boolean(),
|
||||
batchSize: z.number().optional(),
|
||||
mode: z.string(),
|
||||
list: z.string(),
|
||||
filters: z.array(z.any()),
|
||||
tasksMaxLevel: z.number(),
|
||||
tasks: z.lazy(() => z.array(WorkflowTaskSchema)),
|
||||
});
|
||||
|
||||
// ── 触发器节点 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const WebhookTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("webhook"),
|
||||
sampleId: z.string(),
|
||||
params: z.array(z.object({ key: z.string(), value: z.string() })),
|
||||
urlPath: z.string(),
|
||||
});
|
||||
|
||||
// ── 动作节点 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const StopTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("stop"),
|
||||
});
|
||||
|
||||
export const HttpTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("http"),
|
||||
method: z.string(),
|
||||
url: z.string(),
|
||||
bodyType: z.string().optional(),
|
||||
bodyRaw: z.record(z.string(), z.any()).optional(),
|
||||
header: z.array(z.any()),
|
||||
params: z.array(z.object({ key: z.string(), value: z.string() })),
|
||||
successCode: z.array(z.string()),
|
||||
sampleData: z.record(z.string(), z.any()).optional(),
|
||||
});
|
||||
|
||||
export const FlowDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-detail"),
|
||||
specificationId: z.string(),
|
||||
mapping: z.union([
|
||||
z.boolean(),
|
||||
z.array(z.object({ key: z.string(), value: z.string() })),
|
||||
]),
|
||||
flowCode: z.string(),
|
||||
});
|
||||
|
||||
export const CodeTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("code"),
|
||||
code: z.string(),
|
||||
});
|
||||
|
||||
export const CodeJs2TaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("code-js2"),
|
||||
code: z.string(),
|
||||
mapping: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
});
|
||||
|
||||
export const EkuaibaoDatalinkFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-filter"),
|
||||
mode: z.string(),
|
||||
entityId: z.string(),
|
||||
fields: z.array(FieldMappingSchema),
|
||||
filters: z.array(z.any()),
|
||||
selectFields: z.array(z.any()),
|
||||
combineFilters: FilterGroupSchema,
|
||||
orderKey: z.string(),
|
||||
orderMode: z.string(),
|
||||
limitCount: z.string(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
});
|
||||
|
||||
export const EkuaibaoDatalinkCreateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-create"),
|
||||
mode: z.string(),
|
||||
entityId: z.string(),
|
||||
fields: z.array(FieldMappingSchema),
|
||||
filters: z.array(z.any()),
|
||||
combineFilters: FilterGroupSchema,
|
||||
});
|
||||
|
||||
export const DataConvertTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("data-convert"),
|
||||
mode: z.string(),
|
||||
path: z.array(z.string()),
|
||||
fields: z.array(z.object({ key: z.string(), value: z.string() })),
|
||||
onError: OnErrorSchema.optional(),
|
||||
subType: z.string(),
|
||||
itemType: z.string(),
|
||||
targetType: z.string(),
|
||||
feeFormType: z.string(),
|
||||
});
|
||||
|
||||
export const FlowCreateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-create-task"),
|
||||
specificationId: z.string(),
|
||||
formState: z.string(),
|
||||
form: z.record(z.string(), z.string()),
|
||||
details: z.record(z.string(), z.any()),
|
||||
onError: OnErrorSchema.optional(),
|
||||
});
|
||||
|
||||
export const DynamicDelayTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("task-dynamic-delay"),
|
||||
sleepTime: z.union([z.number(), z.string()]).optional(),
|
||||
});
|
||||
|
||||
// 兜底节点:遇到未收录类型时仍保留全部字段
|
||||
export const UnknownTaskSchema = z
|
||||
.object({
|
||||
name: z.string().default("task"),
|
||||
type: z.string(),
|
||||
label: z.string().optional(),
|
||||
desc: z.string().optional(),
|
||||
groupName: z.string().default("trigger"),
|
||||
orderIndex: z.number().default(0),
|
||||
levelIndex: z.array(z.number()).default([0]),
|
||||
status: z.string().default("active"),
|
||||
displayName: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// 统一任务节点类型
|
||||
export const WorkflowTaskSchema: z.ZodType<WorkflowTask> = z.union([
|
||||
WebhookTaskSchema,
|
||||
ConditionTaskSchema,
|
||||
EveryTaskSchema,
|
||||
StopTaskSchema,
|
||||
HttpTaskSchema,
|
||||
FlowDetailTaskSchema,
|
||||
CodeTaskSchema,
|
||||
CodeJs2TaskSchema,
|
||||
EkuaibaoDatalinkFilterTaskSchema,
|
||||
EkuaibaoDatalinkCreateTaskSchema,
|
||||
DataConvertTaskSchema,
|
||||
FlowCreateTaskSchema,
|
||||
DynamicDelayTaskSchema,
|
||||
UnknownTaskSchema,
|
||||
]);
|
||||
|
||||
|
||||
export type FilterGroup = z.infer<typeof FilterGroupSchema>;
|
||||
/**
|
||||
* 工作流任务节点统一模型与子节点契约出口
|
||||
* 节点各类型 Schema 与字段已原子化拆分至 ./nodes/ 子目录
|
||||
*/
|
||||
export * from "./nodes/index.js";
|
||||
@@ -0,0 +1,61 @@
|
||||
# 工作流节点原子模型定义(models/nodes)
|
||||
|
||||
本目录将工作流各类型节点的数据模型与 Schema 从原本庞大的单文件按类型原子化拆分,确保各节点具备清晰的强类型边界和独立演进能力。
|
||||
|
||||
## 文件分工
|
||||
|
||||
| 文件 | 节点类型 / 职责 |
|
||||
|---|---|
|
||||
| [common.ts](./common.ts) | 基础任务契约(`BaseTaskSchema`、`WorkflowTask`)、过滤与映射通用 Schema |
|
||||
| [http.ts](./http.ts) | HTTP 请求动作节点(包含 `authId` / `appId` 授权凭证、URL、参数与报文) |
|
||||
| [delay.ts](./delay.ts) | 动态延迟等待节点(`task-dynamic-delay` / `sleepTime`) |
|
||||
| [code.ts](./code.ts) | 脚本代码节点(MVEL `code` / JavaScript `code-js2`) |
|
||||
| [webhook.ts](./webhook.ts) | Webhook 外部触发器节点(`sampleId` / `urlPath`) |
|
||||
| [trigger.ts](./trigger.ts) | 工作流官方触发器全家桶(`clock`、`start`、单据与台账变更触发器等 18 类) |
|
||||
| [stop.ts](./stop.ts) | 终止流程控制节点(`stop`) |
|
||||
| [flow.ts](./flow.ts) | 单据操作节点(`flow-detail` 查询详情 / `flow-create-task` 创建单据 / `flow-update-task` / `recalculate-the-approval-flow` 等) |
|
||||
| [datalink.ts](./datalink.ts) | 数据连接台账与转换节点(`ekuaibao-datalink-filter`、`create`、`edit` 与 `data-convert`) |
|
||||
| [condition.ts](./condition.ts) | 条件分支控制节点工厂(`createConditionTaskSchema`) |
|
||||
| [every.ts](./every.ts) | 依次执行循环控制节点工厂(`createEveryTaskSchema`) |
|
||||
| [control.ts](./control.ts) | 流程控制节点工厂(`if`、`loop`、`while`、`amortization`、`apportion`) |
|
||||
| [message.ts](./message.ts) | 消息与通知节点(`message-dingtalk`、`message-feishu`、`email`、`message`、`message-internet`、`message-outnet`、`oa`) |
|
||||
| [ai.ts](./ai.ts) | AI 智能匹配、提取与大模型节点(`ai-classification`、`ai-extraction`、`ai-attachment`、`ekb-ai`、`dify` 等) |
|
||||
| [org.ts](./org.ts) | 组织架构人员与部门节点(`ekuaibao-staff-filter`、`ekuaibao-staff-detail`、`staff-create`、`department-create` 等) |
|
||||
| [utility.ts](./utility.ts) | 基础通用工具节点(`excel` 导出表格、`aggregation` 分类汇总、`flow-format`、`task-log` 流程日志、`dmn` 等) |
|
||||
| [integration.ts](./integration.ts) | 第三方系统集成与定制数据节点(NetSuite、纷享销客、易桥、天润工单、招商银行等) |
|
||||
| [invoice-tmc.ts](./invoice-tmc.ts) | 发票验真巡检与差旅/TMC行程数据节点(`invoice-verification`、`invoice-inspector` 等) |
|
||||
| [requisition.ts](./requisition.ts) | 申请事项与易商卡/随手记节点(`ekuaibao-requision-detail`、`ekuaibao-ecard-fee-filter` 等) |
|
||||
| [unknown.ts](./unknown.ts) | 兜底节点模型(未知节点类型全透传) |
|
||||
| [index.ts](./index.ts) | 实例化递归容器节点、聚合统一 `WorkflowTaskSchema` 并集中导出 |
|
||||
|
||||
## 核心节点规范详情
|
||||
|
||||
### HTTP 请求节点 (`http.ts`)
|
||||
|
||||
HTTP 动作节点用于调用外部 API 或合思原生 OpenAPI。主要字段如下:
|
||||
|
||||
1. **请求方法 (`method`)**:
|
||||
- 严格枚举:`GET`、`POST`、`PUT`、`PATCH`、`DELETE`
|
||||
- 当为 `POST`、`PUT`、`PATCH` 时显示并支持请求体;为 `GET`、`DELETE` 时不传递请求体。
|
||||
|
||||
2. **连接器与授权联动 (`appId` 与 `authId`)**:
|
||||
- **连接器 (`appId`)**:决定 API 调用的预置鉴权通道与目标服务类型。
|
||||
- 获取接口:`POST /api/easo/dsl/task-openapi/select/appId`
|
||||
- 常见预置连接器代码:
|
||||
- `4`: **费控原生**(`ekuaibao_app`,合思开放平台鉴权,Piper 自动换取并注入 `?accessToken=...`)
|
||||
- `5`: **费控钉钉**
|
||||
- `9`: **纷享销客**
|
||||
- `11`: **ai应用**
|
||||
- `14`: **招商银行商务卡查询**
|
||||
- `15`: **费控企微**
|
||||
- `16`: **开放平台**
|
||||
- **授权实例 (`authId`)**:连接器具体的授权账户或凭据实例。
|
||||
- 获取接口:`POST /api/easo/corpApp/getAuthList`,参数 `{ appId, size: 100 }`
|
||||
- 需携带 Piper `Authorization: Bearer <jwtToken>`。
|
||||
- 必须与选定的 `appId` 配对。如未配置或传错,调用合思开放平台接口时将因缺少凭证报错 `400 缺少accessToken参数`。
|
||||
|
||||
3. **请求体与格式 (`bodyType` / `bodyRaw` / `contentType`)**:
|
||||
- `bodyType` 枚举:`none`、`raw`、`from-data`、`form-urlencoded`(默认 `raw`)
|
||||
- `contentType` 枚举(当 `raw` 时):`application/json`(默认)、`text/plain`、`application/javascript`、`text/html`、`application/xml`
|
||||
- `bodyRaw`:支持直接入参对象或字符串,兼容合思变量插值模板(`@{choose(...)}`)。
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── AI 相关节点 (分类、提取、理解与大模型对接) ──────────────────────────────────
|
||||
|
||||
export const AiClassificationTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ai-classification"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const AiExtractionTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ai-extraction"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const AiAttachmentTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ai-attachment"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkbAiTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekb-ai"),
|
||||
model: z.string().optional(),
|
||||
prompt: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkbMinimaxTextTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekb-minimax-text"),
|
||||
prompt: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkbMinimaxPhotoTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekb-minimax-photo"),
|
||||
imageUrl: z.string().optional(),
|
||||
prompt: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkbAiPdfTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekb-ai-pdf"),
|
||||
attachmentUrl: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkbAiUrlTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekb-ai-url"),
|
||||
url: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const DifyTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("dify"),
|
||||
apiKey: z.string().optional(),
|
||||
inputs: z.record(z.string(), z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type AiClassificationTask = z.infer<typeof AiClassificationTaskSchema>;
|
||||
export type AiExtractionTask = z.infer<typeof AiExtractionTaskSchema>;
|
||||
export type AiAttachmentTask = z.infer<typeof AiAttachmentTaskSchema>;
|
||||
export type EkbAiTask = z.infer<typeof EkbAiTaskSchema>;
|
||||
export type EkbMinimaxTextTask = z.infer<typeof EkbMinimaxTextTaskSchema>;
|
||||
export type EkbMinimaxPhotoTask = z.infer<typeof EkbMinimaxPhotoTaskSchema>;
|
||||
export type EkbAiPdfTask = z.infer<typeof EkbAiPdfTaskSchema>;
|
||||
export type EkbAiUrlTask = z.infer<typeof EkbAiUrlTaskSchema>;
|
||||
export type DifyTask = z.infer<typeof DifyTaskSchema>;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 脚本代码节点 (MVEL / JavaScript) ──────────────────────────────────────────
|
||||
|
||||
export const CodeTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("code"),
|
||||
code: z.string(),
|
||||
}).passthrough();
|
||||
|
||||
export const CodeJs2TaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("code-js2"),
|
||||
code: z.string().optional(),
|
||||
mapping: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const CodeJsTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("code-js"),
|
||||
code: z.string().optional(),
|
||||
mapping: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type CodeTask = z.infer<typeof CodeTaskSchema>;
|
||||
export type CodeJs2Task = z.infer<typeof CodeJs2TaskSchema>;
|
||||
export type CodeJsTask = z.infer<typeof CodeJsTaskSchema>;
|
||||
@@ -0,0 +1,57 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 工作流任务节点基础 Schema ─────────────────────────────────────────────────
|
||||
|
||||
export const BaseTaskSchema = z.object({
|
||||
name: z.string(),
|
||||
type: z.string(),
|
||||
label: z.string(),
|
||||
desc: z.string().optional(),
|
||||
groupName: z.string(),
|
||||
orderIndex: z.number(),
|
||||
levelIndex: z.array(z.number()),
|
||||
status: z.string(),
|
||||
displayName: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
// 任务节点运行时类型(用于递归结构中的类型标注)
|
||||
export interface WorkflowTask {
|
||||
name: string;
|
||||
type: string;
|
||||
label?: string;
|
||||
desc?: string;
|
||||
groupName: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
status: string;
|
||||
displayName?: string;
|
||||
tasks?: WorkflowTask[];
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 条件/过滤的递归结构:condition / combineFilters
|
||||
export const FilterConditionSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.any().optional(),
|
||||
compare: z.string(),
|
||||
});
|
||||
|
||||
export const FilterGroupSchema: z.ZodType<any> = z.lazy(() =>
|
||||
z.object({
|
||||
filters: z.array(z.union([FilterConditionSchema, FilterGroupSchema])),
|
||||
condition: z.string(),
|
||||
})
|
||||
);
|
||||
|
||||
// 字段映射条目的两种形态:只读 key 或 key-value 映射(保留 value 及其余配置项)
|
||||
export const FieldMappingSchema = z.object({
|
||||
key: z.string(),
|
||||
value: z.any().optional(),
|
||||
}).passthrough();
|
||||
|
||||
// 错误处理配置
|
||||
export const OnErrorSchema = z.object({
|
||||
defaultAction: z.string(),
|
||||
});
|
||||
|
||||
export type FilterGroup = z.infer<typeof FilterGroupSchema>;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, FilterGroupSchema, type WorkflowTask } from "./common.js";
|
||||
|
||||
// ── 条件分支控制节点 ─────────────────────────────────────────────────────────
|
||||
|
||||
export function createConditionTaskSchema(
|
||||
getTaskSchema: () => z.ZodType<WorkflowTask>
|
||||
): z.ZodType<WorkflowTask> {
|
||||
return BaseTaskSchema.extend({
|
||||
type: z.literal("condition"),
|
||||
tasksMaxLevel: z.number(),
|
||||
combineFilters: FilterGroupSchema,
|
||||
tasks: z.lazy(() => z.array(getTaskSchema())),
|
||||
}).passthrough();
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, type WorkflowTask } from "./common.js";
|
||||
|
||||
// ── 流程控制节点 (if, loop, while, amortization, apportion) ───────────────────
|
||||
|
||||
export function createIfTaskSchema(
|
||||
getTaskSchema: () => z.ZodType<WorkflowTask>
|
||||
): z.ZodType<WorkflowTask> {
|
||||
return BaseTaskSchema.extend({
|
||||
type: z.literal("if"),
|
||||
tasksMaxLevel: z.number().optional(),
|
||||
combineFilters: z.any().optional(),
|
||||
conditions: z.any().optional(),
|
||||
tasks: z.lazy(() => z.array(getTaskSchema())).optional(),
|
||||
}).passthrough();
|
||||
}
|
||||
|
||||
export function createLoopTaskSchema(
|
||||
getTaskSchema: () => z.ZodType<WorkflowTask>
|
||||
): z.ZodType<WorkflowTask> {
|
||||
return BaseTaskSchema.extend({
|
||||
type: z.literal("loop"),
|
||||
list: z.any().optional(),
|
||||
batchSize: z.number().optional(),
|
||||
tasksMaxLevel: z.number().optional(),
|
||||
tasks: z.lazy(() => z.array(getTaskSchema())).optional(),
|
||||
}).passthrough();
|
||||
}
|
||||
|
||||
export function createWhileTaskSchema(
|
||||
getTaskSchema: () => z.ZodType<WorkflowTask>
|
||||
): z.ZodType<WorkflowTask> {
|
||||
return BaseTaskSchema.extend({
|
||||
type: z.literal("while"),
|
||||
combineFilters: z.any().optional(),
|
||||
conditions: z.any().optional(),
|
||||
maxLoop: z.number().optional(),
|
||||
tasksMaxLevel: z.number().optional(),
|
||||
tasks: z.lazy(() => z.array(getTaskSchema())).optional(),
|
||||
}).passthrough();
|
||||
}
|
||||
|
||||
export function createAmortizationTaskSchema(
|
||||
getTaskSchema: () => z.ZodType<WorkflowTask>
|
||||
): z.ZodType<WorkflowTask> {
|
||||
return BaseTaskSchema.extend({
|
||||
type: z.literal("amortization"),
|
||||
tasksMaxLevel: z.number().optional(),
|
||||
tasks: z.lazy(() => z.array(getTaskSchema())).optional(),
|
||||
}).passthrough();
|
||||
}
|
||||
|
||||
export function createApportionTaskSchema(
|
||||
getTaskSchema: () => z.ZodType<WorkflowTask>
|
||||
): z.ZodType<WorkflowTask> {
|
||||
return BaseTaskSchema.extend({
|
||||
type: z.literal("apportion"),
|
||||
tasksMaxLevel: z.number().optional(),
|
||||
tasks: z.lazy(() => z.array(getTaskSchema())).optional(),
|
||||
}).passthrough();
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, FieldMappingSchema, FilterGroupSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 数据连接 / 台账与转换节点 ────────────────────────────────────────────────
|
||||
|
||||
export const EkuaibaoDatalinkFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-filter"),
|
||||
mode: z.string(),
|
||||
entityId: z.string(),
|
||||
fields: z.array(FieldMappingSchema),
|
||||
filters: z.array(z.any()),
|
||||
selectFields: z.array(z.any()),
|
||||
combineFilters: FilterGroupSchema,
|
||||
orderKey: z.string(),
|
||||
orderMode: z.string(),
|
||||
limitCount: z.string(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoDatalinkCreateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-create"),
|
||||
mode: z.string(),
|
||||
entityId: z.string(),
|
||||
fields: z.array(FieldMappingSchema),
|
||||
filters: z.array(z.any()),
|
||||
combineFilters: FilterGroupSchema,
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoDatalinkEditTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-edit"),
|
||||
mode: z.string().optional(),
|
||||
entityId: z.string().optional(),
|
||||
fields: z.array(FieldMappingSchema).optional(),
|
||||
filters: z.array(z.any()).optional(),
|
||||
combineFilters: FilterGroupSchema.optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const DataConvertTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("data-convert"),
|
||||
mode: z.string().optional(),
|
||||
path: z.array(z.string()).optional(),
|
||||
fields: z.array(z.object({ key: z.string(), value: z.string() })).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
subType: z.string().optional(),
|
||||
itemType: z.string().optional(),
|
||||
targetType: z.string().optional(),
|
||||
feeFormType: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type EkuaibaoDatalinkFilterTask = z.infer<typeof EkuaibaoDatalinkFilterTaskSchema>;
|
||||
export type EkuaibaoDatalinkCreateTask = z.infer<typeof EkuaibaoDatalinkCreateTaskSchema>;
|
||||
export type EkuaibaoDatalinkEditTask = z.infer<typeof EkuaibaoDatalinkEditTaskSchema>;
|
||||
export type DataConvertTask = z.infer<typeof DataConvertTaskSchema>;
|
||||
@@ -0,0 +1,11 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema } from "./common.js";
|
||||
|
||||
// ── 延迟等待节点 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const DynamicDelayTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("task-dynamic-delay"),
|
||||
sleepTime: z.union([z.number(), z.string()]).optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type DynamicDelayTask = z.infer<typeof DynamicDelayTaskSchema>;
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, type WorkflowTask } from "./common.js";
|
||||
|
||||
// ── 依次执行循环控制节点 ─────────────────────────────────────────────────────
|
||||
|
||||
export function createEveryTaskSchema(
|
||||
getTaskSchema: () => z.ZodType<WorkflowTask>
|
||||
): z.ZodType<WorkflowTask> {
|
||||
return BaseTaskSchema.extend({
|
||||
type: z.literal("every"),
|
||||
batch: z.boolean(),
|
||||
batchSize: z.number().optional(),
|
||||
mode: z.string(),
|
||||
list: z.string(),
|
||||
filters: z.array(z.any()),
|
||||
tasksMaxLevel: z.number(),
|
||||
tasks: z.lazy(() => z.array(getTaskSchema())),
|
||||
}).passthrough();
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 单据相关节点 (详情查询 / 创建单据) ─────────────────────────────────────────
|
||||
|
||||
export const FlowDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-detail"),
|
||||
specificationId: z.string(),
|
||||
mapping: z.union([
|
||||
z.boolean(),
|
||||
z.array(z.object({ key: z.string(), value: z.string() })),
|
||||
]),
|
||||
flowCode: z.string(),
|
||||
}).passthrough();
|
||||
|
||||
export const FlowCreateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-create-task"),
|
||||
specificationId: z.string().optional(),
|
||||
formState: z.string().optional(),
|
||||
form: z.record(z.string(), z.any()).optional(),
|
||||
details: z.record(z.string(), z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FlowUpdateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-update-task"),
|
||||
specificationId: z.string().optional(),
|
||||
formState: z.string().optional(),
|
||||
form: z.record(z.string(), z.any()).optional(),
|
||||
details: z.record(z.string(), z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const RecalculateApprovalFlowTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("recalculate-the-approval-flow"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FlowListTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-list"),
|
||||
specificationId: z.string().optional(),
|
||||
combineFilters: z.any().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FlowDetailVersionedTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-detail-versioned"),
|
||||
specificationId: z.string().optional(),
|
||||
flowCode: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FlowSampleListTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-sample-list"),
|
||||
specificationId: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EbotApprovalFlowTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ebot-approval-flow"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const RiskTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("risk"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type FlowDetailTask = z.infer<typeof FlowDetailTaskSchema>;
|
||||
export type FlowCreateTask = z.infer<typeof FlowCreateTaskSchema>;
|
||||
export type FlowUpdateTask = z.infer<typeof FlowUpdateTaskSchema>;
|
||||
export type RecalculateApprovalFlowTask = z.infer<typeof RecalculateApprovalFlowTaskSchema>;
|
||||
export type FlowListTask = z.infer<typeof FlowListTaskSchema>;
|
||||
export type FlowDetailVersionedTask = z.infer<typeof FlowDetailVersionedTaskSchema>;
|
||||
export type FlowSampleListTask = z.infer<typeof FlowSampleListTaskSchema>;
|
||||
export type EbotApprovalFlowTask = z.infer<typeof EbotApprovalFlowTaskSchema>;
|
||||
export type RiskTask = z.infer<typeof RiskTaskSchema>;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema } from "./common.js";
|
||||
|
||||
// ── HTTP 请求方法与请求体枚举 ──────────────────────────────────────────────────
|
||||
|
||||
export const HttpMethodSchema = z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]);
|
||||
export type HttpMethod = z.infer<typeof HttpMethodSchema>;
|
||||
|
||||
export const HttpBodyTypeSchema = z.enum(["none", "raw", "from-data", "form-urlencoded"]);
|
||||
export type HttpBodyType = z.infer<typeof HttpBodyTypeSchema>;
|
||||
|
||||
export const HttpContentTypeSchema = z.enum([
|
||||
"application/json",
|
||||
"text/plain",
|
||||
"application/javascript",
|
||||
"text/html",
|
||||
"application/xml",
|
||||
]);
|
||||
export type HttpContentType = z.infer<typeof HttpContentTypeSchema>;
|
||||
|
||||
// ── HTTP 请求动作节点 ─────────────────────────────────────────────────────────
|
||||
|
||||
export const HttpTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("http"),
|
||||
method: z.union([HttpMethodSchema, z.string()]),
|
||||
url: z.string(),
|
||||
bodyType: z.union([HttpBodyTypeSchema, z.string()]).optional(),
|
||||
bodyRaw: z.union([z.string(), z.record(z.string(), z.any())]).optional(),
|
||||
contentType: z.union([HttpContentTypeSchema, z.string()]).optional(),
|
||||
header: z.array(z.any()),
|
||||
params: z.array(z.object({ key: z.string(), value: z.string() })),
|
||||
successCode: z.array(z.string()),
|
||||
sampleData: z.record(z.string(), z.any()).optional(),
|
||||
authId: z.union([z.number(), z.string()]).optional(),
|
||||
appId: z.union([z.number(), z.string()]).optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type HttpTask = z.infer<typeof HttpTaskSchema>;
|
||||
@@ -0,0 +1,275 @@
|
||||
import { z } from "zod";
|
||||
import type { WorkflowTask } from "./common.js";
|
||||
import { createConditionTaskSchema } from "./condition.js";
|
||||
import { createEveryTaskSchema } from "./every.js";
|
||||
import {
|
||||
createIfTaskSchema,
|
||||
createLoopTaskSchema,
|
||||
createWhileTaskSchema,
|
||||
createAmortizationTaskSchema,
|
||||
createApportionTaskSchema,
|
||||
} from "./control.js";
|
||||
import { WebhookTaskSchema } from "./webhook.js";
|
||||
import {
|
||||
ClockTriggerTaskSchema,
|
||||
StartTriggerTaskSchema,
|
||||
FlowChangeTriggerTaskSchema,
|
||||
EkuaibaoFlowformTriggerTaskSchema,
|
||||
EkuaibaoDatalinkCreateTriggerTaskSchema,
|
||||
EkuaibaoDatalinkChangeTriggerTaskSchema,
|
||||
EkuaibaoDatalinkTimeTriggerTaskSchema,
|
||||
DatalinkButtonTriggerTaskSchema,
|
||||
FxiaokeTriggerTaskSchema,
|
||||
XrxsTriggerTaskSchema,
|
||||
EkuaibaoTmcDatalinkCreateTriggerTaskSchema,
|
||||
EkuaibaoTmcDatalinkChangeTriggerTaskSchema,
|
||||
EkuaibaoTmcDatalinkTimeTriggerTaskSchema,
|
||||
EkuaibaoEbotTriggerTaskSchema,
|
||||
OtherEventTriggerTaskSchema,
|
||||
HabTriggerTaskSchema,
|
||||
EkuaibaoRequisitionTriggerTaskSchema,
|
||||
} from "./trigger.js";
|
||||
import { StopTaskSchema } from "./stop.js";
|
||||
import { HttpTaskSchema } from "./http.js";
|
||||
import {
|
||||
FlowDetailTaskSchema,
|
||||
FlowCreateTaskSchema,
|
||||
FlowUpdateTaskSchema,
|
||||
RecalculateApprovalFlowTaskSchema,
|
||||
FlowListTaskSchema,
|
||||
FlowDetailVersionedTaskSchema,
|
||||
FlowSampleListTaskSchema,
|
||||
EbotApprovalFlowTaskSchema,
|
||||
RiskTaskSchema,
|
||||
} from "./flow.js";
|
||||
import { CodeTaskSchema, CodeJs2TaskSchema, CodeJsTaskSchema } from "./code.js";
|
||||
import {
|
||||
EkuaibaoDatalinkFilterTaskSchema,
|
||||
EkuaibaoDatalinkCreateTaskSchema,
|
||||
EkuaibaoDatalinkEditTaskSchema,
|
||||
DataConvertTaskSchema,
|
||||
} from "./datalink.js";
|
||||
import { DynamicDelayTaskSchema } from "./delay.js";
|
||||
import {
|
||||
MessageDingtalkTaskSchema,
|
||||
MessageFeishuTaskSchema,
|
||||
FeishuSendMsgTaskSchema,
|
||||
MessageSmsTaskSchema,
|
||||
EmailTaskSchema,
|
||||
MessageInternetTaskSchema,
|
||||
MessageOutnetTaskSchema,
|
||||
OaReminderTaskSchema,
|
||||
} from "./message.js";
|
||||
import {
|
||||
AiClassificationTaskSchema,
|
||||
AiExtractionTaskSchema,
|
||||
AiAttachmentTaskSchema,
|
||||
EkbAiTaskSchema,
|
||||
EkbMinimaxTextTaskSchema,
|
||||
EkbMinimaxPhotoTaskSchema,
|
||||
EkbAiPdfTaskSchema,
|
||||
EkbAiUrlTaskSchema,
|
||||
DifyTaskSchema,
|
||||
} from "./ai.js";
|
||||
import {
|
||||
EkuaibaoStaffFilterTaskSchema,
|
||||
EkuaibaoStaffDetailTaskSchema,
|
||||
StaffCreateTaskSchema,
|
||||
DepartmentCreateTaskSchema,
|
||||
DepartmentFilterTaskSchema,
|
||||
EkuaibaoDepartmentDetailTaskSchema,
|
||||
EkuaibaoDepartmentUpdateTaskSchema,
|
||||
FeishuDepartmentFilterTaskSchema,
|
||||
WecomDepartmentTaskSchema,
|
||||
TaskDynamicDingAttendanceTaskSchema,
|
||||
SearchStaffByRoleTaskSchema,
|
||||
RoleUpdateTaskSchema,
|
||||
} from "./org.js";
|
||||
import {
|
||||
ExcelTaskSchema,
|
||||
AggregationTaskSchema,
|
||||
FlowFormatTaskSchema,
|
||||
TaskLogTaskSchema,
|
||||
TaskDynamicTestTaskSchema,
|
||||
TaskOpenapiTaskSchema,
|
||||
ContextTaskSchema,
|
||||
DmnTaskSchema,
|
||||
MappingTaskSchema,
|
||||
UiDialogTaskSchema,
|
||||
UiNotificationTaskSchema,
|
||||
OutputTaskSchema,
|
||||
} from "./utility.js";
|
||||
import {
|
||||
EBridgeMapDataTaskSchema,
|
||||
EBridgeAuthTaskSchema,
|
||||
FxiaokeAuthTaskSchema,
|
||||
FxiaokeListTaskSchema,
|
||||
NetsuiteSyncTaskSchema,
|
||||
NetsuiteCreateTaskSchema,
|
||||
NetsuiteDeleteTaskSchema,
|
||||
TrSelectTaskSchema,
|
||||
TrCommentTaskSchema,
|
||||
TrDetailTaskSchema,
|
||||
TaskZsTaskSchema,
|
||||
EscapeTaskSchema,
|
||||
HlDetailTaskSchema,
|
||||
HlTaskSchema,
|
||||
MappingDetailTaskSchema,
|
||||
} from "./integration.js";
|
||||
import {
|
||||
InvoiceVerificationTaskSchema,
|
||||
EkuaibaoInvoiceInspectorTaskSchema,
|
||||
EkuaibaoInvoiceDatalinkFilterTaskSchema,
|
||||
EkuaibaoTmcDatalinkFilterTaskSchema,
|
||||
} from "./invoice-tmc.js";
|
||||
import {
|
||||
EkuaibaoRequisitionDetailTaskSchema,
|
||||
EkuaibaoEcardFeeFilterTaskSchema,
|
||||
EkuaibaoEcardRequisitionFilterTaskSchema,
|
||||
EkuaibaoEcardFeeDetailFilterTaskSchema,
|
||||
} from "./requisition.js";
|
||||
import { UnknownTaskSchema } from "./unknown.js";
|
||||
|
||||
// 导出所有基础与分类模型
|
||||
export * from "./common.js";
|
||||
export * from "./http.js";
|
||||
export * from "./delay.js";
|
||||
export * from "./code.js";
|
||||
export * from "./webhook.js";
|
||||
export * from "./trigger.js";
|
||||
export * from "./stop.js";
|
||||
export * from "./flow.js";
|
||||
export * from "./datalink.js";
|
||||
export * from "./condition.js";
|
||||
export * from "./every.js";
|
||||
export * from "./control.js";
|
||||
export * from "./message.js";
|
||||
export * from "./ai.js";
|
||||
export * from "./org.js";
|
||||
export * from "./utility.js";
|
||||
export * from "./integration.js";
|
||||
export * from "./invoice-tmc.js";
|
||||
export * from "./requisition.js";
|
||||
export * from "./unknown.js";
|
||||
|
||||
// 递归容器节点 Schema 实例化
|
||||
export const ConditionTaskSchema: z.ZodType<WorkflowTask> = createConditionTaskSchema(() => WorkflowTaskSchema);
|
||||
export const EveryTaskSchema: z.ZodType<WorkflowTask> = createEveryTaskSchema(() => WorkflowTaskSchema);
|
||||
export const IfTaskSchema: z.ZodType<WorkflowTask> = createIfTaskSchema(() => WorkflowTaskSchema);
|
||||
export const LoopTaskSchema: z.ZodType<WorkflowTask> = createLoopTaskSchema(() => WorkflowTaskSchema);
|
||||
export const WhileTaskSchema: z.ZodType<WorkflowTask> = createWhileTaskSchema(() => WorkflowTaskSchema);
|
||||
export const AmortizationTaskSchema: z.ZodType<WorkflowTask> = createAmortizationTaskSchema(() => WorkflowTaskSchema);
|
||||
export const ApportionTaskSchema: z.ZodType<WorkflowTask> = createApportionTaskSchema(() => WorkflowTaskSchema);
|
||||
|
||||
// 统一任务节点联合 Schema
|
||||
export const WorkflowTaskSchema: z.ZodType<WorkflowTask> = z.union([
|
||||
WebhookTaskSchema,
|
||||
ClockTriggerTaskSchema,
|
||||
StartTriggerTaskSchema,
|
||||
FlowChangeTriggerTaskSchema,
|
||||
EkuaibaoFlowformTriggerTaskSchema,
|
||||
EkuaibaoDatalinkCreateTriggerTaskSchema,
|
||||
EkuaibaoDatalinkChangeTriggerTaskSchema,
|
||||
EkuaibaoDatalinkTimeTriggerTaskSchema,
|
||||
DatalinkButtonTriggerTaskSchema,
|
||||
FxiaokeTriggerTaskSchema,
|
||||
XrxsTriggerTaskSchema,
|
||||
EkuaibaoTmcDatalinkCreateTriggerTaskSchema,
|
||||
EkuaibaoTmcDatalinkChangeTriggerTaskSchema,
|
||||
EkuaibaoTmcDatalinkTimeTriggerTaskSchema,
|
||||
EkuaibaoEbotTriggerTaskSchema,
|
||||
OtherEventTriggerTaskSchema,
|
||||
HabTriggerTaskSchema,
|
||||
EkuaibaoRequisitionTriggerTaskSchema,
|
||||
ConditionTaskSchema,
|
||||
EveryTaskSchema,
|
||||
IfTaskSchema,
|
||||
LoopTaskSchema,
|
||||
WhileTaskSchema,
|
||||
AmortizationTaskSchema,
|
||||
ApportionTaskSchema,
|
||||
StopTaskSchema,
|
||||
HttpTaskSchema,
|
||||
FlowDetailTaskSchema,
|
||||
FlowCreateTaskSchema,
|
||||
FlowUpdateTaskSchema,
|
||||
RecalculateApprovalFlowTaskSchema,
|
||||
FlowListTaskSchema,
|
||||
FlowDetailVersionedTaskSchema,
|
||||
FlowSampleListTaskSchema,
|
||||
EbotApprovalFlowTaskSchema,
|
||||
RiskTaskSchema,
|
||||
CodeTaskSchema,
|
||||
CodeJs2TaskSchema,
|
||||
CodeJsTaskSchema,
|
||||
EkuaibaoDatalinkFilterTaskSchema,
|
||||
EkuaibaoDatalinkCreateTaskSchema,
|
||||
EkuaibaoDatalinkEditTaskSchema,
|
||||
DataConvertTaskSchema,
|
||||
DynamicDelayTaskSchema,
|
||||
MessageDingtalkTaskSchema,
|
||||
MessageFeishuTaskSchema,
|
||||
FeishuSendMsgTaskSchema,
|
||||
MessageSmsTaskSchema,
|
||||
EmailTaskSchema,
|
||||
MessageInternetTaskSchema,
|
||||
MessageOutnetTaskSchema,
|
||||
OaReminderTaskSchema,
|
||||
AiClassificationTaskSchema,
|
||||
AiExtractionTaskSchema,
|
||||
AiAttachmentTaskSchema,
|
||||
EkbAiTaskSchema,
|
||||
EkbMinimaxTextTaskSchema,
|
||||
EkbMinimaxPhotoTaskSchema,
|
||||
EkbAiPdfTaskSchema,
|
||||
EkbAiUrlTaskSchema,
|
||||
DifyTaskSchema,
|
||||
EkuaibaoStaffFilterTaskSchema,
|
||||
EkuaibaoStaffDetailTaskSchema,
|
||||
StaffCreateTaskSchema,
|
||||
DepartmentCreateTaskSchema,
|
||||
DepartmentFilterTaskSchema,
|
||||
EkuaibaoDepartmentDetailTaskSchema,
|
||||
EkuaibaoDepartmentUpdateTaskSchema,
|
||||
FeishuDepartmentFilterTaskSchema,
|
||||
WecomDepartmentTaskSchema,
|
||||
TaskDynamicDingAttendanceTaskSchema,
|
||||
SearchStaffByRoleTaskSchema,
|
||||
RoleUpdateTaskSchema,
|
||||
ExcelTaskSchema,
|
||||
AggregationTaskSchema,
|
||||
FlowFormatTaskSchema,
|
||||
TaskLogTaskSchema,
|
||||
TaskDynamicTestTaskSchema,
|
||||
TaskOpenapiTaskSchema,
|
||||
ContextTaskSchema,
|
||||
DmnTaskSchema,
|
||||
MappingTaskSchema,
|
||||
UiDialogTaskSchema,
|
||||
UiNotificationTaskSchema,
|
||||
OutputTaskSchema,
|
||||
EBridgeMapDataTaskSchema,
|
||||
EBridgeAuthTaskSchema,
|
||||
FxiaokeAuthTaskSchema,
|
||||
FxiaokeListTaskSchema,
|
||||
NetsuiteSyncTaskSchema,
|
||||
NetsuiteCreateTaskSchema,
|
||||
NetsuiteDeleteTaskSchema,
|
||||
TrSelectTaskSchema,
|
||||
TrCommentTaskSchema,
|
||||
TrDetailTaskSchema,
|
||||
TaskZsTaskSchema,
|
||||
EscapeTaskSchema,
|
||||
HlDetailTaskSchema,
|
||||
HlTaskSchema,
|
||||
MappingDetailTaskSchema,
|
||||
InvoiceVerificationTaskSchema,
|
||||
EkuaibaoInvoiceInspectorTaskSchema,
|
||||
EkuaibaoInvoiceDatalinkFilterTaskSchema,
|
||||
EkuaibaoTmcDatalinkFilterTaskSchema,
|
||||
EkuaibaoRequisitionDetailTaskSchema,
|
||||
EkuaibaoEcardFeeFilterTaskSchema,
|
||||
EkuaibaoEcardRequisitionFilterTaskSchema,
|
||||
EkuaibaoEcardFeeDetailFilterTaskSchema,
|
||||
UnknownTaskSchema,
|
||||
]);
|
||||
@@ -0,0 +1,95 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 第三方系统集成与定制数据节点 ─────────────────────────────────────────────
|
||||
|
||||
export const EBridgeMapDataTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("eBridge-mapData"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EBridgeAuthTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ebridge-auth"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FxiaokeAuthTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("fxiaoke-auth"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FxiaokeListTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("fxiaoke-list"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const NetsuiteSyncTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("netsuite-sync"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const NetsuiteCreateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("netsuite-create"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const NetsuiteDeleteTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("netsuite-delete"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TrSelectTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("tr-select"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TrCommentTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("tr-comment"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TrDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("tr-detail"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TaskZsTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("task-zs"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EscapeTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("escape"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const HlDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("hl-detail"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const HlTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("hl"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const MappingDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("mapping-detail"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type EBridgeMapDataTask = z.infer<typeof EBridgeMapDataTaskSchema>;
|
||||
export type EBridgeAuthTask = z.infer<typeof EBridgeAuthTaskSchema>;
|
||||
export type FxiaokeAuthTask = z.infer<typeof FxiaokeAuthTaskSchema>;
|
||||
export type FxiaokeListTask = z.infer<typeof FxiaokeListTaskSchema>;
|
||||
export type NetsuiteSyncTask = z.infer<typeof NetsuiteSyncTaskSchema>;
|
||||
export type NetsuiteCreateTask = z.infer<typeof NetsuiteCreateTaskSchema>;
|
||||
export type NetsuiteDeleteTask = z.infer<typeof NetsuiteDeleteTaskSchema>;
|
||||
export type TrSelectTask = z.infer<typeof TrSelectTaskSchema>;
|
||||
export type TrCommentTask = z.infer<typeof TrCommentTaskSchema>;
|
||||
export type TrDetailTask = z.infer<typeof TrDetailTaskSchema>;
|
||||
export type TaskZsTask = z.infer<typeof TaskZsTaskSchema>;
|
||||
export type EscapeTask = z.infer<typeof EscapeTaskSchema>;
|
||||
export type HlDetailTask = z.infer<typeof HlDetailTaskSchema>;
|
||||
export type HlTask = z.infer<typeof HlTaskSchema>;
|
||||
export type MappingDetailTask = z.infer<typeof MappingDetailTaskSchema>;
|
||||
@@ -0,0 +1,31 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 发票验真巡检与差旅/TMC行程节点 ──────────────────────────────────────────
|
||||
|
||||
export const InvoiceVerificationTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("invoice-verification"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoInvoiceInspectorTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-invoice-inspector"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoInvoiceDatalinkFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-invoice-datalink-filter"),
|
||||
combineFilters: z.any().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoTmcDatalinkFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-tmc-datalink-filter"),
|
||||
combineFilters: z.any().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type InvoiceVerificationTask = z.infer<typeof InvoiceVerificationTaskSchema>;
|
||||
export type EkuaibaoInvoiceInspectorTask = z.infer<typeof EkuaibaoInvoiceInspectorTaskSchema>;
|
||||
export type EkuaibaoInvoiceDatalinkFilterTask = z.infer<typeof EkuaibaoInvoiceDatalinkFilterTaskSchema>;
|
||||
export type EkuaibaoTmcDatalinkFilterTask = z.infer<typeof EkuaibaoTmcDatalinkFilterTaskSchema>;
|
||||
@@ -0,0 +1,75 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 消息通知相关节点 ──────────────────────────────────────────────────────────
|
||||
|
||||
export const MessageDingtalkTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("message-dingtalk"),
|
||||
receiverType: z.string().optional(),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
content: z.string().optional(),
|
||||
title: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const MessageFeishuTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("message-feishu"),
|
||||
receiverType: z.string().optional(),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
content: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FeishuSendMsgTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("feishu-sendMsg"),
|
||||
receiverType: z.string().optional(),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
content: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const MessageSmsTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("message"),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
content: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EmailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("email"),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
title: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const MessageInternetTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("message-internet"),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
title: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const MessageOutnetTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("message-outnet"),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
content: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const OaReminderTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("oa"),
|
||||
receivers: z.array(z.any()).optional(),
|
||||
content: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type MessageDingtalkTask = z.infer<typeof MessageDingtalkTaskSchema>;
|
||||
export type MessageFeishuTask = z.infer<typeof MessageFeishuTaskSchema>;
|
||||
export type FeishuSendMsgTask = z.infer<typeof FeishuSendMsgTaskSchema>;
|
||||
export type MessageSmsTask = z.infer<typeof MessageSmsTaskSchema>;
|
||||
export type EmailTask = z.infer<typeof EmailTaskSchema>;
|
||||
export type MessageInternetTask = z.infer<typeof MessageInternetTaskSchema>;
|
||||
export type MessageOutnetTask = z.infer<typeof MessageOutnetTaskSchema>;
|
||||
export type OaReminderTask = z.infer<typeof OaReminderTaskSchema>;
|
||||
@@ -0,0 +1,88 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 组织架构与人员/部门节点 ───────────────────────────────────────────────────
|
||||
|
||||
export const EkuaibaoStaffFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-staff-filter"),
|
||||
combineFilters: z.any().optional(),
|
||||
filters: z.array(z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoStaffDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-staff-detail"),
|
||||
staffId: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const StaffCreateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("staff-create"),
|
||||
form: z.record(z.string(), z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const DepartmentCreateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("department-create"),
|
||||
form: z.record(z.string(), z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const DepartmentFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("department-filter"),
|
||||
combineFilters: z.any().optional(),
|
||||
filters: z.array(z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoDepartmentDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-department-detail"),
|
||||
departmentId: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoDepartmentUpdateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-department-update"),
|
||||
departmentId: z.string().optional(),
|
||||
form: z.record(z.string(), z.any()).optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FeishuDepartmentFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("feishu-department-filter"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const WecomDepartmentTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("wecom-department"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TaskDynamicDingAttendanceTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("task-dynamic-ding-attendance"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const SearchStaffByRoleTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("search-staff-by-role"),
|
||||
roleId: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const RoleUpdateTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("role-update"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type EkuaibaoStaffFilterTask = z.infer<typeof EkuaibaoStaffFilterTaskSchema>;
|
||||
export type EkuaibaoStaffDetailTask = z.infer<typeof EkuaibaoStaffDetailTaskSchema>;
|
||||
export type StaffCreateTask = z.infer<typeof StaffCreateTaskSchema>;
|
||||
export type DepartmentCreateTask = z.infer<typeof DepartmentCreateTaskSchema>;
|
||||
export type DepartmentFilterTask = z.infer<typeof DepartmentFilterTaskSchema>;
|
||||
export type EkuaibaoDepartmentDetailTask = z.infer<typeof EkuaibaoDepartmentDetailTaskSchema>;
|
||||
export type EkuaibaoDepartmentUpdateTask = z.infer<typeof EkuaibaoDepartmentUpdateTaskSchema>;
|
||||
export type FeishuDepartmentFilterTask = z.infer<typeof FeishuDepartmentFilterTaskSchema>;
|
||||
export type WecomDepartmentTask = z.infer<typeof WecomDepartmentTaskSchema>;
|
||||
export type TaskDynamicDingAttendanceTask = z.infer<typeof TaskDynamicDingAttendanceTaskSchema>;
|
||||
export type SearchStaffByRoleTask = z.infer<typeof SearchStaffByRoleTaskSchema>;
|
||||
export type RoleUpdateTask = z.infer<typeof RoleUpdateTaskSchema>;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 申请事项与易商卡/随手记节点 ──────────────────────────────────────────────
|
||||
|
||||
export const EkuaibaoRequisitionDetailTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-requision-detail"),
|
||||
specificationId: z.string().optional(),
|
||||
requisitionId: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoEcardFeeFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-ecard-fee-filter"),
|
||||
combineFilters: z.any().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoEcardRequisitionFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-ecard-requisition-filter"),
|
||||
combineFilters: z.any().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoEcardFeeDetailFilterTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-ecard-fee-detail-filter"),
|
||||
combineFilters: z.any().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type EkuaibaoRequisitionDetailTask = z.infer<typeof EkuaibaoRequisitionDetailTaskSchema>;
|
||||
export type EkuaibaoEcardFeeFilterTask = z.infer<typeof EkuaibaoEcardFeeFilterTaskSchema>;
|
||||
export type EkuaibaoEcardRequisitionFilterTask = z.infer<typeof EkuaibaoEcardRequisitionFilterTaskSchema>;
|
||||
export type EkuaibaoEcardFeeDetailFilterTask = z.infer<typeof EkuaibaoEcardFeeDetailFilterTaskSchema>;
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema } from "./common.js";
|
||||
|
||||
// ── 终止流程节点 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const StopTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("stop"),
|
||||
}).passthrough();
|
||||
|
||||
export type StopTask = z.infer<typeof StopTaskSchema>;
|
||||
@@ -0,0 +1,114 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema } from "./common.js";
|
||||
|
||||
// ── 工作流触发器节点 (全量官方 18 类触发器) ───────────────────────────────────
|
||||
|
||||
export const ClockTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("clock"),
|
||||
mode: z.string().optional(),
|
||||
triggerDateTime: z.string().optional(),
|
||||
cron: z.string().optional(),
|
||||
timezone: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const StartTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("start"),
|
||||
cron: z.string().optional(),
|
||||
mode: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FlowChangeTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-change-trigger"),
|
||||
specificationId: z.string().optional(),
|
||||
dateField: z.string().optional(),
|
||||
advanceDays: z.number().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoFlowformTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-flowform-trigger"),
|
||||
specificationId: z.string().optional(),
|
||||
flowState: z.string().optional(),
|
||||
event: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoDatalinkCreateTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-create-trigger"),
|
||||
datalinkModelId: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoDatalinkChangeTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-change-trigger"),
|
||||
datalinkModelId: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoDatalinkTimeTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-datalink-time-trigger"),
|
||||
datalinkModelId: z.string().optional(),
|
||||
dateField: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const DatalinkButtonTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("datalink-button-trigger"),
|
||||
datalinkModelId: z.string().optional(),
|
||||
buttonCode: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FxiaokeTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("fxiaoke-trigger"),
|
||||
objectDescribeApiName: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const XrxsTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("xrxs-trigger"),
|
||||
event: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoTmcDatalinkCreateTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-tmc-datalink-create-trigger"),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoTmcDatalinkChangeTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-tmc-datalink-change-trigger"),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoTmcDatalinkTimeTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-tmc-datalink-time-trigger"),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoEbotTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-ebot-trigger"),
|
||||
botId: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const OtherEventTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("other-event-trigger"),
|
||||
eventType: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const HabTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("hab-trigger-task"),
|
||||
appCode: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const EkuaibaoRequisitionTriggerTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ekuaibao-requisition-trigger"),
|
||||
specificationId: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type ClockTriggerTask = z.infer<typeof ClockTriggerTaskSchema>;
|
||||
export type StartTriggerTask = z.infer<typeof StartTriggerTaskSchema>;
|
||||
export type FlowChangeTriggerTask = z.infer<typeof FlowChangeTriggerTaskSchema>;
|
||||
export type EkuaibaoFlowformTriggerTask = z.infer<typeof EkuaibaoFlowformTriggerTaskSchema>;
|
||||
export type EkuaibaoDatalinkCreateTriggerTask = z.infer<typeof EkuaibaoDatalinkCreateTriggerTaskSchema>;
|
||||
export type EkuaibaoDatalinkChangeTriggerTask = z.infer<typeof EkuaibaoDatalinkChangeTriggerTaskSchema>;
|
||||
export type EkuaibaoDatalinkTimeTriggerTask = z.infer<typeof EkuaibaoDatalinkTimeTriggerTaskSchema>;
|
||||
export type DatalinkButtonTriggerTask = z.infer<typeof DatalinkButtonTriggerTaskSchema>;
|
||||
export type FxiaokeTriggerTask = z.infer<typeof FxiaokeTriggerTaskSchema>;
|
||||
export type XrxsTriggerTask = z.infer<typeof XrxsTriggerTaskSchema>;
|
||||
export type EkuaibaoTmcDatalinkCreateTriggerTask = z.infer<typeof EkuaibaoTmcDatalinkCreateTriggerTaskSchema>;
|
||||
export type EkuaibaoTmcDatalinkChangeTriggerTask = z.infer<typeof EkuaibaoTmcDatalinkChangeTriggerTaskSchema>;
|
||||
export type EkuaibaoTmcDatalinkTimeTriggerTask = z.infer<typeof EkuaibaoTmcDatalinkTimeTriggerTaskSchema>;
|
||||
export type EkuaibaoEbotTriggerTask = z.infer<typeof EkuaibaoEbotTriggerTaskSchema>;
|
||||
export type OtherEventTriggerTask = z.infer<typeof OtherEventTriggerTaskSchema>;
|
||||
export type HabTriggerTask = z.infer<typeof HabTriggerTaskSchema>;
|
||||
export type EkuaibaoRequisitionTriggerTask = z.infer<typeof EkuaibaoRequisitionTriggerTaskSchema>;
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 兜底节点:遇到未收录类型时仍保留全部字段 ─────────────────────────────────────
|
||||
|
||||
export const UnknownTaskSchema = z
|
||||
.object({
|
||||
name: z.string().default("task"),
|
||||
type: z.string(),
|
||||
label: z.string().optional(),
|
||||
desc: z.string().optional(),
|
||||
groupName: z.string().default("trigger"),
|
||||
orderIndex: z.number().default(0),
|
||||
levelIndex: z.array(z.number()).default([0]),
|
||||
status: z.string().default("active"),
|
||||
displayName: z.string().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type UnknownTask = z.infer<typeof UnknownTaskSchema>;
|
||||
@@ -0,0 +1,80 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema, OnErrorSchema } from "./common.js";
|
||||
|
||||
// ── 基础通用/工具类节点 ────────────────────────────────────────────────────────
|
||||
|
||||
export const ExcelTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("excel"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const AggregationTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("aggregation"),
|
||||
list: z.any().optional(),
|
||||
groupBy: z.any().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const FlowFormatTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("flow-format"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TaskLogTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("task-log"),
|
||||
message: z.string().optional(),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TaskDynamicTestTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("task-dynamic-test"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const TaskOpenapiTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("task-openapi"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const ContextTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("context"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const DmnTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("dmn"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const MappingTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("mapping"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const UiDialogTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ui-dialog"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const UiNotificationTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("ui-notification"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const OutputTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("output"),
|
||||
onError: OnErrorSchema.optional(),
|
||||
}).passthrough();
|
||||
|
||||
export type ExcelTask = z.infer<typeof ExcelTaskSchema>;
|
||||
export type AggregationTask = z.infer<typeof AggregationTaskSchema>;
|
||||
export type FlowFormatTask = z.infer<typeof FlowFormatTaskSchema>;
|
||||
export type TaskLogTask = z.infer<typeof TaskLogTaskSchema>;
|
||||
export type TaskDynamicTestTask = z.infer<typeof TaskDynamicTestTaskSchema>;
|
||||
export type TaskOpenapiTask = z.infer<typeof TaskOpenapiTaskSchema>;
|
||||
export type ContextTask = z.infer<typeof ContextTaskSchema>;
|
||||
export type DmnTask = z.infer<typeof DmnTaskSchema>;
|
||||
export type MappingTask = z.infer<typeof MappingTaskSchema>;
|
||||
export type UiDialogTask = z.infer<typeof UiDialogTaskSchema>;
|
||||
export type UiNotificationTask = z.infer<typeof UiNotificationTaskSchema>;
|
||||
export type OutputTask = z.infer<typeof OutputTaskSchema>;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { z } from "zod";
|
||||
import { BaseTaskSchema } from "./common.js";
|
||||
|
||||
// ── Webhook 触发器节点 ────────────────────────────────────────────────────────
|
||||
|
||||
export const WebhookTaskSchema = BaseTaskSchema.extend({
|
||||
type: z.literal("webhook"),
|
||||
sampleId: z.string(),
|
||||
params: z.array(z.object({ key: z.string(), value: z.string() })),
|
||||
urlPath: z.string(),
|
||||
}).passthrough();
|
||||
|
||||
export type WebhookTask = z.infer<typeof WebhookTaskSchema>;
|
||||
@@ -125,12 +125,12 @@ export async function grantWorkflowNodesApi(options: {
|
||||
timeout: 30000,
|
||||
});
|
||||
const json = (await response.json()) as any;
|
||||
const data = json?.data ?? {};
|
||||
const innerData = json?.data?.data ?? json?.data ?? {};
|
||||
return {
|
||||
success: interpretGatewayOutcome(json),
|
||||
saved: Array.isArray(data.saved) ? data.saved : [],
|
||||
skipped: Array.isArray(data.skipped) ? data.skipped : [],
|
||||
rawMessage: json?.msg || json?.message || "",
|
||||
saved: Array.isArray(innerData.saved) ? innerData.saved : [],
|
||||
skipped: Array.isArray(innerData.skipped) ? innerData.skipped : [],
|
||||
rawMessage: json?.data?.msg || json?.msg || json?.message || "",
|
||||
};
|
||||
} catch (err: any) {
|
||||
const message = err?.message || String(err);
|
||||
|
||||
Reference in new issue
Block a user