profile.ts 2.99 KB
import type { Route } from './context';
import { loadProjectProfile, saveProjectProfile, projectProfileTemplate } from '../config';
import { scanProject } from '../project-scanner';

/** 目标项目画像(profile):读取、持久化、扫描草拟。 */
export const profileRoutes: Route[] = [
    // ---- GET /api/project-profile ----
    // 返回「项目接入」设置面板所用的目标项目画像;未设置时返回一份全新种子模板。
    {
        method: 'GET',
        path: '/api/project-profile',
        handle: ({ ctx, res }) => {
            const profile = loadProjectProfile() ?? projectProfileTemplate();
            const exists = loadProjectProfile() !== null;
            ctx.sendJson(res, 200, { exists, profile });
        },
    },

    // ---- PUT /api/project-profile ----
    // 持久化 UI 编辑的画像。PUT 整体替换;引擎按次运行读取文件,无需重启即生效。
    {
        method: 'PUT',
        path: '/api/project-profile',
        handle: async ({ ctx, req, res }) => {
            let incoming: unknown;
            try {
                incoming = await ctx.readJsonBody(req);
            } catch {
                ctx.sendJson(res, 400, { error: 'Invalid JSON body' });
                return;
            }
            if (!incoming || typeof incoming !== 'object') {
                ctx.sendJson(res, 400, { error: 'profile must be an object' });
                return;
            }
            // 用模板兜底缺失字段,防止前端少传导致画像结构不完整
            const profile = {
                ...projectProfileTemplate(),
                ...(incoming as Record<string, unknown>),
            } as never;
            try {
                saveProjectProfile(profile);
                ctx.sendJson(res, 200, { ok: true, profile });
            } catch (e) {
                ctx.sendJson(res, 500, { error: e instanceof Error ? e.message : '保存失败' });
            }
        },
    },

    // ---- POST /api/project-profile/scan ----
    // 扫描目标项目根目录并草拟画像。Phase 1 扫描器:只读不写,返回草稿供 UI 审阅。
    {
        method: 'POST',
        path: '/api/project-profile/scan',
        handle: async ({ ctx, req, res }) => {
            let body: { rootDir?: string } = {};
            try {
                body = await ctx.readJsonBody<{ rootDir?: string }>(req);
            } catch {
                ctx.sendJson(res, 400, { error: 'Invalid JSON body' });
                return;
            }
            const rootDir = (body.rootDir || '').trim();
            if (!rootDir) {
                ctx.sendJson(res, 400, { error: 'rootDir 为必填项(目标项目根目录)' });
                return;
            }
            try {
                const result = scanProject(rootDir);
                ctx.sendJson(res, 200, result);
            } catch (e) {
                ctx.sendJson(res, 500, { error: e instanceof Error ? e.message : '扫描失败' });
            }
        },
    },
];