@zerodep-dev/flow-ts-engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/LICENSE +21 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/client/client.d.ts +112 -0
  4. package/dist/client/client.d.ts.map +1 -0
  5. package/dist/client/client.js +67 -0
  6. package/dist/client/client.js.map +1 -0
  7. package/dist/client/endpoint.d.ts +20 -0
  8. package/dist/client/endpoint.d.ts.map +1 -0
  9. package/dist/client/endpoint.js +153 -0
  10. package/dist/client/endpoint.js.map +1 -0
  11. package/dist/client/http.d.ts +30 -0
  12. package/dist/client/http.d.ts.map +1 -0
  13. package/dist/client/http.js +67 -0
  14. package/dist/client/http.js.map +1 -0
  15. package/dist/client/index.d.ts +12 -0
  16. package/dist/client/index.d.ts.map +1 -0
  17. package/dist/client/index.js +11 -0
  18. package/dist/client/index.js.map +1 -0
  19. package/dist/client/port.d.ts +24 -0
  20. package/dist/client/port.d.ts.map +1 -0
  21. package/dist/client/port.js +53 -0
  22. package/dist/client/port.js.map +1 -0
  23. package/dist/client/protocol.d.ts +26 -0
  24. package/dist/client/protocol.d.ts.map +1 -0
  25. package/dist/client/protocol.js +13 -0
  26. package/dist/client/protocol.js.map +1 -0
  27. package/dist/commands/admin.d.ts +41 -0
  28. package/dist/commands/admin.d.ts.map +1 -0
  29. package/dist/commands/admin.js +228 -0
  30. package/dist/commands/admin.js.map +1 -0
  31. package/dist/commands/complete.d.ts +36 -0
  32. package/dist/commands/complete.d.ts.map +1 -0
  33. package/dist/commands/complete.js +289 -0
  34. package/dist/commands/complete.js.map +1 -0
  35. package/dist/commands/dispatch.d.ts +11 -0
  36. package/dist/commands/dispatch.d.ts.map +1 -0
  37. package/dist/commands/dispatch.js +77 -0
  38. package/dist/commands/dispatch.js.map +1 -0
  39. package/dist/commands/operate.d.ts +14 -0
  40. package/dist/commands/operate.d.ts.map +1 -0
  41. package/dist/commands/operate.js +72 -0
  42. package/dist/commands/operate.js.map +1 -0
  43. package/dist/commands/operations.d.ts +75 -0
  44. package/dist/commands/operations.d.ts.map +1 -0
  45. package/dist/commands/operations.js +417 -0
  46. package/dist/commands/operations.js.map +1 -0
  47. package/dist/commands/signal.d.ts +9 -0
  48. package/dist/commands/signal.d.ts.map +1 -0
  49. package/dist/commands/signal.js +78 -0
  50. package/dist/commands/signal.js.map +1 -0
  51. package/dist/commands/start.d.ts +41 -0
  52. package/dist/commands/start.d.ts.map +1 -0
  53. package/dist/commands/start.js +186 -0
  54. package/dist/commands/start.js.map +1 -0
  55. package/dist/commands/submission.d.ts +20 -0
  56. package/dist/commands/submission.d.ts.map +1 -0
  57. package/dist/commands/submission.js +29 -0
  58. package/dist/commands/submission.js.map +1 -0
  59. package/dist/core/channels.d.ts +13 -0
  60. package/dist/core/channels.d.ts.map +1 -0
  61. package/dist/core/channels.js +13 -0
  62. package/dist/core/channels.js.map +1 -0
  63. package/dist/core/context.d.ts +76 -0
  64. package/dist/core/context.d.ts.map +1 -0
  65. package/dist/core/context.js +148 -0
  66. package/dist/core/context.js.map +1 -0
  67. package/dist/core/entities.d.ts +392 -0
  68. package/dist/core/entities.d.ts.map +1 -0
  69. package/dist/core/entities.js +282 -0
  70. package/dist/core/entities.js.map +1 -0
  71. package/dist/core/errors.d.ts +35 -0
  72. package/dist/core/errors.d.ts.map +1 -0
  73. package/dist/core/errors.js +18 -0
  74. package/dist/core/errors.js.map +1 -0
  75. package/dist/engine.d.ts +146 -0
  76. package/dist/engine.d.ts.map +1 -0
  77. package/dist/engine.js +85 -0
  78. package/dist/engine.js.map +1 -0
  79. package/dist/extensions.d.ts +198 -0
  80. package/dist/extensions.d.ts.map +1 -0
  81. package/dist/extensions.js +7 -0
  82. package/dist/extensions.js.map +1 -0
  83. package/dist/index.d.ts +19 -0
  84. package/dist/index.d.ts.map +1 -0
  85. package/dist/index.js +15 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/jobs/jobs.d.ts +27 -0
  88. package/dist/jobs/jobs.d.ts.map +1 -0
  89. package/dist/jobs/jobs.js +299 -0
  90. package/dist/jobs/jobs.js.map +1 -0
  91. package/dist/notify/collect.d.ts +38 -0
  92. package/dist/notify/collect.d.ts.map +1 -0
  93. package/dist/notify/collect.js +100 -0
  94. package/dist/notify/collect.js.map +1 -0
  95. package/dist/notify/inbox.d.ts +26 -0
  96. package/dist/notify/inbox.d.ts.map +1 -0
  97. package/dist/notify/inbox.js +87 -0
  98. package/dist/notify/inbox.js.map +1 -0
  99. package/dist/org/directory.d.ts +74 -0
  100. package/dist/org/directory.d.ts.map +1 -0
  101. package/dist/org/directory.js +254 -0
  102. package/dist/org/directory.js.map +1 -0
  103. package/dist/org/entities.d.ts +69 -0
  104. package/dist/org/entities.d.ts.map +1 -0
  105. package/dist/org/entities.js +39 -0
  106. package/dist/org/entities.js.map +1 -0
  107. package/dist/org/index.d.ts +5 -0
  108. package/dist/org/index.d.ts.map +1 -0
  109. package/dist/org/index.js +5 -0
  110. package/dist/org/index.js.map +1 -0
  111. package/dist/proxy/proxies.d.ts +18 -0
  112. package/dist/proxy/proxies.d.ts.map +1 -0
  113. package/dist/proxy/proxies.js +102 -0
  114. package/dist/proxy/proxies.js.map +1 -0
  115. package/dist/publish/project.d.ts +45 -0
  116. package/dist/publish/project.d.ts.map +1 -0
  117. package/dist/publish/project.js +176 -0
  118. package/dist/publish/project.js.map +1 -0
  119. package/dist/publish/publish.d.ts +42 -0
  120. package/dist/publish/publish.d.ts.map +1 -0
  121. package/dist/publish/publish.js +274 -0
  122. package/dist/publish/publish.js.map +1 -0
  123. package/dist/queries/queries.d.ts +24 -0
  124. package/dist/queries/queries.d.ts.map +1 -0
  125. package/dist/queries/queries.js +326 -0
  126. package/dist/queries/queries.js.map +1 -0
  127. package/dist/queries/stats.d.ts +9 -0
  128. package/dist/queries/stats.d.ts.map +1 -0
  129. package/dist/queries/stats.js +189 -0
  130. package/dist/queries/stats.js.map +1 -0
  131. package/dist/runtime/assignees.d.ts +32 -0
  132. package/dist/runtime/assignees.d.ts.map +1 -0
  133. package/dist/runtime/assignees.js +93 -0
  134. package/dist/runtime/assignees.js.map +1 -0
  135. package/dist/runtime/calls.d.ts +18 -0
  136. package/dist/runtime/calls.d.ts.map +1 -0
  137. package/dist/runtime/calls.js +182 -0
  138. package/dist/runtime/calls.js.map +1 -0
  139. package/dist/runtime/countersign.d.ts +26 -0
  140. package/dist/runtime/countersign.d.ts.map +1 -0
  141. package/dist/runtime/countersign.js +63 -0
  142. package/dist/runtime/countersign.js.map +1 -0
  143. package/dist/runtime/execution.d.ts +150 -0
  144. package/dist/runtime/execution.d.ts.map +1 -0
  145. package/dist/runtime/execution.js +792 -0
  146. package/dist/runtime/execution.js.map +1 -0
  147. package/dist/runtime/next-steps.d.ts +56 -0
  148. package/dist/runtime/next-steps.d.ts.map +1 -0
  149. package/dist/runtime/next-steps.js +145 -0
  150. package/dist/runtime/next-steps.js.map +1 -0
  151. package/dist/runtime/state.d.ts +26 -0
  152. package/dist/runtime/state.d.ts.map +1 -0
  153. package/dist/runtime/state.js +32 -0
  154. package/dist/runtime/state.js.map +1 -0
  155. package/dist/testing/scenarios.d.ts +35 -0
  156. package/dist/testing/scenarios.d.ts.map +1 -0
  157. package/dist/testing/scenarios.js +63 -0
  158. package/dist/testing/scenarios.js.map +1 -0
  159. package/dist/testing/simulate.d.ts +55 -0
  160. package/dist/testing/simulate.d.ts.map +1 -0
  161. package/dist/testing/simulate.js +122 -0
  162. package/dist/testing/simulate.js.map +1 -0
  163. package/dist/testing/testing.d.ts +31 -0
  164. package/dist/testing/testing.d.ts.map +1 -0
  165. package/dist/testing/testing.js +54 -0
  166. package/dist/testing/testing.js.map +1 -0
  167. package/dist/types.d.ts +283 -0
  168. package/dist/types.d.ts.map +1 -0
  169. package/dist/types.js +2 -0
  170. package/dist/types.js.map +1 -0
  171. package/dist/views.d.ts +317 -0
  172. package/dist/views.d.ts.map +1 -0
  173. package/dist/views.js +9 -0
  174. package/dist/views.js.map +1 -0
  175. package/package.json +76 -3
  176. package/src/client/client.ts +194 -0
  177. package/src/client/endpoint.ts +174 -0
  178. package/src/client/http.ts +99 -0
  179. package/src/client/index.ts +12 -0
  180. package/src/client/port.ts +78 -0
  181. package/src/client/protocol.ts +36 -0
  182. package/src/commands/admin.ts +308 -0
  183. package/src/commands/complete.ts +368 -0
  184. package/src/commands/dispatch.ts +106 -0
  185. package/src/commands/operate.ts +110 -0
  186. package/src/commands/operations.ts +524 -0
  187. package/src/commands/signal.ts +96 -0
  188. package/src/commands/start.ts +255 -0
  189. package/src/commands/submission.ts +51 -0
  190. package/src/core/channels.ts +14 -0
  191. package/src/core/context.ts +252 -0
  192. package/src/core/entities.ts +335 -0
  193. package/src/core/errors.ts +42 -0
  194. package/src/engine.ts +247 -0
  195. package/src/extensions.ts +231 -0
  196. package/src/index.ts +77 -0
  197. package/src/jobs/jobs.ts +320 -0
  198. package/src/notify/collect.ts +155 -0
  199. package/src/notify/inbox.ts +107 -0
  200. package/src/org/directory.ts +332 -0
  201. package/src/org/entities.ts +62 -0
  202. package/src/org/index.ts +21 -0
  203. package/src/proxy/proxies.ts +132 -0
  204. package/src/publish/project.ts +230 -0
  205. package/src/publish/publish.ts +314 -0
  206. package/src/queries/queries.ts +427 -0
  207. package/src/queries/stats.ts +207 -0
  208. package/src/runtime/assignees.ts +121 -0
  209. package/src/runtime/calls.ts +196 -0
  210. package/src/runtime/countersign.ts +83 -0
  211. package/src/runtime/execution.ts +915 -0
  212. package/src/runtime/next-steps.ts +213 -0
  213. package/src/runtime/state.ts +55 -0
  214. package/src/testing/scenarios.ts +95 -0
  215. package/src/testing/simulate.ts +190 -0
  216. package/src/testing/testing.ts +84 -0
  217. package/src/types.ts +286 -0
  218. package/src/views.ts +334 -0
  219. package/README.md +0 -3
@@ -0,0 +1,915 @@
1
+ /**
2
+ * 一次命令里的推进(docs/decisions/0001 第 9 节):实例行已经锁住,这里按定义进入、离开节点,攒下待办、事件、作业,
3
+ * 最后 flush 一起写回。规则沿用 Java 版:选边见模型包的 selectEdges,并行与包容的汇合按分叉时记下的分支数等,
4
+ * 退回跳出并行区域时取消区域里还开着的待办,一个命令最多推进 1000 步。
5
+ */
6
+ import {
7
+ applyEffects,
8
+ gatewayPairs,
9
+ processGraph,
10
+ selectEdges,
11
+ type ProcessDefinition,
12
+ type ProcessEdge,
13
+ type ProcessGraph,
14
+ type ProcessNode,
15
+ type CallNode,
16
+ type Due,
17
+ type Duration,
18
+ type TaskNode,
19
+ plainValue,
20
+ } from '@zerodep-dev/flow-ts-model';
21
+ import type { Row } from '@zerodep-dev/easy-query-ts';
22
+ import {
23
+ candidateToken,
24
+ expandToUsers,
25
+ parseCandidate,
26
+ resolveCandidates,
27
+ type Candidate,
28
+ } from './assignees.ts';
29
+ import {
30
+ FlowCc,
31
+ FlowEvent,
32
+ FlowInstance,
33
+ FlowJob,
34
+ FlowWorkItem,
35
+ type FlowDb,
36
+ FlowNotification,
37
+ } from '../core/entities.ts';
38
+ import { collectNotifications } from '../notify/collect.ts';
39
+ import { agentOf } from '../proxy/proxies.ts';
40
+ import { FLOW_CHANNEL } from '../core/channels.ts';
41
+ import { FlowError } from '../core/errors.ts';
42
+ import type { FlowLogic } from '../extensions.ts';
43
+ import { emptyRunState, type RunState } from './state.ts';
44
+ import type {
45
+ Actor,
46
+ CustomNode,
47
+ CustomNodeContext,
48
+ CustomNodeResult,
49
+ ExtensionContext,
50
+ FlowEngineOptions,
51
+ FlowEventView,
52
+ InstanceSummary,
53
+ WorkItemSummary,
54
+ } from '../types.ts';
55
+
56
+ /** 自定义节点(`x-` 开头的类型)在定义里的样子:共同字段之外的属性引擎不解释 */
57
+ export interface CustomNodeDef {
58
+ readonly id: string;
59
+ readonly type: string;
60
+ readonly name: string;
61
+ readonly [attribute: string]: unknown;
62
+ }
63
+
64
+ /** 实例行 */
65
+ export type InstanceRow = Row<typeof FlowInstance>;
66
+ /** 待办行 */
67
+ export type WorkItemRow = Row<typeof FlowWorkItem>;
68
+
69
+ /** 一个命令最多推进的步数:网关绕圈时报错,不卡死 */
70
+ const MAX_STEPS = 1000;
71
+
72
+ /** 记一条事件时可以带的 */
73
+ type EventFields = Partial<Omit<FlowEventView, 'type' | 'instanceId' | 'at'>>;
74
+
75
+ /** 待办行 → 概要 */
76
+ export const workItemSummary = (row: WorkItemRow): WorkItemSummary => ({
77
+ id: row.id,
78
+ instanceId: row.instanceId,
79
+ node: row.node,
80
+ nodeName: row.nodeName,
81
+ round: row.round,
82
+ state: row.state,
83
+ assignment: row.assignment,
84
+ assignee: row.assignee,
85
+ proxyFor: row.proxyFor,
86
+ arrival: row.arrival,
87
+ createdAt: row.createdAt,
88
+ dueAt: row.dueAt,
89
+ });
90
+
91
+ /** 推进的现场 */
92
+ export class Execution {
93
+ readonly graph: ProcessGraph;
94
+ readonly variables: Record<string, unknown>;
95
+ readonly state: RunState;
96
+ readonly current: Set<string>;
97
+ status: InstanceRow['status'];
98
+ result: string | null;
99
+ endedAt: Date | null;
100
+ /** 结束时写的原因(终止、撤回):子实例被一起终止时用它 */
101
+ endComment: string | null = null;
102
+ /** 这次新建的待办 */
103
+ readonly created: WorkItemRow[] = [];
104
+ private readonly events: FlowEventView[] = [];
105
+ private steps = 0;
106
+ /** 刚处理完上一步的人(自动跳过的“与上一步相同”) */
107
+ lastHandler: string | null = null;
108
+ /** 流程自带的 TS 模块的导出(prepare 时加载) */
109
+ /** 流程工程的逻辑(logic.ts 的默认导出);引擎建现场时给 */
110
+ logic: FlowLogic | undefined;
111
+ /** 调用流程:引擎在同一个事务里发起子实例(engine.ts 设置) */
112
+ startChild: ((exec: Execution, node: CallNode) => Promise<void>) | undefined;
113
+
114
+ readonly tx: FlowDb;
115
+ readonly options: FlowEngineOptions;
116
+ readonly definition: ProcessDefinition;
117
+ readonly instance: InstanceRow;
118
+ readonly actor: Actor | null;
119
+ readonly now: Date;
120
+ /** 这一步生成了通知、事务提交之后:引擎核心接上外部投递(notify/inbox.ts 的 deliverPending) */
121
+ onNotified?: () => Promise<unknown>;
122
+
123
+ constructor(
124
+ tx: FlowDb,
125
+ options: FlowEngineOptions,
126
+ definition: ProcessDefinition,
127
+ instance: InstanceRow,
128
+ actor: Actor | null,
129
+ now: Date,
130
+ ) {
131
+ this.tx = tx;
132
+ this.options = options;
133
+ this.definition = definition;
134
+ this.instance = instance;
135
+ this.actor = actor;
136
+ this.now = now;
137
+ this.graph = processGraph(definition);
138
+ this.variables = { ...instance.variables };
139
+ // 新加的字段在旧实例里没有:先铺上空的
140
+ this.state = { ...emptyRunState(), ...structuredClone(instance.state) };
141
+ this.current = new Set(instance.current);
142
+ this.status = instance.status;
143
+ this.result = instance.result;
144
+ this.endedAt = instance.endedAt;
145
+ }
146
+
147
+ /**
148
+ * 按名字找扩展:`logic.名字` 是流程工程 logic.ts 里这一类的,其余是引擎选项里注册的
149
+ */
150
+ extension<K extends keyof NonNullable<FlowEngineOptions['extensions']>>(
151
+ kind: K,
152
+ name: string,
153
+ ): NonNullable<NonNullable<FlowEngineOptions['extensions']>[K]>[string] | undefined {
154
+ if (name.startsWith('logic.')) return this.logic?.[kind]?.[name.slice(6)] as never;
155
+ return this.options.extensions?.[kind]?.[name] as never;
156
+ }
157
+
158
+ get finished(): boolean {
159
+ return this.status !== 'active' && this.status !== 'suspended';
160
+ }
161
+
162
+ /** 扩展与条件取值的现场 */
163
+ context(args: Readonly<Record<string, unknown>> = {}): ExtensionContext {
164
+ return {
165
+ instance: {
166
+ id: this.instance.id,
167
+ processKey: this.instance.processKey,
168
+ businessKey: this.instance.businessKey,
169
+ startedBy: this.instance.startedBy,
170
+ },
171
+ variables: this.variables,
172
+ read: this.read,
173
+ args,
174
+ };
175
+ }
176
+
177
+ /** 按字段名取值:`sys.名字`、`fn.名字`、`form.字段`(就是流程变量)、流程变量 */
178
+ readonly read = (field: string): unknown => {
179
+ if (field.startsWith('sys.')) {
180
+ const name = field.slice(4);
181
+ if (name === 'initiator') return this.instance.startedBy;
182
+ if (name === 'businessKey') return this.instance.businessKey;
183
+ if (name === 'now') return this.now.toISOString();
184
+ if (name === 'actor') return this.actor?.id ?? null;
185
+ return undefined;
186
+ }
187
+ if (field.startsWith('fn.')) {
188
+ const fn = this.extension('functions', field.slice(3));
189
+ if (!fn) throw new FlowError('invalid-definition', `没有注册计算值 ${field}`);
190
+ const { args: _, ...context } = this.context();
191
+ return fn(context);
192
+ }
193
+ const name = field.startsWith('form.') ? field.slice(5) : field;
194
+ return this.variables[name];
195
+ };
196
+
197
+ /** 记一条事件(flush 时写入,提交后通知监听) */
198
+ addEvent(type: string, fields: EventFields = {}): void {
199
+ this.events.push({
200
+ type,
201
+ instanceId: this.instance.id,
202
+ workItemId: fields.workItemId ?? null,
203
+ at: this.now,
204
+ actor: fields.actor ?? this.actor?.id ?? null,
205
+ node: fields.node ?? null,
206
+ edge: fields.edge ?? null,
207
+ outcome: fields.outcome ?? null,
208
+ comment: fields.comment ?? null,
209
+ data: fields.data ?? null,
210
+ });
211
+ }
212
+
213
+ /** 改流程变量 */
214
+ /** 改流程变量:强类型的值写成文字再存(单据是普通 JSON,见模型包的 plainValue) */
215
+ setVariables(values: Readonly<Record<string, unknown>>): void {
216
+ Object.assign(this.variables, plainValue(values));
217
+ }
218
+
219
+ node(id: string): ProcessNode {
220
+ const node = this.graph.node(id);
221
+ if (!node)
222
+ throw new FlowError('invalid-definition', `流程 ${this.definition.key} 里没有节点 ${id}`);
223
+ return node;
224
+ }
225
+
226
+ /** 离开一个节点:按结果选出边,依次进入目标节点 */
227
+ async leave(nodeId: string, outcome: string | null = null): Promise<void> {
228
+ if (this.finished) return;
229
+ const edges = selectEdges(this.graph, nodeId, { outcome, read: this.read });
230
+ if (edges.length === 0) {
231
+ throw new FlowError(
232
+ 'invalid-definition',
233
+ `节点 ${nodeId} 选不出出边(结果 ${outcome ?? '无'})`,
234
+ {
235
+ node: nodeId,
236
+ outcome,
237
+ },
238
+ );
239
+ }
240
+ const node = this.node(nodeId);
241
+ if (node.type === 'parallel' || node.type === 'inclusive') {
242
+ const join = gatewayPairs(this.definition).joinOf(nodeId);
243
+ if (join) this.state.waiting[join] = edges.length;
244
+ }
245
+ for (const edge of edges) {
246
+ if (this.finished) return;
247
+ await this.follow(nodeId, edge, outcome);
248
+ }
249
+ }
250
+
251
+ /** 走一条线:记事件、执行副作用、退回的处理,进入目标节点 */
252
+ async follow(from: string, edge: ProcessEdge, outcome: string | null): Promise<void> {
253
+ this.addEvent('node.left', { node: from, edge: edge.id, outcome });
254
+ this.setVariables(applyEffects(edge.effects ?? [], this.variables, this.read));
255
+ if (edge.kind === 'return') {
256
+ this.state.returnedFrom[edge.to] = from;
257
+ await this.leaveRegions(from, edge.to);
258
+ }
259
+ const arrival =
260
+ edge.kind === 'return' || edge.kind === 'escalate'
261
+ ? edge.kind
262
+ : this.graph.node(from)?.type === 'start'
263
+ ? 'start'
264
+ : 'forward';
265
+ await this.enter(edge.to, arrival);
266
+ }
267
+
268
+ /** 进入一个节点 */
269
+ async enter(nodeId: string, arrival: string): Promise<void> {
270
+ if (this.finished) return;
271
+ if (++this.steps > MAX_STEPS) {
272
+ throw new FlowError(
273
+ 'invalid-definition',
274
+ `一个命令里推进超过 ${MAX_STEPS} 步,流程可能在绕圈`,
275
+ );
276
+ }
277
+ const node = this.node(nodeId);
278
+ // 开始节点不记“进入”(同 Java 版):发起本身就是 instance.started
279
+ if (node.type !== 'start') this.addEvent('node.entered', { node: nodeId });
280
+ switch (node.type) {
281
+ case 'start':
282
+ return this.leave(nodeId);
283
+ case 'end':
284
+ return this.finish('completed', node.result ?? null);
285
+ case 'task':
286
+ return this.arriveTask(node, arrival);
287
+ case 'exclusive':
288
+ return this.leave(nodeId);
289
+ case 'parallel':
290
+ case 'inclusive': {
291
+ // 汇合:等分叉时记下的分支都到了才往下走
292
+ if (gatewayPairs(this.definition).forkOf(nodeId) !== undefined) {
293
+ const left = (this.state.waiting[nodeId] ?? 1) - 1;
294
+ if (left > 0) {
295
+ this.state.waiting[nodeId] = left;
296
+ return;
297
+ }
298
+ delete this.state.waiting[nodeId];
299
+ }
300
+ return this.leave(nodeId);
301
+ }
302
+ case 'service':
303
+ return this.runService(nodeId);
304
+ case 'cc':
305
+ await this.sendCc(nodeId, node.to, node.message);
306
+ return this.leave(nodeId);
307
+ case 'timer':
308
+ return this.waitTimer(nodeId);
309
+ case 'call':
310
+ if (!this.startChild) throw new FlowError('invalid-definition', '没有发起子流程的引擎');
311
+ return this.startChild(this, node);
312
+ case 'receive': {
313
+ // 等外部事件;写了时限时排一个等超时的作业
314
+ this.current.add(nodeId);
315
+ const round = this.bumpRound(nodeId);
316
+ if (node.due) {
317
+ await this.schedule(
318
+ 'receiveTimeout',
319
+ dueAt(node.due, this.now, this.read, this.options),
320
+ {
321
+ node: nodeId,
322
+ round,
323
+ },
324
+ );
325
+ }
326
+ return;
327
+ }
328
+ default:
329
+ if (node.type.startsWith('x-')) return this.arriveCustom(node as unknown as CustomNodeDef);
330
+ throw new FlowError('invalid-definition', `这一版不支持 ${node.type} 节点`, {
331
+ node: nodeId,
332
+ });
333
+ }
334
+ }
335
+
336
+ /** 自定义节点的实现:流程工程 logic.ts 的 nodes,或引擎选项里注册的 */
337
+ customNode(type: string): CustomNode | undefined {
338
+ return this.logic?.nodes?.[type] ?? this.options.extensions?.nodes?.[type];
339
+ }
340
+
341
+ /** 自定义节点拿到的现场:节点上除共同字段以外的属性原样给出 */
342
+ customContext(node: CustomNodeDef): CustomNodeContext {
343
+ const { id: _, type: __, name: ___, ...attributes } = node;
344
+ const { args: ____, ...context } = this.context();
345
+ return { ...context, node: node.id, attributes };
346
+ }
347
+
348
+ /** 到达自定义节点:交给注册的实现,按它说的往下走或停下来等事件 */
349
+ private async arriveCustom(node: CustomNodeDef): Promise<void> {
350
+ const handler = this.customNode(node.type);
351
+ if (!handler) {
352
+ throw new FlowError('invalid-definition', `没有注册自定义节点 ${node.type}`, {
353
+ node: node.id,
354
+ });
355
+ }
356
+ await this.applyCustom(node, await handler.arrive(this.customContext(node)));
357
+ }
358
+
359
+ /** 自定义节点的结果:改变量;等事件时停在这里,否则按结果往下走 */
360
+ async applyCustom(node: CustomNodeDef, result: CustomNodeResult): Promise<void> {
361
+ if (result.variables) this.setVariables(result.variables);
362
+ if (result.waitFor) {
363
+ this.current.add(node.id);
364
+ this.bumpRound(node.id);
365
+ this.state.events[node.id] = result.waitFor;
366
+ return;
367
+ }
368
+ await this.leave(node.id, result.outcome ?? null);
369
+ }
370
+
371
+ /** 人工节点:解析处理人、建待办;会签每个参与人一份;可以自动跳过 */
372
+ private async arriveTask(node: TaskNode, arrival: string): Promise<void> {
373
+ const round = (this.state.rounds[node.id] ?? 0) + 1;
374
+ this.state.rounds[node.id] = round;
375
+ const scope = {
376
+ context: this.context(),
377
+ handledBy: this.state.handledBy,
378
+ options: this.options,
379
+ resolver: (name: string) => this.extension('resolvers', name),
380
+ picked: this.state.picks?.[node.id],
381
+ };
382
+ const settings = this.definition.settings ?? {};
383
+
384
+ // 退回到这里、重新提交回到这里:落回上次的处理人
385
+ const previous = this.state.handledBy[node.id];
386
+ if ((arrival === 'return' || arrival === 'resubmit') && previous && !node.multi) {
387
+ return this.createItems(node, round, arrival, { users: [previous], pool: [] });
388
+ }
389
+
390
+ if (node.multi) {
391
+ const sources = Array.isArray(node.multi.participants)
392
+ ? node.multi.participants
393
+ : [{ user: node.multi.participants as never }];
394
+ const users = await expandToUsers(await resolveCandidates(sources, scope), this.options);
395
+ if (users.length === 0) return this.emptyAssignee(node, round);
396
+ // 票签:指定的人可以带票数(weight),别的一人一票
397
+ const weights = new Map<string, number>();
398
+ for (const source of sources) {
399
+ if (!('user' in source) || source.weight === undefined) continue;
400
+ for (const c of await resolveCandidates([source], scope))
401
+ weights.set(c.value, source.weight);
402
+ }
403
+ return this.createSignItems(node, round, arrival, users, weights);
404
+ }
405
+
406
+ const sources = node.assignees ?? laneInbox(this.graph, node);
407
+ const candidates = await resolveCandidates(sources, scope);
408
+ if (candidates.length === 0) return this.emptyAssignee(node, round);
409
+ const users = candidates.filter((c) => c.kind === 'user').map((c) => c.value);
410
+ const direct = candidates.length === 1 && users.length === 1 ? users[0]! : null;
411
+
412
+ // 自动跳过:落到一个人、这个人是发起人或刚处理完上一步的人
413
+ const skip = node.autoSkip ?? settings.autoSkip;
414
+ const approve = node.outcomes.find((o) => (o.kind ?? 'approve') === 'approve');
415
+ if (direct && approve && skip && (arrival === 'forward' || arrival === 'start')) {
416
+ const byInitiator = skip.initiator && direct === this.instance.startedBy;
417
+ const bySame = skip.sameAsPrevious && direct === this.lastHandler;
418
+ if (byInitiator || bySame) {
419
+ this.addEvent('node.skipped', {
420
+ node: node.id,
421
+ actor: direct,
422
+ outcome: approve.key,
423
+ data: { reason: byInitiator ? 'initiator' : 'sameAsPrevious' },
424
+ });
425
+ this.state.handledBy[node.id] = direct;
426
+ this.lastHandler = direct;
427
+ return this.leave(node.id, approve.key);
428
+ }
429
+ }
430
+ return this.createItems(node, round, arrival, {
431
+ users: direct ? [direct] : [],
432
+ pool: direct ? [] : candidates,
433
+ });
434
+ }
435
+
436
+ /** 处理人解析为空:按节点或流程的设置自动通过、交给管理员或报错 */
437
+ private async emptyAssignee(node: TaskNode, round: number): Promise<void> {
438
+ const mode = node.emptyAssignee ?? this.definition.settings?.emptyAssignee ?? 'admin';
439
+ if (mode === 'error') {
440
+ throw new FlowError('no-assignee', `节点 ${node.name} 解析不出处理人`, { node: node.id });
441
+ }
442
+ if (mode === 'autoPass') {
443
+ const approve = node.outcomes.find((o) => (o.kind ?? 'approve') === 'approve');
444
+ this.addEvent('node.skipped', { node: node.id, data: { reason: 'emptyAssignee' } });
445
+ return this.leave(node.id, approve?.key ?? null);
446
+ }
447
+ const admins = this.options.admins ?? [];
448
+ if (admins.length === 0) {
449
+ throw new FlowError('no-assignee', `节点 ${node.name} 解析不出处理人,也没有配置管理员`, {
450
+ node: node.id,
451
+ });
452
+ }
453
+ // 一个管理员时直接落到他(同 Java 版),几个时进以他们为候选的收件箱
454
+ return this.createItems(node, round, 'emptyAssignee', { users: admins, pool: [] });
455
+ }
456
+
457
+ /** 建一个待办:落到一个人,或进以候选为成员的收件箱 */
458
+ async createItems(
459
+ node: TaskNode,
460
+ round: number,
461
+ arrival: string,
462
+ target: { users: readonly string[]; pool: readonly Candidate[] },
463
+ ): Promise<void> {
464
+ const assignee =
465
+ target.users.length === 1 && target.pool.length === 0 ? target.users[0]! : null;
466
+ const pool = assignee
467
+ ? []
468
+ : [...target.pool, ...target.users.map((value) => ({ kind: 'user' as const, value }))];
469
+ await this.insertItem(node, round, arrival, {
470
+ assignee,
471
+ assignment: assignee ? 'direct' : 'pool',
472
+ state: 'open',
473
+ candidates: pool.map(candidateToken),
474
+ });
475
+ this.current.add(node.id);
476
+ }
477
+
478
+ /** 会签:每个参与人一份待办;依次会签先开第一份,其余排队 */
479
+ private async createSignItems(
480
+ node: TaskNode,
481
+ round: number,
482
+ arrival: string,
483
+ users: readonly string[],
484
+ weights: ReadonlyMap<string, number>,
485
+ ) {
486
+ const group = `${node.id}#${round}`;
487
+ const sequential = node.multi!.complete === 'sequential';
488
+ for (const [seq, user] of users.entries()) {
489
+ if (sequential && seq > 0) break;
490
+ await this.insertItem(node, round, arrival, {
491
+ assignee: user,
492
+ assignment: 'direct',
493
+ state: 'open',
494
+ signGroup: group,
495
+ signSeq: seq + 1,
496
+ weight: node.multi!.complete === 'votes' ? (weights.get(user) ?? 1) : null,
497
+ });
498
+ }
499
+ if (sequential && users.length > 1) this.state.queues[group] = users.slice(1);
500
+ this.current.add(node.id);
501
+ }
502
+
503
+ /** 插入一行待办,记事件 */
504
+ async insertItem(
505
+ node: TaskNode,
506
+ round: number,
507
+ arrival: string,
508
+ fields: Pick<WorkItemRow, 'assignee' | 'assignment' | 'state'> &
509
+ Partial<
510
+ Pick<
511
+ WorkItemRow,
512
+ 'signGroup' | 'signSeq' | 'candidates' | 'parentItemId' | 'fromUser' | 'weight'
513
+ >
514
+ >,
515
+ ): Promise<WorkItemRow> {
516
+ const routed = await this.applyProxies(fields);
517
+ const values = {
518
+ instanceId: this.instance.id,
519
+ node: node.id,
520
+ nodeName: node.name,
521
+ round,
522
+ arrival,
523
+ signGroup: fields.signGroup ?? null,
524
+ signSeq: fields.signSeq ?? null,
525
+ createdAt: this.now,
526
+ dueAt: node.due ? dueAt(node.due, this.now, this.read, this.options) : null,
527
+ completedAt: null,
528
+ completedBy: null,
529
+ outcome: null,
530
+ comment: null,
531
+ candidates: [],
532
+ parentItemId: null,
533
+ pendingOutcome: null,
534
+ fromUser: null,
535
+ proxyFor: null,
536
+ designator: null,
537
+ awaitingDesignation: false,
538
+ draft: null,
539
+ weight: null,
540
+ remindedAt: null,
541
+ ...routed,
542
+ };
543
+ const id = Number(await this.tx.insert(FlowWorkItem).values(values).returnId());
544
+ const row = { id, ...values } as WorkItemRow;
545
+ this.created.push(row);
546
+ this.addEvent('workItem.created', {
547
+ workItemId: id,
548
+ node: node.id,
549
+ data: { assignee: row.assignee, ...(row.proxyFor ? { proxyFor: row.proxyFor } : {}) },
550
+ });
551
+ await this.scheduleDeadlines(node, row);
552
+ return row;
553
+ }
554
+
555
+ /**
556
+ * 代理(docs/decisions/0010 第 3 节):处理人此刻设了代理时交给代理人、记下本该是谁的;收件箱里的候选人设了代理时,
557
+ * 代理人也加进候选(本人回来了照样能认领)。会签里代理人本来就在这一组时不代理,免得一人两票
558
+ */
559
+ private async applyProxies<
560
+ F extends { assignee: string | null; candidates?: string[]; signGroup?: string | null },
561
+ >(fields: F): Promise<F & { proxyFor?: string }> {
562
+ const key = this.instance.processKey;
563
+ if (fields.assignee) {
564
+ const agent = await agentOf(this.tx, fields.assignee, key, this.now);
565
+ if (!agent) return fields;
566
+ if (fields.signGroup) {
567
+ const inGroup = await this.tx
568
+ .queryable(FlowWorkItem)
569
+ .where((w) => [w.signGroup.eq(fields.signGroup!), w.assignee.eq(agent)])
570
+ .count();
571
+ if (inGroup > 0) return fields;
572
+ }
573
+ return { ...fields, assignee: agent, proxyFor: fields.assignee };
574
+ }
575
+ const agents: string[] = [];
576
+ for (const token of fields.candidates ?? []) {
577
+ const candidate = parseCandidate(token);
578
+ if (candidate.kind !== 'user') continue;
579
+ const agent = await agentOf(this.tx, candidate.value, key, this.now);
580
+ if (agent) agents.push(`user:${agent}`);
581
+ }
582
+ if (agents.length === 0) return fields;
583
+ return { ...fields, candidates: [...new Set([...fields.candidates!, ...agents])] };
584
+ }
585
+
586
+ /**
587
+ * 待办的时限与提醒:到期时记超时并按 overdue 处理;before 的提醒在到期前,every 的在到期后每隔一段、最多 times 次;
588
+ * 进收件箱后 unclaimed.after 还没人认领时提醒。作业执行时待办已不开着(或已认领)就什么也不做
589
+ */
590
+ private async scheduleDeadlines(node: TaskNode, item: WorkItemRow): Promise<void> {
591
+ const at = { node: node.id, round: item.round, workItemId: item.id };
592
+ if (item.dueAt) {
593
+ const due = item.dueAt.getTime();
594
+ await this.schedule('overdue', item.dueAt, at);
595
+ for (const reminder of node.reminders ?? []) {
596
+ if ('before' in reminder) {
597
+ const when = due - durationMs(reminder.before);
598
+ if (when > this.now.getTime())
599
+ await this.schedule('remind', new Date(when), { ...at, reason: 'dueSoon' });
600
+ } else {
601
+ const step = durationMs(reminder.every);
602
+ for (let n = 1; n <= (reminder.times ?? 1); n++) {
603
+ await this.schedule('remind', new Date(due + n * step), { ...at, reason: 'overdue' });
604
+ }
605
+ }
606
+ }
607
+ }
608
+ if (node.unclaimed && item.assignment === 'pool') {
609
+ const when = new Date(this.now.getTime() + durationMs(node.unclaimed.after));
610
+ await this.schedule('unclaimed', when, { ...at, action: node.unclaimed.action });
611
+ }
612
+ }
613
+
614
+ /** 退回跳出并行区域:取消区域里还开着的待办,清掉汇合计数 */
615
+ async leaveRegions(from: string, to: string): Promise<void> {
616
+ const pairs = gatewayPairs(this.definition);
617
+ for (const fork of pairs.forksAround(from)) {
618
+ const region = pairs.region(fork);
619
+ if (region.has(to)) continue;
620
+ const join = pairs.joinOf(fork);
621
+ if (join) delete this.state.waiting[join];
622
+ const nodes = [...region].filter((id) => id !== from);
623
+ if (nodes.length > 0) await this.cancelItems(nodes);
624
+ for (const id of region) this.current.delete(id);
625
+ }
626
+ }
627
+
628
+ /** 取消这些节点上还开着(或排队)的待办 */
629
+ async cancelItems(nodes: readonly string[]): Promise<void> {
630
+ if (nodes.length === 0) return;
631
+ await this.cancelWhere((w) => [w.node.in(nodes as string[])]);
632
+ for (const key of Object.keys(this.state.queues)) {
633
+ if (nodes.includes(key.slice(0, key.lastIndexOf('#')))) delete this.state.queues[key];
634
+ }
635
+ }
636
+
637
+ /** 自动节点:同步执行注册的动作,按它给的结果走;异步的交给作业 */
638
+ private async runService(nodeId: string): Promise<void> {
639
+ const node = this.node(nodeId);
640
+ if (node.type !== 'service') return;
641
+ if ((node.mode ?? 'async') === 'async') {
642
+ this.current.add(nodeId);
643
+ await this.schedule('action', this.now, { node: nodeId, round: this.bumpRound(nodeId) });
644
+ return;
645
+ }
646
+ const result = await this.callAction(nodeId);
647
+ return this.leave(nodeId, result?.outcome ?? null);
648
+ }
649
+
650
+ /** 执行自动节点注册的动作,改变量,返回它给的结果 */
651
+ async callAction(nodeId: string): Promise<{ outcome?: string } | undefined> {
652
+ const node = this.node(nodeId);
653
+ if (node.type !== 'service') return undefined;
654
+ const action = this.extension('actions', node.action);
655
+ if (!action)
656
+ throw new FlowError('invalid-definition', `没有注册动作 ${node.action}`, { node: nodeId });
657
+ let result: Awaited<ReturnType<typeof action>>;
658
+ try {
659
+ result = await action({ ...this.context(node.args ?? {}), node: nodeId });
660
+ } catch (error) {
661
+ // 同步的动作出错整个命令失败;异步的由作业重试(作业那边按普通错误处理)
662
+ if ((node.mode ?? 'async') === 'sync') {
663
+ throw new FlowError('extension-failed', `动作 ${node.action} 出错:${String(error)}`, {
664
+ node: nodeId,
665
+ });
666
+ }
667
+ throw error;
668
+ }
669
+
670
+ if (result?.variables) this.setVariables(result.variables);
671
+ this.addEvent('service.done', { node: nodeId, outcome: result?.outcome ?? null });
672
+ return result ?? undefined;
673
+ }
674
+
675
+ /** 定时等待:到点的作业 */
676
+ private async waitTimer(nodeId: string): Promise<void> {
677
+ const node = this.node(nodeId);
678
+ if (node.type !== 'timer') return;
679
+ const at = dueAt(node.wait, this.now, this.read, this.options);
680
+ if (at <= this.now) return this.leave(nodeId);
681
+ this.current.add(nodeId);
682
+ await this.schedule('timer', at, { node: nodeId, round: this.bumpRound(nodeId) });
683
+ }
684
+
685
+ /** 节点进入一轮(定时、自动节点等的作业按轮次判断是否过时) */
686
+ bumpRound(nodeId: string): number {
687
+ const round = (this.state.rounds[nodeId] ?? 0) + 1;
688
+ this.state.rounds[nodeId] = round;
689
+ return round;
690
+ }
691
+
692
+ /** 抄送:展开成人,每人一条;手动抄送时节点为空 */
693
+ /** 处理人的来源解析成人(抄送、通知加的收件人):角色、部门经 org 展开,去重 */
694
+ async resolveUsers(sources: Parameters<typeof resolveCandidates>[0]): Promise<string[]> {
695
+ const scope = {
696
+ context: this.context(),
697
+ handledBy: this.state.handledBy,
698
+ options: this.options,
699
+ resolver: (name: string) => this.extension('resolvers', name),
700
+ };
701
+ return expandToUsers(await resolveCandidates(sources, scope), this.options);
702
+ }
703
+
704
+ async sendCc(
705
+ nodeId: string | null,
706
+ sources: Parameters<typeof resolveCandidates>[0],
707
+ message?: string,
708
+ ): Promise<void> {
709
+ const users = await this.resolveUsers(sources);
710
+ if (users.length === 0) return;
711
+ await this.tx
712
+ .insert(FlowCc)
713
+ .values(
714
+ users.map((recipient) => ({
715
+ instanceId: this.instance.id,
716
+ node: nodeId,
717
+ recipient,
718
+ sender: nodeId === null ? (this.actor?.id ?? null) : null,
719
+ message: message ?? null,
720
+ at: this.now,
721
+ readAt: null,
722
+ })),
723
+ )
724
+ .execute();
725
+ this.addEvent('instance.cc', {
726
+ node: nodeId,
727
+ comment: message ?? null,
728
+ data: { to: users },
729
+ });
730
+ }
731
+
732
+ /** 排一个作业(和命令同一事务) */
733
+ async schedule(
734
+ kind: string,
735
+ at: Date,
736
+ payload: { node?: string; round?: number; workItemId?: number } & Record<string, unknown>,
737
+ ): Promise<void> {
738
+ await this.tx
739
+ .insert(FlowJob)
740
+ .values({
741
+ kind,
742
+ instanceId: this.instance.id,
743
+ workItemId: payload.workItemId ?? null,
744
+ node: payload.node ?? null,
745
+ round: payload.round ?? null,
746
+ dueAt: at,
747
+ payload,
748
+ attempts: 0,
749
+ state: 'pending',
750
+ lockedBy: null,
751
+ lockedUntil: null,
752
+ lastError: null,
753
+ })
754
+ .execute();
755
+ }
756
+
757
+ /** 结束实例:取消还开着的待办,删掉还没到点的作业 */
758
+ async finish(
759
+ status: Exclude<InstanceRow['status'], 'draft' | 'active' | 'suspended'>,
760
+ result: string | null,
761
+ comment: string | null = null,
762
+ ): Promise<void> {
763
+ if (this.finished) return;
764
+ this.status = status;
765
+ this.endComment = comment;
766
+ this.result = result;
767
+ this.endedAt = this.now;
768
+ await this.cancelWhere(() => []);
769
+ await this.tx
770
+ .delete(FlowJob)
771
+ .where((j) => [j.instanceId.eq(this.instance.id), j.state.eq('pending')])
772
+ .execute();
773
+ this.current.clear();
774
+ this.state.waiting = {};
775
+ this.state.queues = {};
776
+ // 正常走到结束记 instance.finished,其余按状态(instance.withdrawn、instance.terminated),同 Java 版
777
+ this.addEvent(status === 'completed' ? 'instance.finished' : `instance.${status}`, {
778
+ comment,
779
+ data: result ? { result } : null,
780
+ });
781
+ }
782
+
783
+ /** 取消这个实例上符合条件、还开着(或排队)的待办,每份记一条事件 */
784
+ async cancelWhere(filter: (w: any) => unknown[]): Promise<void> {
785
+ const where = (w: any) => [
786
+ w.instanceId.eq(this.instance.id),
787
+ w.state.in(['open', 'waiting']),
788
+ ...filter(w),
789
+ ];
790
+ const open = await this.tx
791
+ .queryable(FlowWorkItem)
792
+ .where(where as never)
793
+ .orderBy((w) => w.id)
794
+ .toList();
795
+ if (open.length === 0) return;
796
+ await this.tx
797
+ .update(FlowWorkItem)
798
+ .set({ state: 'canceled', completedAt: this.now })
799
+ .where(where as never)
800
+ .execute();
801
+ for (const item of open)
802
+ this.addEvent('workItem.canceled', { workItemId: item.id, node: item.node });
803
+ }
804
+
805
+ /** 写回实例、事件;监听在提交后执行 */
806
+ async flush(): Promise<{ instance: InstanceSummary; events: FlowEventView[] }> {
807
+ const title = renderTitle(this.definition.title, this.read) ?? this.instance.title;
808
+ const rev = this.instance.rev + 1;
809
+ await this.tx
810
+ .update(FlowInstance)
811
+ .set({
812
+ variables: this.variables,
813
+ state: this.state,
814
+ current: [...this.current],
815
+ status: this.status,
816
+ result: this.result,
817
+ endedAt: this.endedAt,
818
+ title,
819
+ rev,
820
+ })
821
+ .where((i) => i.id.eq(this.instance.id))
822
+ .execute();
823
+ if (this.events.length > 0) {
824
+ await this.tx
825
+ .insert(FlowEvent)
826
+ .values(this.events.map((event) => ({ ...event })))
827
+ .execute();
828
+ // 广播:随提交发出,多实例部署时别的进程据此刷新页面(core/channels.ts)
829
+ await this.tx.notify(FLOW_CHANNEL, JSON.stringify({ instance: this.instance.id }));
830
+ const notices = await collectNotifications(this, this.events, title);
831
+ if (notices.length > 0) {
832
+ await this.tx.insert(FlowNotification).values(notices).execute();
833
+ if (this.options.notifications?.deliver) this.tx.afterCommit(() => this.onNotified?.());
834
+ }
835
+ const listeners = this.options.on;
836
+ if (listeners) {
837
+ const events = [...this.events];
838
+ this.tx.afterCommit(async () => {
839
+ for (const event of events) {
840
+ await listeners[event.type]?.(event);
841
+ await listeners['*']?.(event);
842
+ }
843
+ });
844
+ }
845
+ }
846
+ return {
847
+ instance: {
848
+ id: this.instance.id,
849
+ processKey: this.instance.processKey,
850
+ version: this.instance.version,
851
+ status: this.status,
852
+ result: this.result,
853
+ title,
854
+ current: [...this.current].map((node) => ({
855
+ node,
856
+ name: this.graph.node(node)?.name ?? node,
857
+ })),
858
+ variables: { ...this.variables },
859
+ },
860
+ events: [...this.events],
861
+ };
862
+ }
863
+ }
864
+
865
+ /** 没写处理人时用所在泳道的收件箱 */
866
+ function laneInbox(graph: ProcessGraph, node: TaskNode): Parameters<typeof resolveCandidates>[0] {
867
+ const inbox = graph.lane(node.lane)?.inbox;
868
+ if (!inbox) return [];
869
+ if ('role' in inbox) return [{ role: inbox.role }];
870
+ if ('department' in inbox) return [{ department: inbox.department }];
871
+ return [{ group: inbox.group, id: inbox.id }];
872
+ }
873
+
874
+ /** 实例标题:模板里花括号中是字段名 */
875
+ export function renderTitle(
876
+ template: string | undefined,
877
+ read: (field: string) => unknown,
878
+ ): string | null {
879
+ if (!template) return null;
880
+ return template.replace(/\{([^}]+)\}/g, (_, field: string) => {
881
+ const value = read(field.trim());
882
+ return value === undefined || value === null ? '' : String(value as string | number);
883
+ });
884
+ }
885
+
886
+ /** 一段时长的毫秒数(工作日按自然日算:提醒的间隔用它;时限的工作日由 dueAt 按日历数) */
887
+ function durationMs(duration: Duration): number {
888
+ if ('minutes' in duration) return duration.minutes * 60_000;
889
+ if ('hours' in duration) return duration.hours * 3_600_000;
890
+ if ('days' in duration) return duration.days * 86_400_000;
891
+ return duration.workdays * 86_400_000;
892
+ }
893
+
894
+ /** 时长或时刻 → 到点的时刻(工作日跳过非工作日) */
895
+ export function dueAt(
896
+ due: Due,
897
+ from: Date,
898
+ read: (field: string) => unknown,
899
+ options: FlowEngineOptions,
900
+ ): Date {
901
+ if ('until' in due) {
902
+ const value = typeof due.until === 'string' ? due.until : read(due.until.ref);
903
+ return new Date(value as string);
904
+ }
905
+ if (!('workdays' in due)) return new Date(from.getTime() + durationMs(due));
906
+ const isWorkday =
907
+ options.isWorkday ?? ((day: Date) => day.getUTCDay() !== 0 && day.getUTCDay() !== 6);
908
+ const at = new Date(from);
909
+ let left = due.workdays;
910
+ while (left > 0) {
911
+ at.setUTCDate(at.getUTCDate() + 1);
912
+ if (isWorkday(at)) left--;
913
+ }
914
+ return at;
915
+ }