2026-04-17 21:04:52 +08:00

475 lines
14 KiB
JavaScript

import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { API_DOC_AGENT_API_LIST_UPDATE_CONFIG } from "./config.mjs";
function formatLocalDateTime(input = new Date()) {
const date = input instanceof Date ? input : new Date(input);
const year = String(date.getFullYear());
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
async function writeText(filePath, text) {
await mkdir(path.dirname(filePath), { recursive: true });
await writeFile(filePath, `${text.trimEnd()}\n`, "utf8");
}
async function readTextIfExists(filePath, fallbackValue = "") {
try {
return await readFile(filePath, "utf8");
} catch (error) {
if (error?.code === "ENOENT") {
return fallbackValue;
}
throw error;
}
}
async function listTsFiles(rootDir) {
const stack = [rootDir];
const files = [];
while (stack.length > 0) {
const current = stack.pop();
const entries = await readdir(current, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(current, entry.name);
if (entry.isDirectory()) {
stack.push(fullPath);
continue;
}
if (entry.isFile() && entry.name.endsWith(".ts")) {
files.push(fullPath);
}
}
}
return files.sort((a, b) => a.localeCompare(b, "zh-CN"));
}
function createCommentMask(content) {
const mask = new Array(content.length).fill(false);
let i = 0;
let inSingle = false;
let inDouble = false;
let inTemplate = false;
let inLineComment = false;
let inBlockComment = false;
while (i < content.length) {
const ch = content[i];
const next = content[i + 1] ?? "";
const prev = content[i - 1] ?? "";
if (inLineComment) {
mask[i] = true;
if (ch === "\n") {
inLineComment = false;
}
i += 1;
continue;
}
if (inBlockComment) {
mask[i] = true;
if (ch === "*" && next === "/") {
mask[i + 1] = true;
inBlockComment = false;
i += 2;
continue;
}
i += 1;
continue;
}
if (!inDouble && !inTemplate && ch === "'" && prev !== "\\") {
inSingle = !inSingle;
i += 1;
continue;
}
if (!inSingle && !inTemplate && ch === '"' && prev !== "\\") {
inDouble = !inDouble;
i += 1;
continue;
}
if (!inSingle && !inDouble && ch === "`" && prev !== "\\") {
inTemplate = !inTemplate;
i += 1;
continue;
}
if (!inSingle && !inDouble && !inTemplate) {
if (ch === "/" && next === "/") {
mask[i] = true;
mask[i + 1] = true;
inLineComment = true;
i += 2;
continue;
}
if (ch === "/" && next === "*") {
mask[i] = true;
mask[i + 1] = true;
inBlockComment = true;
i += 2;
continue;
}
}
i += 1;
}
return mask;
}
function buildExportAnchors(content) {
const anchors = [];
const reg = /export\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)|export\s+const\s+([A-Za-z_$][\w$]*)/g;
for (const match of content.matchAll(reg)) {
anchors.push({
index: match.index ?? 0,
name: match[1] || match[2] || "",
});
}
return anchors;
}
function getNearestExportName(anchors, index) {
let name = "";
for (const item of anchors) {
if (item.index > index) {
break;
}
name = item.name;
}
return name || null;
}
function detectPlaceholder(content, index) {
const start = Math.max(0, index - 160);
const end = Math.min(content.length, index + 160);
const context = content.slice(start, end);
return /(占位|placeholder|todo)/i.test(context);
}
function parseInterfacesFromFile(content, filePath, srcApiDir) {
const commentMask = createCommentMask(content);
const exportAnchors = buildExportAnchors(content);
const relPath = path.relative(srcApiDir, filePath).replaceAll("\\", "/");
const segments = relPath.split("/");
const moduleName = segments[0] || "unknown";
const matches = [];
const collectMatch = (method, index, httpMethodFallback = "post") => {
const normalizedMethod = (method || "").trim();
if (!normalizedMethod) {
return;
}
const isCommented = Boolean(commentMask[index]);
const functionName = getNearestExportName(exportAnchors, index);
const requestStart = content.lastIndexOf("request(", index);
const requestWindow =
requestStart >= 0 ? content.slice(requestStart, Math.min(content.length, index + 280)) : content.slice(index, index + 280);
const httpMethod =
requestWindow.match(/\bmethod\s*:\s*['"`](get|post|put|delete|patch|options|head)['"`]/i)?.[1] ?? httpMethodFallback;
matches.push({
moduleName,
filePath: relPath,
interfaceName: functionName || normalizedMethod,
method: normalizedMethod,
httpMethod: httpMethod.toLowerCase(),
isEnabled: !isCommented,
isPlaceholder: detectPlaceholder(content, index),
});
};
// Pattern 1: request params carries literal method name.
const methodInParamsRegex = /params\s*:\s*\{[\s\S]*?\bmethod\s*:\s*['"`]([^'"`]+)['"`]/g;
for (const match of content.matchAll(methodInParamsRegex)) {
const index = match.index ?? 0;
collectMatch(match[1], index, "post");
}
// Pattern 2: wrapper call passes literal method name, e.g. getDashboardData('dashboard.xxx', data).
const wrappedMethodCallRegex = /return\s+[A-Za-z_$][\w$]*\(\s*['"`]([a-zA-Z0-9_.-]+)['"`]\s*(?:,|\))/g;
for (const match of content.matchAll(wrappedMethodCallRegex)) {
const index = match.index ?? 0;
collectMatch(match[1], index, "post");
}
return matches;
}
function uniqueInterfaces(items) {
const map = new Map();
for (const item of items) {
const key = `${item.filePath}::${item.method}`;
if (!map.has(key)) {
map.set(key, item);
}
}
return [...map.values()];
}
function parseZhBool(value, fallback = false) {
if (value === "是") {
return true;
}
if (value === "否") {
return false;
}
return fallback;
}
function parseMarkdownCells(line) {
return line
.trim()
.split("|")
.slice(1, -1)
.map((item) => item.trim());
}
function parseExistingInterfaceRows(markdown) {
const sectionAnchor = "## 接口明细";
const sectionIndex = markdown.indexOf(sectionAnchor);
if (sectionIndex < 0) {
return [];
}
const sectionText = markdown.slice(sectionIndex);
const lines = sectionText
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0);
const tableLines = lines.filter((line) => line.startsWith("|"));
if (tableLines.length < 3) {
return [];
}
const headers = parseMarkdownCells(tableLines[0]);
const getCol = (name) => headers.indexOf(name);
const col = {
moduleName: getCol("模块"),
interfaceName: getCol("接口名"),
method: getCol("method"),
httpMethod: getCol("HTTP Method"),
isEnabled: getCol("启用"),
isPlaceholder: getCol("占位"),
filePath: getCol("文件"),
remark: getCol("备注"),
};
if (col.method < 0 || col.filePath < 0 || col.moduleName < 0) {
return [];
}
const rows = [];
for (const rowLine of tableLines.slice(2)) {
const cells = parseMarkdownCells(rowLine);
if (cells.length < headers.length) {
continue;
}
const method = cells[col.method] ?? "";
const filePath = cells[col.filePath] ?? "";
if (!method || !filePath) {
continue;
}
rows.push({
moduleName: cells[col.moduleName] ?? "",
interfaceName: col.interfaceName >= 0 ? (cells[col.interfaceName] ?? "") : method,
method,
httpMethod: (cells[col.httpMethod] ?? "POST").toLowerCase(),
isEnabled: parseZhBool(cells[col.isEnabled], true),
isPlaceholder: parseZhBool(cells[col.isPlaceholder], false),
filePath,
remark: col.remark >= 0 ? (cells[col.remark] ?? "") : "",
});
}
return rows;
}
function buildRowKey(item) {
return `${item.moduleName}::${item.method}::${item.filePath}`;
}
function mergeInterfaceRows(scannedInterfaces, existingRows) {
const byExactKey = new Map(existingRows.map((item) => [buildRowKey(item), item]));
const byMethod = new Map();
for (const item of existingRows) {
if (!byMethod.has(item.method)) {
byMethod.set(item.method, item);
}
}
const merged = [];
const consumedExisting = new Set();
for (const item of scannedInterfaces) {
const key = buildRowKey(item);
const baseline = byExactKey.get(key) ?? byMethod.get(item.method) ?? null;
if (byExactKey.has(key)) {
consumedExisting.add(key);
}
merged.push({
moduleName: item.moduleName,
interfaceName: item.interfaceName,
method: item.method,
httpMethod: item.httpMethod,
filePath: item.filePath,
isEnabled: baseline ? baseline.isEnabled : item.isEnabled,
isPlaceholder: baseline ? baseline.isPlaceholder : item.isPlaceholder,
remark: baseline?.remark ?? "",
});
}
for (const item of existingRows) {
const key = buildRowKey(item);
if (consumedExisting.has(key)) {
continue;
}
const existsInScan = scannedInterfaces.some(
(scanned) => scanned.method === item.method && scanned.filePath === item.filePath,
);
if (existsInScan) {
continue;
}
merged.push({
...item,
isEnabled: false,
});
}
return merged.sort((a, b) => {
if (a.moduleName !== b.moduleName) {
return a.moduleName.localeCompare(b.moduleName, "zh-CN");
}
if (a.filePath !== b.filePath) {
return a.filePath.localeCompare(b.filePath, "zh-CN");
}
return a.method.localeCompare(b.method, "zh-CN");
});
}
function buildMarkdown(payload) {
const lines = [
"# 接口",
"",
`- 更新时间: ${payload.generatedAtLocal}`,
`- 扫描目录: \`${payload.source.srcApiDir}\``,
`- 模块数: ${payload.summary.moduleCount}`,
`- API 文件数: ${payload.summary.fileCount}`,
`- 接口数: ${payload.summary.interfaceCount}`,
`- 已启用: ${payload.summary.enabledCount}`,
`- 占位接口: ${payload.summary.placeholderCount}`,
"",
"## 模块统计",
"",
"| 模块 | 文件数 | 接口数 | 已启用 | 占位 |",
"| --- | ---: | ---: | ---: | ---: |",
];
for (const module of payload.modules) {
lines.push(
`| ${module.moduleName} | ${module.fileCount} | ${module.interfaceCount} | ${module.enabledCount} | ${module.placeholderCount} |`,
);
}
lines.push(
"",
"## 接口明细",
"",
"| 模块 | 接口名 | method | HTTP Method | 启用 | 占位 | 文件 | 备注 |",
"| --- | --- | --- | --- | --- | --- | --- | --- |",
);
for (const item of payload.interfaces) {
lines.push(
`| ${item.moduleName} | ${item.interfaceName} | ${item.method} | ${item.httpMethod.toUpperCase()} | ${item.isEnabled ? "是" : "否"} | ${item.isPlaceholder ? "是" : "否"} | ${item.filePath} | ${item.remark || ""} |`,
);
}
return lines.join("\n");
}
export async function runScript() {
const now = new Date();
const srcApiDir = API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.srcApiDir;
const files = await listTsFiles(srcApiDir);
const allInterfaces = [];
for (const filePath of files) {
const content = await readFile(filePath, "utf8");
const parsed = parseInterfacesFromFile(content, filePath, srcApiDir);
allInterfaces.push(...parsed);
}
const scannedInterfaces = uniqueInterfaces(allInterfaces).sort((a, b) => {
if (a.moduleName !== b.moduleName) {
return a.moduleName.localeCompare(b.moduleName, "zh-CN");
}
if (a.filePath !== b.filePath) {
return a.filePath.localeCompare(b.filePath, "zh-CN");
}
return a.method.localeCompare(b.method, "zh-CN");
});
const existingMarkdown = await readTextIfExists(API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.outputConfig, "");
const existingRows = parseExistingInterfaceRows(existingMarkdown);
const interfaces = mergeInterfaceRows(scannedInterfaces, existingRows);
const moduleMap = new Map();
for (const item of interfaces) {
const current = moduleMap.get(item.moduleName) ?? {
moduleName: item.moduleName,
fileSet: new Set(),
interfaceCount: 0,
enabledCount: 0,
placeholderCount: 0,
};
current.fileSet.add(item.filePath);
current.interfaceCount += 1;
if (item.isEnabled) {
current.enabledCount += 1;
}
if (item.isPlaceholder) {
current.placeholderCount += 1;
}
moduleMap.set(item.moduleName, current);
}
const modules = [...moduleMap.values()]
.map((item) => ({
moduleName: item.moduleName,
fileCount: item.fileSet.size,
interfaceCount: item.interfaceCount,
enabledCount: item.enabledCount,
placeholderCount: item.placeholderCount,
}))
.sort((a, b) => a.moduleName.localeCompare(b.moduleName, "zh-CN"));
const payload = {
script: "api-list-update",
generatedAt: now.toISOString(),
generatedAtLocal: formatLocalDateTime(now),
source: {
srcApiDir,
},
summary: {
moduleCount: modules.length,
fileCount: new Set(interfaces.map((item) => item.filePath)).size,
interfaceCount: interfaces.length,
enabledCount: interfaces.filter((item) => item.isEnabled).length,
placeholderCount: interfaces.filter((item) => item.isPlaceholder).length,
},
modules,
interfaces,
};
const markdown = buildMarkdown(payload);
await writeText(API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.outputConfig, markdown);
console.log(`执行时间: ${payload.generatedAtLocal}`);
console.log(`已同步配置文档: ${API_DOC_AGENT_API_LIST_UPDATE_CONFIG.file.outputConfig}`);
console.log(JSON.stringify(payload.summary, null, 2));
}