const fs = require('fs');
const path = require('path');
const cheerio = require('cheerio');
const {
buildParseApiUrl,
fetchParseHtml,
resolveSiteOrigin,
toOutputBaseName,
} = require('./utils');
/** Wiki 语言列到稳定 key 的映射,匹配前会去掉空白和括号 */
const LANGUAGE_ALIASES = {
english: 'en',
'chinese simplified': 'zh-Hans',
'chinese (simplified)': 'zh-Hans',
'chinese s': 'zh-Hans',
'chinese traditional': 'zh-Hant',
'chinese (traditional)': 'zh-Hant',
'chinese t': 'zh-Hant',
japanese: 'ja',
korean: 'ko',
spanish: 'es',
french: 'fr',
russian: 'ru',
thai: 'th',
vietnamese: 'vi',
german: 'de',
indonesian: 'id',
portuguese: 'pt',
turkish: 'tr',
italian: 'it',
};
const LANGUAGE_ORDER = [
'en',
'zh-Hans',
'zh-Hant',
'ja',
'ko',
'es',
'fr',
'ru',
'th',
'vi',
'de',
'id',
'pt',
'tr',
'it',
];
function getDataFilePath(config) {
return path.join(__dirname, 'data', `${config.name}.json`);
}
function loadCharacterData(filePath) {
if (!fs.existsSync(filePath)) {
return {};
}
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (error) {
console.warn(`读取角色数据失败,将重新收集: ${error.message}`);
return {};
}
}
function sortNames(names) {
const ordered = {};
for (const key of LANGUAGE_ORDER) {
if (names[key]) {
ordered[key] = names[key];
}
}
for (const key of Object.keys(names).sort()) {
if (!ordered[key]) {
ordered[key] = names[key];
}
}
return ordered;
}
function saveCharacterData(filePath, data) {
const sorted = Object.fromEntries(
Object.keys(data)
.sort((a, b) => a.localeCompare(b))
.map((key) => {
const entry = { ...data[key] };
if (entry.names) {
entry.names = sortNames(entry.names);
}
return [key, entry];
})
);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const tmpPath = `${filePath}.tmp`;
fs.writeFileSync(tmpPath, `${JSON.stringify(sorted, null, 2)}\n`, 'utf8');
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
fs.renameSync(tmpPath, filePath);
}
/** 把 /wiki/Aino 或完整 URL 转成 parse API 用的页面标题 */
function wikiHrefToPageTitle(href) {
if (!href) {
return null;
}
try {
const pathname = href.startsWith('http') ? new URL(href).pathname : href;
const match = pathname.match(/\/wiki\/([^?#]+)/);
if (!match) {
return null;
}
return decodeURIComponent(match[1].replace(/_/g, ' '));
} catch {
return null;
}
}
function normalizeText(text) {
return (text || '').replace(/\s+/g, ' ').trim();
}
function findHeaderIndex(headers, name) {
if (!name) {
return -1;
}
const target = name.toLowerCase();
return headers.findIndex((header) => header.toLowerCase() === target);
}
function getTableHeaders($, $table) {
return $table
.find('tr')
.first()
.find('th')
.map((_, el) => normalizeText($(el).text()))
.get();
}
/**
* 从角色列表行提取 wiki 链接和国家。
* 链接优先取图片外层 a;国家取配置的列表表头列(如 Region)。
*/
function extractRowMeta($, $img, regionHeader) {
const $row = $img.closest('tr');
let wikiHref = $img.closest('a').attr('href') || null;
if (!wikiHref && $row.length) {
wikiHref =
$row
.find('a[href*="/wiki/"]')
.filter((_, el) => {
const href = $(el).attr('href') || '';
return !/\/wiki\/(Category|File|Version):/i.test(href);
})
.first()
.attr('href') || null;
}
let listRegion = null;
if (regionHeader && $row.length) {
const headers = getTableHeaders($, $img.closest('table'));
const index = findHeaderIndex(headers, regionHeader);
if (index >= 0) {
const $cell = $row.find('td').eq(index);
const linkText = $cell
.find('a')
.map((_, el) => $(el).text().trim())
.get()
.find(Boolean);
listRegion = linkText || normalizeText($cell.text()) || null;
}
}
return { wikiHref, listRegion };
}
function languageKey(label) {
const normalized = normalizeText(label)
.toLowerCase()
.replace(/[()]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
return (
LANGUAGE_ALIASES[normalized] ||
normalized.replace(/\s+/g, '-') ||
label
);
}
/** 正式名在第一个非注音 span[lang] 里,后面的 small 是罗马音 */
function extractOfficialName($, $cell) {
const $name = $cell
.find('span[lang]')
.filter((_, el) => {
const lang = $(el).attr('lang') || '';
return !lang.endsWith('-rm') && lang !== 'zh-Latn';
})
.first();
if ($name.length) {
return normalizeText($name.text());
}
const $clone = $cell.clone();
$clone.find('small, sup, .reference').remove();
const html = $clone.html() || '';
const firstPart = html.split(/
/i)[0];
return normalizeText(cheerio.load(`