wangzhibo
2026-07-16 b57020623cf0c946706573bf102e548c3a544423
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
import { createDir, error, firstUpperCase, readFile, rootDir, toCamel } from "../utils";
import { join } from "path";
import axios from "axios";
import { compact, isEmpty, last, uniqBy, values } from "lodash";
import { createWriteStream } from "fs";
import prettier from "prettier";
import { config } from "../config";
import type { Eps } from "../../types";
import { flatten } from "../uniapp-x/flatten";
import { interfaceToType } from "../uniapp-x/utils";
 
// 全局 service 对象,用于存储服务结构
const service = {};
// eps 实体列表
let list: Eps.Entity[] = [];
 
/**
 * 获取 eps 请求地址
 * @returns {string} eps url
 */
function getEpsUrl(): string {
    let url = config.eps.api;
 
    if (!url) {
        url = config.type;
    }
 
    switch (url) {
        case "app":
        case "uniapp-x":
            url = "/app/base/comm/eps";
            break;
        case "admin":
            url = "/admin/base/open/eps";
            break;
    }
 
    return url;
}
 
/**
 * 获取 eps 路径
 * @param filename 文件名
 * @returns {string} 完整路径
 */
function getEpsPath(filename?: string): string {
    return join(
        config.type == "admin" ? config.eps.dist : rootDir(config.eps.dist),
        filename || "",
    );
}
 
/**
 * 获取对象方法名(排除 namespace、permission 字段)
 * @param v 对象
 * @returns {string[]} 方法名数组
 */
function getNames(v: any): string[] {
    return Object.keys(v).filter((e) => !["namespace", "permission"].includes(e));
}
 
/**
 * 获取字段类型
 */
function getType({ propertyName, type }: any) {
    for (const map of config.eps.mapping) {
        if (map.custom) {
            const resType = map.custom({ propertyName, type });
            if (resType) return resType;
        }
        if (map.test) {
            if (map.test.includes(type)) return map.type;
        }
    }
    return type;
}
 
/**
 * 格式化方法名,去除特殊字符
 */
function formatName(name: string) {
    return (name || "").replace(/[:,\s,\/,-]/g, "");
}
 
/**
 * 检查方法名是否合法(不包含特殊字符)
 */
function checkName(name: string) {
    return name && !["{", "}", ":"].some((e) => name.includes(e));
}
 
/**
 * 不支持 uniapp-x 平台显示
 */
function noUniappX(text: string, defaultText: string = "") {
    if (config.type == "uniapp-x") {
        return defaultText;
    } else {
        return text;
    }
}
 
/**
 * 查找字段
 * @param sources 字段 source 数组
 * @param item eps 实体
 * @returns {Eps.Column[]} 字段数组
 */
function findColumns(sources: string[], item: Eps.Entity): Eps.Column[] {
    const columns = [item.columns, item.pageColumns].flat().filter(Boolean);
    return (sources || [])
        .map((e) => columns.find((c) => c.source == e))
        .filter(Boolean) as Eps.Column[];
}
 
/**
 * 使用 prettier 格式化 TypeScript 代码
 * @param text 代码文本
 * @returns {Promise<string|null>} 格式化后的代码
 */
async function formatCode(text: string): Promise<string | null> {
    return prettier
        .format(text, {
            parser: "typescript",
            useTabs: true,
            tabWidth: 4,
            endOfLine: "lf",
            semi: true,
            singleQuote: false,
            printWidth: 100,
            trailingComma: "none",
        })
        .catch((err) => {
            console.log(err);
            error(`[cool-eps] File format error, please try again`);
            return null;
        });
}
 
/**
 * 获取 eps 数据(本地优先,远程兜底)
 */
async function getData() {
    // 读取本地 eps.json
    list = readFile(getEpsPath("eps.json"), true) || [];
 
    // 拼接请求地址
    const url = config.reqUrl + getEpsUrl();
 
    // 请求远程 eps 数据
    await axios
        .get(url, {
            timeout: 5000,
        })
        .then((res) => {
            const { code, data, message } = res.data;
            if (code === 1000) {
                if (!isEmpty(data) && data) {
                    list = values(data).flat();
                }
            } else {
                error(`[cool-eps] ${message || "Failed to fetch data"}`);
            }
        })
        .catch(() => {
            error(`[cool-eps] API service is not running → ${url}`);
        });
 
    // 初始化处理,补全缺省字段
    list.forEach((e) => {
        if (!e.namespace) e.namespace = "";
        if (!e.api) e.api = [];
        if (!e.columns) e.columns = [];
        if (!e.search) {
            e.search = {
                fieldEq: findColumns(e.pageQueryOp?.fieldEq, e),
                fieldLike: findColumns(e.pageQueryOp?.fieldLike, e),
                keyWordLikeFields: findColumns(e.pageQueryOp?.keyWordLikeFields, e),
            };
        }
    });
 
    if (config.type == "uniapp-x" || config.type == "app") {
        list = list.filter((e) => e.prefix.startsWith("/app") || e.prefix.startsWith("/admin"));
    }
}
 
/**
 * 创建 eps.json 文件
 * @returns {boolean} 是否有更新
 */
function createJson(): boolean {
    let data: any[] = [];
 
    if (config.type != "uniapp-x") {
        data = list.map((e) => {
            return {
                prefix: e.prefix,
                name: e.name || "",
                api: e.api.map((apiItem) => ({
                    name: apiItem.name,
                    method: apiItem.method,
                    path: apiItem.path,
                })),
                search: e.search,
            };
        });
    } else {
        data = list;
    }
 
    const content = JSON.stringify(data);
    const local_content = readFile(getEpsPath("eps.json"));
 
    // 判断是否需要更新
    const isUpdate = content != local_content;
 
    if (isUpdate) {
        createWriteStream(getEpsPath("eps.json"), {
            flags: "w",
        }).write(content);
    }
 
    return isUpdate;
}
 
/**
 * 创建 eps 类型描述文件(d.ts/ts)
 * @param param0 list: eps实体列表, service: service对象
 */
async function createDescribe({ list, service }: { list: Eps.Entity[]; service: any }) {
    /**
     * 创建 Entity 接口定义
     */
    function createEntity() {
        const ignore: string[] = [];
        let t0 = "";
 
        for (const item of list) {
            if (!checkName(item.name)) continue;
 
            if (formatName(item.name) == "BusinessInterface") {
                console.log(111);
            }
 
            let t = `interface ${formatName(item.name)} {`;
 
            // 合并 columns 和 pageColumns,去重
            const columns: Eps.Column[] = uniqBy(
                compact([...(item.columns || []), ...(item.pageColumns || [])]),
                "source",
            );
 
            for (const col of columns || []) {
                t += `
                    /**
                     * ${col.comment}
                     */
                    ${col.propertyName}?: ${getType({
                        propertyName: col.propertyName,
                        type: col.type,
                    })};
                `;
            }
 
            t += `
                /**
                 * 任意键值
                 */
                [key: string]: any;
            }
            `;
 
            if (!ignore.includes(item.name)) {
                ignore.push(item.name);
                t0 += t + "\n\n";
            }
        }
 
        return t0;
    }
 
    /**
     * 创建 Controller 接口定义
     */
    async function createController() {
        let controller = "";
        let chain = "";
        let pageResponse = "";
 
        /**
         * 递归处理 service 树,生成接口定义
         * @param d 当前节点
         * @param k 前缀
         */
        function deep(d: any, k?: string) {
            if (!k) k = "";
 
            for (const i in d) {
                const name = k + toCamel(firstUpperCase(formatName(i)));
 
                // 检查方法名
                if (!checkName(name)) continue;
 
                if (d[i].namespace) {
                    // 查找配置
                    const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`);
 
                    if (item) {
                        //
                        let t = `interface ${name} {`;
 
                        // 插入方法
                        if (item.api) {
                            // 权限列表
                            const permission: string[] = [];
 
                            item.api.forEach((a) => {
                                // 方法名
                                const n = toCamel(formatName(a.name || last(a.path.split("/"))!));
 
                                // 检查方法名
                                if (!checkName(n)) return;
 
                                if (n) {
                                    // 参数类型
                                    let q: string[] = [];
 
                                    // 参数列表
                                    const { parameters = [] } = a.dts || {};
 
                                    parameters.forEach((p) => {
                                        if (p.description) {
                                            q.push(`\n/** ${p.description}  */\n`);
                                        }
 
                                        // 检查参数名
                                        if (!checkName(p.name)) {
                                            return false;
                                        }
 
                                        const a = `${p.name}${p.required ? "" : "?"}`;
                                        const b = `${p.schema.type || "string"}`;
 
                                        q.push(`${a}: ${b};`);
                                    });
 
                                    if (isEmpty(q)) {
                                        q = ["any"];
                                    } else {
                                        q.unshift("{");
                                        q.push("}");
                                    }
 
                                    // 返回类型
                                    let res = "";
 
                                    // 实体名
                                    const en = item.name || "any";
 
                                    switch (a.path) {
                                        case "/page":
                                            res = `${name}PageResponse`;
 
                                            pageResponse += `
                                                interface ${name}PageResponse {
                                                    pagination: PagePagination;
                                                    list: ${en}[];
                                                }
                                            `;
 
                                            break;
                                        case "/list":
                                            res = `${en} []`;
                                            break;
                                        case "/info":
                                            res = en;
                                            break;
                                        default:
                                            res = "any";
                                            break;
                                    }
 
                                    // 方法描述
                                    if (config.type == "uniapp-x") {
                                        t += `
                                            /**
                                             * ${a.summary || n}
                                             */
                                            ${n}(data${q.length == 1 ? "?" : ""}: ${q.join("")}): Promise<any>;
                                        `;
                                    } else {
                                        t += `
                                            /**
                                             * ${a.summary || n}
                                             */
                                            ${n}(data${q.length == 1 ? "?" : ""}: ${q.join("")}): Promise<${res}>;
                                        `;
                                    }
 
                                    if (!permission.includes(n)) {
                                        permission.push(n);
                                    }
                                }
                            });
 
                            // 权限标识
                            t += noUniappX(`
                                /**
                                 * 权限标识
                                 */
                                permission: { ${permission.map((e) => `${e}: string;`).join("\n")} };
                            `);
 
                            // 权限状态
                            t += noUniappX(`
                                /**
                                 * 权限状态
                                 */
                                _permission: { ${permission.map((e) => `${e}: boolean;`).join("\n")} };
                            `);
 
                            // 请求
                            t += noUniappX(`
                                request: Request;
                            `);
                        }
 
                        t += "}\n\n";
 
                        controller += t;
                        chain += `${formatName(i)}: ${name};`;
                    }
                } else {
                    chain += `${formatName(i)}: {`;
                    deep(d[i], name);
                    chain += "};";
                }
            }
        }
 
        // 遍历 service 树
        deep(service);
 
        return `
            type json = any;
 
            ${await createDict()}
 
            interface PagePagination {
                size: number;
                page: number;
                total: number;
                [key: string]: any;
            };
 
            interface PageResponse<T> {
                pagination: PagePagination;
                list: T[];
                [key: string]: any;
            };
 
            ${pageResponse}
 
            ${controller}
 
            ${noUniappX(`interface RequestOptions {
                url: string;
                method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT';
                data?: any;
                params?: any;
                headers?: any;
                timeout?: number;
                [key: string]: any;
            }`)}
 
            ${noUniappX("type Request = (options: RequestOptions) => Promise<any>;")}
 
            type Service = {
                ${noUniappX("request: Request;")}
 
                ${chain}
            }
        `;
    }
 
    // 组装文件内容
    let text = `
        ${createEntity()}
        ${await createController()}
    `;
 
    // 文件名
    let name = "eps.d.ts";
 
    if (config.type == "uniapp-x") {
        name = "eps.ts";
        text = text
            .replaceAll("interface ", "export interface ")
            .replaceAll("type ", "export type ")
            .replaceAll("[key: string]: any;", "");
 
        text = flatten(text);
        text = interfaceToType(text);
    } else {
        text = `
            declare namespace Eps {
                ${text}
            }
        `;
    }
 
    // 格式化文本内容
    const content = await formatCode(text);
 
    const local_content = readFile(getEpsPath(name));
 
    // 是否需要更新
    if (content && content != local_content && list.length > 0) {
        // 创建 eps 描述文件
        createWriteStream(getEpsPath(name), {
            flags: "w",
        }).write(content);
    }
}
 
/**
 * 构建 service 对象树
 */
function createService() {
    // 路径第一层作为 id 标识
    const id = getEpsUrl().split("/")[1];
 
    list.forEach((e) => {
        // 请求地址
        const path = e.prefix[0] == "/" ? e.prefix.substring(1, e.prefix.length) : e.prefix;
 
        // 分隔路径,去除 id,转驼峰
        const arr = path.replace(id, "").split("/").filter(Boolean).map(toCamel);
 
        /**
         * 递归构建 service 树
         * @param d 当前节点
         * @param i 当前索引
         */
        function deep(d: any, i: number) {
            const k = arr[i];
 
            if (k) {
                // 是否最后一个
                if (arr[i + 1]) {
                    if (!d[k]) {
                        d[k] = {};
                    }
                    deep(d[k], i + 1);
                } else {
                    // 不存在则创建
                    if (!d[k]) {
                        d[k] = {
                            permission: {},
                        };
                    }
 
                    if (!d[k].namespace) {
                        d[k].namespace = path;
                    }
 
                    // 创建权限
                    if (d[k].namespace) {
                        getNames(d[k]).forEach((i) => {
                            d[k].permission[i] =
                                `${d[k].namespace.replace(`${id}/`, "")}/${i}`.replace(/\//g, ":");
                        });
                    }
 
                    // 创建搜索
                    d[k].search = e.search;
 
                    // 创建方法
                    e.api.forEach((a) => {
                        // 方法名
                        const n = a.path.replace("/", "");
                        if (n && !/[-:]/g.test(n)) {
                            d[k][n] = a;
                        }
                    });
                }
            }
        }
 
        deep(service, 0);
    });
}
 
/**
 * 创建 service 代码
 * @returns {string} service 代码
 */
function createServiceCode(): { content: string; types: string[] } {
    const types: string[] = [];
 
    let chain = "";
 
    /**
     * 递归处理 service 树,生成接口代码
     * @param d 当前节点
     * @param k 前缀
     */
    function deep(d: any, k?: string) {
        if (!k) k = "";
 
        for (const i in d) {
            if (["swagger"].includes(i)) {
                continue;
            }
 
            const name = k + toCamel(firstUpperCase(formatName(i)));
 
            // 检查方法名
            if (!checkName(name)) continue;
 
            if (d[i].namespace) {
                // 查找配置
                const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`);
 
                if (item) {
                    //
                    let t = `{`;
 
                    // 插入方法
                    if (item.api) {
                        item.api.forEach((a) => {
                            // 方法名
                            const n = toCamel(formatName(a.name || last(a.path.split("/"))!));
 
                            // 检查方法名
                            if (!checkName(n)) return;
 
                            if (n) {
                                // 参数类型
                                let q: string[] = [];
 
                                // 参数列表
                                const { parameters = [] } = a.dts || {};
 
                                parameters.forEach((p) => {
                                    if (p.description) {
                                        q.push(`\n/** ${p.description}  */\n`);
                                    }
 
                                    // 检查参数名
                                    if (!checkName(p.name)) {
                                        return false;
                                    }
 
                                    const a = `${p.name}${p.required ? "" : "?"}`;
                                    const b = `${p.schema.type || "string"}`;
 
                                    q.push(`${a}: ${b}, `);
                                });
 
                                if (isEmpty(q)) {
                                    q = ["any"];
                                } else {
                                    q.unshift("{");
                                    q.push("}");
                                }
 
                                if (item.name) {
                                    types.push(item.name);
                                }
 
                                // 方法描述
                                t += `
                                    /**
                                     * ${a.summary || n}
                                     */
                                    ${n}(data?: any): Promise<any> {
                                        return request({
                                            url: "/${d[i].namespace}${a.path}",
                                            method: "${(a.method || "get").toLocaleUpperCase()}",
                                            data,
                                        });
                                    },
                                `;
                            }
                        });
                    }
 
                    t += `} as ${name}\n`;
 
                    types.push(name);
 
                    chain += `${formatName(i)}: ${t},\n`;
                }
            } else {
                chain += `${formatName(i)}: {`;
                deep(d[i], name);
                chain += `} as ${firstUpperCase(i)}Interface,`;
 
                types.push(`${firstUpperCase(i)}Interface`);
            }
        }
    }
 
    // 遍历 service 树
    deep(service);
 
    return {
        content: `{ ${chain} }`,
        types,
    };
}
 
/**
 * 获取字典类型定义
 * @returns {Promise<string>} 字典类型 type 定义
 */
async function createDict(): Promise<string> {
    let p = "";
 
    switch (config.type) {
        case "app":
        case "uniapp-x":
            p = "/app";
            break;
        case "admin":
            p = "/admin";
            break;
    }
 
    const url = config.reqUrl + p + "/dict/info/types";
 
    const text = await axios
        .get(url)
        .then((res) => {
            const { code, data } = res.data as { code: number; data: any[] };
 
            if (code === 1000) {
                let v = "string";
                if (!isEmpty(data)) {
                    v = data.map((e) => `"${e.key}"`).join(" | ");
                }
                return `type DictKey = ${v}`;
            }
        })
        .catch(() => {
            error(`[cool-eps] Error:${url}`);
        });
 
    return text || "";
}
 
/**
 * 主入口:创建 eps 相关文件和 service
 */
export async function createEps() {
    if (config.eps.enable) {
        // 获取 eps 数据
        await getData();
 
        // 构建 service 对象
        createService();
 
        const serviceCode = createServiceCode();
 
        // 创建 eps 目录
        createDir(getEpsPath(), true);
 
        // 创建 eps.json 文件
        const isUpdate = createJson();
 
        // 创建类型描述文件
        createDescribe({ service, list });
 
        return {
            service,
            serviceCode,
            list,
            isUpdate,
        };
    } else {
        return {
            service: {},
            list: [],
        };
    }
}