/** * client.ts — JnpfClient * * 借鉴 ddcc/jnpf.ts (已验证), 加 token 自动加载 + baseUrl 兜底。 * * 关键: baseUrl 必须含 /api, path 不再带 /api 前缀。 * 例: baseUrl='http://nginx/api' + path='/visualdev/Base/list' → 'http://nginx/api/visualdev/Base/list' */ import { encryptPassword, isEncrypted } from './crypto.ts' import { loadToken, saveToken, baseUrlCandidates } from './config.ts' import { DacliError } from './types.ts' import type { AppContext, FormSummary, JnpfResp, LoginResp, TokenFile } from './types.ts' import { log } from './log.ts' import { resolveDbLinkId as resolveDbLinkIdUtil } from './dbLinkId.ts' export interface ClientOptions { baseUrl?: string appCode?: string account?: string password?: string /** true=强制不读 token, 重新登录 */ forceLogin?: boolean } export class JnpfClient { baseUrl: string appCode: string account: string password: string token = '' /** 业务库 id, login 后自动拉 */ dbLinkId?: string /** * 最近一次请求 body 中的 enCode / table / tableName, 供 diagnoseError 用 * 多并发不安全 (单请求场景 OK); 不入 persist (运行时状态) */ private lastRequestEnCode: string = '' private lastRequestTableName: string = '' constructor(opt: ClientOptions = {}) { this.baseUrl = (opt.baseUrl || '').replace(/\/+$/, '') this.appCode = opt.appCode || '' this.account = opt.account || '' this.password = opt.password || '' } /** 走 token 缓存, 没就登录 */ static async fromToken(opt: ClientOptions = {}): Promise { const cached = opt.forceLogin ? null : loadToken() if (cached && !opt.forceLogin) { // BS-新10 (jxcj 2026-06-30): 检测 token 残留到上次 app // 多次会话后 cached.appCode 是上次的, 如果调用方传了 --appCode= 不一致则警告 if (opt.appCode && opt.appCode !== cached.appCode) { log.warn( `BS-新10: token 残留到上次 app "${cached.appCode}", 但本次要求 "${opt.appCode}". 建议先 \`dacli app login --account=admin --password=123456 --appCode=${opt.appCode}\``, ) } // BS-新10 主动提示当前 token 状态 (不传 --appCode 时也有用, 让用户知道当前是哪个 app) else if (process.env.DACLI_SHOW_TOKEN === '1') { log.dim(`[token] appCode=${cached.appCode} dbLinkId=${cached.dbLinkId || '(none)'} (set DACLI_SHOW_TOKEN=0 to disable)`) } const c = new JnpfClient({ baseUrl: opt.baseUrl || cached.baseUrl, appCode: opt.appCode || cached.appCode, account: opt.account || cached.account, password: opt.password || '', }) c.token = cached.token c.dbLinkId = cached.dbLinkId return c } // 没缓存或强制 → 完整 login return JnpfClient.login(opt) } /** 完整登录 (encrypt + POST /oauth/Login + 持久化) */ static async login(opt: ClientOptions = {}): Promise { const candidates = opt.baseUrl ? [opt.baseUrl] : baseUrlCandidates() let lastErr: Error | null = null for (const base of candidates) { try { const c = new JnpfClient({ ...opt, baseUrl: base }) await c.doLogin() await c.detectDbLinkId() c.persist() return c } catch (e) { lastErr = e as Error log.debug(`login via ${base} failed: ${(e as Error).message}`) } } throw lastErr || new DacliError('所有 baseUrl 候选都失败, 请确认 JNPF 是否启动') } private async doLogin(): Promise { const encrypted = isEncrypted(this.password) ? this.password : encryptPassword(this.password) const body = new URLSearchParams({ account: this.account, password: encrypted, code: '', origin: 'hash', timestamp: '0', jnpf_ticket: '', grant_type: 'password', }).toString() const url = `${this.baseUrl}/oauth/Login` log.debug('POST', url) const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, }) const text = await res.text() const r = parseJson(text) if (r.code !== 200 || !r.data) { throw new DacliError(`登录失败 (code ${r.code}): ${r.msg}`, r.code, text.slice(0, 200)) } this.token = r.data.token } /** 拉业务库 id (非主库). 失败不致命, 仅 debug */ private async detectDbLinkId(): Promise { try { const r = await this.get<{ list?: Array<{ id: string; fullName: string; enCode?: string }> }>('/system/DataSource') const list = r.data?.list || [] if (Array.isArray(list) && list.length > 0) { // 优先匹 appCode 同名, 其次任何非平台库 const byApp = list.find((d) => d.fullName === this.appCode || d.enCode === this.appCode) const fallback = list.find((d) => d.id && d.id !== '0') const biz = byApp || fallback if (biz) this.dbLinkId = biz.id } } catch (e) { log.debug('detectDbLinkId failed:', (e as Error).message) } } persist(): void { const t: TokenFile = { baseUrl: this.baseUrl, appCode: this.appCode, account: this.account, token: this.token, loginAt: new Date().toISOString(), dbLinkId: this.dbLinkId, } saveToken(t) } /** 当前登录 token (供 online-kick 等需防自踢/防自调的子命令读) */ getCurrentToken(): string | undefined { return this.token || undefined } /** * 解析 dbLinkId 参数: '--dbLinkId=default' 字面量 → token.dbLinkId * * 与 web formDesign/Form.vue + sysForm/Form.vue 一致: "default" 是 token.dbLinkId 的语义别名 * 设计文档 (BS-48): https://... 详见 .claude/skills/dacli-ts/references/errors.md "dbLinkId" * * 委托给 core/dbLinkId.ts 的 resolveDbLinkId 工具函数 (单一权威) * 优先级: opts.dbLinkId (别名 → ctx.dbLinkId) > ctx.dbLinkId > '0' */ resolveDbLinkId(optsDbLinkId?: string | null): string { // 直接使用 this.dbLinkId, 不构造完整 AppContext (client 内部无完整 ctx) // 委托给工具函数时构造最小 ctx 即可 (AppContext.dbLinkId 必填, 此处用 ?? 兜底) return resolveDbLinkIdUtil(optsDbLinkId, { appCode: this.appCode, dbLinkId: this.dbLinkId ?? '', tokenStatus: 'valid', existingEnCodes: [], unreleasedForms: [], releasedForms: [], modifiedAfterPublishForms: [], workflowList: [], existingTables: [], menus: [], topLevelMenus: [], currentSystemId: '', currentVersion: '', warnings: [], }) } // ----- HTTP ----- async get(path: string, query?: Record): Promise> { let url = `${this.baseUrl}${path}` if (query) { const cleaned: Record = {} for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null) cleaned[k] = String(v) const qs = new URLSearchParams(cleaned).toString() if (qs) url += `?${qs}` } log.debug('GET', url) const res = await fetch(url, { method: 'GET', headers: this.headers() }) return parseJson(await res.text()) } async postJson(path: string, body: unknown): Promise> { log.debug('POST', this.baseUrl + path) this.recordRequestContext(body) const res = await fetch(`${this.baseUrl}${path}`, { method: 'POST', headers: this.headers(), body: JSON.stringify(body), }) return parseJson(await res.text()) } async putJson(path: string, body: unknown): Promise> { log.debug('PUT', this.baseUrl + path) this.recordRequestContext(body) const res = await fetch(`${this.baseUrl}${path}`, { method: 'PUT', headers: this.headers(), body: JSON.stringify(body), }) return parseJson(await res.text()) } // ----- OnlineDev CRUD wrappers (BS-53 fix: data 必须 JSON.stringify 后包成 {data: ...}) ----- /** * 调 OnlineDev Create API. * * 后端 VisualdevModelDataCrForm.data 是 String (line 16-19 of VisualdevModelDataCrForm.java), * Controller 用 JsonUtil.stringToMap(crForm.getData()) 反序列化. 后端期望请求体是 * `{ data: "" }`, data 字段是字符串化的 JSON. * * web 行为 (CustomForm.vue:78): `state.dataForm.data = JSON.stringify(formData); createModel(...)` * * 不裸用 postJson 调 OnlineDev Create/Update, 否则后端报 "System abnormality" * (map is null, 因 getData() 返 null). */ async postJsonOnlineDevCreate(modelId: string, data: Record): Promise> { return this.postJson(`/visualdev/OnlineDev/${modelId}`, { data: JSON.stringify(data) }) } /** * 调 OnlineDev Update API. * * 路径: PUT /visualdev/OnlineDev/{modelId}/{id}, body 同样要包成 {data: JSON.stringify(...)}. */ async putJsonOnlineDevUpdate( modelId: string, recordId: string, data: Record, ): Promise> { return this.putJson(`/visualdev/OnlineDev/${modelId}/${recordId}`, { data: JSON.stringify(data) }) } async del(path: string): Promise> { log.debug('DELETE', this.baseUrl + path) const res = await fetch(`${this.baseUrl}${path}`, { method: 'DELETE', headers: this.headers(), }) return parseJson(await res.text()) } /** 业务码非 200 直接抛 */ ok(r: JnpfResp): T { if (r.code !== 200) throw new DacliError(`API code=${r.code}: ${r.msg}`, r.code, JSON.stringify(r)) return r.data as T } // ----- P0.2 主动诊断 (client 层 catch 时调用) ----- /** * 从请求 body 里提取 enCode / table / tableName, 供 diagnoseError 用 * 规则: enCode 字段、表名(table / tableInfo.table / newTable) 字段 */ private recordRequestContext(body: unknown): void { if (typeof body !== 'object' || body === null) return const b = body as Record if (typeof b.enCode === 'string' && b.enCode) this.lastRequestEnCode = b.enCode if (typeof b.table === 'string' && b.table) this.lastRequestTableName = b.table if (typeof b.tableName === 'string' && b.tableName) this.lastRequestTableName = b.tableName // dm create body: { tableInfo: { table, newTable, tableName }, tableFieldList: [...] } const ti = b.tableInfo as Record | undefined if (ti && typeof ti === 'object') { if (typeof ti.table === 'string' && ti.table) this.lastRequestTableName = ti.table if (typeof ti.newTable === 'string' && ti.newTable) this.lastRequestTableName = ti.newTable } } /** * 主动诊断: 把 JNPF 模糊错误翻译成可能原因列表 (P0.2, 详见 doc/ai-optimization-plan.md §2.2) * * 设计: * - 纯函数 (无副作用, 不发请求), 仅依赖 context + lastRequestEnCode / lastRequestTableName * - 覆盖 doc/ai-error-analysis.md §C 列举的"同一报错 10 种根因" * - 返回 causes: string[], 调用方负责 log.warn 输出 (便于 AI 解析) * - 兜底: 未识别错误时给出"跑 context 看环境 + 看后端日志"指引 */ diagnoseError(errorMsg: string, context: AppContext): string[] { const causes: string[] = [] // 规则 1: Database exception (盲点 48 — JNPF 把所有 DB 异常都包成这串) if (/Database exception/i.test(errorMsg)) { if (!context.dbLinkId || context.dbLinkId === '0') { causes.push( `dbLinkId 未设置或为 0 (当前 token.dbLinkId="${context.dbLinkId || '(空)'}").` + ` 修复: dacli app login 重新登录自动识别业务库, 或显式 --dbLinkId=<非0 id>`, ) } if (this.lastRequestEnCode && context.existingEnCodes?.includes(this.lastRequestEnCode)) { causes.push( `enCode "${this.lastRequestEnCode}" 已存在 (context 已记录 ${context.existingEnCodes.length} 个 enCode).` + ` 修复: 改名加 _v2 后缀, 或 dacli form delete 后重建`, ) } if ( this.lastRequestTableName && context.existingTables && !context.existingTables.includes(this.lastRequestTableName) ) { causes.push( `表 "${this.lastRequestTableName}" 不存在 (context 已记录 ${context.existingTables.length} 张表).` + ` 修复: dacli dm create --table=${this.lastRequestTableName} --tableName="中文名" --dbLinkId= --fields='[...]' 先建表`, ) } if (causes.length === 0) { causes.push('未识别 Database exception 根因, 建议:') causes.push(' 1. dacli app context --json 确认环境快照') causes.push(' 2. 检查 tables 字段是否完整 (useBtnPermission / useFormPermission / useDataPermission)') causes.push(' 3. 检查 category 字段是否匹配业务库分类') causes.push(' 4. dacli tool logs --level=error --lines=50 看后端真实堆栈') } return causes } // 规则 2: Encoding cannot be repeated (盲点 49 + 跨 app 冲突 BS-新4 jxcj 2026-06-30) if (/Encoding cannot be repeated/i.test(errorMsg)) { if (this.lastRequestEnCode) { causes.push(`enCode "${this.lastRequestEnCode}" 已存在.`) } else { causes.push('enCode 重复.') } // 跨 app 全平台 enCode 唯一 (jnpf 后端约束). 当前 app 可能 existingEnCodes=[] 但仍冲突. causes.push( ' 修复 (同一 app): 改名加 _v2 后缀, 或 dacli form delete 后重建', ) causes.push( ' 修复 (跨 app 冲突, BS-新4): 加业务前缀 (e.g. competitioninfo → JxcjCompetitionInfo). jnpf 全平台 enCode 唯一, 即便新 app 干净, 其它 app 已用同名仍冲突', ) return causes } // 规则 3: 表不存在 (dm create 误用 / form create 引不存在的表) if (/table.*not.*exist|TableNotFound|does not exist/i.test(errorMsg)) { if (this.lastRequestTableName) { causes.push(`表 "${this.lastRequestTableName}" 不存在.`) causes.push( ` 修复: dacli dm create --table=${this.lastRequestTableName} --tableName="中文名" --dbLinkId= --fields='[...]' 先建表`, ) } else { causes.push('请求引用的表不存在.') causes.push(' 修复: 跑 dacli app context --json 看现有表名, 或 dacli dm list 看完整列表') } return causes } // 规则 4: 表已存在 (dm create 重名) if (/Table already exists|table.*exist/i.test(errorMsg) && /create/i.test(errorMsg)) { causes.push(`表 "${this.lastRequestTableName || '(未知)'}" 已存在.`) causes.push(' 修复: 换表名, 或 dacli dm drop 后重建 (破坏性, 慎用)') return causes } // 规则 5: 主键冲突 / Duplicate column name (盲点 38 — f_description 重复) if (/Duplicate entry|duplicate key/i.test(errorMsg)) { causes.push('主键冲突.') causes.push(' 修复: 检查数据是否已存在, 或换 ID') return causes } if (/Duplicate column name/i.test(errorMsg)) { const m = errorMsg.match(/Duplicate column name '([^']+)'/) const col = m?.[1] || '(未知)' if (col === 'f_description') { causes.push(`列 ${col} 已被系统自动注入为 "描述(text)" 列, 用户不应再传.`) causes.push(' 修复: 移除 --fields 里的 f_description, 或改名为 f_desc') } else { causes.push(`列 ${col} 重复.`) causes.push(' 修复: 检查 --fields 是否含与系统列同名的字段') } return causes } // 规则 6: workflow form 缺 f_flow_task_id 列 (盲点 15) if (/f_flow_task_id|flowTaskId/i.test(errorMsg)) { causes.push('enableFlow=1 表必须含 f_flow_task_id / f_flow_id / f_flow_state 列.') causes.push( ' 修复: dacli v10.6+ 自动补 9 系统列; 确认 dacli 版本, 或手动 ALTER TABLE 添加', ) return causes } // 规则 7: System abnormality — JNPF 后端 Velocity 模板 bug // 根因 (高频): form 的 formData.fields[].__config__.trigger 为空字符串 '' // PublicMacro/FormMarco.vm:1226 调用 ${trigger.substring(0,1)} 对 '' 抛 StringIndexOutOfBoundsException // 只在 state=1 (发布态) 触发, state=2 (草稿) 不触发 (因为没走发布代码生成路径) // 注: 后端堆栈只在 log_error.log 可见, dacli 客户端只看到 "System abnormality" 字面 if (/System abnormality/i.test(errorMsg)) { causes.push('JNPF 后端 "System abnormality" 错误, 最常见根因:') causes.push(' form formData.fields[].__config__.trigger = "" (空串)') causes.push(' PublicMacro/FormMarco.vm:1226 对空串调 substring(0,1) 抛 StringIndexOutOfBoundsException') causes.push(' (仅 state=1 发布态触发, state=2 草稿不触发)') causes.push(' 历史 form (老 dacli/老 web 设计器) 易中招, 新 form FieldBuilder.ts:215-223 已正确设') causes.push('') causes.push('诊断:') causes.push(' 1. 查后端日志确认: log/jnpf-java-boot/log_error.log | grep FormMarco') causes.push(' → 含 FormMarco.vm:1226 + StringIndexOutOfBoundsException 即本错误') causes.push(' 2. 一次性 PATCH 修复 (Python):') causes.push(' a) GET /visualdev/Base/ → 解析 formData.fields[].__config__') causes.push(' b) trigger=="" → 按 jnpfKey 设值 (input/textarea/editor="blur", 其他="change")') causes.push(' c) PUT /visualdev/Base/ (触发 state 1→2)') causes.push(' d) POST /visualdev/Base//Actions/Release (state 2→1, 修复生效)') causes.push(' 3. 或在 web UI 设计器打开 form 保存一次, JNPF 自动补 trigger') causes.push('') causes.push('⚠ 重要: 只在 state=1 (已发布) 出现, state=2 (草稿) 不报错') return causes } // 兜底 causes.push(`未识别的错误: ${errorMsg.slice(0, 200)}`) causes.push(' 建议: 跑 dacli app context --json 确认环境, 或 dacli tool logs --level=error --lines=50 看后端日志') return causes } /** * 包装方法: 执行 + 自动诊断 * 调用方: form/dm create 等需要在出错时给 AI 友好诊断的命令 * * 行为: * - 正常路径: 直接透传结果 * - 异常路径: log.warn 打诊断, 然后 rethrow (不吞错) * - context=null: 只 log.warn 错误信息 + "无 AppContext" 提示, 不打诊断 * * 用法: * const ctx = await loadAppContext().catch(() => null) * try { * const r = await c.callWithDiagnosis(() => c.postJson('/visualdev/Base', body), ctx) * } catch (e) { process.exit(1) } */ async callWithDiagnosis( fn: () => Promise>, context: AppContext | null, ): Promise> { try { return await fn() } catch (e) { const err = e as Error log.warn(`! 诊断: ${err.message}`) if (context) { const causes = this.diagnoseError(err.message, context) log.warn(' 可能原因:') for (const c of causes) log.warn(` ${c}`) } else { log.warn(' (无 AppContext, 建议先跑 dacli app context --json)') } throw e } } private headers(): Record { return { 'Content-Type': 'application/json', Authorization: this.token, 'App-Code': this.appCode, } } } function parseJson(text: string): JnpfResp { try { return JSON.parse(text) as JnpfResp } catch { return { code: -1, msg: `JSON parse error: ${text.slice(0, 200)}`, data: null } } }