#!/usr/bin/env node
/**
* 跨檔案內容總檢工具 (Editor Pass: verify-content-editor.mjs)
*
* 檢查項目:
* 1. 專案管理核心文件(docs/management/STATUS.md, OPEN.md, decisions.md, INBOX.md 及 AGENTS.md)存在與格式檢查
* 2. 跨檔案設定與 ID 去重檢查(BUILDINGS, MERCHANT.items, TITLE_DEFS, SCHEDULE, WORLD_BOSS_ROSTER)
* 3. 武將 TCG 卡牌跨檔案一致性檢查(docs/hero_figurines.json 15 名將 × C/R/SR/SSR 圖資與 _prompts 對齊)
* 4. 題庫(data/banks/*.json 與 data/english960.json)結構完整性、空選項、答案有效性與重複題檢查
* 5. 全專案 HTML 入口 ?v= 快取版號與 APP_BUILD_VERSION 一致性檢查
* 6. 介面禁用詞彙掃描(確保古風軍政語彙一致,無「升級建築」「購買建築」等違規字眼)
* 7. 西域萬國大市集視覺資產(5 張 PNG 存在性、檔案大小 > 20KB、PNG 標頭尺寸)與 4 期制霸稱號註冊檢查
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
let passCount = 0;
let warnCount = 0;
const failures = [];
function pass(msg) {
passCount++;
console.log(` ✅ [PASS] ${msg}`);
}
function warn(msg) {
warnCount++;
console.warn(` ⚠️ [WARN] ${msg}`);
}
function fail(msg) {
failures.push(msg);
console.error(` ❌ [FAIL] ${msg}`);
}
async function main() {
console.log('====================================================');
console.log('🔍 啟動跨檔案內容總檢 (Editor Pass: verify-content-editor.mjs)');
console.log('====================================================\n');
// ---------------------------------------------------------
// 1. 檢查專案管理持久化文件與根目錄入口規範
// ---------------------------------------------------------
console.log('--- [1/7] 專案管理與入口規範文件檢查 ---');
const requiredDocs = [
'AGENTS.md',
'GEMINI.md',
'docs/management/STATUS.md',
'docs/management/OPEN.md',
'docs/management/decisions.md',
'docs/management/INBOX.md',
];
for (const relPath of requiredDocs) {
const fullPath = path.join(ROOT, relPath);
if (!fs.existsSync(fullPath)) {
fail(`缺少必要管理文件: ${relPath}`);
} else {
const content = fs.readFileSync(fullPath, 'utf8').trim();
if (content.length < 50) {
fail(`管理文件內容過短或空白: ${relPath} (${content.length} chars)`);
} else {
pass(`管理文件齊備: ${relPath}`);
}
}
}
// 檢查 decisions.md 是否符合最新置頂 (DEC-YYYYMMDD-XX 降序)
const decisionsPath = path.join(ROOT, 'docs/management/decisions.md');
if (fs.existsSync(decisionsPath)) {
const decContent = fs.readFileSync(decisionsPath, 'utf8');
const decMatches = [...decContent.matchAll(/^## \[DEC-(\d{8})-\d+\]/gm)].map(m => m[1]);
if (decMatches.length === 0) {
fail('docs/management/decisions.md 未找到任何 [DEC-YYYYMMDD-XX] 標題');
} else {
let isSortedDesc = true;
for (let i = 1; i < decMatches.length; i++) {
if (decMatches[i] > decMatches[i - 1]) {
isSortedDesc = false;
break;
}
}
if (!isSortedDesc) {
fail(`docs/management/decisions.md 違反「最新置頂」順序: ${decMatches.join(' -> ')}`);
} else {
pass(`decisions.md 決策紀錄共 ${decMatches.length} 筆,符合最新置頂規範`);
}
}
}
// ---------------------------------------------------------
// 2. 跨檔案設定與 ID 唯一性檢查 (js/config.js)
// ---------------------------------------------------------
console.log('\n--- [2/7] 核心設定表 ID 去重與完整性檢查 ---');
const configUrl = pathToFileURL(path.join(ROOT, 'js/config.js')).href;
const config = await import(configUrl);
function checkUniqueIds(listOrObj, label, key = 'id') {
const list = Array.isArray(listOrObj)
? listOrObj
: (listOrObj && typeof listOrObj === 'object')
? Object.entries(listOrObj).map(([k, v]) => ({ [key]: v?.[key] || k, ...v }))
: [];
if (list.length === 0) {
fail(`${label} 不是有效非空集合`);
return;
}
const seen = new Set();
const seenNames = new Set();
for (const item of list) {
const id = item[key];
if (!id) {
fail(`${label} 存在缺少 ${key} 的項目: ${JSON.stringify(item)}`);
} else if (seen.has(id)) {
fail(`${label} 存在重複 ID: "${id}"`);
} else {
seen.add(id);
}
if (item.name) {
if (seenNames.has(item.name)) {
warn(`${label} 存在重複名稱: "${item.name}"`);
}
seenNames.add(item.name);
}
}
pass(`${label} 共 ${list.length} 項,ID 與結構唯一無衝突`);
}
checkUniqueIds(config.BUILDINGS, 'BUILDINGS (九州城池)');
checkUniqueIds(config.MERCHANT?.items, 'MERCHANT.items (西域商隊黑市道具)');
checkUniqueIds(config.TITLE_DEFS, 'TITLE_DEFS (主帥稱號)');
checkUniqueIds(config.SCHEDULE, 'SCHEDULE (測驗排程區間)');
// ---------------------------------------------------------
// 3. 武將 TCG 卡牌跨檔案對齊檢查
// ---------------------------------------------------------
console.log('\n--- [3/7] 武將 TCG 卡牌圖資與設定對齊檢查 ---');
const figurinesPath = path.join(ROOT, 'docs/hero_figurines.json');
if (!fs.existsSync(figurinesPath)) {
fail('缺少 docs/hero_figurines.json');
} else {
const figData = JSON.parse(fs.readFileSync(figurinesPath, 'utf8'));
const heroes = Object.entries(figData).filter(([k]) => !k.startsWith('_'));
const heroIds = new Set();
const tiers = ['c', 'r', 'sr', 'ssr'];
let missingCards = 0;
let missingPrompts = 0;
for (const [heroName, info] of heroes) {
if (!info.id || !info.figurine) {
fail(`hero_figurines.json 中 "${heroName}" 缺少 id 或 figurine 描述`);
continue;
}
if (heroIds.has(info.id)) {
fail(`hero_figurines.json 存在重複 hero_id: "${info.id}"`);
}
heroIds.add(info.id);
for (const tier of tiers) {
const jpgPath = path.join(ROOT, 'assets/cards', `tcg_${info.id}_${tier}.jpg`);
const webpPath = path.join(ROOT, 'assets/cards', `tcg_${info.id}_${tier}.webp`);
const promptPathUpper = path.join(ROOT, 'assets/cards/_prompts', `${info.id}_${tier.toUpperCase()}.txt`);
const promptPathTcg = path.join(ROOT, 'assets/cards/_prompts', `tcg_${info.id}_${tier}.txt`);
if (!fs.existsSync(jpgPath) || !fs.existsSync(webpPath)) {
missingCards++;
fail(`名將 ${heroName} (${info.id}) 缺少 ${tier.toUpperCase()} 圖檔 (.jpg 或 .webp)`);
}
if (!fs.existsSync(promptPathUpper) && !fs.existsSync(promptPathTcg)) {
missingPrompts++;
fail(`名將 ${heroName} (${info.id}) 缺少 ${tier.toUpperCase()} 提示詞檔 (_prompts/${info.id}_${tier.toUpperCase()}.txt)`);
}
}
}
if (missingCards === 0 && missingPrompts === 0) {
pass(`15 位名將 × 4 品階 (C/R/SR/SSR) 圖資 (120 檔) 與提示詞 (60 檔) 100% 齊全對齊`);
}
}
// ---------------------------------------------------------
// 4. 題庫結構與內容品質總檢 (data/banks/*.json & english960.json)
// ---------------------------------------------------------
console.log('\n--- [4/7] 專業題庫與英語 960 資料品質檢查 ---');
const banksIndexPath = path.join(ROOT, 'data/banks/index.json');
if (!fs.existsSync(banksIndexPath)) {
fail('缺少 data/banks/index.json');
} else {
const banksIndex = JSON.parse(fs.readFileSync(banksIndexPath, 'utf8'));
const bankList = Array.isArray(banksIndex) ? banksIndex : (banksIndex.banks || []);
let totalQuestions = 0;
let invalidQuestions = 0;
const validLetterAns = new Set(['A', 'B', 'C', 'D', '1', '2', '3', '4']);
const stripImgAndWs = (s) => String(s || '').replace(/
]*>/gi, '').replace(/\s+/g, '').trim();
let dupGuardFailures = 0;
for (const bankMeta of bankList) {
const bankFile = bankMeta.file || `${bankMeta.id}.json`;
const bankPath = path.join(ROOT, 'data/banks', path.basename(bankFile));
if (!fs.existsSync(bankPath)) {
fail(`題庫索引指向不存在的檔案: ${bankFile}`);
continue;
}
const bankData = JSON.parse(fs.readFileSync(bankPath, 'utf8'));
const questions = Array.isArray(bankData) ? bankData : (bankData.questions || []);
totalQuestions += questions.length;
if (typeof bankMeta.count === 'number' && bankMeta.count !== questions.length) {
fail(`data/banks/index.json 中 ${bankMeta.id} 標記題數 (${bankMeta.count}) 與實際題數 (${questions.length}) 不符`);
}
if (!Array.isArray(bankData) && typeof bankData.count === 'number' && bankData.count !== questions.length) {
fail(`題庫 ${bankFile} 標記 count (${bankData.count}) 與實際題數 (${questions.length}) 不符`);
}
const seenNumbers = new Set();
const seenSignatures = new Map();
const seenSocialStems = new Map();
const bankDupPairs = [];
for (let i = 0; i < questions.length; i++) {
const q = questions[i];
const qText = String(q.q || q.question || '').trim();
const opts = q.o || q.options || q.opts || [];
const ans = q.a ?? q.answer ?? q.ans;
const isAnsValid =
(typeof ans === 'number' && ans >= 0 && ans < opts.length) ||
(typeof ans === 'string' && validLetterAns.has(ans.trim().toUpperCase()));
if (!qText || !Array.isArray(opts) || opts.length < 2 || !isAnsValid) {
invalidQuestions++;
if (invalidQuestions <= 5) {
fail(`題庫 ${bankFile} 第 ${i + 1} 題格式異常 (題號 ${q.n || q.id || i})`);
}
}
const qNum = q.n ?? q.id;
if (qNum !== undefined && qNum !== null) {
if (seenNumbers.has(qNum)) {
dupGuardFailures++;
fail(`題庫 ${bankFile} 出現重複題號 n=${qNum}`);
}
seenNumbers.add(qNum);
}
const normStem = stripImgAndWs(qText);
const normOpts = Array.isArray(opts) ? opts.map(stripImgAndWs) : [];
const isVisualGeneric = (normStem.length < 12 && /
!o);
if (!isVisualGeneric && normStem) {
if (bankMeta.id === 'social') {
if (seenSocialStems.has(normStem)) {
dupGuardFailures++;
bankDupPairs.push({ firstN: seenSocialStems.get(normStem), dupN: qNum ?? (i + 1), stem: normStem.slice(0, 28) });
} else {
seenSocialStems.set(normStem, qNum ?? (i + 1));
}
} else {
const sig = `${normStem}||${normOpts.join('|')}||${String(ans ?? '').trim().toUpperCase()}`;
if (seenSignatures.has(sig)) {
bankDupPairs.push({ firstN: seenSignatures.get(sig), dupN: qNum ?? (i + 1), stem: normStem.slice(0, 28) });
} else {
seenSignatures.set(sig, qNum ?? (i + 1));
}
}
}
}
if (bankMeta.id === 'social' && bankDupPairs.length > 0) {
const preview = bankDupPairs.slice(0, 5).map(d => `#${d.dupN}(同#${d.firstN})`).join('、');
fail(`社會題庫 ${bankFile} 嚴禁重複題目,發現 ${bankDupPairs.length} 筆重複 (${preview})`);
} else if (bankDupPairs.length >= 2) {
dupGuardFailures++;
const preview = bankDupPairs.slice(0, 5).map(d => `#${d.dupN}(同#${d.firstN})`).join('、');
fail(`題庫 ${bankFile} 發現過多完全重複題目 (${bankDupPairs.length} 筆: ${preview})`);
} else if (bankDupPairs.length === 1) {
const d = bankDupPairs[0];
warn(`官方題庫 ${bankFile} 含 1 筆既定重複題 (#${d.dupN} 同 #${d.firstN}:「${d.stem}…」)`);
}
}
if (invalidQuestions === 0 && dupGuardFailures === 0) {
pass(`8 大職群題庫共 ${totalQuestions} 題,題幹、選項、答案索引、題號唯一性與重複題護欄全數合法`);
}
}
const engPath = path.join(ROOT, 'data/english960.json');
if (fs.existsSync(engPath)) {
const engData = JSON.parse(fs.readFileSync(engPath, 'utf8'));
const words = Array.isArray(engData) ? engData : (engData.words || []);
if (words.length < 900) {
fail(`data/english960.json 單字量異常偏少: ${words.length}`);
} else {
pass(`data/english960.json 共 ${words.length} 筆單字,結構完整`);
}
} else {
fail('缺少 data/english960.json');
}
// ---------------------------------------------------------
// 5. HTML 入口 ?v= 快取版號一致性檢查
// ---------------------------------------------------------
console.log('\n--- [5/7] HTML 入口 ?v= 快取版號與 APP_BUILD_VERSION 對齊檢查 ---');
const expectedVer = config.APP_BUILD_VERSION;
const htmlFiles = ['index.html', 'teacher.html', 'boss.html', 'boss-test.html', 'lottery-draw.html'];
let verMismatch = 0;
for (const htmlFile of htmlFiles) {
const fullPath = path.join(ROOT, htmlFile);
if (!fs.existsSync(fullPath)) continue;
const html = fs.readFileSync(fullPath, 'utf8');
const matches = [...html.matchAll(/\?v=([a-zA-Z0-9_.-]+)/g)];
if (matches.length === 0) {
warn(`${htmlFile} 未包含任何 ?v= 快取版號參數`);
}
for (const m of matches) {
if (m[1] !== expectedVer) {
verMismatch++;
fail(`${htmlFile} 發現過期或不一致的版號參數 "?v=${m[1]}" (預期為 "${expectedVer}")`);
}
}
}
if (verMismatch === 0) {
pass(`所有主 HTML 入口之 ?v= 參數皆與 APP_BUILD_VERSION (${expectedVer}) 完全一致`);
}
// ---------------------------------------------------------
// 6. 介面禁用詞彙掃描(古風軍政語彙守護)
// ---------------------------------------------------------
console.log('\n--- [6/7] 古風軍政禁用詞彙掃描 ---');
const forbiddenTerms = ['購買建築', '升級建築'];
const jsFiles = fs.readdirSync(path.join(ROOT, 'js')).filter(f => f.endsWith('.js'));
let forbiddenFound = 0;
for (const file of jsFiles) {
const content = fs.readFileSync(path.join(ROOT, 'js', file), 'utf8');
for (const term of forbiddenTerms) {
if (content.includes(term)) {
forbiddenFound++;
fail(`js/${file} 發現禁用詞彙 "${term}"(請改用「駐防擴軍 / 加官進爵 / 出征收復」)`);
}
}
}
if (forbiddenFound === 0) {
pass(`js/*.js 全數通過古風軍政語彙檢查,無禁用詞彙`);
}
// ---------------------------------------------------------
// 7. 西域萬國大市集視覺資產與稱號註冊檢查
// ---------------------------------------------------------
console.log('\n--- [7/7] 西域萬國大市集視覺資產與稱號註冊檢查 ---');
const bazaarAssets = [
{ file: 'assets/bazaar_camp.png', width: 1200, height: 896 },
{ file: 'assets/bazaar_street_bg.png', width: 1200, height: 896 },
{ file: 'assets/bazaar_npc_weaver.png', width: 896, height: 1200 },
{ file: 'assets/bazaar_npc_lutist.png', width: 896, height: 1200 },
{ file: 'assets/bazaar_npc_scholar.png', width: 896, height: 1200 },
];
const PNG_SIG = '89504e470d0a1a0a';
let bazaarAssetErrors = 0;
for (const spec of bazaarAssets) {
const assetPath = path.join(ROOT, spec.file);
if (!fs.existsSync(assetPath)) {
bazaarAssetErrors++;
fail(`西域萬國大市集缺少圖資檔案: ${spec.file}`);
continue;
}
const stat = fs.statSync(assetPath);
if (stat.size <= 20 * 1024) {
bazaarAssetErrors++;
fail(`西域萬國大市集圖資檔案過小 (${stat.size} bytes <= 20KB): ${spec.file}`);
continue;
}
const buf = fs.readFileSync(assetPath);
const sig = buf.subarray(0, 8).toString('hex');
const ihdr = buf.subarray(12, 16).toString('ascii');
if (buf.length < 24 || sig !== PNG_SIG || ihdr !== 'IHDR') {
bazaarAssetErrors++;
fail(`西域萬國大市集圖資非有效 PNG 標頭: ${spec.file}`);
continue;
}
const w = buf.readUInt32BE(16);
const h = buf.readUInt32BE(20);
if (w !== spec.width || h !== spec.height) {
bazaarAssetErrors++;
fail(`西域萬國大市集圖資尺寸不符 ${spec.file}: 實際 ${w}×${h},預期 ${spec.width}×${spec.height}`);
}
}
if (bazaarAssetErrors === 0) {
pass(`西域萬國大市集 5 張 PNG 圖資全數齊備(> 20KB 且 PNG 標頭尺寸精確為 1200×896 / 896×1200)`);
}
const bazaarCycles = Object.values(config.BAZAAR_CONFIG?.cycles || {});
if (bazaarCycles.length !== 4) {
fail(`BAZAAR_CONFIG.cycles 預期 4 期,實際為 ${bazaarCycles.length} 期`);
} else {
let missingTitles = 0;
for (const cycle of bazaarCycles) {
if (!cycle.grandTitle || !config.TITLE_DEFS?.[cycle.grandTitle]) {
missingTitles++;
fail(`BAZAAR_CONFIG.cycles.${cycle.id} 的 grandTitle ("${cycle.grandTitle}") 未於 TITLE_DEFS 註冊`);
}
}
if (missingTitles === 0) {
pass(`BAZAAR_CONFIG 4 期 grandTitle (${bazaarCycles.map(c => c.grandTitle).join('、')}) 皆已於 TITLE_DEFS 註冊`);
}
}
// ---------------------------------------------------------
// 總結輸出
// ---------------------------------------------------------
console.log('\n====================================================');
if (failures.length > 0) {
console.error(`❌ Editor Pass 失敗:共 ${failures.length} 項錯誤,${warnCount} 項警告。`);
process.exit(1);
} else {
console.log(`🎉 Editor Pass 全數通過!(${passCount} 項檢查 PASS,${warnCount} 項提醒)`);
}
}
main().catch(err => {
console.error('❌ verify-content-editor 執行發生未預期例外:', err);
process.exit(1);
});