| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- #!/usr/bin/env node
- 'use strict';
- // 把接口目录和参数库写成「每个接口一行」的紧凑格式。
- // 体积比缩进格式小约三分之一,同时每个接口独占一行,git diff 仍然逐接口可读。
- // 用脚本改过目录后运行 `npm run catalog:format`。
- const fs = require('fs');
- const path = require('path');
- const CATALOG_DIR = path.resolve(__dirname, '..', 'mcp', 'catalog');
- const CATALOG_PATH = path.join(CATALOG_DIR, 'voc-social-endpoints.json');
- const PARAMS_DIR = path.join(CATALOG_DIR, 'params');
- function readJson(file) {
- const text = fs.readFileSync(file, 'utf8');
- return JSON.parse(text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text);
- }
- function formatCatalog(catalog) {
- const { endpoints, ...header } = catalog;
- const head = JSON.stringify(header, null, 2).replace(/\n}$/, '');
- const rows = (endpoints || []).map(item => ` ${JSON.stringify(item)}`).join(',\n');
- return `${head},\n "endpoints": [\n${rows}\n ]\n}\n`;
- }
- function formatParams(store) {
- const rows = Object.entries(store).map(([id, params]) => ` ${JSON.stringify(id)}: ${JSON.stringify(params)}`).join(',\n');
- return `{\n${rows}\n}\n`;
- }
- function writeIfChanged(file, content, original) {
- // 格式化不能改变数据:写入前确认解析结果与原数据完全一致。
- if (JSON.stringify(JSON.parse(content)) !== JSON.stringify(original)) {
- throw new Error(`formatting would change data: ${file}`);
- }
- const before = fs.readFileSync(file, 'utf8');
- if (before === content) return 0;
- fs.writeFileSync(file, content, 'utf8');
- return Buffer.byteLength(before, 'utf8') - Buffer.byteLength(content, 'utf8');
- }
- let saved = 0;
- const catalog = readJson(CATALOG_PATH);
- saved += writeIfChanged(CATALOG_PATH, formatCatalog(catalog), catalog);
- for (const name of fs.readdirSync(PARAMS_DIR).filter(item => item.endsWith('.json'))) {
- const file = path.join(PARAMS_DIR, name);
- const store = readJson(file);
- saved += writeIfChanged(file, formatParams(store), store);
- }
- console.log(`catalog formatted, ${Math.round(saved / 1024)}KB smaller`);
|