#!/usr/bin/env node /** * 验证 TypeScript 实现与 AsyncAPI 规范的一致性 */ import { Parser } from '@asyncapi/parser'; import * as fs from 'fs'; import * as path from 'path'; import { MessageType, RegisterMessage, CommandMessage } from '../src/index'; async function validateProtocolConsistency() { // 1. 解析 AsyncAPI 文档 const parser = new Parser(); const asyncApiPath = path.join(__dirname, '../../jrsoft-subway-gateway/asyncapi.yaml'); const asyncApiContent = fs.readFileSync(asyncApiPath, 'utf8'); const { document, diagnostics } = await parser.parse(asyncApiContent); if (diagnostics.length > 0) { console.error('AsyncAPI parsing errors:', diagnostics); return false; } // 2. 提取 AsyncAPI 中定义的消息类型 const asyncApiMessages = new Set(); const channels = document?.channels(); if (channels) { for (const [channelName, channel] of Object.entries(channels)) { const publish = channel.publish(); const subscribe = channel.subscribe(); [publish, subscribe].forEach(operation => { if (operation?.messages()) { operation.messages().forEach(msg => { const payload = msg.payload(); if (payload?.properties?.type?.const) { asyncApiMessages.add(payload.properties.type.const); } }); } }); } } // 3. 比较 TypeScript 枚举与 AsyncAPI 定义 const tsMessageTypes = Object.values(MessageType); const missingInAsyncApi = tsMessageTypes.filter(type => !asyncApiMessages.has(type)); const missingInTypeScript = Array.from(asyncApiMessages).filter(type => !tsMessageTypes.includes(type as any)); // 4. 输出验证结果 console.log('=== Protocol Validation Results ==='); console.log(`TypeScript message types: ${tsMessageTypes.length}`); console.log(`AsyncAPI message types: ${asyncApiMessages.size}`); if (missingInAsyncApi.length > 0) { console.error('❌ Missing in AsyncAPI:', missingInAsyncApi); } if (missingInTypeScript.length > 0) { console.error('❌ Missing in TypeScript:', missingInTypeScript); } if (missingInAsyncApi.length === 0 && missingInTypeScript.length === 0) { console.log('✅ All message types are synchronized!'); } return missingInAsyncApi.length === 0 && missingInTypeScript.length === 0; } // 运行验证 validateProtocolConsistency().then(isValid => { process.exit(isValid ? 0 : 1); });