init: TS 版 dacli v0.7 baseline (8 父命令/26+ 子命令, 0.4MB, .claude/skills/dacli-ts)

参考 boot/ 仓库结构初始化, 同步到 gitea:3000/ssw/dacli (private).

包括:
- src/  8 父命令 (form/menu/dm/dict/di/apis/doc/workflow + login/status) + core (client/crypto/help/log/types/config)
- src/schema/ FieldBuilder (从 JNPF web 源码提取, 避免 53 个手写 builder)
- tests/ vitest 单元 + playwright E2E (含 workSystem/developSystem baseline regression)
- scripts/ extract-all.mjs (从 jnpf-web 源码生成 schema) + seed-tds-baseline.ts
- doc/  architecture/plan/api/extractors/baseline/RESUME/help-system + v0.6/v0.7 changelog
- .claude/skills/dacli-ts/  Claude 集成 skill (SKILL.md + 5 references + 7 examples + 3 baseline)
- CLAUDE.md (项目说明) + README.md + prompt.md (开发任务说明书)
- 配置文件: package.json/lock, tsconfig, vitest.config, playwright.config
This commit is contained in:
ssw committed 2026-06-12 18:26:39 +08:00
commit c98ad4f425
93 files changed
+12718

No files matched your search

+197
View File
@@ -0,0 +1,197 @@
/**
* 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 { JnpfResp, LoginResp, TokenFile } from './types.ts'
import { log } from './log.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
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<JnpfClient> {
const cached = opt.forceLogin ? null : loadToken()
if (cached && !opt.forceLogin) {
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<JnpfClient> {
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<void> {
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<LoginResp>(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<void> {
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)
}
// ----- HTTP -----
async get<T = unknown>(path: string, query?: Record<string, string | number | undefined>): Promise<JnpfResp<T>> {
let url = `${this.baseUrl}${path}`
if (query) {
const cleaned: Record<string, string> = {}
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<T>(await res.text())
}
async postJson<T = unknown>(path: string, body: unknown): Promise<JnpfResp<T>> {
log.debug('POST', this.baseUrl + path)
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'POST',
headers: this.headers(),
body: JSON.stringify(body),
})
return parseJson<T>(await res.text())
}
async putJson<T = unknown>(path: string, body: unknown): Promise<JnpfResp<T>> {
log.debug('PUT', this.baseUrl + path)
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'PUT',
headers: this.headers(),
body: JSON.stringify(body),
})
return parseJson<T>(await res.text())
}
async del<T = unknown>(path: string): Promise<JnpfResp<T>> {
log.debug('DELETE', this.baseUrl + path)
const res = await fetch(`${this.baseUrl}${path}`, {
method: 'DELETE',
headers: this.headers(),
})
return parseJson<T>(await res.text())
}
/** 业务码非 200 直接抛 */
ok<T>(r: JnpfResp<T>): T {
if (r.code !== 200) throw new DacliError(`API code=${r.code}: ${r.msg}`, r.code, JSON.stringify(r))
return r.data as T
}
private headers(): Record<string, string> {
return {
'Content-Type': 'application/json',
Authorization: this.token,
'App-Code': this.appCode,
}
}
}
function parseJson<T>(text: string): JnpfResp<T> {
try {
return JSON.parse(text) as JnpfResp<T>
} catch {
return { code: -1, msg: `JSON parse error: ${text.slice(0, 200)}`, data: null }
}
}
+68
View File
@@ -0,0 +1,68 @@
/**
* config.ts — token / baseUrl / appCode 持久化
*
* 路径: $DACLI_TOKEN_DIR/token.json 或 ./.dacli-token/token.json
*
* 与 Java 版兼容: 路径写在 cwd 下 (CLAUDE.md "$ccWorkDir/.dacli-token/token.json")
* 但 TS 版只管 $ccWorkDir/dacli 自己, 不动 Java 版的 token (Java 版已废弃归档)。
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import type { TokenFile } from './types.ts'
const DEFAULT_BASE_URL = process.env.JNPF_BASE_URL || 'http://nginx/api'
function tokenDir(): string {
if (process.env.DACLI_TOKEN_DIR) return resolve(process.env.DACLI_TOKEN_DIR)
return resolve(process.cwd(), '.dacli-token')
}
function tokenPath(): string {
return join(tokenDir(), 'token.json')
}
export function getTokenPath(): string {
return tokenPath()
}
export function loadToken(): TokenFile | null {
const p = tokenPath()
if (!existsSync(p)) return null
try {
return JSON.parse(readFileSync(p, 'utf-8')) as TokenFile
} catch {
return null
}
}
export function saveToken(t: TokenFile): void {
const dir = tokenDir()
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
writeFileSync(tokenPath(), JSON.stringify(t, null, 2), 'utf-8')
}
export function clearToken(): void {
const p = tokenPath()
if (existsSync(p)) rmSync(p)
}
/** 当前 baseUrl (优先 env, 然后 token, 然后默认) */
export function currentBaseUrl(): string {
const t = loadToken()
return process.env.JNPF_BASE_URL || t?.baseUrl || DEFAULT_BASE_URL
}
/** 默认凭据 (供 login 默认值用) */
export const DEFAULT_ACCOUNT = process.env.JNPF_ACCOUNT || 'admin'
export const DEFAULT_PASSWORD = process.env.JNPF_PASSWORD || '123456'
export const DEFAULT_APP_CODE = process.env.JNPF_APP_CODE || 'developSystem'
/** baseUrl 兜底列表 (按优先级) */
export function baseUrlCandidates(): string[] {
const list = [
process.env.JNPF_BASE_URL,
'http://nginx/api',
'http://127.0.0.1:30000/api',
].filter(Boolean) as string[]
return Array.from(new Set(list))
}
+78
View File
@@ -0,0 +1,78 @@
/**
* crypto.ts — 严格 1:1 复刻 web cipher.ts (字节级一致)
*
* 流程: 明文 → md5(hex) → AES-ECB-Pkcs7(key=md5(VITE_CIPHER_KEY)) → Base64 → Hex
*
* 关键: cipher.ts:34-37 `Hex.stringify(Base64.parse(result))` 是对 Base64 字符串做 hex,
* 不是对密文字节做 hex。这是 ddcc 实验里踩过的最大坑。
*
* 输入 '123456' 应输出 96 字符 hex (与 web 一致)。
*/
import CryptoJS from 'crypto-js'
import { existsSync, readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
/** 默认密钥来自 web .env VITE_CIPHER_KEY */
const FALLBACK_KEY = 'EY8WePvjM5GGwQzn'
let _cipherKey: string | null = null
function loadCipherKey(): string {
if (_cipherKey) return _cipherKey
if (process.env.VITE_CIPHER_KEY) {
_cipherKey = process.env.VITE_CIPHER_KEY
return _cipherKey
}
try {
const here = dirname(fileURLToPath(import.meta.url))
const candidates = [
resolve(here, '../../../../web/apps/jnpf-web-apps-main/.env'),
resolve(here, '../../../web/apps/jnpf-web-apps-main/.env'),
resolve(here, '../../web/apps/jnpf-web-apps-main/.env'),
]
for (const p of candidates) {
if (existsSync(p)) {
const m = readFileSync(p, 'utf-8').match(/VITE_CIPHER_KEY\s*=\s*(\S+)/)
if (m) {
_cipherKey = m[1]
return _cipherKey
}
}
}
} catch {
/* ignore — fallback */
}
_cipherKey = FALLBACK_KEY
return _cipherKey
}
export function encryptByMd5(plain: string): string {
return CryptoJS.MD5(plain).toString()
}
/** AES-ECB-Pkcs7(密钥=md5(CIPHER_KEY)),再 Base64→Hex */
function aesEcbHex(inputHex: string): string {
const aesKey = encryptByMd5(loadCipherKey())
const encrypted = CryptoJS.AES.encrypt(
inputHex,
CryptoJS.enc.Utf8.parse(aesKey),
{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 },
)
const base64 = encrypted.toString()
// 注意: 是对 base64 字符串做 hex (web cipher.ts:36)
return CryptoJS.enc.Hex.stringify(CryptoJS.enc.Base64.parse(base64))
}
/**
* 完整登录加密 (与 LoginForm.handleLogin 一致):
* md5(plain) → aesEncryption.encryptByAES(md5Hex)
*/
export function encryptPassword(plain: string): string {
return aesEcbHex(encryptByMd5(plain))
}
/** 96 字符的 hex 即认为已加密 */
export function isEncrypted(p: string | undefined | null): boolean {
return !!p && p.length === 96 && /^[0-9a-f]+$/i.test(p)
}
+111
View File
@@ -0,0 +1,111 @@
/**
* help.ts — AI 友好帮助体系
*
* 用法: 给 Commander.js 命令对象挂元数据 (cmd as any)._aiMeta = meta
* 由 cli.ts 顶层在 parse 之前扫 argv 拦截 --ai-help / --example / --source
* 打印后 process.exit, 避免命令真正执行 / 校验 requiredOption
*/
import type { Command } from 'commander'
export interface AiHelp {
purpose: string
required?: Record<string, string>
optional?: Record<string, string>
example?: string | string[]
source?: { web?: string; api?: string; ref?: string }
notes?: string[]
}
const AI_FLAGS = new Set(['--ai-help', '--example', '--source'])
/** 把元数据挂到 command 上, cli.ts 顶层会读 */
export function installAiHelpHook(cmd: Command, meta: AiHelp): void {
;(cmd as unknown as { _aiMeta?: AiHelp })._aiMeta = meta
}
function getMeta(cmd: Command): AiHelp | undefined {
return (cmd as unknown as { _aiMeta?: AiHelp })._aiMeta
}
/**
* 顶层在 parse 前调用. 命中 ai flag 则打印 + exit, 返回 true.
*/
export function maybeInterceptAiHelp(program: Command): boolean {
const argv = process.argv.slice(2)
const flagIdx = argv.findIndex((a) => AI_FLAGS.has(a))
if (flagIdx < 0) return false
const flag = argv[flagIdx]
// 把 flag 之前的非选项 token 当成命令路径
const path = argv.slice(0, flagIdx).filter((a) => !a.startsWith('-'))
// 走命令树
let cur: Command = program
for (const p of path) {
const sub = cur.commands.find((c) => c.name() === p)
if (!sub) break
cur = sub
}
const meta = getMeta(cur)
if (!meta) {
console.error(`(no ai-help for: ${path.join(' ') || '<root>'})`)
process.exit(2)
}
if (flag === '--example') {
const ex = Array.isArray(meta.example) ? meta.example.join('\n') : meta.example || '(no example)'
console.log(ex)
} else if (flag === '--source') {
const lines: string[] = []
if (meta.source?.web) lines.push(`web: ${meta.source.web}`)
if (meta.source?.api) lines.push(`api: ${meta.source.api}`)
console.log(lines.join('\n') || '(no source)')
} else {
console.log(renderAiHelp(cur, meta))
}
process.exit(0)
}
function renderAiHelp(cmd: Command, meta: AiHelp): string {
const lines: string[] = []
// 拼出完整路径
const path: string[] = [cmd.name()]
let p: Command | null = cmd.parent as Command | null
while (p) {
path.unshift(p.name())
p = p.parent as Command | null
}
// 去 root 名
const fullCmd = path.slice(1).join(' ') || path[0]
lines.push(`# dacli ${fullCmd}`)
lines.push('')
lines.push('## 用途')
lines.push(meta.purpose)
if (meta.required && Object.keys(meta.required).length) {
lines.push('')
lines.push('## 必传参数')
for (const [k, v] of Object.entries(meta.required)) lines.push(`- \`${k}\`: ${v}`)
}
if (meta.optional && Object.keys(meta.optional).length) {
lines.push('')
lines.push('## 可选参数')
for (const [k, v] of Object.entries(meta.optional)) lines.push(`- \`${k}\`: ${v}`)
}
if (meta.source?.web || meta.source?.api) {
lines.push('')
lines.push('## 来源')
if (meta.source.web) lines.push(`- web 源码: ${meta.source.web}`)
if (meta.source.api) lines.push(`- API: ${meta.source.api}`)
}
if (meta.example) {
lines.push('')
lines.push('## 例子')
lines.push('```bash')
lines.push(Array.isArray(meta.example) ? meta.example.join('\n') : meta.example)
lines.push('```')
}
if (meta.notes && meta.notes.length) {
lines.push('')
lines.push('## 注意')
for (const n of meta.notes) lines.push(`- ${n}`)
}
return lines.join('\n')
}
+44
View File
@@ -0,0 +1,44 @@
/**
* log.ts — 极简彩色日志
*/
const isTTY = process.stdout.isTTY
const C = {
reset: isTTY ? '\x1b[0m' : '',
dim: isTTY ? '\x1b[2m' : '',
red: isTTY ? '\x1b[31m' : '',
green: isTTY ? '\x1b[32m' : '',
yellow: isTTY ? '\x1b[33m' : '',
blue: isTTY ? '\x1b[34m' : '',
cyan: isTTY ? '\x1b[36m' : '',
bold: isTTY ? '\x1b[1m' : '',
}
export const log = {
info(...args: unknown[]) {
console.log(`${C.cyan}ℹ${C.reset}`, ...args)
},
ok(...args: unknown[]) {
console.log(`${C.green}✓${C.reset}`, ...args)
},
warn(...args: unknown[]) {
console.warn(`${C.yellow}!${C.reset}`, ...args)
},
error(...args: unknown[]) {
console.error(`${C.red}✗${C.reset}`, ...args)
},
dim(...args: unknown[]) {
console.log(`${C.dim}${args.join(' ')}${C.reset}`)
},
raw(s: string) {
process.stdout.write(s)
},
/** 仅在 DACLI_DEBUG=1 时打 */
debug(...args: unknown[]) {
if (process.env.DACLI_DEBUG === '1') console.error(`${C.dim}[debug]${C.reset}`, ...args)
},
}
/** JSON 美化输出 (供命令直接打到 stdout, 便于 jq 管道) */
export function printJson(v: unknown): void {
console.log(JSON.stringify(v, null, 2))
}
+66
View File
@@ -0,0 +1,66 @@
/**
* types.ts — 共享类型定义
*/
export interface JnpfResp<T = unknown> {
code: number
msg: string
data: T | null
}
export interface DataSourceMeta {
id: string
fullName: string
enCode: string
dbType: string
}
export interface LoginResp {
token: string
theme?: string
isSaas?: boolean
}
export interface TokenFile {
baseUrl: string
appCode: string
account: string
token: string
/** ISO 时间, token 7 天过期 */
loginAt: string
/** 业务库 id (从 /system/DataSource 取第一个非主库) */
dbLinkId?: string
}
export interface FormSummary {
id: string
fullName: string
enCode: string
state: number
type: number
webType: number
dbLinkId?: string
category?: string
creatorTime?: string
}
export interface FormDetail extends FormSummary {
formData?: unknown
columnData?: unknown
tables?: unknown[]
[k: string]: unknown
}
/**
* dacli 内部错误 (包装 HTTP 业务码 != 200)
*/
export class DacliError extends Error {
code: number
raw?: string
constructor(message: string, code = -1, raw?: string) {
super(message)
this.name = 'DacliError'
this.code = code
this.raw = raw
}
}