import fs from 'node:fs'; import path from 'node:path'; import converter from './converter.cjs'; const [input, output, mappingFile, zero = 'north'] = process.argv.slice(2); if (!input || !output) { console.error('用法:node convert.mjs 输入文件或目录 新建输出目录 [映射表.json] [north|east|south|west]'); process.exit(1); } const source = path.resolve(input), target = path.resolve(output); if (fs.existsSync(target)) throw new Error('输出目录已存在,请指定新目录,避免覆盖已有文件'); if (target === source || target.startsWith(source + path.sep)) throw new Error('输出目录不能位于输入目录中'); const mapping = mappingFile ? JSON.parse(fs.readFileSync(mappingFile, 'utf8')) : converter.defaults; const files = fs.statSync(source).isDirectory() ? fs.readdirSync(source).filter(name => /^level\d+\.json$/i.test(name)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).map(name => path.join(source, name)) : [source]; if (!files.length) throw new Error('输入目录没有 level数字.json 文件'); fs.mkdirSync(target, { recursive: true }); const report = { source, mapping: mappingFile || '默认对象映射', angleZero: zero, success: 0, failed: 0, files: [] }; for (const file of files) { let result; try { result = converter.convert(JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')), mapping, zero); } catch (error) { result = { ok: false, errors: ['读取或解析失败:' + error.message], warnings: [] }; } const { layout, ...summary } = result; const output = converter.outputName(path.basename(file)); report.files.push({ file: path.basename(file), output, ...summary }); if (result.ok) { fs.writeFileSync(path.join(target, output), JSON.stringify(layout, null, 2), { flag: 'wx' }); report.success++; } else report.failed++; } fs.writeFileSync(path.join(target, '转换报告.json'), JSON.stringify(report, null, 2)); console.log('转换完成:成功 ' + report.success + ',未转换 ' + report.failed + ';输出:' + target); if (report.failed) process.exitCode = 2;