feat(webapi): v0.11+ Phase 1 - webapi/visualDev + dataModel + dataSource 直接 import web 端

实现 docs/dacli/v0.11-mirror-refactor.md Step 1-3:
- src/webapi/_loader.ts: 通用 web 端源码加载器 (读源→替换 import→写 tmp→dynamic import)
- src/webapi/_defhttp_shim.ts: 用 JnpfClient 实现 web 端 defHttp (get/post/put/delete)
- src/webapi/visualDev.ts: 30+ 函数直接 import web/.../api/onlineDev/visualDev.ts
- src/webapi/dataModel.ts: 10 函数 import + lodash omit shim
- src/webapi/dataSource.ts: 11 函数 import
- src/commands/form/list.ts: 改造样板 (c.get → loadVisualDev.getVisualDevList)

关键技术:
- 读 web 端源 → 替换 #/api/request → shim 路径 → 替换 #/ → WEB_SRC → 替换 lodash-es → Node 原生
- 用 globalThis 共享 client (避免 tsx/动态 import 多实例)
- shim 自动 strip /api 前缀 (因 JnpfClient.baseUrl 已含 /api)

Checkpoint PASS:
- test-webapi-visualdev.ts: visualDev 11 函数 import + 实测 (getVisualDevList + getInfo 返回数据正确)
- test-webapi-datamodel.ts: dataModel 10 函数 import + 实测 (getDataModelList 返回数据)
- dataSource smoke test: getDataSourceSelector 返回 2 项
- form list 命令 webapi 版与原版输出完全一致
- baseline 跑通, 无新 fail

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-06-25 12:12:21 +08:00
1 parent fd8ef3bb20
commit d4506fe4de
8 files changed
+486 -6

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
/**
* _defhttp_shim.ts — 用 JnpfClient 实现 web 端的 defHttp (v0.11+ Phase 1)
*
* 设计:
* - web 端 request.ts 用 Vben 的 RequestClient, 依赖 axios + Vite + Vue ecosystem
* - dacli 是 Node CLI, 没 Vue/Vite, 但 defHttp.get/post/put/delete 签名是稳定的
* - 此 shim 用 JnpfClient.fetch 实现, 签名与 web 完全一致
* - 调用方 (visualDev.ts) 不感知 shim, 仍调 defHttp.x({ url, data, ...opts })
*
* 注意:
* - 签名严格匹配 web Vben defHttp:
* defHttp.get({ url, params?, data? }) → GET (data 当 query)
* defHttp.post({ url, data }) → POST JSON
* defHttp.put({ url, data }) → PUT JSON
* defHttp.delete({ url, data? }) → DELETE
* - 响应统一返回 res.data (已经过 Vben transformResponseHook 解构)
* 即: { code: 200, msg: 'ok', data: ... } 解出 → 直接拿 .data
* - 不支持: useCipher 加密 / 上传下载进度 / axios 拦截器
* (dacli 不需要这些, web 也只在 useCipher=true 时启用加密)
* - 用 globalThis 共享 client, 避免 tsx/动态 import 导致的多实例问题
*/
import { JnpfClient } from '../core/client.ts'
const GLOBAL_KEY = '__dacli_defhttp_shim_client__'
type GlobalWithClient = typeof globalThis & { [GLOBAL_KEY]?: JnpfClient }
function getClient(): JnpfClient {
const client = (globalThis as GlobalWithClient)[GLOBAL_KEY]
if (!client) throw new Error('defHttp shim 未初始化, 请先调 initDefHttpShim(client)')
return client
}
/** 初始化 shim, 必须先调一次 (visualDev / dataModel 模块加载前) */
export function initDefHttpShim(client: JnpfClient): void {
;(globalThis as GlobalWithClient)[GLOBAL_KEY] = client
}
/** 把 undefined/null 值从 query 里去掉 (与 JnpfClient.get 行为一致) */
function cleanQuery(data: Record<string, unknown> | undefined): Record<string, string | number | undefined> {
if (!data) return {}
const out: Record<string, string | number | undefined> = {}
for (const [k, v] of Object.entries(data)) {
if (v === undefined || v === null) continue
if (typeof v === 'object') out[k] = JSON.stringify(v)
else out[k] = v as string | number
}
return out
}
/** 统一响应包装: web 的 transformResponseHook 已经解出 {code,data,msg} → 取 data */
async function unwrap<T>(resp: { code: number; msg?: string; data: T | null }): Promise<T> {
if (resp.code !== 200) {
throw new Error(`API code=${resp.code}: ${resp.msg ?? ''}`)
}
return resp.data as T
}
/**
* 把 web 端 url 里的 /api 前缀去掉, 因为 JnpfClient.baseUrl 已含 /api
*
* web 端 url: '/api/visualdev/Base' → JNPF base 'http://nginx/api'
* dacli 期望: '/visualdev/Base' → 'http://nginx/api' + '/visualdev/Base' = 'http://nginx/api/visualdev/Base'
*
* 不改 baseUrl (会破坏现有命令), 仅在 shim 里 strip
*/
function stripApiPrefix(url: string): string {
if (url.startsWith('/api/')) return url.slice(4)
if (url === '/api') return ''
return url
}
/**
* shim of web defHttp — 与 Vben defHttp 签名一致
* 用法 (web 端 visualDev.ts 不感知):
* defHttp.get({ url: '/api/visualdev/Base', data: { keyword: 'foo' } })
*/
export const defHttp = {
async get<T = unknown>(config: { url: string; data?: Record<string, unknown> }): Promise<T> {
const c = getClient()
const r = await c.get<T>(stripApiPrefix(config.url), cleanQuery(config.data))
return unwrap<T>(r)
},
async post<T = unknown>(config: { url: string; data?: unknown }): Promise<T> {
const c = getClient()
const r = await c.postJson<T>(stripApiPrefix(config.url), config.data ?? {})
return unwrap<T>(r)
},
async put<T = unknown>(config: { url: string; data?: unknown }): Promise<T> {
const c = getClient()
const r = await c.putJson<T>(stripApiPrefix(config.url), config.data ?? {})
return unwrap<T>(r)
},
async delete<T = unknown>(config: { url: string; data?: unknown }): Promise<T> {
const c = getClient()
// 注意: web 端 defHttp.delete 也可能带 data (axios 支持), 我们忽略
const r = await c.del<T>(stripApiPrefix(config.url))
return unwrap<T>(r)
},
}
+103
View File
@@ -0,0 +1,103 @@
/**
* _loader.ts — 通用 web 端源码加载器 (v0.11+ Phase 1)
*
* 设计: 与 _buildformdata.ts 同样的技巧 — 读源码 → 替换 import → 写 tmp → dynamic import
*
* 替换规则 (按顺序, 避免误伤):
* 1. `from '#/api/request'` → `from '<shim path>'` (defHttp shim, 优先于 #/)
* 2. `from '#/...'` → `from '${WEB_SRC}/...'` (其他 #/ alias)
* 3. `from '@jnpf/utils'` → `from '${JNPF_UTILS_UUID}'` (uuid only, 避开 Vite env)
* 4. `import { cloneDeep } from 'lodash-es';?` → `const cloneDeep = (x) => structuredClone(x);`
* 5. `import { omit } from 'lodash-es';?` → `function omit(obj, keys) { ... }`
*
* 注意:
* - 不修改 web/ 源码 (CLAUDE.md §15 禁止)
* - 单进程缓存: 同一 source 路径只 load 一次
* - shim 路径指向 _defhttp_shim.ts (位于本目录)
*/
import { readFileSync, writeFileSync, mkdirSync } from 'fs'
import { tmpdir } from 'os'
import { join, dirname } from 'path'
import { pathToFileURL } from 'url'
const WEB_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src'
const JNPF_UTILS_UUID = '/home/ubuntu/ccWorkDir/web/packages/jnpf/utils/src/helpers/uuid.ts'
const SHIM_PATH = join(dirname(new URL(import.meta.url).pathname), '_defhttp_shim.ts')
/** lodash omit 的最小实现 (web dataModel.ts 用) */
const LODASH_OMIT_STUB = `
const omit = (obj, keys) => {
if (!obj) return obj;
const out = { ...obj };
for (const k of (Array.isArray(keys) ? keys : [keys])) delete out[k];
return out;
};`
export interface LoadOptions {
/** 自定义 shim 路径 (默认 _defhttp_shim.ts) */
shimPath?: string
/** 跳过 lodash 替换 (默认 true, visualDev.ts 不需要) */
handleLodash?: boolean
}
/** 单进程缓存: path → module */
const cache = new Map<string, Promise<any>>()
/**
* 加载 web 端 TypeScript 文件, 替换 import, dynamic import
* @param sourcePath web 端 .ts 源文件绝对路径
* @returns 加载后的 ES module (含所有 named export)
*/
export async function loadWebModule<T = any>(sourcePath: string, opts: LoadOptions = {}): Promise<T> {
if (cache.has(sourcePath)) return cache.get(sourcePath) as Promise<T>
const promise = (async () => {
const shimPath = opts.shimPath ?? SHIM_PATH
// 1. 读源
let src = readFileSync(sourcePath, 'utf-8')
// 2. 替换 #/api/request → shim (必须在 #/ 通用规则之前)
src = src.replace(/from\s+['"]#\/api\/request['"]/g, `from '${shimPath}'`)
// 3. 替换其他 #/... → WEB_SRC/... (但已替换的 #/api/request 不再被命中)
src = src.replace(/from\s+['"]#\/(.+?)['"]/g, (_, p) => `from '${WEB_SRC}/${p}'`)
// 4. 替换 @jnpf/utils → uuid (避开 Vite env)
src = src.replace(/from\s+['"]@jnpf\/utils['"]/g, `from '${JNPF_UTILS_UUID}'`)
// 5. 替换 lodash-es → Node 原生实现 (按需)
if (opts.handleLodash !== false) {
src = src.replace(
/import\s*\{\s*cloneDeep\s*\}\s*from\s+['"]lodash-es['"];?/g,
`const cloneDeep = (x) => structuredClone(x);`,
)
src = src.replace(
/import\s*\{\s*omit\s*\}\s*from\s+['"]lodash-es['"];?/g,
LODASH_OMIT_STUB,
)
}
// 6. 写 tmp
const tmpDir = `${tmpdir()}/dacli-webapi-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
mkdirSync(tmpDir, { recursive: true })
const tmpFile = join(tmpDir, sourcePath.split('/').pop()!)
writeFileSync(tmpFile, src)
// 7. dynamic import
return await import(pathToFileURL(tmpFile).href)
})()
cache.set(sourcePath, promise)
return promise
}
/** 清空缓存 (测试用) */
export function clearCache(): void {
cache.clear()
}
/** 检查缓存状态 (调试用) */
export function getCacheKeys(): string[] {
return Array.from(cache.keys())
}
+36
View File
@@ -0,0 +1,36 @@
/**
* webapi/dataModel.ts — 直接 import web 端 dataModel.ts (v0.11+ Phase 1)
*
* 注意:
* - dataModel.ts 用 `import { omit } from 'lodash-es'`, _loader.ts 已处理
* - 9 个函数: getDataModelList / getDataModelListAll / previewDataModel / createDataModel /
* updateDataModel / getDataModelInfo / delDataModel / getDataModelFieldList /
* addTableFields / exportTable
*/
import { JnpfClient } from '../core/client.ts'
import { loadWebModule } from './_loader.ts'
const DATA_MODEL_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src/api/systemData/dataModel.ts'
let cached: any = null
export async function initWebapi(client: JnpfClient): Promise<void> {
if (cached) return
// visualDev.ts 已经在 visualDev.ts 里 init 过 shim, 但单独用 dataModel 也要兜底
const { initDefHttpShim } = await import('./_defhttp_shim.ts')
initDefHttpShim(client)
cached = await loadWebModule(DATA_MODEL_SRC)
}
export function isWebapiLoaded(): boolean {
return cached !== null
}
export const loadDataModel: any = new Proxy({} as any, {
get(_target, prop) {
if (!cached) {
throw new Error(`dataModel 模块未初始化, 请先 await initWebapi(client)`)
}
return cached[prop]
},
})
+35
View File
@@ -0,0 +1,35 @@
/**
* webapi/dataSource.ts — 直接 import web 端 dataSource.ts (v0.11+ Phase 1)
*
* 注意:
* - dataSource.ts 仅用 `defHttp`, 不需 lodash-es
* - 11 个函数: getDataSourceList / getDataSourceSelector / createDataSource /
* updateDataSource / getDataSourceInfo / delDataSource / testDbConnection /
* dataSync / execute / batchExecute / checkDbLink
*/
import { JnpfClient } from '../core/client.ts'
import { loadWebModule } from './_loader.ts'
const DATA_SOURCE_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src/api/systemData/dataSource.ts'
let cached: any = null
export async function initWebapi(client: JnpfClient): Promise<void> {
if (cached) return
const { initDefHttpShim } = await import('./_defhttp_shim.ts')
initDefHttpShim(client)
cached = await loadWebModule(DATA_SOURCE_SRC)
}
export function isWebapiLoaded(): boolean {
return cached !== null
}
export const loadDataSource: any = new Proxy({} as any, {
get(_target, prop) {
if (!cached) {
throw new Error(`dataSource 模块未初始化, 请先 await initWebapi(client)`)
}
return cached[prop]
},
})
+48
View File
@@ -0,0 +1,48 @@
/**
* webapi/visualDev.ts — 直接 import web 端 visualDev.ts 的 30+ 函数 (v0.11+ Phase 1)
*
* 设计:
* - 不重写 API wrapper, 而是从 web/apps/jnpf-web-apps-main/src/api/onlineDev/visualDev.ts 直接 import
* - web 端用 defHttp (#/api/request), 由 _loader.ts 替换为我们自己的 _defhttp_shim.ts
* - 缓存: _loader 单进程缓存, 同一 source 只 load 一次
*
* 使用:
* import { loadVisualDev, initWebapi } from '../webapi/visualDev.ts'
* await initWebapi() // 必须先 await (初始化 defHttp shim + load 模块)
* const r = await loadVisualDev.getVisualDevList({ keyword: 'foo' })
*/
import { JnpfClient } from '../core/client.ts'
import { loadWebModule } from './_loader.ts'
const VISUAL_DEV_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src/api/onlineDev/visualDev.ts'
let cached: any = null
/**
* 初始化 webapi 层: 必须先 await 一次
* - initDefHttpShim(client): 让 visualDev 函数能用我们 JnpfClient
* - loadWebModule(VISUAL_DEV_SRC): 加载并缓存 visualDev 模块
*/
export async function initWebapi(client: JnpfClient): Promise<void> {
if (cached) return
// 1. 注入 shim 用的 JnpfClient (循环依赖解决: 在 _defhttp_shim.ts 直接 import JnpfClient)
const { initDefHttpShim } = await import('./_defhttp_shim.ts')
initDefHttpShim(client)
// 2. 加载 visualDev.ts
cached = await loadWebModule(VISUAL_DEV_SRC)
}
/** 检查是否已初始化 (调试用) */
export function isWebapiLoaded(): boolean {
return cached !== null
}
/** 重新导出所有 web visualDev 函数 — 调用方用 `loadVisualDev.xxx(args)` */
export const loadVisualDev: any = new Proxy({} as any, {
get(_target, prop) {
if (!cached) {
throw new Error(`visualDev 模块未初始化, 请先 await initWebapi(client)`)
}
return cached[prop]
},
})