import { mkdirSync, mkdtempSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { HttpError } from '../src/util/common.js'; export function tempDir(prefix = 'cda-test-') { const directory = mkdtempSync(path.join(os.tmpdir(), prefix)); mkdirSync(directory, { recursive: true }); return directory; } export function testSettings(dataDir) { return { repoRoot: path.resolve(import.meta.dirname, '..', '..', '..'), host: '127.0.0.1', port: 0, toolsUrl: 'http://127.0.0.1:1', dataDir, webDist: path.resolve(import.meta.dirname, '..', '..', '..', 'web', 'dist'), presetFile: path.resolve(import.meta.dirname, '..', '..', '..', 'agent.cordis.yml'), apiKey: 'test-key', baseUrl: 'http://127.0.0.1:1', modelOverride: null, providerOverride: null, maxUploadBytes: 10 * 1024 * 1024, verificationEnabled: true, llmMode: 'replay', replayFile: '', }; } /** 假工具服务:内存对象库 + 固定数据,用于 BFF 单测与联调。 */ export class FakeToolsClient { workspaces = [ { id: 'ws_test', name: '测试工作区', description: '', created_at: '2026-01-01T00:00:00+08:00', object_count: 1 }, ]; objects = []; runs = []; dataRows = {}; calculatorResult = '400316.13'; processSheets = [ { name: '1.0-3.0_MLCC', sqlite_name: 's_1_0_3_0_MLCC', rows: 20, columns: ['基础类目', '年度', '月度', '实际金额(美元)'] }, ]; constructor() { this.objects.push(makeObject({ id: 'obj_raw', name: 'small.csv', kind: 'raw', rows: 100 })); this.objects.push(makeObject({ id: 'obj_stat', name: 'small_统计结果.xlsx', kind: 'stat', rows: 23, tables: this.processSheets })); this.dataRows['obj_stat:1.0-3.0_MLCC'] = [ { values: { 基础类目: '多层瓷介电容器(MLCC)', 年度: 2025, 月度: 1, '实际金额(美元)': '400316.13' }, row_index: 0, row_hash: 'sha256:aaa' }, { values: { 基础类目: '多层瓷介电容器(MLCC)', 年度: 2025, 月度: 2, '实际金额(美元)': '410000.00' }, row_index: 1, row_hash: 'sha256:bbb' }, ]; } async health() { return { ok: true, service: 'tools', version: 'test', data_dir: '/tmp' }; } async meta() { return { tools: ['customs_process', 'data_read', 'calculator'] }; } async listWorkspaces() { return { items: this.workspaces }; } async createWorkspace(name, description = '') { const workspace = { id: `ws_${this.workspaces.length + 1}`, name, description, created_at: '2026-01-01T00:00:00+08:00', object_count: 0 }; this.workspaces.push(workspace); return workspace; } async deleteWorkspace(id) { this.workspaces = this.workspaces.filter((item) => item.id !== id); return { ok: true }; } async listObjects(workspaceId, kind) { const items = this.objects.filter((item) => (!kind ? true : item.kind === kind)); return { items }; } async getObject(objectId) { const item = this.objects.find((entry) => entry.id === objectId); if (!item) throw new HttpError(404, `对象不存在: ${objectId}`); return item; } async deleteObject(objectId) { this.objects = this.objects.filter((item) => item.id !== objectId); return { ok: true }; } async uploadObject(_workspaceId, filename, bytes) { const object = makeObject({ id: `obj_raw_${this.objects.length + 1}`, name: filename, kind: 'raw', rows: bytes.length }); this.objects.push(object); return object; } async preview(objectId, table = 'raw', limit = 20, offset = 0) { const all = this.dataRows[`${objectId}:${table}`] ?? []; const page = all.slice(offset, offset + limit); return { columns: Object.keys(all[0]?.values ?? {}), rows: page.map((row) => row.values), row_indexes: page.map((row) => row.row_index ?? 0), row_hashes: page.map((row) => row.row_hash ?? 'sha256:x'), offset, limit, total: all.length, }; } async row(objectId, table, rowIndex) { const all = this.dataRows[`${objectId}:${table}`] ?? []; const row = all.find((item) => (item.row_index ?? 0) === rowIndex); if (!row) throw new HttpError(404, `表 ${table} 中没有第 ${rowIndex} 行`); return { object_id: objectId, table, row_index: rowIndex, row_hash: row.row_hash ?? 'sha256:x', values: row.values, lineage: { source_object_id: 'obj_raw', source_rows: { year: '2025' } }, }; } async lineage(objectId) { return { object_id: objectId, parents: ['obj_raw'], lineage: { output_hash: 'sha256:out' } }; } async download() { return new Response('col1,col2\n1,2\n', { headers: { 'content-type': 'text/csv' } }); } async createRun(payload) { const run = { id: `run_${this.runs.length + 1}`, object_id: 'obj_stat', input_object: payload.input_object_id, status: 'succeeded', operation: payload.operation ?? 'full_pipeline', progress: 1, message: '处理完成', error: '', started_at: '2026-01-01T00:00:00+08:00', finished_at: '2026-01-01T00:00:10+08:00', params: payload.options ?? {}, }; this.runs.push(run); return run; } async getRun(runId) { const run = this.runs.find((item) => item.id === runId); if (!run) throw new HttpError(404, '任务不存在'); return run; } async listRuns() { return { items: this.runs }; } async processCustoms(payload) { return { run_id: 'run_tool_1', object_id: 'obj_stat_new', name: payload.output_filename ?? 'small_统计结果.xlsx', sheets: this.processSheets, lineage: { input_sha256: 'sha256:in', params_hash: 'sha256:p', output_hash: 'sha256:out', engine: { name: 'fake', version: '1' } }, stats: { included: 100 }, warnings: [], files: ['统计结果.xlsx'], }; } async dataRead(payload) { const rows = (this.dataRows[`${payload.object_id}:${payload.table ?? 'raw'}`] ?? []).slice(payload.offset ?? 0, (payload.offset ?? 0) + (payload.limit ?? 20)); return { object_id: payload.object_id, table: payload.table ?? 'raw', columns: Object.keys(rows[0]?.values ?? {}), rows: rows.map((row) => ({ values: row.values, _trace: { object_id: payload.object_id, table: payload.table ?? 'raw', row_index: row.row_index ?? 0, row_hash: row.row_hash ?? 'sha256:x', }, })), total: (this.dataRows[`${payload.object_id}:${payload.table ?? 'raw'}`] ?? []).length, offset: payload.offset ?? 0, limit: payload.limit ?? 20, exhausted: true, }; } async calculate(payload) { const values = (payload.inputs ?? []).map((input) => Number(input.value)); const result = values.length ? String(values.reduce((sum, value) => sum + value, 0)) : this.calculatorResult; return { call_id: 'calc_test_1', tool: 'calculator', op: payload.op, result: payload.op === 'sum' ? result : this.calculatorResult, expression: payload.op, inputs: (payload.inputs ?? []).map((input, index) => ({ index, value: String(input.value), from_call_id: input.from_call_id ?? null, row_hash: input.row_hash ?? null, verified: Boolean(input.from_call_id), })), unverified_inputs: 0, all_inputs_verified: true, _trace: { calculation_id: 'calc_test_1', result_hash: 'sha256:calc', op: payload.op }, }; } async ledgerStats() { return { calls: 1, indexed_values: 2, chain_ok: true }; } } export function makeObject(input) { return { id: input.id, workspace_id: 'ws_test', name: input.name, kind: input.kind, media_type: 'text/csv', path: `/data/${input.id}`, sha256: 'sha256:obj', bytes: 1024, rows: input.rows, columns: ['I_E_FLAG', 'HS_CODE', 'MONORSUM'], producer: 'upload', parents: [], meta: {}, created_at: '2026-01-01T00:00:00+08:00', tables: input.tables ?? [{ name: 'raw', sqlite_name: 'raw', rows: input.rows, columns: ['I_E_FLAG', 'HS_CODE'] }], }; } export function asToolsClient(fake) { return fake; } export function listen(server) { return new Promise((resolve, reject) => { server.listen(0, '127.0.0.1', () => { const address = server.address(); resolve({ url: `http://127.0.0.1:${address.port}`, server, close: () => new Promise((done) => { server.close(() => done()); }), }); }); server.on('error', reject); }); } /** 解析 SSE 响应为事件数组。 */ export async function collectSse(response) { const text = await response.text(); const events = []; for (const block of text.split('\n\n')) { const lines = block.split('\n').filter(Boolean); let event = 'message'; let data = ''; for (const line of lines) { if (line.startsWith('event:')) event = line.slice(6).trim(); else if (line.startsWith('data:')) data += line.slice(5).trim(); } if (!data) continue; try { events.push({ event, data: JSON.parse(data) }); } catch { events.push({ event, data }); } } return events; } //# sourceMappingURL=fakes.js.map