fix(workflow): wire create.ts caller, real webapi, try/catch, lint routing all forms, CLAUDE.md compliance

This commit is contained in:
ssw committed 2026-07-28 18:23:49 +08:00
1 parent 22d8111462
commit e03418d3ee
6 files changed
+304 -112

No files matched your search

+71 -33
View File
@@ -1,36 +1,53 @@
/**
* workflow 审批人变量解析 (webapi hardening)
* workflow 审批人变量解析.
*
* 镜像 web 端 FlowApproverSelect + ssw-common build-workflow 的 candidateResolver.
*
* 设计原则:
* - 解析 BPMN userTask assignee 表达式, 返回候选人列表 + 失败原因 (reason).
* - 失败原因显式化, 方便 _semantic_lint.ts 阻断坏 BPMN 进后端 Flowable 部署.
* - 不直接调 JnpfClient, 接受 webapi 容器 (resolveApproverExpr 是纯函数, 易于测试 + 复用).
* 解析 BPMN userTask assignee 表达式, 返回候选人列表 + 失败原因 (reason).
* 与 _semantic_lint 协同: 阻断坏 BPMN 进后端 Flowable 部署.
*
* 支持的表达式:
* - `role:<enCode>` → 调用 webapi.getUserListByRole(enCode)
* - `${deptManager}` → 调用 webapi.getDeptManager() (web 端发起人部门主管)
* - `${currentUser}` → 调用 webapi.getCurrentUser() (运行时上下文)
* - 显式 id (u\d+|v\d+) → 视为单候选人占位 (不解析, 视为合法)
* - `role:<enCode>` → webapi.getUserListByRole(enCode)
* - `${deptManager}` → webapi.getDeptManager() (发起人部门主管)
* - `${currentUser}` → webapi.getCurrentUser() (当前登录用户)
* - 显式 id (6+ 位数字) → 视为单候选人占位
*
* 保留关键字 (reserved keyword, 不允许作为审批人):
* - `initiator` / `any` / `starter` / `currentUser` 直接使用 (≠ ${currentUser} 表达式)
* 这些关键字在 BPMN flowable 引擎层有特殊语义, dacli 不应混淆 (避免双重解析).
* - `initiator` / `any` / `starter` / `currentUser` 字面量
* 估算匹配: 这些关键字在 Flowable 引擎层有特殊语义, dacli 不应混淆 (避免双重解析).
*
* 错误时返回空 candidates + reason 字符串, 调用方按需阻断.
* 异步 I/O 包装: 所有 webapi 调用都包在 try/catch, 避免 lint 流程被异常打断.
*/
/** 解析候选人所需的最小 webapi 契约. 真实方法在生产调用点 (create.ts) 注入. */
export interface ResolveWebapi {
/** 角色 enCode → 用户列表. 真实 API 待 wiring (web 端 permission/user.ts 无 byRole 入口). */
getUserListByRole?: (enCode: string) => Promise<Array<{ id: string; name: string }>>
/** 发起人部门主管. 真实 API 待 wiring (web 端 permission/organize.ts 无 manager 入口). */
getDeptManager?: () => Promise<Array<{ id: string; name: string }>>
/** 当前登录用户. 对应 JNPF /api/oauth/CurrentUser (src/webapi/user.ts getUserInfoApi). */
getCurrentUser?: () => Promise<{
id?: string
userId?: string
realName?: string
userName?: string
account?: string
userAccount?: string
} | null | undefined>
}
export interface ResolveCtx {
/** webapi 容器 (测试时可注入 mock). */
webapi: any
webapi?: ResolveWebapi
}
export interface ResolveResult {
candidates: Array<{ id: string; name: string }>
reason?: 'no users in dept' | 'no such role' | 'unknown expression' | 'reserved keyword' | 'api error'
reason?: 'no users in dept' | 'no current user' | 'no such role' | 'unknown expression' | 'reserved keyword' | 'api error'
}
/** 不允许直接当作 assignee 表达式使用的关键字. */
const RESERVED = new Set(['initiator', 'any', 'starter', 'currentUser'])
/** 不允许直接当作 assignee 表达式使用的关键字 (统一小写匹配).
* 注: ${currentUser} 这种变量包装形式是合法的 getter 调用, 不在此列. */
const RESERVED = new Set(['initiator', 'any', 'starter'])
/**
* 解析 BPMN userTask assignee 表达式.
@@ -45,42 +62,63 @@ export async function resolveApproverExpr(expr: string, ctx: ResolveCtx): Promis
return { candidates: [], reason: 'unknown expression' }
}
// 保留关键字 (initiator / any / starter / currentUser 字面量)
if (RESERVED.has(e)) {
// 1. 保留关键字 (unwrap ${...} 后, 不区分大小写检查)
const innerNoVar = e.replace(/^\$\{(.+)\}$/, '$1').trim().toLowerCase()
if (RESERVED.has(innerNoVar)) {
return { candidates: [], reason: 'reserved keyword' }
}
// role:xxx — 角色 enCode
const roleMatch = /^role:(.+)$/.exec(e)
// 2. role:xxx — 角色 enCode (trim 内部空白)
const roleMatch = /^role:\s*(.+?)\s*$/.exec(e)
if (roleMatch) {
const list = (await ctx.webapi?.getUserListByRole?.(roleMatch[1])) ?? []
const enCode = roleMatch[1]
const list = await safeCall(() => ctx.webapi?.getUserListByRole?.(enCode))
if (!Array.isArray(list)) return { candidates: [], reason: 'api error' }
return list.length ? { candidates: list } : { candidates: [], reason: 'no such role' }
}
// ${var} — 运行时变量
// 3. ${var} — 运行时变量
const varMatch = /^\$\{(.+)\}$/.exec(e)
if (varMatch) {
const name = varMatch[1].trim()
if (name === 'deptManager') {
const list = (await ctx.webapi?.getDeptManager?.()) ?? []
const list = await safeCall(() => ctx.webapi?.getDeptManager?.())
if (!Array.isArray(list)) return { candidates: [], reason: 'api error' }
return list.length ? { candidates: list } : { candidates: [], reason: 'no users in dept' }
}
if (name === 'currentUser') {
const me = await ctx.webapi?.getCurrentUser?.()
if (me && (me.id || me.userId)) {
const id = String(me.id ?? me.userId)
const name2 = String(me.realName ?? me.userName ?? me.account ?? id)
return { candidates: [{ id, name: name2 }] }
}
return { candidates: [], reason: 'no users in dept' }
const me = await safeCall(() => ctx.webapi?.getCurrentUser?.())
if (me === undefined) return { candidates: [], reason: 'api error' }
if (!me) return { candidates: [], reason: 'no current user' }
// JNPF 用空字符串表 unset (而不是 null), 用 || 链而非 ??
const id = String(me.userId || me.id || '')
const displayName = String(me.realName || me.userName || me.userAccount || me.account || id)
if (!id) return { candidates: [], reason: 'no current user' }
return { candidates: [{ id, name: displayName }] }
}
return { candidates: [], reason: 'unknown expression' }
}
// 显式 id (u\d+ 或 v\d+, JNPF userId / Vben v-id 风格) — 视为单候选人占位
if (/^[uv]\d+$/.test(e)) {
// 4. 显式 id (JNPF userId 风格, 6+ 位数字) — 视为单候选人占位
if (/^\d{6,}$/.test(e)) {
return { candidates: [{ id: e, name: e }] }
}
return { candidates: [], reason: 'unknown expression' }
}
/**
* 安全调用 webapi 方法.
* - 正常返回: webapi 返回值 (任意类型, 包括 null — 调用方区分 list / object)
* - 抛错: 返回 undefined (调用方按 'api error' 处理)
*/
async function safeCall<T>(fn: () => Promise<T> | undefined): Promise<T | undefined> {
try {
return await fn()
} catch {
return undefined
}
}
+14 -25
View File
@@ -1,5 +1,5 @@
/**
* workflow 语义 lint (webapi hardening)
* workflow 语义 lint.
*
* 与 BPMN layout lint 分离: layout 自动修复不掩盖语义错误.
* 使用 bpmn-moddle 解析 (项目已有依赖 ^10.0.0).
@@ -9,7 +9,7 @@
* - semanticLint 基于原始 BPMN XML 解析 (bpmn-moddle), 检查:
* 1. 节点完整性 (no start / no end)
* 2. 多结束节点无合流网关
* 3. userTask assignee 解析 (空字符串 / ${var} 无法解析)
* 3. userTask assignee 解析 (空 / ${var} / role / 关键字 / 显式 id)
*
* 设计原则: 在 Save(type=1) 之前阻断, 不让坏 BPMN 进入后端 Flowable 部署阶段.
*
@@ -21,7 +21,7 @@
*/
import { BpmnModdle } from 'bpmn-moddle'
import { resolveApproverExpr } from './_approver_resolve.ts'
import { resolveApproverExpr, type ResolveWebapi } from './_approver_resolve.ts'
export interface SemanticDiagnostic {
nodeId: string
@@ -35,17 +35,15 @@ export interface SemanticResult {
}
export interface ResolverCtx {
/** webapi 容器 (T5 接入). 优先使用, 解析失败时返回 reason. */
webapi?: any
/** 旧版 fallback (T4 阶段使用). 仅 webapi 缺失时启用, 兼容老调用点. */
candidateResolver?: (assigneeExpr: string) => Array<{ id: string; name: string }>
/** 候选人解析所需的最小 webapi 契约. 任意方法缺失时按 'api error' 阻断. */
webapi?: ResolveWebapi
}
/**
* 跑 workflow 语义 lint.
*
* @param xml - 原始 BPMN 2.0 XML
* @param ctx - 解析上下文 (T4 阶段 candidateResolver 占位, T5 接 resolveApproverExpr)
* @param xml 原始 BPMN 2.0 XML
* @param ctx 解析上下文 (webapi 容器, 供 resolveApproverExpr 使用)
*/
export async function semanticLint(xml: string, ctx: ResolverCtx): Promise<SemanticResult> {
const errors: string[] = []
@@ -115,22 +113,13 @@ export async function semanticLint(xml: string, ctx: ResolverCtx): Promise<Seman
continue
}
// 3b. assignee 是 ${var} 表达式, 尝试解析
if (assignee && /\$\{.+\}/.test(assignee)) {
let resolved: Array<{ id: string; name: string }> = []
let reason: string | undefined
if (ctx.webapi) {
const r = await resolveApproverExpr(assignee, { webapi: ctx.webapi })
resolved = r.candidates
reason = r.reason
} else if (ctx.candidateResolver) {
// 向后兼容: T4 阶段调用点只传 candidateResolver
resolved = ctx.candidateResolver(assignee) || []
if (resolved.length === 0) reason = 'no candidate'
}
if (resolved.length === 0) {
errors.push(`userTask ${ut.id}: assignee ${assignee} unresolved (${reason ?? 'no candidate'})`)
diagnostics.push({ nodeId: ut.id, message: `unresolved: ${assignee}${reason ? ` (${reason})` : ''}` })
// 3b. 路由 ALL forms 到 resolveApproverExpr (含 reserved keyword / role / ${var} / 显式 id / 空字符串)
if (assignee) {
const r = await resolveApproverExpr(assignee, { webapi: ctx.webapi })
if (r.candidates.length === 0) {
const reason = r.reason ?? 'unknown expression'
errors.push(`userTask ${ut.id}: assignee ${assignee} unresolved (${reason})`)
diagnostics.push({ nodeId: ut.id, message: `unresolved: ${assignee} (${reason})` })
}
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ export interface StepValidation {
}
/** 语义 lint — workflow/create.ts 在 Save(type=1) 之前调用, 阻断坏 BPMN 进后端.
* T4: 多结束无合并 / 无 start / assignee 空 / ${var} 无法解析 4 场景. */
* 覆盖: 多结束无合并 / 无 start / assignee 空 / ${var} 解析失败 / 保留关键字 / 显式 id 失败. */
export { semanticLint } from './_semantic_lint.ts'
export type { SemanticResult, SemanticDiagnostic, ResolverCtx } from './_semantic_lint.ts'
+14 -3
View File
@@ -28,6 +28,7 @@ import { callAiWorkflow, detectTrivialFlowXml } from '../form/_ai.ts'
import { buildFlowNodes, validateFlowNodeStructure } from './_webapi_helpers.ts'
import { autoLayoutFlowXml, isLayoutNeeded } from './_autoLayout.ts'
import { initWebapi, loadWorkflow } from '../../webapi/workflow.ts'
import { getUserInfoApi } from '../../webapi/user.ts'
import { validateWorkflowCreate, semanticLint } from './_validate.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): enCode/fullName strip 已统一到 runCommandAutoFix (commands/_auto_fix.ts), 不再 inline 调 autoStripEnCode/autoStripFullName (替代原 line 96-112 的 inline 调用 + warn log, BS-新38/BS-新52).
@@ -380,12 +381,22 @@ export function buildWorkflowCreateCommand(): Command {
log.ok(` ↳ ${structCheck.okMessage}`)
}
// 语义 lint (T4) — 阻断坏 BPMN 进后端 Flowable 部署.
// 语义 lint — 阻断坏 BPMN 进后端 Flowable 部署.
// 与 _webapi_helpers.validateFlowNodeStructure 互补:
// - validateFlowNodeStructure 检查 flowNodes Map 形态 (数量/类型)
// - semanticLint 检查原始 flowXml BPMN 语义 (assignee 解析, 多结束无合并)
// T4 阶段 candidateResolver 是占位, T5 会替换为真实 resolveApproverExpr.
const semantic = await semanticLint(flowXml, { candidateResolver: () => [] })
// 注入真实 webapi: getCurrentUser 调 JNPF /api/oauth/CurrentUser (src/webapi/user.ts getUserInfoApi).
// getUserListByRole / getDeptManager 暂未在 web 端暴露, 保留 undefined → 解析时会 'api error' 阻断.
const webapi = {
getCurrentUser: async () => {
try {
return await getUserInfoApi(c, { systemCode: c.appCode, isBackend: 1 })
} catch {
return null
}
},
}
const semantic = await semanticLint(flowXml, { webapi })
if (!semantic.ok) {
log.error(`✗ workflow 语义 lint 失败 (${semantic.errors.length} 个错误):`)
for (const e of semantic.errors) {
+179 -17
View File
@@ -1,21 +1,22 @@
/**
* workflow approver expr resolve tests (Task 5 — webapi hardening)
* workflow approver 表达式解析测试.
*
* 镜像 web 端 FlowApproverSelect + ssw-common build-workflow 的 candidateResolver.
* 4 场景:
* 1. 显式 `role:finance` 解析
* 2. 变量 `${deptManager}` 解析为空 → reason=no users in dept
* 3. unknown expression → reason=unknown expression
* 4. `initiator` / `any` 不允许作为审批人 → reason=reserved keyword
*
* 与 _semantic_lint.ts 集成 (T5):
* - ResolverCtx 扩展: 支持 webapi, 保留 candidateResolver fallback
* - semanticLint 在解析 ${var} 时, 用 resolveApproverExpr 替代 ctx.candidateResolver 直接调用
* 覆盖:
* - role:xxx (有结果 / 无结果 / trim 内部空白)
* - ${deptManager} (有结果 / 无结果)
* - ${currentUser} (有结果 / 无 login / 空字段)
* - ${other} 未知变量
* - 显式 id (6+ 位数字)
* - reserved keyword (initiator / any / starter / currentUser 字面量, 大小写 + ${...} 包裹)
* - throwing webapi → 'api error'
* - empty / whitespace 输入
* - 集成: lint 调用 webapi 路径 (非 candidateResolver)
*/
import { describe, expect, it, vi } from 'vitest'
import { resolveApproverExpr } from '../../src/commands/workflow/_approver_resolve.ts'
import { semanticLint } from '../../src/commands/workflow/_semantic_lint.ts'
describe('workflow approver resolve (Task 5)', () => {
describe('workflow approver resolve', () => {
it('显式 role:finance → 解析', async () => {
const webapi = { getUserListByRole: vi.fn().mockResolvedValue([{ id: 'u1', name: 'Alice' }]) }
const r = await resolveApproverExpr('role:finance', { webapi })
@@ -23,21 +24,182 @@ describe('workflow approver resolve (Task 5)', () => {
expect(r.reason).toBeUndefined()
})
it('变量 ${deptManager} 解析为空 → reason=no users in dept', async () => {
it('role:finance → 候选人为空 → no such role', async () => {
const webapi = { getUserListByRole: vi.fn().mockResolvedValue([]) }
const r = await resolveApproverExpr('role:finance', { webapi })
expect(r.candidates).toEqual([])
expect(r.reason).toBe('no such role')
})
it('role: finance (trim 内部空白) → 解析', async () => {
const webapi = { getUserListByRole: vi.fn().mockResolvedValue([{ id: 'u1', name: 'Alice' }]) }
const r = await resolveApproverExpr('role: finance ', { webapi })
expect(webapi.getUserListByRole).toHaveBeenCalledWith('finance')
expect(r.candidates).toEqual([{ id: 'u1', name: 'Alice' }])
})
it('变量 ${deptManager} 解析为空 → no users in dept', async () => {
const webapi = { getDeptManager: vi.fn().mockResolvedValue([]) }
const r = await resolveApproverExpr('${deptManager}', { webapi })
expect(r.candidates).toEqual([])
expect(r.reason).toBe('no users in dept')
})
it('unknown expression → reason=unknown expression', async () => {
const r = await resolveApproverExpr('${mystery}', { webapi: {} as any })
it('变量 ${deptManager} 解析有值 → 成功', async () => {
const webapi = { getDeptManager: vi.fn().mockResolvedValue([{ id: 'd1', name: 'Manager' }]) }
const r = await resolveApproverExpr('${deptManager}', { webapi })
expect(r.candidates).toEqual([{ id: 'd1', name: 'Manager' }])
})
it('变量 ${currentUser} 解析成功 → 候选人显示 prefer realName', async () => {
const webapi = { getCurrentUser: vi.fn().mockResolvedValue({ id: 'u1', realName: 'Alice' }) }
const r = await resolveApproverExpr('${currentUser}', { webapi })
expect(r.candidates).toEqual([{ id: 'u1', name: 'Alice' }])
})
it('变量 ${currentUser} userId 字段 + 空字段 fallback → 候选人', async () => {
// JNPF 用空字符串表 unset, 用 || 链.
const webapi = { getCurrentUser: vi.fn().mockResolvedValue({ userId: 'u2', realName: '', userName: '', userAccount: '', account: '' }) }
const r = await resolveApproverExpr('${currentUser}', { webapi })
expect(r.candidates).toEqual([{ id: 'u2', name: 'u2' }])
})
it('变量 ${currentUser} 解析为空 (未登录) → no current user', async () => {
const webapi = { getCurrentUser: vi.fn().mockResolvedValue(null) }
const r = await resolveApproverExpr('${currentUser}', { webapi })
expect(r.candidates).toEqual([])
expect(r.reason).toBe('no current user')
})
it('unknown expression → unknown expression', async () => {
const r = await resolveApproverExpr('${mystery}', { webapi: {} })
expect(r.candidates).toEqual([])
expect(r.reason).toBe('unknown expression')
})
it('initiator/any 不允许作为审批人 → reason=reserved keyword', async () => {
const r = await resolveApproverExpr('initiator', { webapi: {} as any })
it('initiator 不允许作为审批人 → reserved keyword', async () => {
const r = await resolveApproverExpr('initiator', { webapi: {} })
expect(r.candidates).toEqual([])
expect(r.reason).toBe('reserved keyword')
})
it('any / starter / INITIATOR 大写 + ${initiator} 包裹 → reserved keyword', async () => {
// 大小写不敏感: 'INITIATOR' → lowercase 'initiator' → reserved
// ${...} 包裹: unwrap 后 'initiator' → reserved
for (const kw of ['any', 'starter', 'INITIATOR', ' initiator ', '${initiator}']) {
const r = await resolveApproverExpr(kw, { webapi: {} })
expect(r.reason, `${kw} should be reserved`).toBe('reserved keyword')
}
})
it('${currentUser} 字面量包装 → 非 reserved (是合法 getter)', async () => {
// ${currentUser} 不是 reserved keyword, 是 webapi.getCurrentUser() 的 getter 入口.
const webapi = { getCurrentUser: vi.fn().mockResolvedValue({ id: 'u1', realName: 'Alice' }) }
const r = await resolveApproverExpr('${currentUser}', { webapi })
expect(r.reason).toBeUndefined()
expect(r.candidates).toEqual([{ id: 'u1', name: 'Alice' }])
})
it('显式 id (6+ 位数字) → single candidate passthrough', async () => {
const r1 = await resolveApproverExpr('123456', { webapi: {} })
const r2 = await resolveApproverExpr('1234567890123', { webapi: {} })
expect(r1.candidates).toEqual([{ id: '123456', name: '123456' }])
expect(r2.candidates).toEqual([{ id: '1234567890123', name: '1234567890123' }])
})
it('短 id (< 6 位) → unknown expression', async () => {
const r = await resolveApproverExpr('12345', { webapi: {} })
expect(r.candidates).toEqual([])
expect(r.reason).toBe('unknown expression')
})
it('throwing webapi → api error', async () => {
const webapi = {
getUserListByRole: vi.fn().mockRejectedValue(new Error('upstream timeout')),
}
const r = await resolveApproverExpr('role:finance', { webapi })
expect(r.candidates).toEqual([])
expect(r.reason).toBe('api error')
})
it('throwing webapi (getDeptManager) → api error', async () => {
const webapi = {
getDeptManager: vi.fn().mockRejectedValue(new Error('boom')),
}
const r = await resolveApproverExpr('${deptManager}', { webapi })
expect(r.reason).toBe('api error')
})
it('webapi method 不存在 → api error', async () => {
const r = await resolveApproverExpr('role:finance', { webapi: {} })
expect(r.reason).toBe('api error')
})
it('empty / whitespace 输入 → unknown expression', async () => {
expect((await resolveApproverExpr('', { webapi: {} })).reason).toBe('unknown expression')
expect((await resolveApproverExpr(' ', { webapi: {} })).reason).toBe('unknown expression')
expect((await resolveApproverExpr('\t\n', { webapi: {} })).reason).toBe('unknown expression')
})
it('webapi 返回 null → api error', async () => {
const webapi = { getUserListByRole: vi.fn().mockResolvedValue(null) }
const r = await resolveApproverExpr('role:finance', { webapi })
expect(r.reason).toBe('api error')
})
it('webapi 返回 non-array → api error', async () => {
const webapi = { getUserListByRole: vi.fn().mockResolvedValue({ not: 'array' }) }
const r = await resolveApproverExpr('role:finance', { webapi })
expect(r.reason).toBe('api error')
})
})
describe('workflow semantic lint + real webapi 集成', () => {
it('integration: lint 路由 role:xxx → 真实 webapi 路径', async () => {
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:camunda="http://camunda.org/schema/1.0/bpmn">
<bpmn:process id="p1">
<bpmn:startEvent id="s1"/>
<bpmn:userTask id="t1" camunda:assignee="role:finance"/>
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const webapi = {
getUserListByRole: vi.fn().mockResolvedValue([{ id: 'u1', name: 'Alice' }]),
}
const r = await semanticLint(xml, { webapi })
expect(r.ok).toBe(true)
expect(webapi.getUserListByRole).toHaveBeenCalledWith('finance')
})
it('integration: lint 路由 ${deptManager} 时遇空 → 阻断', async () => {
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
<bpmn:process id="p1">
<bpmn:startEvent id="s1"/>
<bpmn:userTask id="t1" assignee="\${deptManager}"/>
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const webapi = { getDeptManager: vi.fn().mockResolvedValue([]) }
const r = await semanticLint(xml, { webapi })
expect(r.ok).toBe(false)
expect(r.errors.some(e => /no users in dept/.test(e))).toBe(true)
})
it('integration: lint 路由 reserved keyword → 阻断', async () => {
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:camunda="http://camunda.org/schema/1.0/bpmn">
<bpmn:process id="p1">
<bpmn:startEvent id="s1"/>
<bpmn:userTask id="t1" camunda:assignee="initiator"/>
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { webapi: {} })
expect(r.ok).toBe(false)
expect(r.errors.some(e => /reserved keyword/.test(e))).toBe(true)
})
})
+25 -33
View File
@@ -1,26 +1,22 @@
/**
* workflow semantic lint tests (Task 4 — webapi hardening)
* workflow semantic lint tests.
*
* 原始 4 场景 (T4):
* 8 场景:
* 1. 多结束节点且无合并 → 阻断
* 2. 无 start → 阻断
* 3. userTask 无 assignee 且无 potentialOwner → 阻断
* 4. 显式 ${deptManager} 无法解析 → 阻断并 diagnostics
*
* T4 critical fix 回归 (C1/C2):
* 5. userTask assignee="" + <bpmn:potentialOwner/> → ok=true (C1: potentialOwner array)
* 6. userTask camunda:assignee="alice" → ok=true (C2: namespaced assignee)
*
* M3 稳定性测试:
* 4. 显式 ${deptManager} 解析为空 → 阻断并 diagnostics
* 5. userTask 无 assignee 但有 potentialOwner → ok=true
* 6. userTask camunda:assignee="12345678" (6+ 位数字) → ok=true
* 7. 空 XML → errors 含 'flowXml is empty'
* 8. 单 End + Gateway → ok=true (短路验证)
* 8. 单 End + Gateway → 无 multiple-end (短路验证)
*
* 与 BPMN layout lint 分离: layout 自动修复不掩盖语义错误.
*/
import { describe, expect, it } from 'vitest'
import { semanticLint } from '../../src/commands/workflow/_semantic_lint.ts'
describe('workflow semantic lint (Task 4)', () => {
describe('workflow semantic lint', () => {
it('多结束无合并 → ok=false, errors 含 multiple-end', async () => {
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
@@ -31,7 +27,7 @@ describe('workflow semantic lint (Task 4)', () => {
<bpmn:endEvent id="e2"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
const r = await semanticLint(xml, { webapi: {} })
expect(r.ok).toBe(false)
expect(r.errors.some(e => /multiple-end/.test(e))).toBe(true)
})
@@ -44,14 +40,11 @@ describe('workflow semantic lint (Task 4)', () => {
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
const r = await semanticLint(xml, { webapi: {} })
expect(r.ok).toBe(false)
})
it('userTask 无 assignee 且无 potentialOwner → ok=false', async () => {
// 测试 "真的没候选人" 的情况: 既没有 assignee 属性, 也没有 potentialOwner 元素.
// (T4 critical fix 之前, 这个 XML 含 <bpmn:potentialOwner/>, 但用错误的 resources?.potentialOwner 访问
// 一直拿到空数组, 误判为 "no candidate" 而阻断; 修复后 potentialOwner 元素被识别, 此测试改成真无候选人.)
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
<bpmn:process id="p1">
@@ -60,7 +53,7 @@ describe('workflow semantic lint (Task 4)', () => {
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
const r = await semanticLint(xml, { webapi: {} })
expect(r.ok).toBe(false)
expect(r.errors.some(e => /assignee|candidate/.test(e))).toBe(true)
})
@@ -74,17 +67,17 @@ describe('workflow semantic lint (Task 4)', () => {
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
const webapi = { getDeptManager: async () => [] as Array<{ id: string; name: string }> }
const r = await semanticLint(xml, { webapi })
expect(r.ok).toBe(false)
expect(r.diagnostics.some(d => /unresolved/.test(d.message))).toBe(true)
expect(r.diagnostics.some(d => /no users in dept/.test(d.message))).toBe(true)
})
// ─── T4 critical fix 回归 (C1: potentialOwner array 访问模式) ─────────────
// ─── critical fix 回归 (C1: potentialOwner array 访问模式) ─────────────
it('C1 回归: userTask 无 assignee + <bpmn:potentialOwner/> → ok=true', async () => {
// BPMN 标准 pattern: <bpmn:potentialOwner> 元素表达 "存在候选人 wrapper"
// (具体用户在 <bpmn:resourceAssignmentExpression> 里, 这里只看 potentialOwner 元素是否存在)
// 修复前: resources?.potentialOwner → undefined → 错判为 "no candidate"
// 修复后: resources.filter($type === 'bpmn:PotentialOwner') → 1 → 视为有候选
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
<bpmn:process id="p1">
@@ -93,38 +86,38 @@ describe('workflow semantic lint (Task 4)', () => {
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
const r = await semanticLint(xml, { webapi: {} })
expect(r.ok).toBe(true)
expect(r.errors).toEqual([])
})
// ─── T4 critical fix 回归 (C2: namespaced assignee) ─────────────────────
it('C2 回归: userTask camunda:assignee="alice" → ok=true', async () => {
// ─── critical fix 回归 (C2: namespaced assignee) ─────────────────────
it('C2 回归: userTask camunda:assignee="12345678" (6+ 位数字) → ok=true', async () => {
// JNPF/Camunda XML 风格: userTask 用命名空间前缀属性 camunda:assignee
// 修复前: 只查 ut.assignee + $attrs.assignee → 错失命名空间属性
// 修复后: 查 ut.assignee + $attrs.assignee + $attrs['camunda:assignee'] + $attrs['flowable:assignee']
// 6+ 位数字被 _approver_resolve 视为 JNPF userId 风格单候选人占位.
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:camunda="http://camunda.org/schema/1.0/bpmn">
<bpmn:process id="p1">
<bpmn:startEvent id="s1"/>
<bpmn:userTask id="t1" camunda:assignee="alice"/>
<bpmn:userTask id="t1" camunda:assignee="12345678"/>
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
const r = await semanticLint(xml, { webapi: {} })
expect(r.ok).toBe(true)
expect(r.errors).toEqual([])
})
// ─── M3 稳定性测试 ─────────────────────────────────────────────────────
it('M3 稳定性: 空 XML → errors 含 "flowXml is empty"', async () => {
const r = await semanticLint('', { candidateResolver: () => [] })
// ─── 稳定性测试 ─────────────────────────────────────────────────────
it('稳定性: 空 XML → errors 含 "flowXml is empty"', async () => {
const r = await semanticLint('', { webapi: {} })
expect(r.ok).toBe(false)
expect(r.errors).toContain('flowXml is empty')
})
it('M3 稳定性: 单 End + Gateway → ok=true (短路验证)', async () => {
it('稳定性: 单 End + Gateway → ok=true (短路验证)', async () => {
// ends.length === 1 时 hasConvergingGateway 短路返回 true, 不会触发 multiple-end
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
@@ -136,8 +129,7 @@ describe('workflow semantic lint (Task 4)', () => {
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
// 两个 userTask 都没 assignee/po → 但 ends.length=1 + Gateway → single 短路 → only userTask errors
const r = await semanticLint(xml, { webapi: {} })
expect(r.errors.some(e => /multiple-end/.test(e))).toBe(false)
})
})