387 lines
12 KiB
JavaScript
387 lines
12 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const ROOT = process.cwd();
|
|
const METHODS_DIR = path.join(ROOT, 'methods');
|
|
const CHANGES_DIR = path.join(METHODS_DIR, 'changes');
|
|
|
|
function parseArgs(argv) {
|
|
const args = {
|
|
specPath: '',
|
|
dryRun: false,
|
|
docOnly: false,
|
|
help: false,
|
|
};
|
|
|
|
for (const item of argv) {
|
|
if (item === '--dry-run') {
|
|
args.dryRun = true;
|
|
continue;
|
|
}
|
|
|
|
if (item === '--doc-only') {
|
|
args.docOnly = true;
|
|
continue;
|
|
}
|
|
|
|
if (item === '--help' || item === '-h') {
|
|
args.help = true;
|
|
continue;
|
|
}
|
|
|
|
if (item.startsWith('--spec=')) {
|
|
const raw = String(item.slice('--spec='.length)).trim();
|
|
args.specPath = raw ? path.resolve(ROOT, raw) : '';
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (!args.help && !args.specPath) {
|
|
throw new Error('Missing required --spec=<path> argument.');
|
|
}
|
|
|
|
return args;
|
|
}
|
|
|
|
function printHelp() {
|
|
console.log([
|
|
'Usage:',
|
|
' npm run doc:api:update -- --spec=temp/api-doc-update.json',
|
|
' npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run',
|
|
' npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only',
|
|
'',
|
|
'Options:',
|
|
' --spec=<path> Path to the fixed update spec JSON file.',
|
|
' --dry-run Validate and print the planned changes without writing files.',
|
|
' --doc-only Update methods/<docName>.json only and skip methods/changes/<docName>.json.',
|
|
].join('\n'));
|
|
}
|
|
|
|
function isPlainObject(value) {
|
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
}
|
|
|
|
function assert(condition, message) {
|
|
if (!condition) {
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
function readJsonFile(filePath) {
|
|
const raw = fs.readFileSync(filePath, 'utf8');
|
|
return {
|
|
json: JSON.parse(raw),
|
|
indent: detectIndent(raw),
|
|
eol: detectEol(raw),
|
|
};
|
|
}
|
|
|
|
function detectIndent(raw) {
|
|
const match = raw.match(/^([ \t]+)"[^"]+":/m);
|
|
return match ? match[1] : ' ';
|
|
}
|
|
|
|
function detectEol(raw) {
|
|
return raw.includes('\r\n') ? '\r\n' : '\n';
|
|
}
|
|
|
|
function writeJsonFile(filePath, value, indent, eol) {
|
|
const formatted = JSON.stringify(value, null, indent).replace(/\n/g, eol);
|
|
fs.writeFileSync(filePath, `${formatted}${eol}`, 'utf8');
|
|
}
|
|
|
|
function ensureString(value, fieldPath) {
|
|
assert(typeof value === 'string' && value.trim(), `${fieldPath} must be a non-empty string.`);
|
|
}
|
|
|
|
function ensureBoolean(value, fieldPath) {
|
|
assert(typeof value === 'boolean', `${fieldPath} must be a boolean.`);
|
|
}
|
|
|
|
function ensureArray(value, fieldPath) {
|
|
assert(Array.isArray(value), `${fieldPath} must be an array.`);
|
|
}
|
|
|
|
function ensureStringArray(value, fieldPath) {
|
|
ensureArray(value, fieldPath);
|
|
value.forEach((item, index) => ensureString(item, `${fieldPath}[${index}]`));
|
|
}
|
|
|
|
function validateListOption(option, fieldPath) {
|
|
assert(isPlainObject(option), `${fieldPath} must be an object.`);
|
|
const hasValue = Object.prototype.hasOwnProperty.call(option, 'value');
|
|
assert(hasValue, `${fieldPath}.value is required.`);
|
|
}
|
|
|
|
function validateNamedField(field, fieldPath, allowSource) {
|
|
assert(isPlainObject(field), `${fieldPath} must be an object.`);
|
|
ensureString(field.name, `${fieldPath}.name`);
|
|
ensureString(field.type, `${fieldPath}.type`);
|
|
ensureBoolean(field.required, `${fieldPath}.required`);
|
|
ensureString(field.description, `${fieldPath}.description`);
|
|
|
|
if (allowSource && Object.prototype.hasOwnProperty.call(field, 'source')) {
|
|
ensureString(field.source, `${fieldPath}.source`);
|
|
}
|
|
|
|
if (Object.prototype.hasOwnProperty.call(field, 'list')) {
|
|
ensureArray(field.list, `${fieldPath}.list`);
|
|
field.list.forEach((item, index) => validateListOption(item, `${fieldPath}.list[${index}]`));
|
|
}
|
|
}
|
|
|
|
function validateErrorField(field, fieldPath) {
|
|
assert(isPlainObject(field), `${fieldPath} must be an object.`);
|
|
assert(Object.prototype.hasOwnProperty.call(field, 'code'), `${fieldPath}.code is required.`);
|
|
ensureString(field.message, `${fieldPath}.message`);
|
|
}
|
|
|
|
function validateMethodDoc(methodDoc, fieldPath) {
|
|
assert(isPlainObject(methodDoc), `${fieldPath} must be an object.`);
|
|
ensureString(methodDoc.method, `${fieldPath}.method`);
|
|
ensureString(methodDoc.description, `${fieldPath}.description`);
|
|
ensureBoolean(methodDoc.isNeedAuth, `${fieldPath}.isNeedAuth`);
|
|
ensureBoolean(methodDoc.isNeedLogin, `${fieldPath}.isNeedLogin`);
|
|
ensureArray(methodDoc.headers, `${fieldPath}.headers`);
|
|
ensureArray(methodDoc.params, `${fieldPath}.params`);
|
|
ensureArray(methodDoc.response, `${fieldPath}.response`);
|
|
ensureArray(methodDoc.errors, `${fieldPath}.errors`);
|
|
|
|
methodDoc.headers.forEach((item, index) => validateNamedField(item, `${fieldPath}.headers[${index}]`, false));
|
|
methodDoc.params.forEach((item, index) => validateNamedField(item, `${fieldPath}.params[${index}]`, true));
|
|
methodDoc.response.forEach((item, index) => validateNamedField(item, `${fieldPath}.response[${index}]`, false));
|
|
methodDoc.errors.forEach((item, index) => validateErrorField(item, `${fieldPath}.errors[${index}]`));
|
|
}
|
|
|
|
function validateChange(change, fieldPath) {
|
|
assert(isPlainObject(change), `${fieldPath} must be an object.`);
|
|
ensureString(change.version, `${fieldPath}.version`);
|
|
ensureString(change.date, `${fieldPath}.date`);
|
|
ensureString(change.summary, `${fieldPath}.summary`);
|
|
ensureStringArray(change.methods, `${fieldPath}.methods`);
|
|
ensureStringArray(change.notes, `${fieldPath}.notes`);
|
|
|
|
if (Object.prototype.hasOwnProperty.call(change, 'type')) {
|
|
ensureString(change.type, `${fieldPath}.type`);
|
|
}
|
|
}
|
|
|
|
function validateCurrentDoc(doc, fieldPath) {
|
|
assert(isPlainObject(doc), `${fieldPath} must be an object.`);
|
|
assert(isPlainObject(doc.methods), `${fieldPath}.methods must be an object.`);
|
|
ensureArray(doc.methods.groups, `${fieldPath}.methods.groups`);
|
|
}
|
|
|
|
function validateCurrentChanges(changes, fieldPath) {
|
|
ensureArray(changes, fieldPath);
|
|
}
|
|
|
|
function validateSpec(spec, args) {
|
|
assert(isPlainObject(spec), 'Spec root must be an object.');
|
|
ensureString(spec.docName, 'spec.docName');
|
|
assert(/^[a-z0-9_-]+$/i.test(spec.docName), 'spec.docName must contain only letters, numbers, underscore, or dash.');
|
|
|
|
const docPath = path.join(METHODS_DIR, `${spec.docName}.json`);
|
|
const changePath = path.join(CHANGES_DIR, `${spec.docName}.json`);
|
|
|
|
assert(fs.existsSync(docPath), `Target doc file not found: ${docPath}`);
|
|
if (!args.docOnly) {
|
|
assert(fs.existsSync(changePath), `Target change file not found: ${changePath}`);
|
|
}
|
|
|
|
if (Object.prototype.hasOwnProperty.call(spec, 'docMeta')) {
|
|
assert(isPlainObject(spec.docMeta), 'spec.docMeta must be an object.');
|
|
if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'updatedAt')) {
|
|
ensureString(spec.docMeta.updatedAt, 'spec.docMeta.updatedAt');
|
|
}
|
|
if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'version')) {
|
|
ensureString(spec.docMeta.version, 'spec.docMeta.version');
|
|
}
|
|
}
|
|
|
|
assert(isPlainObject(spec.group), 'spec.group must be an object.');
|
|
ensureString(spec.group.groupName, 'spec.group.groupName');
|
|
ensureString(spec.group.module, 'spec.group.module');
|
|
|
|
ensureArray(spec.methods, 'spec.methods');
|
|
assert(spec.methods.length > 0, 'spec.methods must contain at least one method doc.');
|
|
const methodNames = new Set();
|
|
spec.methods.forEach((item, index) => {
|
|
validateMethodDoc(item, `spec.methods[${index}]`);
|
|
assert(!methodNames.has(item.method), `Duplicate method in spec.methods: ${item.method}`);
|
|
methodNames.add(item.method);
|
|
});
|
|
|
|
if (!args.docOnly) {
|
|
validateChange(spec.change, 'spec.change');
|
|
} else if (Object.prototype.hasOwnProperty.call(spec, 'change')) {
|
|
validateChange(spec.change, 'spec.change');
|
|
}
|
|
|
|
return {
|
|
docName: spec.docName,
|
|
docPath,
|
|
changePath,
|
|
docMeta: spec.docMeta || {},
|
|
group: spec.group,
|
|
methods: spec.methods,
|
|
change: spec.change || null,
|
|
};
|
|
}
|
|
|
|
function findGroupIndex(groups, groupSpec) {
|
|
const byModule = groups.findIndex(group => group && group.module === groupSpec.module);
|
|
if (byModule >= 0) return byModule;
|
|
return groups.findIndex(group => group && group.groupName === groupSpec.groupName);
|
|
}
|
|
|
|
function findMethodLocation(groups, methodName) {
|
|
for (let groupIndex = 0; groupIndex < groups.length; groupIndex += 1) {
|
|
const group = groups[groupIndex];
|
|
const list = group && Array.isArray(group.list) ? group.list : [];
|
|
const methodIndex = list.findIndex(item => item && item.method === methodName);
|
|
if (methodIndex >= 0) {
|
|
return { groupIndex, methodIndex };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function cloneJson(value) {
|
|
return JSON.parse(JSON.stringify(value));
|
|
}
|
|
|
|
function applyDocUpdate(doc, groupSpec, methods, docMeta) {
|
|
const groups = doc.methods.groups;
|
|
let groupIndex = findGroupIndex(groups, groupSpec);
|
|
|
|
if (groupIndex < 0) {
|
|
groups.push({
|
|
groupName: groupSpec.groupName,
|
|
module: groupSpec.module,
|
|
list: [],
|
|
});
|
|
groupIndex = groups.length - 1;
|
|
}
|
|
|
|
const targetGroup = groups[groupIndex];
|
|
targetGroup.groupName = groupSpec.groupName;
|
|
targetGroup.module = groupSpec.module;
|
|
if (!Array.isArray(targetGroup.list)) {
|
|
targetGroup.list = [];
|
|
}
|
|
|
|
const summary = {
|
|
inserted: [],
|
|
updated: [],
|
|
moved: [],
|
|
};
|
|
|
|
for (const methodDoc of methods) {
|
|
const nextMethod = cloneJson(methodDoc);
|
|
const existingLocation = findMethodLocation(groups, methodDoc.method);
|
|
|
|
if (!existingLocation) {
|
|
targetGroup.list.push(nextMethod);
|
|
summary.inserted.push(methodDoc.method);
|
|
continue;
|
|
}
|
|
|
|
if (existingLocation.groupIndex === groupIndex) {
|
|
targetGroup.list[existingLocation.methodIndex] = nextMethod;
|
|
summary.updated.push(methodDoc.method);
|
|
continue;
|
|
}
|
|
|
|
groups[existingLocation.groupIndex].list.splice(existingLocation.methodIndex, 1);
|
|
targetGroup.list.push(nextMethod);
|
|
summary.moved.push(methodDoc.method);
|
|
}
|
|
|
|
if (docMeta.updatedAt) {
|
|
doc.updatedAt = docMeta.updatedAt;
|
|
}
|
|
|
|
if (docMeta.version) {
|
|
doc.version = docMeta.version;
|
|
}
|
|
|
|
return summary;
|
|
}
|
|
|
|
function appendChange(changes, change) {
|
|
const exists = changes.some(item => item && item.version === change.version);
|
|
assert(!exists, `Duplicate change version detected: ${change.version}`);
|
|
changes.push(cloneJson(change));
|
|
}
|
|
|
|
function main() {
|
|
const args = parseArgs(process.argv.slice(2));
|
|
if (args.help) {
|
|
printHelp();
|
|
return;
|
|
}
|
|
|
|
assert(fs.existsSync(args.specPath), `Spec file not found: ${args.specPath}`);
|
|
|
|
const specRaw = fs.readFileSync(args.specPath, 'utf8');
|
|
const spec = JSON.parse(specRaw);
|
|
const normalized = validateSpec(spec, args);
|
|
|
|
const docState = readJsonFile(normalized.docPath);
|
|
validateCurrentDoc(docState.json, normalized.docPath);
|
|
|
|
let changeState = null;
|
|
if (!args.docOnly) {
|
|
changeState = readJsonFile(normalized.changePath);
|
|
validateCurrentChanges(changeState.json, normalized.changePath);
|
|
}
|
|
|
|
const docNext = cloneJson(docState.json);
|
|
const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta);
|
|
JSON.parse(JSON.stringify(docNext));
|
|
|
|
let changeNext = null;
|
|
if (!args.docOnly) {
|
|
changeNext = cloneJson(changeState.json);
|
|
appendChange(changeNext, normalized.change);
|
|
JSON.parse(JSON.stringify(changeNext));
|
|
}
|
|
|
|
console.log(`docName: ${normalized.docName}`);
|
|
console.log(`group: ${normalized.group.module} (${normalized.group.groupName})`);
|
|
console.log(`inserted: ${summary.inserted.length ? summary.inserted.join(', ') : '-'}`);
|
|
console.log(`updated: ${summary.updated.length ? summary.updated.join(', ') : '-'}`);
|
|
console.log(`moved: ${summary.moved.length ? summary.moved.join(', ') : '-'}`);
|
|
if (!args.docOnly && normalized.change) {
|
|
console.log(`change version: ${normalized.change.version}`);
|
|
}
|
|
|
|
if (args.dryRun) {
|
|
console.log('dry-run: validated successfully, no files were written.');
|
|
return;
|
|
}
|
|
|
|
writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol);
|
|
console.log(`wrote: ${path.relative(ROOT, normalized.docPath)}`);
|
|
|
|
if (!args.docOnly) {
|
|
writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol);
|
|
console.log(`wrote: ${path.relative(ROOT, normalized.changePath)}`);
|
|
}
|
|
}
|
|
|
|
if (require.main === module) {
|
|
try {
|
|
main();
|
|
} catch (error) {
|
|
console.error(error.message || error);
|
|
process.exitCode = 1;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
applyDocUpdate,
|
|
parseArgs,
|
|
validateSpec,
|
|
}; |