_precheck.handlePreCheckResult + _blindspot_guards.handleGuardResult: process.exit(2) → throw Error (wrapCommand handler catch → ctx.fail 落 L3). 沿用 DirtyCheckError 同款模式. dm/create: 完整 wrapCommand 迁移 (runDmStepMachine process.exit → throw + await 修复未 await 逃逸, precheck/guard throw 被 handler catch). form/release: wrapCommand 迁移 (承接 guard throw). menu/create 已 wrapCommand (自动承接). form/create 下一 commit 承接 (P2 batch2). Co-Authored-By: Claude <[email protected]>
262 lines
11 KiB
TypeScript
262 lines
11 KiB
TypeScript
/**
|
||
* commands/_precheck.ts — form/dm/menu create 执行前的依赖检查
|
||
*
|
||
* v0.11+: form schema 完整性检查 (BS-51/52/54) 由 buildFormData 自动保证, 但 dbLinkId / enCode 重复
|
||
* / 必填项验证仍有价值. 调用方: form/dm/menu create.
|
||
*
|
||
* 与 P0.1 (AppContext) 衔接:
|
||
* - 直接 import { loadAppContext } 复用 context.ts 的采集逻辑
|
||
* - 失败容错: context 加载失败时仅 warning 不阻断 (避免双重失败)
|
||
* - 与 P1.3 (form-type-rules.json) 软联动: 文件不存在时跳过规则检查
|
||
*/
|
||
import type { JnpfClient } from '../core/client.ts'
|
||
import { loadAppContext } from './app/context.ts'
|
||
import { log } from '../core/log.ts'
|
||
|
||
export interface PreCheckResult {
|
||
pass: boolean
|
||
errors: string[]
|
||
warnings: string[]
|
||
}
|
||
|
||
export interface PreCheckOptions {
|
||
/** 期望创建的表单 enCode */
|
||
enCode?: string
|
||
/** 期望创建的表名 */
|
||
table?: string
|
||
/** 期望的 dbLinkId(覆盖 token 中的) */
|
||
dbLinkId?: string
|
||
/** webType */
|
||
webType?: number
|
||
/** type (1=自定义 2=系统 3=接口 4=视图) */
|
||
type?: number
|
||
}
|
||
|
||
/**
|
||
* 加载 AppContext(容错,失败返 null + warning)
|
||
*
|
||
* 注意: 不传 client, 因为 loadAppContext 内部已自带 client 构造
|
||
* 这里保留 client 参数仅为未来扩展 (e.g. 复用调用方已登录的 client)
|
||
*/
|
||
export async function loadContextSafe(_client: JnpfClient | null): Promise<{ ctx: Awaited<ReturnType<typeof loadAppContext>> | null; warning?: string }> {
|
||
try {
|
||
const ctx = await loadAppContext()
|
||
return { ctx }
|
||
} catch (e) {
|
||
return { ctx: null, warning: `AppContext 加载失败: ${(e as Error).message}` }
|
||
}
|
||
}
|
||
|
||
/**
|
||
* form create pre-check
|
||
*
|
||
* 检查项:
|
||
* 1. dbLinkId 有效 (≥1 或非 '0')
|
||
* 2. enCode 不重复 (vs ctx.existingEnCodes)
|
||
* 3. type/webType 组合合法 (vs data/form-type-rules.json, 可选)
|
||
*/
|
||
export async function preCheckFormCreate(
|
||
_client: JnpfClient | null,
|
||
opts: PreCheckOptions,
|
||
): Promise<PreCheckResult> {
|
||
const errors: string[] = []
|
||
const warnings: string[] = []
|
||
|
||
const { ctx, warning } = await loadContextSafe(_client)
|
||
if (warning) warnings.push(warning)
|
||
|
||
if (!ctx) {
|
||
warnings.push('AppContext 加载失败(dacli app context 不可用),跳过 pre-check')
|
||
return { pass: true, errors, warnings } // 容错:加载失败不阻断
|
||
}
|
||
|
||
// 检查 1: dbLinkId 有效
|
||
// '0' 是平台库, type=4 视图不需物理表 (兼容), 其他场景要求 ≥1
|
||
// 注: type=4 时 dbLinkId 可以是 '0', 这里给软警告而非硬错
|
||
const isType4 = String(opts.type) === '4'
|
||
if (!opts.dbLinkId || opts.dbLinkId === '') {
|
||
errors.push(`dbLinkId="${opts.dbLinkId || '(空)'}" 无效(pre-check 要求 ≥ 1)`)
|
||
errors.push(' 修复:从 dacli app context --json 取 dbLinkId,或显式 --dbLinkId=<id>')
|
||
} else if (opts.dbLinkId === '0' && !isType4) {
|
||
errors.push(`dbLinkId="0" 为主库/平台库 (type≠4 时业务表单需业务库)`)
|
||
errors.push(' 修复:从 dacli app context --json 取业务库 dbLinkId (非 "0")')
|
||
} else {
|
||
// v0.19+ BS-新73: 校验 dbLinkId 真实存在 (jnpf datasource 列表)
|
||
// 当前只警告不阻断 (datasource 列表可能权限问题 + '0' 主库不在列表)
|
||
try {
|
||
const { initWebapi, loadDataSource } = await import('../webapi/dataSource.ts')
|
||
await initWebapi(_client || (await import('../core/client.ts')).JnpfClient.fromToken())
|
||
const ds = (await loadDataSource.getDataSourceList({})) as {
|
||
list?: Array<{ id?: string; enCode?: string; fullName?: string }>
|
||
}
|
||
const dsIds = new Set((ds?.list || []).map((d: any) => String(d.id)))
|
||
const dsEncodes = new Set((ds?.list || []).map((d: any) => String(d.enCode)))
|
||
const exists = dsIds.has(opts.dbLinkId) || dsEncodes.has(opts.dbLinkId)
|
||
if (!exists) {
|
||
const examples = (ds?.list || []).slice(0, 3).map((d: any) => `${d.fullName || '?'}(${d.id})`).join(', ')
|
||
warnings.push(
|
||
`dbLinkId="${opts.dbLinkId}" 不在 datasource 列表 (现有 ${ds?.list?.length || 0} 个, 示例: ${examples})`
|
||
)
|
||
warnings.push(' 建议: 从 dacli datasource list 取业务库 dbLinkId, 或确认该 dbLinkId 存在')
|
||
}
|
||
} catch (e) {
|
||
warnings.push(`datasource 列表查询失败: ${(e as Error).message?.slice(0, 60)} (跳过 BS-新73 校验)`)
|
||
}
|
||
}
|
||
|
||
// 检查 2: enCode 不重复
|
||
if (opts.enCode && ctx.existingEnCodes.includes(opts.enCode)) {
|
||
errors.push(`enCode "${opts.enCode}" 已存在(当前 app 已有 ${ctx.existingEnCodes.length} 个 enCode)`)
|
||
errors.push(' 修复方案:')
|
||
errors.push(' a) 改名加 _v2 后缀,如 leaveApply_v2')
|
||
errors.push(' b) dacli form delete <id> 后重建(破坏性)')
|
||
}
|
||
|
||
// 检查 2.5: 表名不重复 (BS-新115, jyzs 2026-07-02)
|
||
// jyzs 实战: AI 自动建表 + release 又建表 → VS032 "database table name should remain unique"
|
||
// 修复: form create 前检测 existingTables, 已存在 → 警告+建议复用 (走 --autoTable 引用现有)
|
||
if (opts.table && ctx.existingTables.includes(opts.table)) {
|
||
errors.push(`表名 "${opts.table}" 已存在(当前业务库已有 ${ctx.existingTables.length} 张表)`)
|
||
errors.push(' 修复方案(BS-新115, jyzs 2026-07-02 实战):')
|
||
errors.push(' a) 换表名(推荐加业务前缀,如 jyzs_<原名>)')
|
||
errors.push(' b) 复用现有表: --autoTable=false + --tables=...[{"table":"' + opts.table + '",...}]')
|
||
errors.push(' c) dacli dm drop ' + opts.table + ' 后重建(破坏性)')
|
||
}
|
||
|
||
// 检查 3: type/webType 合法组合(用 form-type-rules.json,由 P1.3 提供)
|
||
// 如果 form-type-rules.json 不存在,跳过此检查
|
||
try {
|
||
const fs = await import('fs')
|
||
const path = await import('path')
|
||
const rulesPath = path.resolve(process.cwd(), 'data/form-type-rules.json')
|
||
if (fs.existsSync(rulesPath)) {
|
||
const rules = JSON.parse(fs.readFileSync(rulesPath, 'utf8'))
|
||
const typeRules = rules.typeRules || []
|
||
const matched = typeRules.find(
|
||
(r: any) => r.type === opts.type && r.webType === opts.webType,
|
||
)
|
||
if (!matched && opts.type && opts.webType) {
|
||
warnings.push(
|
||
`type=${opts.type} webType=${opts.webType} 未在 form-type-rules.json 中注册,请确认参数`,
|
||
)
|
||
} else if (matched && matched.needsPhysicalTable && !opts.table) {
|
||
errors.push(
|
||
`type=${opts.type} webType=${opts.webType}(${matched.name})需要物理表,请传 --table=<table_name>`,
|
||
)
|
||
errors.push(' 修复:先 dacli dm create,再 dacli form create')
|
||
} else if (matched && !matched.needsPhysicalTable && opts.table) {
|
||
warnings.push(
|
||
`type=${opts.type} webType=${opts.webType}(${matched.name})无需物理表,--table 参数将被忽略`,
|
||
)
|
||
}
|
||
}
|
||
} catch (e) {
|
||
log.debug(`form-type-rules.json 加载失败: ${(e as Error).message}`)
|
||
}
|
||
|
||
return { pass: errors.length === 0, errors, warnings }
|
||
}
|
||
|
||
/**
|
||
* dm create pre-check
|
||
*
|
||
* 检查项:
|
||
* 1. dbLinkId 有效
|
||
* 2. 表不重复 (vs ctx.existingTables)
|
||
*/
|
||
export async function preCheckDmCreate(
|
||
_client: JnpfClient | null,
|
||
opts: { table?: string; dbLinkId?: string },
|
||
): Promise<PreCheckResult> {
|
||
const errors: string[] = []
|
||
const warnings: string[] = []
|
||
|
||
const { ctx, warning } = await loadContextSafe(_client)
|
||
if (warning) warnings.push(warning)
|
||
|
||
if (!ctx) {
|
||
warnings.push('AppContext 加载失败,跳过 pre-check')
|
||
return { pass: true, errors, warnings }
|
||
}
|
||
|
||
// 检查 1: dbLinkId 有效
|
||
if (!opts.dbLinkId || opts.dbLinkId === '0') {
|
||
errors.push(`dbLinkId="${opts.dbLinkId || '(空)'}" 无效`)
|
||
errors.push(' 修复:从 dacli app context --json 取 dbLinkId')
|
||
}
|
||
|
||
// 检查 2: 表不重复
|
||
if (opts.table && ctx.existingTables.includes(opts.table)) {
|
||
errors.push(`表 "${opts.table}" 已存在(当前业务库已有 ${ctx.existingTables.length} 张表)`)
|
||
errors.push(' 修复方案:')
|
||
errors.push(' a) 换表名')
|
||
errors.push(' b) dacli dm drop <table> 后重建(破坏性)')
|
||
}
|
||
|
||
return { pass: errors.length === 0, errors, warnings }
|
||
}
|
||
|
||
/**
|
||
* form release pre-check (v0.15+, P2-6)
|
||
*
|
||
* 检查项:
|
||
* 1. enCode 不重复 (同 create 校验, 防止 release 期间 enCode 已被别人占用)
|
||
* 2. 物理表存在 (release 走 Actions/Release 端点, 后端可能校验 table schema)
|
||
*
|
||
* 注: 旧版 form/release.ts 不走 precheck → release 期间 enCode 已被别人占用仍能发
|
||
* 修复: 加 preCheckFormRelease 入口校验, 跟 form/create 一致
|
||
*/
|
||
export async function preCheckFormRelease(
|
||
_client: JnpfClient | null,
|
||
opts: { enCode?: string; table?: string },
|
||
): Promise<PreCheckResult> {
|
||
const errors: string[] = []
|
||
const warnings: string[] = []
|
||
|
||
const { ctx, warning } = await loadContextSafe(_client)
|
||
if (warning) warnings.push(warning)
|
||
|
||
if (!ctx) {
|
||
warnings.push('AppContext 加载失败,跳过 pre-check')
|
||
return { pass: true, errors, warnings }
|
||
}
|
||
|
||
// 检查 1: enCode 不重复 (除自己外, release 期间可能被改名)
|
||
if (opts.enCode && !ctx.existingEnCodes.includes(opts.enCode)) {
|
||
warnings.push(`enCode "${opts.enCode}" 在现有列表中未找到, 确认是当前 app 的 enCode?`)
|
||
}
|
||
|
||
// 检查 2: 物理表 schema 存在
|
||
if (opts.table && !ctx.existingTables.includes(opts.table)) {
|
||
warnings.push(`物理表 "${opts.table}" 不在现有表列表中, 后端 release 可能失败`)
|
||
warnings.push(' 修复: 先 dacli dm create 建表, 或确认表名拼写正确')
|
||
}
|
||
|
||
return { pass: errors.length === 0, errors, warnings }
|
||
}
|
||
|
||
/**
|
||
* 打印 pre-check 结果 (form/dm 共享)
|
||
*
|
||
* pass=true, warnings.length>0 → 打印警告不阻断
|
||
* pass=false → 打印错误并 throw (v2.2+ 2026-07-21: 改 throw 替代 process.exit(2),
|
||
* 让 wrapCommand handler catch → ctx.fail 落 L3 CommandLog. 所有调用方
|
||
* (form/create, dm/create, menu/create, form/release) 均已 wrapCommand 包裹.)
|
||
*/
|
||
export function handlePreCheckResult(label: string, pre: PreCheckResult): void {
|
||
if (!pre.pass) {
|
||
log.error(`Pre-check 失败(${label} 终止,请修复后重试):`)
|
||
pre.errors.forEach((e) => log.error(` ${e}`))
|
||
if (pre.warnings.length) {
|
||
log.warn('警告:')
|
||
pre.warnings.forEach((w) => log.warn(` ${w}`))
|
||
}
|
||
// v2.2+ (2026-07-21): throw 替代 process.exit(2), wrapCommand handler catch → ctx.fail
|
||
throw new Error(`Pre-check 失败 (${label}): ${pre.errors.join('; ').slice(0, 180)}`)
|
||
}
|
||
if (pre.warnings.length) {
|
||
log.warn(`Pre-check 警告(${label} 不阻断,但请关注):`)
|
||
pre.warnings.forEach((w) => log.warn(` ${w}`))
|
||
}
|
||
}
|