183 lines
5.0 KiB
JavaScript
183 lines
5.0 KiB
JavaScript
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
||
import { createHash } from "node:crypto";
|
||
import path from "node:path";
|
||
import { API_DOC_SYNC_CONFIG } from "./config.mjs";
|
||
|
||
const LEGACY_FILES = {
|
||
localChanges: path.join("src", "apichanges.txt"),
|
||
};
|
||
|
||
function stableId(record) {
|
||
if (record?.version) {
|
||
return String(record.version);
|
||
}
|
||
|
||
const payload = JSON.stringify({
|
||
date: record?.date ?? "",
|
||
summary: record?.summary ?? "",
|
||
methods: Array.isArray(record?.methods) ? record.methods : [],
|
||
notes: Array.isArray(record?.notes) ? record.notes : [],
|
||
});
|
||
return createHash("sha1").update(payload).digest("hex");
|
||
}
|
||
|
||
function normalizePendingRecord(record) {
|
||
return {
|
||
summary: record?.summary ?? "",
|
||
methods: Array.isArray(record?.methods) ? record.methods : [],
|
||
notes: Array.isArray(record?.notes) ? record.notes : [],
|
||
};
|
||
}
|
||
|
||
async function readJsonArray(filePath) {
|
||
try {
|
||
const content = await readFile(filePath, "utf8");
|
||
const parsed = JSON.parse(content);
|
||
return Array.isArray(parsed) ? parsed : [];
|
||
} catch (error) {
|
||
if (error?.code === "ENOENT") {
|
||
return [];
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async function readLocalChangesWithLegacyFallback() {
|
||
const {
|
||
file: { localChanges },
|
||
} = API_DOC_SYNC_CONFIG;
|
||
|
||
const localData = await readJsonArray(localChanges);
|
||
if (localData.length > 0) {
|
||
return localData;
|
||
}
|
||
|
||
const legacyData = await readJsonArray(LEGACY_FILES.localChanges);
|
||
if (legacyData.length > 0) {
|
||
await writeJson(localChanges, legacyData);
|
||
return legacyData;
|
||
}
|
||
|
||
return [];
|
||
}
|
||
|
||
function parseChangesPayload(content) {
|
||
const trimmed = content.trim();
|
||
|
||
try {
|
||
const parsed = JSON.parse(trimmed);
|
||
if (Array.isArray(parsed)) {
|
||
return parsed;
|
||
}
|
||
} catch {
|
||
// Fallback: extract JSON array from HTML/text.
|
||
}
|
||
|
||
const start = trimmed.indexOf("[");
|
||
const end = trimmed.lastIndexOf("]");
|
||
if (start < 0 || end < 0 || end <= start) {
|
||
throw new Error("远端返回内容中未找到可解析的 JSON 数组。");
|
||
}
|
||
|
||
const parsedFallback = JSON.parse(trimmed.slice(start, end + 1));
|
||
if (!Array.isArray(parsedFallback)) {
|
||
throw new Error("远端返回内容解析后不是数组。");
|
||
}
|
||
return parsedFallback;
|
||
}
|
||
|
||
async function fetchRemoteChanges() {
|
||
const response = await fetch(API_DOC_SYNC_CONFIG.changesUrl, {
|
||
method: "GET",
|
||
signal: AbortSignal.timeout(20000),
|
||
});
|
||
|
||
if (!response.ok) {
|
||
throw new Error(`抓取接口日志失败:HTTP ${response.status}`);
|
||
}
|
||
|
||
const text = await response.text();
|
||
return parseChangesPayload(text);
|
||
}
|
||
|
||
async function writeJson(filePath, data) {
|
||
await mkdir(path.dirname(filePath), { recursive: true });
|
||
await writeFile(filePath, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
||
}
|
||
|
||
async function writeHistorySnapshot(changes) {
|
||
const {
|
||
file: { historyDir },
|
||
history: { prefix, suffix },
|
||
} = API_DOC_SYNC_CONFIG;
|
||
await mkdir(historyDir, { recursive: true });
|
||
|
||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||
const snapshotPath = path.join(historyDir, `${prefix}${timestamp}${suffix}`);
|
||
await writeJson(snapshotPath, changes);
|
||
return snapshotPath;
|
||
}
|
||
|
||
async function pruneHistory() {
|
||
const {
|
||
file: { historyDir },
|
||
history: { prefix, suffix },
|
||
historyMaxFiles,
|
||
} = API_DOC_SYNC_CONFIG;
|
||
|
||
await mkdir(historyDir, { recursive: true });
|
||
const files = await readdir(historyDir);
|
||
const historyFiles = files.filter((file) => file.startsWith(prefix) && file.endsWith(suffix));
|
||
if (historyFiles.length <= historyMaxFiles) {
|
||
return;
|
||
}
|
||
|
||
const fileStats = await Promise.all(
|
||
historyFiles.map(async (file) => {
|
||
const filePath = path.join(historyDir, file);
|
||
const fileInfo = await stat(filePath);
|
||
return {
|
||
filePath,
|
||
mtimeMs: fileInfo.mtimeMs,
|
||
};
|
||
}),
|
||
);
|
||
|
||
fileStats.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
||
const expired = fileStats.slice(historyMaxFiles);
|
||
await Promise.all(expired.map((item) => rm(item.filePath)));
|
||
}
|
||
|
||
async function run() {
|
||
const {
|
||
file: { localChanges, pendingChanges },
|
||
} = API_DOC_SYNC_CONFIG;
|
||
|
||
const localData = await readLocalChangesWithLegacyFallback();
|
||
const remoteData = await fetchRemoteChanges();
|
||
|
||
const localIds = new Set(localData.map(stableId));
|
||
const newRecords = remoteData.filter((item) => !localIds.has(stableId(item)));
|
||
|
||
if (newRecords.length === 0) {
|
||
await writeJson(pendingChanges, []);
|
||
console.log("未检测到接口更新,已清理待更新接口文件。");
|
||
return;
|
||
}
|
||
|
||
await writeJson(localChanges, remoteData);
|
||
await writeJson(pendingChanges, newRecords.map(normalizePendingRecord));
|
||
const snapshotPath = await writeHistorySnapshot(remoteData);
|
||
await pruneHistory();
|
||
|
||
console.log(`检测到 ${newRecords.length} 条接口更新。`);
|
||
console.log(`已更新本地日志:${localChanges}`);
|
||
console.log(`已更新待更新文件:${pendingChanges}`);
|
||
console.log(`已生成历史快照:${snapshotPath}`);
|
||
}
|
||
|
||
run().catch((error) => {
|
||
console.error("执行 API 文档更新流程失败:", error);
|
||
process.exitCode = 1;
|
||
});
|