@mldong/jeeflow 1.8.54 → 1.8.55

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.
package/dist/engine.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { TypeStart, TypeEnd, TypeTask, TypeDecision, TypeFork, TypeJoin, TypeCustom, KnownNodeTypes, ProcessInstance, InstanceState, TaskState, SubmitType, } from './model.js';
3
+ import { attachCreated, createTaskAt, executeReapply, mergeReady, newContext, parseMode, reapplyOf, RETURN_TO_SOURCE, scopesOf, stripReserved, withInstanceLock, VAR_BRANCH_CTX, VAR_REAPPLY_CTX, } from './reapply.js';
3
4
  // issues/141 G2:cc 写侧判重的 java `default` 方法在 TS 里的对应物(第三方仓储未实现判重 SPI 时兜旧行为)
4
5
  // issues/141 G10:归属值单值/集合归一的**那一份**判据(漏斗层与写侧层共用;issues/142 B 批
5
6
  // 按 spec 06 §2.11 从"只挂 cc 一支"升为 cc 腿与任务腿共用同一枚,见 spi.normalizeActors)
@@ -417,10 +418,15 @@ export class EngineImpl {
417
418
  // spec04 §完成任务:公开方法回传「本次动作产出的任务行」(基准=java exec.getProcessTaskList())。
418
419
  // 作用域用 AsyncLocalStorage:一个 EngineImpl 实例并发处理多个请求,class 字段会互踩;
419
420
  // 而 node 没有 go 那样的 ctx 可挂,ALS 是等价的每次调用作用域(见 R92 notes)。
420
- await this.createdScope.run(created, () => this.inTx(() => this.executeProcessTaskInner(taskId, operator, args)));
421
+ const pre = await this.repo.findTaskById(taskId);
422
+ await withInstanceLock(this, pre?.processInstanceId, () => this.createdScope.run(created, () => this.inTx(() => this.executeProcessTaskInner(taskId, operator, args))));
421
423
  return created;
422
424
  }
423
425
  async executeProcessTaskInner(taskId, operator, args = {}) {
426
+ args = stripReserved(args);
427
+ const pre = await this.repo.findTaskById(taskId);
428
+ if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables))
429
+ return await executeReapply(this, pre, operator, args);
424
430
  const { task, inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
425
431
  // issues/127 / 规范 11 §11.7「办理时抄送」腿的统一出口:任务更新已在 prepareExecuteTask
426
432
  // 落库,此处建 cc 行并逐人 fire CC_CREATE(4),再回读实例。
@@ -553,6 +559,10 @@ export class EngineImpl {
553
559
  return created;
554
560
  }
555
561
  async executeAndJumpToEndInner(taskId, operator, args = {}) {
562
+ const pre = await this.repo.findTaskById(taskId);
563
+ if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables)) {
564
+ throw new Error("带重提直返标记的申请待办不允许拒绝,只接受重新提交(submitType=5)");
565
+ }
556
566
  const { inst } = await this.prepareExecuteTask(taskId, operator, args);
557
567
  // 门面 submitType=2 REJECT 唯一入口(对齐 Java executeAndJumpToEnd 语义)
558
568
  inst.reject(new Date());
@@ -573,6 +583,11 @@ export class EngineImpl {
573
583
  return created;
574
584
  }
575
585
  async executeAndJumpTaskInner(taskId, operator, args = {}, targetTaskName) {
586
+ // 带直返上下文的进行中申请待办只接受重新提交(5):命名跳转/退回上一步都在改状态前拒绝
587
+ const pre = await this.repo.findTaskById(taskId);
588
+ if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables)) {
589
+ throw new Error("带重提直返标记的申请待办不允许跳转,只接受重新提交(submitType=5)");
590
+ }
576
591
  const { task, inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
577
592
  if (!targetTaskName) {
578
593
  // issues/121 P2:ROLLBACK 走血缘版——复活 task.parentTaskId 指的那条历史行,
@@ -601,11 +616,45 @@ export class EngineImpl {
601
616
  // spec04 §完成任务:公开方法回传「本次动作产出的任务行」(基准=java exec.getProcessTaskList())。
602
617
  // 作用域用 AsyncLocalStorage:一个 EngineImpl 实例并发处理多个请求,class 字段会互踩;
603
618
  // 而 node 没有 go 那样的 ctx 可挂,ALS 是等价的每次调用作用域(见 R92 notes)。
604
- await this.createdScope.run(created, () => this.inTx(() => this.executeAndJumpToFirstTaskNodeInner(taskId, operator, args)));
619
+ const pre = await this.repo.findTaskById(taskId);
620
+ await withInstanceLock(this, pre?.processInstanceId, () => this.createdScope.run(created, () => this.inTx(() => this.executeAndJumpToFirstTaskNodeInner(taskId, operator, args))));
605
621
  return created;
606
622
  }
607
623
  async executeAndJumpToFirstTaskNodeInner(taskId, operator, args = {}) {
608
- const { inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
624
+ args = stripReserved(args);
625
+ // 校验放在任何状态变更之前:带直返上下文的申请待办不得再次退回
626
+ const pre = await this.repo.findTaskById(taskId);
627
+ if (pre && pre.taskState === TaskState.Doing && reapplyOf(pre.variables)) {
628
+ throw new Error("带重提直返标记的申请待办不允许再次退回,只接受重新提交(submitType=5)");
629
+ }
630
+ let sourceNode;
631
+ let direct = false;
632
+ if (pre && pre.taskState === TaskState.Doing) {
633
+ const inst0 = await this.repo.findInstanceById(pre.processInstanceId);
634
+ const def0 = await this.repo.findDefineById(inst0.defineId);
635
+ const flow0 = JSON.parse(typeof def0.content === 'string' ? def0.content : new TextDecoder().decode(def0.content));
636
+ sourceNode = findNode(flow0, pre.taskName);
637
+ if (sourceNode && parseMode(sourceNode) === RETURN_TO_SOURCE)
638
+ direct = true;
639
+ }
640
+ const { task, inst, flow, vars } = await this.prepareExecuteTask(taskId, operator, args);
641
+ if (direct) {
642
+ if (sourceNode.type !== TypeTask)
643
+ throw new Error(`节点[${sourceNode.id}]不是普通审批任务,不支持重提直返`);
644
+ const pt = String(sourceNode.properties?.performType ?? '0').trim().toUpperCase();
645
+ if (pt === '1' || pt === 'ALL' || pt === 'COUNTERSIGN')
646
+ throw new Error(`会签节点[${sourceNode.id}]不支持退回修改直返`);
647
+ if (this.isFirstTaskNode(flow, sourceNode))
648
+ throw new Error(`申请节点[${sourceNode.id}]不能配置重提直返`);
649
+ const start0 = findNodeByType(flow, TypeStart);
650
+ const applyNode = start0 ? followEdges(flow, start0.id).find(n => n.type === TypeTask) : undefined;
651
+ if (!applyNode)
652
+ throw new Error('流程定义缺少申请节点,无法退回发起人');
653
+ applyNode.properties = applyNode.properties ?? {};
654
+ applyNode.properties.assignee = inst.operator;
655
+ await createTaskAt(this, flow, applyNode, inst, inst.operator, vars, task.id, [], newContext(task.id, sourceNode.id, scopesOf(task.variables)));
656
+ return (await this.repo.findInstanceById(inst.id));
657
+ }
609
658
  // 找到第一个任务节点,强制参与者为发起人,重新执行
610
659
  const startNode = findNodeByType(flow, TypeStart);
611
660
  if (startNode) {
@@ -755,7 +804,11 @@ export class EngineImpl {
755
804
  // 任务创建(对齐 Java CreateTaskHandler:不触发节点拦截器——创建任务 ≠ 节点执行完成;
756
805
  // 任务完成的拦截器由 executeProcessTask 显式触发,1.8.0 SYNC 同步演进)
757
806
  if (node.type === TypeTask) {
807
+ const sink = this.createdScope.getStore();
808
+ const before = sink ? sink.length : 0;
758
809
  await this.createTask(node, inst, operator, vars, await this.surrogateProcessName(flow, inst), parentId, this.isFirstTaskNode(flow, node));
810
+ if (sink)
811
+ await attachCreated(this, flow, inst, sink.slice(before), node.id, parentId);
759
812
  return;
760
813
  }
761
814
  // issues/142 A 批(spec 02-flow-definition.md §6.1 表第二行 · owner 2026-09-29/09-30 两次拍):
@@ -777,8 +830,7 @@ export class EngineImpl {
777
830
  await this.executeNode(flow, inst, n, operator, vars, parentId);
778
831
  return;
779
832
  case TypeJoin: {
780
- const doing = await this.repo.findDoingTasks(inst.id);
781
- if (doing.length === 0)
833
+ if (await mergeReady(this, flow, inst, node.id, parentId))
782
834
  for (const n of followEdges(flow, node.id))
783
835
  await this.executeNode(flow, inst, n, operator, vars, parentId);
784
836
  return;
@@ -1208,6 +1260,12 @@ function mergeExecIntoInstance(base, execVars) {
1208
1260
  for (const [k, v] of Object.entries(execVars)) {
1209
1261
  if (k.startsWith('u_'))
1210
1262
  continue;
1263
+ // 「退回修改、重提直返」的两枚保留键(spec 04)是**行级**引擎内部状态:_branchCtx 是分支
1264
+ // 归属栈、_reapplyContext 只出现在申请待办上,实例层没有对应语义。若不挡,任务办结时它们
1265
+ // 会随执行上下文写进实例变量并落库 ⇒ 每个出口(任务行 instanceExt/实例行 ext)都透出内部
1266
+ // 键,且 issues/82-3 的回退目标本身被污染(go mergeExecIntoInstance 同款挡法)。
1267
+ if (k === VAR_BRANCH_CTX || k === VAR_REAPPLY_CTX)
1268
+ continue;
1211
1269
  out[k] = v;
1212
1270
  }
1213
1271
  return out;
package/dist/facade.js CHANGED
@@ -11,6 +11,7 @@ import { TaskState, EXIST_UN_FINISH_INSTANCE, } from './model.js';
11
11
  import { normalizeActorValue } from './spi.js';
12
12
  import { KeyAutoExecute, KeyAdminID, KeyCcActorsStart, KeyNextNodeOperator, KeyProcessStartNextNodeOperator, isCountersign, parseActorIds } from './engine.js';
13
13
  import { EventType } from './extensions.js';
14
+ import { VAR_BRANCH_CTX, VAR_REAPPLY_CTX } from './reapply.js';
14
15
  // submitType 枚举(对齐 boot3)
15
16
  const SUBMIT_APPLY = 0;
16
17
  const SUBMIT_AGREE = 1;
@@ -1987,8 +1988,19 @@ function taskRowToMap(r) {
1987
1988
  const instanceExt = parseVarMap(r.instanceVariable);
1988
1989
  // issues/121 P1:引擎建单必写的控制键不算「任务变量非空」,否则新建任务的 ext
1989
1990
  // 永远不再回退实例变量(issues/82-3 既有契约)。
1990
- const userKeys = Object.keys(r.variables ?? {}).filter(k => k !== 'isFirstTaskNode');
1991
- const ext = userKeys.length > 0 ? r.variables : instanceExt;
1991
+ // 「退回修改、重提直返」又添了两枚引擎内部键(spec 04 保留键 _branchCtx/_reapplyContext,
1992
+ // 建单时无条件写入、空分支也写 []):同样不算用户变量——否则每条任务行从此都不再回退,
1993
+ // 且内部键从公开出口透出。但 _reapplyContext 是前端「重新提交后返回:X」的唯一取数口
1994
+ // (jeeflow-ui helpers.ts 读 ext._reapplyContext)⇒ 回退后原样合回。
1995
+ // 合回必须落在**副本**上:instanceExt 是同一响应里的另一个出口,不能被任务侧的键污染。
1996
+ const vars = r.variables ?? {};
1997
+ const hasUserKey = Object.keys(vars).some(k => k !== 'isFirstTaskNode' && k !== VAR_BRANCH_CTX && k !== VAR_REAPPLY_CTX);
1998
+ let ext = vars;
1999
+ if (!hasUserKey) {
2000
+ ext = { ...instanceExt };
2001
+ if (vars[VAR_REAPPLY_CTX] != null)
2002
+ ext[VAR_REAPPLY_CTX] = vars[VAR_REAPPLY_CTX];
2003
+ }
1992
2004
  return {
1993
2005
  id: r.id, processInstanceId: r.processInstanceId, taskName: r.taskName,
1994
2006
  displayName: r.displayName, taskType: r.taskType, performType: r.performType,
@@ -0,0 +1,28 @@
1
+ export declare const PROP_REAPPLY_MODE = "reapplyMode";
2
+ export declare const VAR_BRANCH_CTX = "_branchCtx";
3
+ export declare const VAR_REAPPLY_CTX = "_reapplyContext";
4
+ export declare const NORMAL = "NORMAL";
5
+ export declare const RETURN_TO_SOURCE = "RETURN_TO_SOURCE";
6
+ export interface BranchScope {
7
+ fork: string;
8
+ join: string;
9
+ round: string;
10
+ root: string;
11
+ }
12
+ /** 同实例串行化(进程内 promise 链)。多进程部署需仓储侧提供跨进程锁。 */
13
+ export declare function withInstanceLock<T>(engine: any, instanceId: string | undefined, fn: () => Promise<T>): Promise<T>;
14
+ export declare function parseMode(node: any): string;
15
+ export declare function stripReserved(args: Record<string, any> | undefined): Record<string, any>;
16
+ export declare function staticScopes(flow: any, nodeId: string): BranchScope[];
17
+ export declare function buildScopes(flow: any, nodeId: string, parentVars: Record<string, any> | undefined, parentId: string, selfId: string): BranchScope[];
18
+ export declare function scopesOf(vars: Record<string, any> | undefined): BranchScope[];
19
+ export declare function reapplyOf(vars: Record<string, any> | undefined): Record<string, any> | undefined;
20
+ export declare function branchOf(rc: Record<string, any> | undefined): BranchScope[];
21
+ export declare function findScope(scopes: BranchScope[], joinId: string): BranchScope | undefined;
22
+ export declare function newContext(sourceTaskId: string, sourceNode: string, branch: BranchScope[]): Record<string, any>;
23
+ /** 建单钩子:给本次新任务补分支归属(父任务在聚合内按 ID 查)。 */
24
+ export declare function attachCreated(engine: any, flow: any, inst: any, created: any[], nodeId: string, parentId: string): Promise<void>;
25
+ export declare function mergeReady(engine: any, flow: any, inst: any, joinId: string, arrivingId: string): Promise<boolean>;
26
+ declare function createTaskAt(engine: any, flow: any, node: any, inst: any, operator: string, vars: Record<string, any>, parentId: string, scopes: BranchScope[], rc: Record<string, any> | undefined): Promise<void>;
27
+ export declare function executeReapply(engine: any, task: any, operator: string, args: Record<string, any>): Promise<any>;
28
+ export { createTaskAt };
@@ -0,0 +1,282 @@
1
+ /**
2
+ * 「退回修改、重提直返」——分支归属与直返上下文(Node 栈)。
3
+ *
4
+ * 状态落点与 Java/Go/Python 参考实现一致:零 DDL,全部寄存在任务变量保留键里
5
+ * (spec 04-engine-ops「退回修改、重提直返」)。
6
+ */
7
+ import { KeyNextNodeOperator, KeySubmitType } from './engine.js';
8
+ import { SubmitType, TaskState, TypeCustom, TypeFork, TypeJoin, TypeTask } from './model.js';
9
+ export const PROP_REAPPLY_MODE = 'reapplyMode';
10
+ export const VAR_BRANCH_CTX = '_branchCtx';
11
+ export const VAR_REAPPLY_CTX = '_reapplyContext';
12
+ export const NORMAL = 'NORMAL';
13
+ export const RETURN_TO_SOURCE = 'RETURN_TO_SOURCE';
14
+ const locks = new Map();
15
+ /** 同实例串行化(进程内 promise 链)。多进程部署需仓储侧提供跨进程锁。 */
16
+ export async function withInstanceLock(engine, instanceId, fn) {
17
+ const key = `${String(engine.__rjId ??= Math.random())}:${instanceId || '0'}`;
18
+ const prev = locks.get(key) ?? Promise.resolve();
19
+ let release;
20
+ const gate = new Promise(res => { release = res; });
21
+ locks.set(key, prev.then(() => gate));
22
+ await prev;
23
+ try {
24
+ return await fn();
25
+ }
26
+ finally {
27
+ release();
28
+ if (locks.get(key) === gate)
29
+ locks.delete(key);
30
+ }
31
+ }
32
+ export function parseMode(node) {
33
+ const raw = String(node?.properties?.[PROP_REAPPLY_MODE] ?? '').trim();
34
+ if (raw === '' || raw === NORMAL)
35
+ return NORMAL;
36
+ if (raw === RETURN_TO_SOURCE)
37
+ return RETURN_TO_SOURCE;
38
+ throw new Error(`节点[${node?.id}]的 reapplyMode 配置非法: ${raw}`);
39
+ }
40
+ export function stripReserved(args) {
41
+ const out = { ...(args ?? {}) };
42
+ delete out[VAR_BRANCH_CTX];
43
+ delete out[VAR_REAPPLY_CTX];
44
+ return out;
45
+ }
46
+ // ─── 模型静态分析 ────────────────────────────────────────────────────────────
47
+ function incoming(flow, nodeId) {
48
+ return flow.edges.filter((e) => e.targetNodeId === nodeId).map((e) => e.sourceNodeId);
49
+ }
50
+ function outgoing(flow, nodeId) {
51
+ return flow.edges.filter((e) => e.sourceNodeId === nodeId).map((e) => e.targetNodeId);
52
+ }
53
+ /**
54
+ * 沿入边回溯到指定分叉之间的任务集合;可穿过嵌套的内层 fork,遇到 stopFork 即止。
55
+ */
56
+ function backwardTaskIds(flow, nodeId, stopFork = '') {
57
+ const out = new Set();
58
+ const stack = incoming(flow, nodeId);
59
+ const visited = new Set();
60
+ const byId = new Map(flow.nodes.map((n) => [n.id, n]));
61
+ while (stack.length) {
62
+ const cur = stack.pop();
63
+ if (!cur || visited.has(cur))
64
+ continue;
65
+ visited.add(cur);
66
+ const n = byId.get(cur);
67
+ if (!n)
68
+ continue;
69
+ if (n.type === TypeFork && cur === stopFork)
70
+ continue;
71
+ if (n.type === TypeTask || n.type === TypeCustom)
72
+ out.add(cur);
73
+ stack.push(...incoming(flow, cur));
74
+ }
75
+ return out;
76
+ }
77
+ /**
78
+ * 汇合点对应的分叉:取「最近后支配汇合点 === 本 join」的 fork,多候选取最外层。
79
+ * 不能取"回溯遇到的第一个 fork"——嵌套并行时外层汇合点沿内层分支回溯会先撞到内层 fork。
80
+ */
81
+ function forkForJoin(flow, joinId) {
82
+ let best = '';
83
+ let bestDepth = -1;
84
+ for (const n of flow.nodes) {
85
+ if (n.type !== TypeFork)
86
+ continue;
87
+ if (nearestPostDominatingJoin(flow, n.id) !== joinId)
88
+ continue;
89
+ const d = maxDistanceToJoin(flow, n.id, joinId);
90
+ if (d > bestDepth) {
91
+ bestDepth = d;
92
+ best = n.id;
93
+ }
94
+ }
95
+ return best;
96
+ }
97
+ function nearestPostDominatingJoin(flow, forkId) {
98
+ let best = '';
99
+ let bestMax = -1;
100
+ for (const n of flow.nodes) {
101
+ if (n.type !== TypeJoin)
102
+ continue;
103
+ if (!postDominates(flow, forkId, n.id))
104
+ continue;
105
+ const d = maxDistanceToJoin(flow, forkId, n.id);
106
+ if (d >= 0 && (bestMax < 0 || d < bestMax)) {
107
+ bestMax = d;
108
+ best = n.id;
109
+ }
110
+ }
111
+ return best;
112
+ }
113
+ /** 屏蔽该汇合点后,fork 的任一分支仍能走到末端即不成立 */
114
+ function postDominates(flow, forkId, joinId) {
115
+ const stack = outgoing(flow, forkId);
116
+ const visited = new Set();
117
+ while (stack.length) {
118
+ const cur = stack.pop();
119
+ if (!cur || cur === joinId || visited.has(cur))
120
+ continue;
121
+ visited.add(cur);
122
+ const outs = outgoing(flow, cur);
123
+ if (!outs.length)
124
+ return false;
125
+ stack.push(...outs);
126
+ }
127
+ return true;
128
+ }
129
+ function maxDistanceToJoin(flow, forkId, joinId) {
130
+ let frontier = Array.from(new Set(outgoing(flow, forkId)));
131
+ const visited = new Set(frontier);
132
+ let d = 1;
133
+ let found = -1;
134
+ while (frontier.length) {
135
+ const next = [];
136
+ for (const cur of frontier) {
137
+ if (cur === joinId)
138
+ found = d;
139
+ for (const t of outgoing(flow, cur)) {
140
+ if (!visited.has(t)) {
141
+ visited.add(t);
142
+ next.push(t);
143
+ }
144
+ }
145
+ }
146
+ frontier = next;
147
+ d++;
148
+ }
149
+ return found;
150
+ }
151
+ export function staticScopes(flow, nodeId) {
152
+ const hits = [];
153
+ for (const n of flow.nodes) {
154
+ if (n.type !== TypeJoin)
155
+ continue;
156
+ const fork = forkForJoin(flow, n.id);
157
+ if (!fork)
158
+ continue;
159
+ const inside = backwardTaskIds(flow, n.id, fork);
160
+ if (!inside.has(nodeId))
161
+ continue;
162
+ hits.push({ size: inside.size, scope: { fork, join: n.id, round: '0', root: '0' } });
163
+ }
164
+ hits.sort((a, b) => b.size - a.size);
165
+ return hits.map(h => h.scope);
166
+ }
167
+ export function buildScopes(flow, nodeId, parentVars, parentId, selfId) {
168
+ const statics = staticScopes(flow, nodeId);
169
+ const parentScopes = scopesOf(parentVars);
170
+ return statics.map(s => {
171
+ const inherited = parentScopes.find(p => p.fork === s.fork && p.join === s.join);
172
+ return inherited
173
+ ? { fork: s.fork, join: s.join, round: inherited.round, root: inherited.root }
174
+ : { fork: s.fork, join: s.join, round: parentId, root: selfId };
175
+ });
176
+ }
177
+ // ─── 变量读写 ────────────────────────────────────────────────────────────────
178
+ export function scopesOf(vars) {
179
+ const raw = vars?.[VAR_BRANCH_CTX];
180
+ if (!Array.isArray(raw))
181
+ return [];
182
+ return raw.filter((x) => x && typeof x === 'object').map((x) => ({
183
+ fork: String(x.fork ?? ''), join: String(x.join ?? ''),
184
+ round: String(x.round ?? '0'), root: String(x.root ?? '0'),
185
+ }));
186
+ }
187
+ export function reapplyOf(vars) {
188
+ const raw = vars?.[VAR_REAPPLY_CTX];
189
+ return raw && typeof raw === 'object' && Object.keys(raw).length ? raw : undefined;
190
+ }
191
+ export function branchOf(rc) {
192
+ if (!rc)
193
+ return [];
194
+ return scopesOf({ [VAR_BRANCH_CTX]: rc.branch });
195
+ }
196
+ export function findScope(scopes, joinId) {
197
+ return scopes.find(s => s.join === joinId);
198
+ }
199
+ export function newContext(sourceTaskId, sourceNode, branch) {
200
+ return { mode: RETURN_TO_SOURCE, sourceTaskId: String(sourceTaskId), sourceNode, branch: branch ?? [] };
201
+ }
202
+ // ─── 引擎侧适配 ──────────────────────────────────────────────────────────────
203
+ /** 建单钩子:给本次新任务补分支归属(父任务在聚合内按 ID 查)。 */
204
+ export async function attachCreated(engine, flow, inst, created, nodeId, parentId) {
205
+ if (!created.length)
206
+ return;
207
+ const parent = (inst.tasks ?? []).find((t) => t.id === parentId);
208
+ for (const nt of created) {
209
+ nt.variables = nt.variables ?? {};
210
+ nt.variables[VAR_BRANCH_CTX] = buildScopes(flow, nodeId, parent?.variables, parentId, nt.id);
211
+ await engine.repo.updateTask(nt);
212
+ }
213
+ }
214
+ export async function mergeReady(engine, flow, inst, joinId, arrivingId) {
215
+ const arriving = (inst.tasks ?? []).find((t) => t.id === arrivingId);
216
+ const scope = arriving ? findScope(scopesOf(arriving.variables), joinId) : undefined;
217
+ if (!scope)
218
+ return (await engine.repo.findDoingTasks(inst.id)).length === 0;
219
+ const roots = new Map();
220
+ for (const t of inst.tasks ?? []) {
221
+ const s = findScope(scopesOf(t.variables), joinId);
222
+ const inRound = !!s && s.fork === scope.fork && s.round === scope.round;
223
+ if (inRound && !roots.has(s.root))
224
+ roots.set(s.root, false);
225
+ if (t.taskState !== TaskState.Doing)
226
+ continue;
227
+ if (inRound)
228
+ roots.set(s.root, true);
229
+ for (const b of branchOf(reapplyOf(t.variables))) {
230
+ if (b.join === joinId && b.fork === scope.fork && b.round === scope.round)
231
+ roots.set(b.root, true);
232
+ }
233
+ }
234
+ if (!roots.size)
235
+ return (await engine.repo.findDoingTasks(inst.id)).length === 0;
236
+ return ![...roots.values()].some(Boolean);
237
+ }
238
+ async function createTaskAt(engine, flow, node, inst, operator, vars, parentId, scopes, rc) {
239
+ const sink = engine.createdScope?.getStore?.();
240
+ const before = sink ? sink.length : 0;
241
+ const pn = await engine.surrogateProcessName(flow, inst);
242
+ await engine.createTask(node, inst, operator, vars, pn, parentId, engine.isFirstTaskNode(flow, node));
243
+ const created = sink ? sink.slice(before) : [];
244
+ for (const nt of created) {
245
+ nt.variables = nt.variables ?? {};
246
+ nt.variables[VAR_BRANCH_CTX] = scopes ?? [];
247
+ if (rc)
248
+ nt.variables[VAR_REAPPLY_CTX] = rc;
249
+ await engine.repo.updateTask(nt);
250
+ }
251
+ }
252
+ export async function executeReapply(engine, task, operator, args) {
253
+ const st = args[KeySubmitType];
254
+ if (st != null && Number(st) !== Number(SubmitType.ReApply)) {
255
+ throw new Error('带重提直返标记的申请待办只接受重新提交(submitType=5)');
256
+ }
257
+ const inst = await engine.repo.findInstanceById(task.processInstanceId);
258
+ if (!inst)
259
+ throw new Error('流程实例不存在');
260
+ const def = await engine.repo.findDefineById(inst.defineId);
261
+ const flow = JSON.parse(typeof def.content === 'string' ? def.content : new TextDecoder().decode(def.content));
262
+ const rc = reapplyOf(task.variables);
263
+ const sourceId = String(rc.sourceTaskId ?? '');
264
+ const source = (inst.tasks ?? []).find((t) => t.id === sourceId);
265
+ if (!source || source.taskState !== TaskState.Done || source.processInstanceId !== inst.id) {
266
+ throw new Error('重提直返来源任务无效或未完成');
267
+ }
268
+ const sourceNode = flow.nodes.find((n) => n.id === source.taskName);
269
+ if (!sourceNode || sourceNode.type !== TypeTask || parseMode(sourceNode) !== RETURN_TO_SOURCE) {
270
+ throw new Error('重提直返来源节点配置已变更,拒绝执行');
271
+ }
272
+ const applyNode = flow.nodes.find((n) => n.id === task.taskName);
273
+ if (!applyNode || !engine.isFirstTaskNode(flow, applyNode)) {
274
+ throw new Error('重提直返必须从申请待办发起');
275
+ }
276
+ const prepared = await engine.prepareExecuteTask(task.id, operator, args);
277
+ const vars = prepared.vars;
278
+ delete vars[KeyNextNodeOperator];
279
+ await createTaskAt(engine, flow, sourceNode, prepared.inst, operator, vars, task.id, branchOf(rc), undefined);
280
+ return await engine.repo.findInstanceById(prepared.inst.id);
281
+ }
282
+ export { createTaskAt };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mldong/jeeflow",
3
- "version": "1.8.54",
3
+ "version": "1.8.55",
4
4
  "description": "jeeflow workflow engine — Node.js / TypeScript implementation",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -19,7 +19,7 @@
19
19
  "scripts": {
20
20
  "build": "tsc",
21
21
  "typecheck": "tsc -p tsconfig.check.json",
22
- "test": "node --import tsx __tests__/spec.test.ts",
22
+ "test": "node --import tsx __tests__/spec.test.ts && node --import tsx --test __tests__/reapply.test.ts",
23
23
  "test-mysql": "node --import tsx --test __tests__/jdbc.test.ts __tests__/tx-tier-145.test.ts __tests__/after_commit_r77.test.ts",
24
24
  "demo": "node --import tsx demo/main.ts",
25
25
  "prepublishOnly": "npm run build"