├── .npmrc ├── src ├── constants.ts ├── utils │ ├── retrieve-language.ts │ ├── ajv.ts │ ├── tests │ │ ├── temp-dir.test.ts │ │ ├── app-openapi.test.ts │ │ └── retrieve-language.test.ts │ ├── temp-dir.ts │ ├── app-openapi.ts │ ├── logger.ts │ └── parser.ts ├── server-api.d.ts ├── configs │ ├── test.json │ ├── production.json │ └── development.json ├── exceptions │ └── problem.exception.ts ├── interfaces.ts ├── controllers │ ├── docs.controller.ts │ ├── validate.controller.ts │ ├── parse.controller.ts │ ├── diff.controller.ts │ ├── bundle.controller.ts │ ├── convert.controller.ts │ ├── tests │ │ ├── parse.controller.test.ts │ │ ├── help.controller.test.ts │ │ ├── diff.controller.test.ts │ │ ├── generate.controller.test.ts │ │ ├── convert.controller.test.ts │ │ ├── validate.controller.test.ts │ │ └── bundle.controller.test.ts │ ├── help.controller.ts │ └── generate.controller.ts ├── services │ ├── generator.service.ts │ ├── tests │ │ ├── generator.service.test.ts │ │ └── convert.service.test.ts │ ├── archiver.service.ts │ └── convert.service.ts ├── middlewares │ ├── problem.middleware.ts │ ├── tests │ │ ├── problem.middleware.test.ts │ │ └── validation.middleware.test.ts │ └── validation.middleware.ts ├── server.ts └── app.ts ├── .eslintignore ├── .dockerignore ├── deployments └── apps │ ├── .gitignore │ ├── .terraform.lock.hcl │ └── main.tf ├── .gitignore ├── .github ├── assets │ └── banner.png └── workflows │ ├── scripts │ ├── README.md │ └── mailchimp │ │ ├── package.json │ │ └── index.js │ ├── update-maintainers-trigger.yaml │ ├── automerge-for-humans-remove-ready-to-merge-label-on-edit.yml │ ├── autoupdate.yml │ ├── release-docker.yml │ ├── bump.yml │ ├── automerge.yml │ ├── please-take-a-look-command.yml │ ├── transfer-issue.yml │ ├── lint-pr-title.yml │ ├── stale-issues-prs.yml │ ├── if-docker-pr-testing.yml │ ├── automerge-orphans.yml │ ├── add-good-first-issue-labels.yml │ ├── if-nodejs-pr-testing.yml │ ├── help-command.yml │ ├── if-nodejs-version-bump.yml │ ├── issues-prs-notifications.yml │ ├── automerge-for-humans-merging.yml │ ├── welcome-first-time-contrib.yml │ ├── update-pr.yml │ ├── bounty-program-commands.yml │ ├── release-announcements.yml │ ├── automerge-for-humans-add-ready-to-merge-or-do-not-merge-label.yml │ └── if-nodejs-release.yml ├── tsconfig.test.json ├── NOTICE ├── tests ├── jest.setup.ts └── test.controller.ts ├── .sonarcloud.properties ├── .asyncapi-tool.yaml ├── nodemon.json ├── tsconfig.json ├── CODEOWNERS ├── .releaserc ├── jest.config.js ├── Dockerfile ├── .all-contributorsrc ├── .eslintrc ├── package.json ├── CONTRIBUTING.md ├── README.md └── CODE_OF_CONDUCT.md /.npmrc: -------------------------------------------------------------------------------- 1 | access=public -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | export const API_VERSION = 'v1'; -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | public 3 | docs 4 | lib 5 | dist 6 | build 7 | dist 8 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | Dockerfile 4 | .dockerignore 5 | .git 6 | -------------------------------------------------------------------------------- /deployments/apps/.gitignore: -------------------------------------------------------------------------------- 1 | .terraform 2 | terraform.tfstate 3 | terraform.tfstate.backup 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode 3 | coverage 4 | lib 5 | dist 6 | examples 7 | logs 8 | *.DS_Store -------------------------------------------------------------------------------- /.github/assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asyncapi-archived-repos/server-api/HEAD/.github/assets/banner.png -------------------------------------------------------------------------------- /tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src/*.ts", "src/**/*.ts", "tests/*.ts", "tests/**/*.ts"], 4 | } -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2016-2025 AsyncAPI Initiative 2 | 3 | This product includes software developed at 4 | AsyncAPI Initiative (http://www.asyncapi.com/). -------------------------------------------------------------------------------- /tests/jest.setup.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | 3 | // for `config` module 4 | process.env['NODE_CONFIG_DIR'] = path.join(__dirname, '../src/configs'); 5 | -------------------------------------------------------------------------------- /.sonarcloud.properties: -------------------------------------------------------------------------------- 1 | # Disable duplicate code in tests since it would introduce more complexity to reduce it. 2 | sonar.cpd.exclusions=**/*.test.ts,**/*.spec.ts -------------------------------------------------------------------------------- /src/utils/retrieve-language.ts: -------------------------------------------------------------------------------- 1 | export function retrieveLangauge(content: string): 'json' | 'yaml' { 2 | if (content.trim()[0] === '{') { 3 | return 'json'; 4 | } 5 | return 'yaml'; 6 | } -------------------------------------------------------------------------------- /.asyncapi-tool.yaml: -------------------------------------------------------------------------------- 1 | title: AsyncAPI Server API 2 | links: 3 | docsUrl: https://api.asyncapi.com/v1/docs 4 | filters: 5 | technology: 6 | - Node.js 7 | - TypeScript 8 | categories: 9 | - api -------------------------------------------------------------------------------- /.github/workflows/scripts/README.md: -------------------------------------------------------------------------------- 1 | The entire `scripts` directory is centrally managed in [.github](https://github.com/asyncapi/.github/) repository. Any changes in this folder should be done in central repository. -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": [ 3 | "src", 4 | ".env" 5 | ], 6 | "ext": "js,ts,json", 7 | "ignore": [ 8 | "src/**/*.spec.ts", 9 | "src/**/*.test.ts" 10 | ], 11 | "exec": "ts-node --transpile-only src/server.ts" 12 | } -------------------------------------------------------------------------------- /src/server-api.d.ts: -------------------------------------------------------------------------------- 1 | import { AsyncAPIDocument } from '@asyncapi/parser'; 2 | 3 | declare module 'express' { 4 | export interface Request { 5 | asyncapi?: { 6 | parsedDocument?: AsyncAPIDocument; 7 | parsedDocuments?: Array; 8 | }, 9 | } 10 | } -------------------------------------------------------------------------------- /src/configs/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": "test", 3 | "log": { 4 | "format": "dev", 5 | "dir": "../logs" 6 | }, 7 | "cors": { 8 | "origin": true, 9 | "credentials": false 10 | }, 11 | "request": { 12 | "body": { 13 | "limit": "5mb" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/configs/production.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": "production", 3 | "log": { 4 | "format": "combined", 5 | "dir": "../logs" 6 | }, 7 | "cors": { 8 | "origin": true, 9 | "credentials": false 10 | }, 11 | "request": { 12 | "body": { 13 | "limit": "5mb" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/configs/development.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": "development", 3 | "log": { 4 | "format": "dev", 5 | "dir": "../logs" 6 | }, 7 | "cors": { 8 | "origin": true, 9 | "credentials": false 10 | }, 11 | "request": { 12 | "body": { 13 | "limit": "5mb" 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/exceptions/problem.exception.ts: -------------------------------------------------------------------------------- 1 | import { ProblemMixin } from '@asyncapi/problem'; 2 | 3 | export interface ProblemExceptionProps { 4 | status: number; 5 | [key: string]: any; 6 | } 7 | 8 | const typePrefix = 'https://api.asyncapi.com/problem'; 9 | 10 | export class ProblemException extends ProblemMixin({ typePrefix }) {} 11 | -------------------------------------------------------------------------------- /.github/workflows/scripts/mailchimp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "schedule-email", 3 | "description": "This code is responsible for scheduling an email campaign. This file is centrally managed in https://github.com/asyncapi/.github/", 4 | "license": "Apache 2.0", 5 | "dependencies": { 6 | "@actions/core": "1.6.0", 7 | "@mailchimp/mailchimp_marketing": "3.0.74" 8 | } 9 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist", 4 | "module": "commonjs", 5 | "target": "es6", 6 | "rootDir": "./src", 7 | "resolveJsonModule": true, 8 | "esModuleInterop": true, 9 | }, 10 | "include": ["src/*.ts", "src/**/*.ts"], 11 | "exclude": ["src/*.test.ts", "src/**/*.test.ts", "src/*.spec.ts", "src/**/*.spec.ts", "tests/*.ts", "tests/**/*.ts"] 12 | } -------------------------------------------------------------------------------- /src/utils/ajv.ts: -------------------------------------------------------------------------------- 1 | import Ajv from 'ajv'; 2 | import addFormats from 'ajv-formats'; 3 | 4 | import type AjvCore from 'ajv/dist/core'; 5 | 6 | export function createAjvInstance(): AjvCore { 7 | const ajv = new Ajv({ 8 | allErrors: true, 9 | meta: true, 10 | strict: false, 11 | allowUnionTypes: true, 12 | logger: false, 13 | unicodeRegExp: false, 14 | }); 15 | addFormats(ajv); 16 | return ajv; 17 | } 18 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # This file provides an overview of code owners in this repository. 2 | 3 | # Each line is a file pattern followed by one or more owners. 4 | # The last matching pattern has the most precedence. 5 | # For more details, read the following article on GitHub: https://help.github.com/articles/about-codeowners/. 6 | 7 | # The default owners are automatically added as reviewers when you open a pull request unless different owners are specified in the file. 8 | 9 | * @smoya @BOLT04 @magicmatatjahu @asyncapi-bot-eve 10 | -------------------------------------------------------------------------------- /src/utils/tests/temp-dir.test.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import { createTempDirectory, removeTempDirectory } from '../temp-dir'; 3 | 4 | describe('createTempDirectory() & removeTempDirectory()', () => { 5 | test('should create and then remove temp folder', async () => { 6 | // create dir 7 | const tempDir = await createTempDirectory(); 8 | expect(fs.existsSync(tempDir)).toEqual(true); 9 | 10 | // remove dir 11 | await removeTempDirectory(tempDir); 12 | expect(fs.existsSync(tempDir)).toEqual(false); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/utils/tests/app-openapi.test.ts: -------------------------------------------------------------------------------- 1 | import { getAppOpenAPI } from '../app-openapi'; 2 | 3 | describe('getAppOpenAPI()', () => { 4 | test('should return OpenAPI document as JSON', async () => { 5 | const openapi = await getAppOpenAPI(); 6 | expect(openapi.openapi).toEqual('3.1.0'); 7 | expect(openapi.info.title).toEqual('AsyncAPI Server API'); 8 | }); 9 | 10 | test('should return always this same instance of JSON', async () => { 11 | const openapi1 = await getAppOpenAPI(); 12 | const openapi2 = await getAppOpenAPI(); 13 | // assert references 14 | expect(openapi1 === openapi2).toEqual(true); 15 | }); 16 | }); -------------------------------------------------------------------------------- /src/utils/temp-dir.ts: -------------------------------------------------------------------------------- 1 | import os from 'os'; 2 | import fs, { promises as fsp } from 'fs'; 3 | import path from 'path'; 4 | import { v4 as uuidv4 } from 'uuid'; 5 | 6 | import { logger } from './logger'; 7 | 8 | export function createTempDirectory() { 9 | return fsp.mkdtemp(path.join(os.tmpdir(), uuidv4())); 10 | } 11 | 12 | export async function removeTempDirectory(tmpDir: string) { 13 | try { 14 | tmpDir && fs.existsSync(tmpDir) && await fsp.rm(tmpDir, { recursive: true }); 15 | } catch (e) { 16 | logger.error(`An error has occurred while removing the temp folder at ${tmpDir}. Please remove it manually. Error: ${e}`); 17 | } 18 | } -------------------------------------------------------------------------------- /src/interfaces.ts: -------------------------------------------------------------------------------- 1 | import specs from '@asyncapi/specs'; 2 | import { Router } from 'express'; 3 | 4 | export interface Controller { 5 | basepath: string; 6 | boot(): Router | Promise; 7 | } 8 | 9 | export interface Problem { 10 | type: string; 11 | title: string; 12 | status: number; 13 | detail?: string; 14 | instance?: string; 15 | [key: string]: any; 16 | } 17 | 18 | export type AsyncAPIDocument = { asyncapi: string } & Record; 19 | 20 | export const ALL_SPECS = [...Object.keys(specs)]; 21 | export const LAST_SPEC_VERSION = ALL_SPECS[ALL_SPECS.length - 1]; 22 | 23 | export type SpecsEnum = keyof typeof specs | 'latest'; 24 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | --- 2 | branches: 3 | - master 4 | # by default release workflow reacts on push not only to master. 5 | #This is why out of the box sematic release is configured for all these branches 6 | - name: next-spec 7 | prerelease: true 8 | - name: next-major 9 | prerelease: true 10 | - name: next-major-spec 11 | prerelease: true 12 | - name: beta 13 | prerelease: true 14 | - name: alpha 15 | prerelease: true 16 | - name: next 17 | prerelease: true 18 | plugins: 19 | - - "@semantic-release/commit-analyzer" 20 | - preset: conventionalcommits 21 | - - "@semantic-release/release-notes-generator" 22 | - preset: conventionalcommits 23 | - "@semantic-release/npm" 24 | - "@semantic-release/github" 25 | -------------------------------------------------------------------------------- /src/utils/tests/retrieve-language.test.ts: -------------------------------------------------------------------------------- 1 | import { retrieveLangauge } from '../retrieve-language'; 2 | 3 | describe('retrieveLangauge()', () => { 4 | test('should check that content is yaml', () => { 5 | const result = retrieveLangauge('asyncapi: 2.2.0\nfoobar: barfoo\n'); 6 | expect(result).toEqual('yaml'); 7 | }); 8 | 9 | test('should check that content is json', () => { 10 | const result = retrieveLangauge('{"asyncapi": "2.2.0", "foobar": "barfoo"}'); 11 | expect(result).toEqual('json'); 12 | }); 13 | 14 | test('should check that content is yaml - fallback for non json content', () => { 15 | const result = retrieveLangauge(''); 16 | expect(result).toEqual('yaml'); 17 | }); 18 | }); -------------------------------------------------------------------------------- /src/controllers/docs.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | import redoc from 'redoc-express'; 3 | 4 | import { Controller } from '../interfaces'; 5 | 6 | import { API_VERSION } from '../constants'; 7 | 8 | export class DocsController implements Controller { 9 | public basepath = '/docs'; 10 | 11 | public boot(): Router { 12 | const router = Router(); 13 | 14 | router.get(`${this.basepath}/openapi.yaml`, (_, res) => { 15 | res.sendFile('openapi.yaml', { root: '.' }); 16 | }); 17 | 18 | router.get( 19 | this.basepath, 20 | redoc({ 21 | title: 'OpenAPI Documentation', 22 | specUrl: `/${API_VERSION}${this.basepath}/openapi.yaml` 23 | }), 24 | ); 25 | 26 | return router; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | coverageReporters: ['json-summary', 'lcov', 'text'], 3 | collectCoverageFrom: ['src/**'], 4 | 5 | preset: 'ts-jest', 6 | testEnvironment: 'node', 7 | transform: { 8 | '^.+\\.tsx?$': 'ts-jest', 9 | '^.+\\.ts?$': 'ts-jest', 10 | }, 11 | 12 | // Test spec file resolution pattern 13 | // Matches parent folder `tests` or `__tests__` and filename 14 | // should contain `test` or `spec`. 15 | testMatch: ['**/__tests__/**/*.ts?(x)', '**/?(*.)+(spec|test).ts?(x)'], 16 | // Module file extensions for importing 17 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 18 | 19 | testTimeout: 20000, 20 | 21 | setupFiles: ['./tests/jest.setup.ts'], 22 | globals: { 23 | 'ts-jest': { 24 | tsconfig: 'tsconfig.test.json', 25 | }, 26 | }, 27 | }; 28 | -------------------------------------------------------------------------------- /src/controllers/validate.controller.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, Router } from 'express'; 2 | 3 | import { validationMiddleware } from '../middlewares/validation.middleware'; 4 | 5 | import { Controller } from '../interfaces'; 6 | 7 | /** 8 | * Controller which exposes the Parser functionality, to validate the AsyncAPI document. 9 | */ 10 | export class ValidateController implements Controller { 11 | public basepath = '/validate'; 12 | 13 | private async validate(_: Request, res: Response) { 14 | res.status(204).end(); 15 | } 16 | 17 | public async boot(): Promise { 18 | const router = Router(); 19 | 20 | router.post( 21 | `${this.basepath}`, 22 | await validationMiddleware({ 23 | path: this.basepath, 24 | method: 'post', 25 | documents: ['asyncapi'], 26 | }), 27 | this.validate.bind(this) 28 | ); 29 | 30 | return router; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/utils/app-openapi.ts: -------------------------------------------------------------------------------- 1 | import { promises as fs } from 'fs'; 2 | import path from 'path'; 3 | 4 | import YAML from 'js-yaml'; 5 | import $RefParser from '@apidevtools/json-schema-ref-parser'; 6 | 7 | let parsedOpenAPI = undefined; 8 | 9 | /** 10 | * Retrieve application's OpenAPI document. 11 | */ 12 | export async function getAppOpenAPI(): Promise { 13 | if (parsedOpenAPI) { 14 | return parsedOpenAPI; 15 | } 16 | 17 | const openaAPI = await fs.readFile(path.join(__dirname, '../../openapi.yaml'), 'utf-8'); 18 | parsedOpenAPI = YAML.load(openaAPI); 19 | // due to the fact that `@asyncapi/specs: 3.0.0` have moved to a new way of bundling schemas, it makes no sense to resolve the references for AsyncAPI specs 20 | parsedOpenAPI.components.schemas.AsyncAPIDocument.oneOf = { type: ['string', 'object'] }; 21 | const refParser = new $RefParser; 22 | await refParser.dereference(parsedOpenAPI); 23 | 24 | return parsedOpenAPI; 25 | } 26 | -------------------------------------------------------------------------------- /tests/test.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | 3 | import { Controller } from '../src/interfaces'; 4 | 5 | interface Path { 6 | path: string, 7 | method: 'all' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head', 8 | callback: (req: Request, res: Response, next: NextFunction) => any; 9 | middlewares?: Array<(req: Request, res: Response, next: NextFunction) => any>; 10 | } 11 | 12 | export function createTestController(paths: Path | Path[]) { 13 | return class implements Controller { 14 | public basepath = '/'; 15 | 16 | public boot(): Router { 17 | const router = Router(); 18 | 19 | const p = Array.isArray(paths) ? paths : [paths]; 20 | p.forEach(path => { 21 | router[path.method]( 22 | path.path, 23 | ...(path.middlewares || []), 24 | path.callback, 25 | ); 26 | }); 27 | 28 | return router; 29 | } 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /src/utils/logger.ts: -------------------------------------------------------------------------------- 1 | import config from 'config'; 2 | import fs from 'fs'; 3 | import path from 'path'; 4 | import winston from 'winston'; 5 | 6 | const logDir: string = path.join(__dirname, config.get('log.dir')); 7 | if (!fs.existsSync(logDir)) { 8 | fs.mkdirSync(logDir); 9 | } 10 | 11 | /* 12 | * Log Level 13 | * error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 14 | */ 15 | const logger = winston.createLogger({ 16 | format: winston.format.combine( 17 | winston.format.timestamp({ 18 | format: 'YYYY-MM-DD HH:mm:ss', 19 | }), 20 | // Define log format 21 | winston.format.printf(({ timestamp, level, message }) => `${timestamp} ${level}: ${message}`), 22 | ), 23 | }); 24 | 25 | logger.add( 26 | new winston.transports.Console({ 27 | format: winston.format.combine(winston.format.splat(), winston.format.colorize()), 28 | }), 29 | ); 30 | 31 | const stream = { 32 | write: (message: string) => { 33 | logger.info(message.substring(0, message.lastIndexOf('\n'))); 34 | }, 35 | }; 36 | 37 | export { logger, stream }; -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # ---- Base Alpine with installed Node ---- 2 | FROM node:14-alpine3.14 AS base 3 | 4 | # install node 5 | RUN apk add --update \ 6 | nghttp2 7 | 8 | # ---- Install dependencies ---- 9 | FROM base AS build 10 | 11 | WORKDIR /app 12 | COPY . . 13 | 14 | # install dependencies 15 | # remove package-lock.json with lockVersion: 1 due to problem described in the https://github.com/asyncapi/.github/issues/123 16 | # remove first run and switch to the `npm ci` when mentioned issue will be resolved 17 | RUN rm package-lock.json; npm install 18 | 19 | # build to a production Javascript 20 | RUN npm run build:prod 21 | 22 | # ---- Serve ---- 23 | FROM base AS release 24 | 25 | WORKDIR /app 26 | COPY --from=build /app/dist ./dist 27 | # A wildcard is used to ensure both package.json AND package-lock.json are copied 28 | COPY --from=build /app/package* ./ 29 | # install only production dependencies (defined in "dependencies") 30 | RUN npm ci --only=production 31 | # copy OpenaAPI document 32 | COPY openapi.yaml ./ 33 | 34 | EXPOSE 80 35 | CMD ["npm", "run", "start:docker"] -------------------------------------------------------------------------------- /src/controllers/parse.controller.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, Router } from 'express'; 2 | import { AsyncAPIDocument } from '@asyncapi/parser'; 3 | 4 | import { validationMiddleware } from '../middlewares/validation.middleware'; 5 | 6 | import { Controller} from '../interfaces'; 7 | 8 | /** 9 | * Controller which exposes the Parser functionality, to parse the AsyncAPI document. 10 | */ 11 | export class ParseController implements Controller { 12 | public basepath = '/parse'; 13 | 14 | private async parse(req: Request, res: Response) { 15 | const stringified = AsyncAPIDocument.stringify(req.asyncapi?.parsedDocument); 16 | res.status(200).json({ 17 | parsed: stringified, 18 | }); 19 | } 20 | 21 | public async boot(): Promise { 22 | const router = Router(); 23 | 24 | router.post( 25 | `${this.basepath}`, 26 | await validationMiddleware({ 27 | path: this.basepath, 28 | method: 'post', 29 | documents: ['asyncapi'], 30 | }), 31 | this.parse.bind(this) 32 | ); 33 | 34 | return router; 35 | } 36 | } -------------------------------------------------------------------------------- /src/services/generator.service.ts: -------------------------------------------------------------------------------- 1 | // @ts-ignore 2 | import AsyncAPIGenerator from '@asyncapi/generator'; 3 | import { AsyncAPIDocument } from '@asyncapi/parser'; 4 | 5 | import { prepareParserConfig } from '../utils/parser'; 6 | 7 | /** 8 | * Service providing `@asyncapi/generate` functionality. 9 | */ 10 | export class GeneratorService { 11 | public async generate( 12 | asyncapi: AsyncAPIDocument | string, 13 | template: string, 14 | parameters: Record, 15 | destDir: string, 16 | parserOptions: ReturnType, 17 | ) { 18 | const generator = new AsyncAPIGenerator(template, destDir, { 19 | forceWrite: true, 20 | templateParams: parameters, 21 | }); 22 | 23 | if (typeof asyncapi === 'string') { 24 | await generator.generateFromString(asyncapi, parserOptions); 25 | } else if (asyncapi instanceof AsyncAPIDocument) { 26 | await generator.generate(asyncapi); 27 | } else { // object case 28 | await generator.generateFromString(JSON.stringify(asyncapi), parserOptions); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/middlewares/problem.middleware.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response } from 'express'; 2 | 3 | import { ProblemException } from '../exceptions/problem.exception'; 4 | import { logger } from '../utils/logger'; 5 | 6 | /** 7 | * Catch problem exception, log it and serialize error to human readable form. 8 | */ 9 | export function problemMiddleware(error: ProblemException, req: Request, res: Response, next: NextFunction) { 10 | if (res.headersSent) { 11 | return next(error); 12 | } 13 | 14 | try { 15 | const problemShape = error.get(); 16 | const status = problemShape.status = problemShape.status || 500; 17 | problemShape.title = problemShape.title || 'Internal server error'; 18 | 19 | logger.error(`[${req.method}] ${req.path} >> Status:: ${status}, Type:: ${problemShape.type.replace('https://api.asyncapi.com/problem/', '')}, Title:: ${problemShape.title}, Detail:: ${problemShape.detail}`); 20 | 21 | const isError = status >= 500; 22 | const problem = error.toObject({ includeStack: isError, includeCause: isError }); 23 | res.status(status).json(problem); 24 | } catch (err: unknown) { 25 | next(err); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/server.ts: -------------------------------------------------------------------------------- 1 | // include production config in the `dist` folder 2 | import './configs/production.json'; 3 | 4 | // for `config` module 5 | process.env['NODE_CONFIG_DIR'] = `${__dirname}/configs`; 6 | 7 | import { App } from './app'; 8 | import { ValidateController } from './controllers/validate.controller'; 9 | import { ParseController } from './controllers/parse.controller'; 10 | import { GenerateController } from './controllers/generate.controller'; 11 | import { ConvertController } from './controllers/convert.controller'; 12 | import { BundleController } from './controllers/bundle.controller'; 13 | import { DiffController } from './controllers/diff.controller'; 14 | import { DocsController } from './controllers/docs.controller'; 15 | import { HelpController } from './controllers/help.controller'; 16 | 17 | async function main() { 18 | const app = new App([ 19 | new ValidateController(), 20 | new ParseController(), 21 | new GenerateController(), 22 | new ConvertController(), 23 | new BundleController(), 24 | new DiffController(), 25 | new DocsController(), 26 | new HelpController(), 27 | ]); 28 | await app.init(); 29 | app.listen(); 30 | } 31 | main(); 32 | -------------------------------------------------------------------------------- /.github/workflows/update-maintainers-trigger.yaml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Trigger MAINTAINERS.yaml file update 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | paths: 10 | # Check all valid CODEOWNERS locations: 11 | # https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners#codeowners-file-location 12 | - 'CODEOWNERS' 13 | - '.github/CODEOWNERS' 14 | - '.docs/CODEOWNERS' 15 | 16 | jobs: 17 | trigger-maintainers-update: 18 | name: Trigger updating MAINTAINERS.yaml because of CODEOWNERS change 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | - name: Repository Dispatch 23 | uses: peter-evans/repository-dispatch@ff45666b9427631e3450c54a1bcbee4d9ff4d7c0 # https://github.com/peter-evans/repository-dispatch/releases/tag/v3.0.0 24 | with: 25 | # The PAT with the 'public_repo' scope is required 26 | token: ${{ secrets.GH_TOKEN }} 27 | repository: ${{ github.repository_owner }}/community 28 | event-type: trigger-maintainers-update 29 | -------------------------------------------------------------------------------- /.github/workflows/automerge-for-humans-remove-ready-to-merge-label-on-edit.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Defence from evil contributor that after adding `ready-to-merge` all suddenly makes evil commit or evil change in PR title 5 | # Label is removed once above action is detected 6 | name: Remove ready-to-merge label 7 | 8 | on: 9 | pull_request_target: 10 | types: 11 | - synchronize 12 | - edited 13 | 14 | jobs: 15 | remove-ready-label: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Remove label 19 | uses: actions/github-script@v7 20 | with: 21 | github-token: ${{ secrets.GH_TOKEN }} 22 | script: | 23 | const labelToRemove = 'ready-to-merge'; 24 | const labels = context.payload.pull_request.labels; 25 | const isLabelPresent = labels.some(label => label.name === labelToRemove) 26 | if(!isLabelPresent) return; 27 | github.rest.issues.removeLabel({ 28 | issue_number: context.issue.number, 29 | owner: context.repo.owner, 30 | repo: context.repo.repo, 31 | name: labelToRemove 32 | }) 33 | -------------------------------------------------------------------------------- /src/controllers/diff.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import { diff } from '@asyncapi/diff'; 3 | 4 | import { validationMiddleware } from '../middlewares/validation.middleware'; 5 | 6 | import { ProblemException } from '../exceptions/problem.exception'; 7 | import { Controller } from '../interfaces'; 8 | 9 | export class DiffController implements Controller { 10 | public basepath = '/diff'; 11 | 12 | private async diff(req: Request, res: Response, next: NextFunction) { 13 | const { asyncapis } = req.body; 14 | 15 | try { 16 | const output = diff(asyncapis[0], asyncapis[1]).getOutput(); 17 | res.status(200).json({ diff: output }); 18 | } catch (err) { 19 | return next( 20 | new ProblemException({ 21 | type: 'internal-diff-error', 22 | title: 'Internal Diff error', 23 | status: 500, 24 | detail: (err as Error).message, 25 | }) 26 | ); 27 | } 28 | } 29 | 30 | public async boot(): Promise { 31 | const router = Router(); 32 | 33 | router.post( 34 | this.basepath, 35 | await validationMiddleware({ 36 | path: this.basepath, 37 | method: 'post', 38 | documents: ['asyncapis'], 39 | }), 40 | this.diff.bind(this) 41 | ); 42 | 43 | return router; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/services/tests/generator.service.test.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | 4 | import { GeneratorService } from '../generator.service'; 5 | import { createTempDirectory, removeTempDirectory } from '../../utils/temp-dir'; 6 | import { prepareParserConfig } from '../../utils/parser'; 7 | 8 | describe('GeneratorService', () => { 9 | const generatorService = new GeneratorService(); 10 | 11 | describe('.generate()', () => { 12 | it('should generate given template to the destination dir', async () => { 13 | const asyncapi = { 14 | asyncapi: '2.2.0', 15 | info: { 16 | title: 'Test Service', 17 | version: '1.0.0', 18 | }, 19 | channels: {}, 20 | }; 21 | const template = '@asyncapi/html-template'; 22 | const parameters = { 23 | version: '2.1.37', 24 | }; 25 | 26 | const tmpDir = await createTempDirectory(); 27 | try { 28 | await generatorService.generate( 29 | JSON.stringify(asyncapi), 30 | template, 31 | parameters, 32 | tmpDir, 33 | prepareParserConfig(), 34 | ); 35 | 36 | expect(fs.existsSync(path.join(tmpDir, 'template'))).toEqual(true); 37 | expect(fs.existsSync(path.join(tmpDir, 'template/index.html'))).toEqual(true); 38 | } catch (e: any) { 39 | await removeTempDirectory(tmpDir); 40 | } 41 | }); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /src/controllers/bundle.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import bundler from '@asyncapi/bundler'; 3 | 4 | import { validationMiddleware } from '../middlewares/validation.middleware'; 5 | 6 | import { ProblemException } from '../exceptions/problem.exception'; 7 | import { Controller } from '../interfaces'; 8 | 9 | export class BundleController implements Controller { 10 | public basepath = '/bundle'; 11 | 12 | private async bundle(req: Request, res: Response, next: NextFunction) { 13 | const asyncapis: Array = req.body.asyncapis; 14 | const base = req.body.base; 15 | 16 | try { 17 | const document = await bundler(asyncapis, { base }); 18 | const bundled = document.json(); 19 | res.status(200).json({ bundled }); 20 | } catch (err) { 21 | return next( 22 | new ProblemException({ 23 | type: 'internal-bundler-error', 24 | title: 'Internal Bundler error', 25 | status: 500, 26 | detail: (err as Error).message, 27 | }) 28 | ); 29 | } 30 | } 31 | 32 | public async boot(): Promise { 33 | const router = Router(); 34 | 35 | router.post( 36 | this.basepath, 37 | await validationMiddleware({ 38 | path: this.basepath, 39 | method: 'post', 40 | documents: ['asyncapis', 'base'], 41 | }), 42 | this.bundle.bind(this) 43 | ); 44 | 45 | return router; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.github/workflows/autoupdate.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # This workflow is designed to work with: 5 | # - autoapprove and automerge workflows for dependabot and asyncapibot. 6 | # - special release branches that we from time to time create in upstream repos. If we open up PRs for them from the very beginning of the release, the release branch will constantly update with new things from the destination branch they are opened against 7 | 8 | # It uses GitHub Action that auto-updates pull requests branches, whenever changes are pushed to their destination branch. 9 | # Autoupdating to latest destination branch works only in the context of upstream repo and not forks 10 | 11 | name: autoupdate 12 | 13 | on: 14 | push: 15 | branches-ignore: 16 | - 'version-bump/**' 17 | - 'dependabot/**' 18 | - 'bot/**' 19 | - 'all-contributors/**' 20 | 21 | jobs: 22 | autoupdate-for-bot: 23 | if: startsWith(github.repository, 'asyncapi/') 24 | name: Autoupdate autoapproved PR created in the upstream 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Autoupdating 28 | uses: docker://chinthakagodawita/autoupdate-action:v1 29 | env: 30 | GITHUB_TOKEN: '${{ secrets.GH_TOKEN_BOT_EVE }}' 31 | PR_FILTER: "labelled" 32 | PR_LABELS: "autoupdate" 33 | PR_READY_STATE: "ready_for_review" 34 | MERGE_CONFLICT_ACTION: "ignore" 35 | -------------------------------------------------------------------------------- /deployments/apps/.terraform.lock.hcl: -------------------------------------------------------------------------------- 1 | # This file is maintained automatically by "terraform init". 2 | # Manual edits may be lost in future updates. 3 | 4 | provider "registry.terraform.io/digitalocean/digitalocean" { 5 | version = "2.34.1" 6 | constraints = ">= 2.0.0" 7 | hashes = [ 8 | "h1:iRyhFUfKnDRWx75+alSOEtdS0BtNUkrvLusC15s34eo=", 9 | "zh:022d4c97af3d022d4e3735a81c6a7297aa43c3b28a8cecaa0ff58273a5677e2e", 10 | "zh:1922f86d5710707eb497fbebcb1a1c5584c843a7e95c3900d750d81bd2785204", 11 | "zh:1b7ab7c67a26c399eb5aa8a7a695cb59279c6a1a562ead3064e4a6b17cdacabe", 12 | "zh:1dc666faa2ec0efc32329b4c8ff79813b54741ef1741bc42d90513e5ba904048", 13 | "zh:220dec61ffd9448a91cca92f2bc6642df10db57b25d3d27036c3a370e9870cb7", 14 | "zh:262301545057e654bd6193dc04b01666531fccfcf722f730827695098d93afa7", 15 | "zh:63677684a14e6b7790833982d203fb2f84b105ad6b9b490b3a4ecc7043cdba81", 16 | "zh:67a2932227623073aa9431a12916b52ce1ccddb96f9a2d6cdae2aaf7558ccbf8", 17 | "zh:70dfc6ac33ee140dcb29a971df7eeb15117741b5a75b9f8486c5468c9dd28f24", 18 | "zh:7e3b3b62754e86442048b4b1284e10807e3e58f417e1d59a4575dd29ac6ba518", 19 | "zh:7e6fe662b1e283ad498eb2549d0c2260b908ab5b848e05f84fa4acdca5b4d5ca", 20 | "zh:9c554170f20e659222896533a3a91954fb1d210eea60de05aea803b36d5ccd5d", 21 | "zh:ad2f64d758bd718eb39171f1c31219900fd2bfb552a14f6a90b18cfd178a74b4", 22 | "zh:cfce070000e95dfe56a901340ac256f9d2f84a73bf62391cba8a8e9bf1f857e0", 23 | "zh:d5ae30eccd53ca7314157e62d8ec53151697ed124e43b24b2d16c565054730c6", 24 | "zh:fbe5edf5337adb7360f9ffef57d02b397555b6a89bba68d1b60edfec6e23f02c", 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /src/services/archiver.service.ts: -------------------------------------------------------------------------------- 1 | import archiver, { Archiver } from 'archiver'; 2 | import { Response } from 'express'; 3 | 4 | import { retrieveLangauge } from '../utils/retrieve-language'; 5 | import { createTempDirectory, removeTempDirectory } from '../utils/temp-dir'; 6 | 7 | /** 8 | * Service wrapping the `archiver` module: 9 | - easier zip creation 10 | - adding proper `Content-Type` header 11 | - easier adding an AsyncAPI document to the archive 12 | - easier stream finalization 13 | */ 14 | export class ArchiverService { 15 | public createZip(res?: Response) { 16 | const zip = archiver('zip', { zlib: { level: 9 } }); 17 | if (res) { 18 | zip.pipe(res); 19 | res.attachment('asyncapi.zip'); 20 | } 21 | return zip; 22 | } 23 | 24 | public appendDirectory(archive: Archiver, from: string, to: string) { 25 | archive.directory(from, to); 26 | } 27 | 28 | public appendAsyncAPIDocument(archive: Archiver, asyncapi: string, fileName = 'asyncapi') { 29 | asyncapi = JSON.stringify(asyncapi); 30 | const language = retrieveLangauge(asyncapi); 31 | if (language === 'yaml') { 32 | archive.append(asyncapi, { name: `${fileName}.yml` }); 33 | } else { 34 | archive.append(asyncapi, { name: `${fileName}.json`}); 35 | } 36 | } 37 | 38 | public async finalize(archive: Archiver) { 39 | await new Promise((resolve) => { 40 | // wait for end stream 41 | archive.on('end', resolve); 42 | archive.finalize(); 43 | }); 44 | } 45 | 46 | public createTempDirectory() { 47 | return createTempDirectory(); 48 | } 49 | 50 | public removeTempDirectory(tmpDir: string) { 51 | return removeTempDirectory(tmpDir); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/middlewares/tests/problem.middleware.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { createTestController } from '../../../tests/test.controller'; 7 | 8 | // problemMiddleware is added to every route 9 | describe('problemMiddleware', () => { 10 | describe('[POST] /test', () => { 11 | it('should handle throwed exception', async () => { 12 | const TestController = createTestController({ 13 | path: '/test', 14 | method: 'post', 15 | callback: () => { 16 | throw new ProblemException({ 17 | type: 'custom-problem', 18 | title: 'Custom problem', 19 | status: 422, 20 | }); 21 | }, 22 | }); 23 | const app = new App([new TestController()]); 24 | await app.init(); 25 | 26 | return await request(app.getServer()) 27 | .post('/v1/test') 28 | .send({}) 29 | .expect(422, { 30 | type: ProblemException.createType('custom-problem'), 31 | title: 'Custom problem', 32 | status: 422, 33 | }); 34 | }); 35 | 36 | it('should not have executed when there was success call', async () => { 37 | const TestController = createTestController({ 38 | path: '/test', 39 | method: 'post', 40 | callback: (_, res) => { 41 | res.status(200).send({ success: true }); 42 | }, 43 | }); 44 | const app = new App([new TestController()]); 45 | await app.init(); 46 | 47 | return await request(app.getServer()) 48 | .post('/v1/test') 49 | .send({}) 50 | .expect(200, { 51 | success: true, 52 | }); 53 | }); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /deployments/apps/main.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_version = ">= 1.0.0" 3 | 4 | required_providers { 5 | digitalocean = { 6 | source = "digitalocean/digitalocean" 7 | version = ">= 2.0.0" 8 | } 9 | } 10 | } 11 | 12 | provider "digitalocean" {} 13 | 14 | resource "digitalocean_app" "server-api" { 15 | spec { 16 | name = "server-api" 17 | region = "sfo3" 18 | 19 | domain { 20 | name = "api.asyncapi.com" 21 | type = "PRIMARY" 22 | } 23 | 24 | ingress { 25 | rule { 26 | component { 27 | name = "asyncapi-server-api" 28 | } 29 | match { 30 | path { 31 | prefix = "/" 32 | } 33 | } 34 | cors { 35 | allow_origins { 36 | exact = "*" 37 | } 38 | allow_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"] 39 | allow_headers = ["*"] 40 | } 41 | } 42 | } 43 | 44 | service { 45 | name = "asyncapi-server-api" 46 | http_port = 80 47 | health_check { 48 | http_path = "/v1/help/validate" 49 | port = 80 50 | } 51 | env { 52 | key = "PORT" 53 | value = "80" 54 | } 55 | 56 | image { 57 | registry_type = "DOCKER_HUB" 58 | registry = "asyncapi" 59 | repository = "server-api" 60 | tag = "latest" 61 | } 62 | 63 | instance_count = 1 64 | instance_size_slug = "basic-xs" // $10/month 65 | 66 | alert { 67 | rule = "CPU_UTILIZATION" 68 | value = 80 69 | operator = "GREATER_THAN" 70 | window = "TEN_MINUTES" 71 | } 72 | } 73 | 74 | alert { 75 | rule = "DEPLOYMENT_FAILED" 76 | } 77 | } 78 | } 79 | 80 | output "live_url" { 81 | value = digitalocean_app.server-api.default_ingress 82 | } 83 | -------------------------------------------------------------------------------- /.github/workflows/release-docker.yml: -------------------------------------------------------------------------------- 1 | name: Release Docker Image 2 | on: 3 | release: 4 | types: 5 | - published 6 | jobs: 7 | 8 | publish-docker: 9 | name: Generating Docker 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout repository 13 | uses: actions/checkout@v3 14 | - name: Get version without v character 15 | id: version 16 | run: | 17 | VERSION=${{github.event.release.tag_name}} 18 | VERSION_WITHOUT_V=${VERSION:1} 19 | echo "value=${VERSION_WITHOUT_V}" >> $GITHUB_OUTPUT 20 | 21 | - name: Release to Docker 22 | run: | 23 | echo ${{secrets.DOCKER_PASSWORD}} | docker login -u ${{secrets.DOCKER_USERNAME}} --password-stdin 24 | npm run docker:build 25 | docker tag asyncapi/server-api:latest asyncapi/server-api:${{ steps.version.outputs.value }} 26 | docker push asyncapi/server-api:${{ steps.version.outputs.value }} 27 | docker push asyncapi/server-api:latest 28 | 29 | - uses: meeDamian/sync-readme@82715041300710d9be7c726c9d6c683b70451087 #version 1.0.6 https://github.com/meeDamian/sync-readme/releases/tag/v1.0.6 30 | with: 31 | user: ${{secrets.DOCKER_USERNAME}} 32 | pass: ${{ secrets.DOCKER_PASSWORD }} 33 | slug: asyncapi/server-api 34 | description: Server API providing official AsyncAPI tools 35 | 36 | deploy-app: 37 | name: Deploy to DigitalOcean App 38 | needs: publish-docker 39 | runs-on: ubuntu-latest 40 | steps: 41 | - name: Deploy to DigitalOcean App 42 | uses: digitalocean/app_action@v1.1.5 43 | with: 44 | app_name: "server-api" 45 | token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} 46 | images: '[{"name":"asyncapi-server-api","image":{"registry_type":"DOCKER_HUB","registry":"asyncapi","repository":"server-api","tag":"latest"}}]' 47 | -------------------------------------------------------------------------------- /src/controllers/convert.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | 3 | import { Controller, AsyncAPIDocument, SpecsEnum } from '../interfaces'; 4 | 5 | import { validationMiddleware } from '../middlewares/validation.middleware'; 6 | 7 | import { ConvertService } from '../services/convert.service'; 8 | 9 | import { ProblemException } from '../exceptions/problem.exception'; 10 | 11 | type ConvertRequestDto = { 12 | asyncapi: AsyncAPIDocument; 13 | /** 14 | * Spec version to upgrade to. 15 | * Default is 'latest'. 16 | */ 17 | version?: SpecsEnum; 18 | /** 19 | * Language to convert the file to. 20 | */ 21 | language?: 'json' | 'yaml' | 'yml', 22 | } 23 | 24 | /** 25 | * Controller which exposes the Convert functionality 26 | */ 27 | export class ConvertController implements Controller { 28 | public basepath = '/convert'; 29 | 30 | private convertService = new ConvertService(); 31 | 32 | private async convert(req: Request, res: Response, next: NextFunction) { 33 | try { 34 | const { version, language, asyncapi } = req.body as ConvertRequestDto; 35 | const convertedSpec = await this.convertService.convert( 36 | asyncapi, 37 | version, 38 | language, 39 | ); 40 | 41 | res.status(200).json({ 42 | converted: convertedSpec 43 | }); 44 | } catch (err: unknown) { 45 | if (err instanceof ProblemException) { 46 | return next(err); 47 | } 48 | 49 | return next(new ProblemException({ 50 | type: 'internal-server-error', 51 | title: 'Internal server error', 52 | status: 500, 53 | detail: (err as Error).message, 54 | })); 55 | } 56 | } 57 | 58 | public async boot(): Promise { 59 | const router = Router(); 60 | 61 | router.post( 62 | this.basepath, 63 | await validationMiddleware({ 64 | path: this.basepath, 65 | method: 'post', 66 | documents: ['asyncapi'], 67 | }), 68 | this.convert.bind(this) 69 | ); 70 | 71 | return router; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /.github/workflows/bump.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this action is to update npm package in libraries that use it. It is like dependabot for asyncapi npm modules only. 5 | # It runs in a repo after merge of release commit and searches for other packages that use released package. Every found package gets updated with lates version 6 | 7 | name: Bump package version in dependent repos - if Node project 8 | 9 | on: 10 | # It cannot run on release event as when release is created then version is not yet bumped in package.json 11 | # This means we cannot extract easily latest version and have a risk that package is not yet on npm 12 | push: 13 | branches: 14 | - master 15 | 16 | jobs: 17 | bump-in-dependent-projects: 18 | name: Bump this package in repositories that depend on it 19 | if: startsWith(github.event.commits[0].message, 'chore(release):') 20 | runs-on: ubuntu-latest 21 | steps: 22 | - name: Checkout repo 23 | uses: actions/checkout@v4 24 | - name: Check if Node.js project and has package.json 25 | id: packagejson 26 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 27 | - name: Setup corepack with pnpm and yarn 28 | if: steps.packagejson.outputs.exists == 'true' 29 | run: corepack enable 30 | - if: steps.packagejson.outputs.exists == 'true' 31 | name: Bumping latest version of this package in other repositories 32 | uses: derberg/npm-dependency-manager-for-your-github-org@f95b99236e8382a210042d8cfb84f42584e29c24 # using v6.2.0.-.- https://github.com/derberg/npm-dependency-manager-for-your-github-org/releases/tag/v6.2.0 33 | with: 34 | github_token: ${{ secrets.GH_TOKEN }} 35 | committer_username: asyncapi-bot 36 | committer_email: info@asyncapi.io 37 | repos_to_ignore: spec,bindings,saunter,server-api 38 | custom_id: "dependency update from asyncapi bot" 39 | search: "true" 40 | ignore_paths: .github/workflows 41 | -------------------------------------------------------------------------------- /.github/workflows/automerge.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo. 3 | 4 | name: Automerge PRs from bots 5 | 6 | on: 7 | pull_request_target: 8 | types: 9 | - opened 10 | - synchronize 11 | 12 | jobs: 13 | autoapprove-for-bot: 14 | name: Autoapprove PR comming from a bot 15 | if: > 16 | contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]"]'), github.event.pull_request.user.login) && 17 | contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]"]'), github.actor) && 18 | !contains(github.event.pull_request.labels.*.name, 'released') 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Autoapproving 22 | uses: hmarr/auto-approve-action@44888193675f29a83e04faf4002fa8c0b537b1e4 # v3.2.1 is used https://github.com/hmarr/auto-approve-action/releases/tag/v3.2.1 23 | with: 24 | github-token: "${{ secrets.GH_TOKEN_BOT_EVE }}" 25 | 26 | - name: Label autoapproved 27 | uses: actions/github-script@v7 28 | with: 29 | github-token: ${{ secrets.GH_TOKEN }} 30 | script: | 31 | github.rest.issues.addLabels({ 32 | issue_number: context.issue.number, 33 | owner: context.repo.owner, 34 | repo: context.repo.repo, 35 | labels: ['autoapproved', 'autoupdate'] 36 | }) 37 | 38 | automerge-for-bot: 39 | name: Automerge PR autoapproved by a bot 40 | needs: [autoapprove-for-bot] 41 | runs-on: ubuntu-latest 42 | steps: 43 | - name: Automerging 44 | uses: pascalgn/automerge-action@22948e0bc22f0aa673800da838595a3e7347e584 #v0.15.6 https://github.com/pascalgn/automerge-action/releases/tag/v0.15.6 45 | env: 46 | GITHUB_TOKEN: "${{ secrets.GH_TOKEN }}" 47 | GITHUB_LOGIN: asyncapi-bot 48 | MERGE_LABELS: "!do-not-merge" 49 | MERGE_METHOD: "squash" 50 | MERGE_COMMIT_MESSAGE: "{pullRequest.title} (#{pullRequest.number})" 51 | MERGE_RETRIES: "20" 52 | MERGE_RETRY_SLEEP: "30000" 53 | -------------------------------------------------------------------------------- /src/services/tests/convert.service.test.ts: -------------------------------------------------------------------------------- 1 | import { ConvertService } from '../convert.service'; 2 | import { ProblemException } from '../../exceptions/problem.exception'; 3 | 4 | const validJsonAsyncAPI2_0_0 = { 5 | asyncapi: '2.0.0', 6 | info: { 7 | title: 'Super test', 8 | version: '1.0.0' 9 | }, 10 | channels: {} 11 | }; 12 | 13 | const validJsonAsyncAPI2_1_0 = { 14 | asyncapi: '2.1.0', 15 | info: { 16 | title: 'Super test', 17 | version: '1.0.0' 18 | }, 19 | channels: {} 20 | }; 21 | 22 | const validYamlAsyncAPI2_4_0 = ` 23 | asyncapi: 2.4.0 24 | info: 25 | title: Super test 26 | version: 1.0.0 27 | channels: {} 28 | `; 29 | 30 | describe('ConvertService', () => { 31 | const convertService = new ConvertService(); 32 | 33 | describe('.convert()', () => { 34 | it('should throw error that the converter cannot convert to a lower version', async () => { 35 | let err: ProblemException | null = null; 36 | try { 37 | await convertService.convert(validJsonAsyncAPI2_1_0, '2.0.0'); 38 | } catch (e) { 39 | err = e; 40 | } 41 | 42 | expect(err).toEqual(new ProblemException({ 43 | type: 'internal-converter-error', 44 | title: 'Could not convert document', 45 | status: 422, 46 | detail: 'Cannot downgrade from 2.1.0 to 2.0.0.', 47 | })); 48 | }); 49 | 50 | it('should pass when converting to 2.4.0 version', async () => { 51 | const converted = await convertService.convert(validJsonAsyncAPI2_0_0, '2.4.0'); 52 | 53 | expect(converted).toEqual({ 54 | asyncapi: '2.4.0', 55 | info: { 56 | title: 'Super test', 57 | version: '1.0.0' 58 | }, 59 | channels: {}, 60 | }); 61 | }); 62 | 63 | it('should pass when converting to latest version', async () => { 64 | const converted = await convertService.convert(validJsonAsyncAPI2_0_0); 65 | 66 | expect(converted).toEqual({ 67 | asyncapi: '2.6.0', 68 | info: { 69 | title: 'Super test', 70 | version: '1.0.0' 71 | }, 72 | channels: {}, 73 | }); 74 | }); 75 | 76 | it('should correctly convert JSON to YAML', async () => { 77 | const converted = await convertService.convert(validJsonAsyncAPI2_0_0, '2.4.0', 'yaml'); 78 | 79 | expect(converted).toEqual(validYamlAsyncAPI2_4_0.trimStart()); 80 | }); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /.github/workflows/please-take-a-look-command.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It uses Github actions to listen for comments on issues and pull requests and 5 | # if the comment contains /please-take-a-look or /ptal it will add a comment pinging 6 | # the code-owners who are reviewers for PR 7 | 8 | name: Please take a Look 9 | 10 | on: 11 | issue_comment: 12 | types: [created] 13 | 14 | jobs: 15 | ping-for-attention: 16 | if: > 17 | github.event.issue.pull_request && 18 | github.event.issue.state != 'closed' && 19 | github.actor != 'asyncapi-bot' && 20 | ( 21 | contains(github.event.comment.body, '/please-take-a-look') || 22 | contains(github.event.comment.body, '/ptal') || 23 | contains(github.event.comment.body, '/PTAL') 24 | ) 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Check for Please Take a Look Command 28 | uses: actions/github-script@v7 29 | with: 30 | github-token: ${{ secrets.GH_TOKEN }} 31 | script: | 32 | const prDetailsUrl = context.payload.issue.pull_request.url; 33 | const { data: pull } = await github.request(prDetailsUrl); 34 | const reviewers = pull.requested_reviewers.map(reviewer => reviewer.login); 35 | 36 | const { data: reviews } = await github.rest.pulls.listReviews({ 37 | owner: context.repo.owner, 38 | repo: context.repo.repo, 39 | pull_number: context.issue.number 40 | }); 41 | 42 | const reviewersWhoHaveReviewed = reviews.map(review => review.user.login); 43 | 44 | const reviewersWhoHaveNotReviewed = reviewers.filter(reviewer => !reviewersWhoHaveReviewed.includes(reviewer)); 45 | 46 | if (reviewersWhoHaveNotReviewed.length > 0) { 47 | const comment = reviewersWhoHaveNotReviewed.filter(reviewer => reviewer !== 'asyncapi-bot-eve' ).map(reviewer => `@${reviewer}`).join(' '); 48 | await github.rest.issues.createComment({ 49 | issue_number: context.issue.number, 50 | owner: context.repo.owner, 51 | repo: context.repo.repo, 52 | body: `${comment} Please take a look at this PR. Thanks! :wave:` 53 | }); 54 | } 55 | -------------------------------------------------------------------------------- /.github/workflows/transfer-issue.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Transfer Issues between repositories 5 | 6 | on: 7 | issue_comment: 8 | types: 9 | - created 10 | 11 | permissions: 12 | issues: write 13 | 14 | jobs: 15 | transfer: 16 | if: ${{(!github.event.issue.pull_request && github.event.issue.state != 'closed' && github.actor != 'asyncapi-bot') && (startsWith(github.event.comment.body, '/transfer-issue') || startsWith(github.event.comment.body, '/ti'))}} 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout Repository 20 | uses: actions/checkout@v4 21 | - name: Extract Input 22 | id: extract_step 23 | env: 24 | COMMENT: "${{ github.event.comment.body }}" 25 | run: | 26 | REPO=$(echo "$COMMENT" | awk '{print $2}') 27 | echo "repo=$REPO" >> $GITHUB_OUTPUT 28 | - name: Check Repo 29 | uses: actions/github-script@v7 30 | with: 31 | github-token: ${{secrets.GH_TOKEN}} 32 | script: | 33 | const r = "${{github.repository}}" 34 | const [owner, repo] = r.split('/') 35 | const repoToMove = process.env.REPO_TO_MOVE 36 | const issue_number = context.issue.number 37 | try { 38 | const {data} = await github.rest.repos.get({ 39 | owner, 40 | repo: repoToMove 41 | }) 42 | }catch (e) { 43 | const body = `${repoToMove} is not a repo under ${owner}. You can only transfer issue to repos that belong to the same organization.` 44 | await github.rest.issues.createComment({ 45 | owner, 46 | repo, 47 | issue_number, 48 | body 49 | }) 50 | process.exit(1) 51 | } 52 | env: 53 | REPO_TO_MOVE: ${{steps.extract_step.outputs.repo}} 54 | - name: Transfer Issue 55 | id: transferIssue 56 | working-directory: ./ 57 | run: | 58 | gh issue transfer "$ISSUE_NUMBER" "asyncapi/$REPO_NAME" 59 | env: 60 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 61 | ISSUE_NUMBER: ${{ github.event.issue.number }} 62 | REPO_NAME: ${{ steps.extract_step.outputs.repo }} 63 | -------------------------------------------------------------------------------- /src/controllers/tests/parse.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { ParseController } from '../parse.controller'; 7 | 8 | const validJSONAsyncAPI = { 9 | asyncapi: '2.0.0', 10 | info: { 11 | title: 'My API', 12 | version: '1.0.0' 13 | }, 14 | channels: {} 15 | }; 16 | const invalidJSONAsyncAPI = { 17 | asyncapi: '2.0.0', 18 | info: { 19 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 20 | version: '1.0.0' 21 | }, 22 | channels: {} 23 | }; 24 | 25 | describe('ParseController', () => { 26 | describe('[POST] /parse', () => { 27 | it('should return stringified AsyncAPI document', async () => { 28 | const app = new App([new ParseController()]); 29 | await app.init(); 30 | 31 | return request(app.getServer()) 32 | .post('/v1/parse') 33 | .send({ 34 | asyncapi: validJSONAsyncAPI 35 | }) 36 | .expect(200, { 37 | parsed: '{"asyncapi":"2.0.0","info":{"title":"My API","version":"1.0.0"},"channels":{},"x-parser-spec-parsed":true,"x-parser-spec-stringified":true}', 38 | }); 39 | }); 40 | 41 | it('should throw error when sent an invalid AsyncAPI document', async () => { 42 | const app = new App([new ParseController()]); 43 | await app.init(); 44 | 45 | return request(app.getServer()) 46 | .post('/v1/parse') 47 | .send({ 48 | asyncapi: invalidJSONAsyncAPI 49 | }) 50 | .expect(422, { 51 | type: ProblemException.createType('validation-errors'), 52 | title: 'There were errors validating the AsyncAPI document.', 53 | status: 422, 54 | validationErrors: [ 55 | { 56 | title: '/info should NOT have additional properties', 57 | location: { 58 | jsonPointer: '/info' 59 | } 60 | }, 61 | { 62 | title: '/info should have required property \'title\'', 63 | location: { 64 | jsonPointer: '/info' 65 | } 66 | } 67 | ], 68 | parsedJSON: { 69 | asyncapi: '2.0.0', 70 | info: { 71 | tite: 'My API', 72 | version: '1.0.0' 73 | }, 74 | channels: {} 75 | } 76 | }); 77 | }); 78 | }); 79 | }); 80 | -------------------------------------------------------------------------------- /.github/workflows/lint-pr-title.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Lint PR title 5 | 6 | on: 7 | pull_request_target: 8 | types: [opened, reopened, synchronize, edited, ready_for_review] 9 | 10 | jobs: 11 | lint-pr-title: 12 | name: Lint PR title 13 | runs-on: ubuntu-latest 14 | steps: 15 | # Since this workflow is REQUIRED for a PR to be mergable, we have to have this 'if' statement in step level instead of job level. 16 | - if: ${{ !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor) }} 17 | uses: amannn/action-semantic-pull-request@c3cd5d1ea3580753008872425915e343e351ab54 #version 5.2.0 https://github.com/amannn/action-semantic-pull-request/releases/tag/v5.2.0 18 | id: lint_pr_title 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}} 21 | with: 22 | subjectPattern: ^(?![A-Z]).+$ 23 | subjectPatternError: | 24 | The subject "{subject}" found in the pull request title "{title}" should start with a lowercase character. 25 | 26 | # Comments the error message from the above lint_pr_title action 27 | - if: ${{ always() && steps.lint_pr_title.outputs.error_message != null && !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor)}} 28 | name: Comment on PR 29 | uses: marocchino/sticky-pull-request-comment@3d60a5b2dae89d44e0c6ddc69dd7536aec2071cd #use 2.5.0 https://github.com/marocchino/sticky-pull-request-comment/releases/tag/v2.5.0 30 | with: 31 | header: pr-title-lint-error 32 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}} 33 | message: | 34 | 35 | We require all PRs to follow [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/). 36 | More details 👇🏼 37 | ``` 38 | ${{ steps.lint_pr_title.outputs.error_message}} 39 | ``` 40 | # deletes the error comment if the title is correct 41 | - if: ${{ steps.lint_pr_title.outputs.error_message == null }} 42 | name: delete the comment 43 | uses: marocchino/sticky-pull-request-comment@3d60a5b2dae89d44e0c6ddc69dd7536aec2071cd #use 2.5.0 https://github.com/marocchino/sticky-pull-request-comment/releases/tag/v2.5.0 44 | with: 45 | header: pr-title-lint-error 46 | delete: true 47 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN}} 48 | -------------------------------------------------------------------------------- /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "server-api", 3 | "projectOwner": "asyncapi", 4 | "repoType": "github", 5 | "repoHost": "https://github.com", 6 | "files": [ 7 | "README.md" 8 | ], 9 | "imageSize": 100, 10 | "commit": false, 11 | "commitConvention": "none", 12 | "contributors": [ 13 | { 14 | "login": "magicmatatjahu", 15 | "name": "Maciej Urbańczyk", 16 | "avatar_url": "https://avatars.githubusercontent.com/u/20404945?v=4", 17 | "profile": "https://github.com/magicmatatjahu", 18 | "contributions": [ 19 | "maintenance", 20 | "code", 21 | "doc", 22 | "bug", 23 | "ideas", 24 | "review", 25 | "test", 26 | "infra", 27 | "mentoring" 28 | ] 29 | }, 30 | { 31 | "login": "BOLT04", 32 | "name": "David Pereira", 33 | "avatar_url": "https://avatars.githubusercontent.com/u/18630253?v=4", 34 | "profile": "https://bolt04.github.io/react-ultimate-resume/", 35 | "contributions": [ 36 | "maintenance", 37 | "code", 38 | "doc", 39 | "bug", 40 | "ideas", 41 | "review", 42 | "test", 43 | "infra", 44 | "mentoring" 45 | ] 46 | }, 47 | { 48 | "login": "smoya", 49 | "name": "Sergio Moya", 50 | "avatar_url": "https://avatars.githubusercontent.com/u/1083296?v=4", 51 | "profile": "https://github.com/smoya", 52 | "contributions": [ 53 | "maintenance", 54 | "code", 55 | "doc", 56 | "bug", 57 | "ideas", 58 | "review", 59 | "test", 60 | "infra", 61 | "mentoring" 62 | ] 63 | }, 64 | { 65 | "login": "ritik307", 66 | "name": "Ritik Rawal", 67 | "avatar_url": "https://avatars.githubusercontent.com/u/22374829?v=4", 68 | "profile": "https://ritik307.github.io/portfolio/", 69 | "contributions": [ 70 | "code", 71 | "doc" 72 | ] 73 | }, 74 | { 75 | "login": "everly-gif", 76 | "name": "Everly Precia Suresh", 77 | "avatar_url": "https://avatars.githubusercontent.com/u/77877486?v=4", 78 | "profile": "https://everly-precia.netlify.app/", 79 | "contributions": [ 80 | "code", 81 | "doc" 82 | ] 83 | }, 84 | { 85 | "login": "Shurtu-gal", 86 | "name": "Ashish Padhy", 87 | "avatar_url": "https://avatars.githubusercontent.com/u/100484401?v=4", 88 | "profile": "http://ashishpadhy.live", 89 | "contributions": [ 90 | "doc", 91 | "infra" 92 | ] 93 | } 94 | ], 95 | "contributorsPerLine": 7, 96 | "commitType": "docs" 97 | } 98 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import bodyParser from 'body-parser'; 2 | import compression from 'compression'; 3 | import config from 'config'; 4 | import cors from 'cors'; 5 | import express from 'express'; 6 | import helmet from 'helmet'; 7 | 8 | import { Controller } from './interfaces'; 9 | 10 | import { problemMiddleware } from './middlewares/problem.middleware'; 11 | 12 | import { logger } from './utils/logger'; 13 | import { API_VERSION } from './constants'; 14 | 15 | export class App { 16 | private app: express.Application; 17 | private port: string | number; 18 | private env: string; 19 | 20 | constructor( 21 | private readonly controllers: Controller[] 22 | ) { 23 | this.app = express(); 24 | this.port = process.env.PORT || 80; 25 | this.env = process.env.NODE_ENV || 'development'; 26 | } 27 | 28 | public async init() { 29 | // initialize core middlewares 30 | await this.initializeMiddlewares(); 31 | // initialize controllers 32 | await this.initializeControllers(); 33 | // initialize error handling 34 | await this.initializeErrorHandling(); 35 | } 36 | 37 | public listen() { 38 | this.app.listen(this.port, () => { 39 | logger.info('================================='); 40 | logger.info(`= ENV: ${this.env}`); 41 | logger.info(`= 🚀 AsyncAPI Server API listening on the port ${this.port}`); 42 | logger.info('================================='); 43 | }); 44 | } 45 | 46 | public getServer() { 47 | return this.app; 48 | } 49 | 50 | private async initializeMiddlewares() { 51 | const requestBodyLimit = config.get('request.body.limit'); 52 | 53 | this.app.use(cors({ origin: config.get('cors.origin'), credentials: config.get('cors.credentials') })); 54 | this.app.use(compression()); 55 | this.app.use(bodyParser.text({ type: ['text/*'], limit: requestBodyLimit })); 56 | this.app.use(bodyParser.urlencoded({ extended: true, limit: requestBodyLimit })); 57 | this.app.use(bodyParser.json({ type: ['json', '*/json', '+json'], limit: requestBodyLimit })); 58 | this.app.use(helmet({ 59 | contentSecurityPolicy: { 60 | directives: { 61 | // for `/docs` path - we need to fetch redoc component from unpkg.com domain 62 | 'script-src': ['\'self\'', 'unpkg.com'], 63 | 'worker-src': ['\'self\' blob:'] 64 | }, 65 | }, 66 | // for `/docs` path 67 | crossOriginEmbedderPolicy: false, 68 | })); 69 | } 70 | 71 | private async initializeControllers() { 72 | for (const controller of this.controllers) { 73 | this.app.use(`/${API_VERSION}/`, await controller.boot()); 74 | } 75 | } 76 | 77 | private async initializeErrorHandling() { 78 | this.app.use(problemMiddleware); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /.github/workflows/stale-issues-prs.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Manage stale issues and PRs 5 | 6 | on: 7 | schedule: 8 | - cron: "0 0 * * *" 9 | 10 | jobs: 11 | stale: 12 | if: startsWith(github.repository, 'asyncapi/') 13 | name: Mark issue or PR as stale 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 #v9.1.0 but pointing to commit for security reasons 17 | with: 18 | repo-token: ${{ secrets.GITHUB_TOKEN }} 19 | stale-issue-message: | 20 | This issue has been automatically marked as stale because it has not had recent activity :sleeping: 21 | 22 | It will be closed in 120 days if no further activity occurs. To unstale this issue, add a comment with a detailed explanation. 23 | 24 | There can be many reasons why some specific issue has no activity. The most probable cause is lack of time, not lack of interest. AsyncAPI Initiative is a Linux Foundation project not owned by a single for-profit company. It is a community-driven initiative ruled under [open governance model](https://github.com/asyncapi/community/blob/master/CHARTER.md). 25 | 26 | Let us figure out together how to push this issue forward. Connect with us through [one of many communication channels](https://github.com/asyncapi/community/issues/1) we established here. 27 | 28 | Thank you for your patience :heart: 29 | stale-pr-message: | 30 | This pull request has been automatically marked as stale because it has not had recent activity :sleeping: 31 | 32 | It will be closed in 120 days if no further activity occurs. To unstale this pull request, add a comment with detailed explanation. 33 | 34 | There can be many reasons why some specific pull request has no activity. The most probable cause is lack of time, not lack of interest. AsyncAPI Initiative is a Linux Foundation project not owned by a single for-profit company. It is a community-driven initiative ruled under [open governance model](https://github.com/asyncapi/community/blob/master/CHARTER.md). 35 | 36 | Let us figure out together how to push this pull request forward. Connect with us through [one of many communication channels](https://github.com/asyncapi/community/issues/1) we established here. 37 | 38 | Thank you for your patience :heart: 39 | days-before-stale: 120 40 | days-before-close: 120 41 | stale-issue-label: stale 42 | stale-pr-label: stale 43 | exempt-issue-labels: keep-open 44 | exempt-pr-labels: keep-open 45 | close-issue-reason: not_planned 46 | -------------------------------------------------------------------------------- /src/services/convert.service.ts: -------------------------------------------------------------------------------- 1 | import { convert } from '@asyncapi/converter'; 2 | 3 | import YAML from 'js-yaml'; 4 | 5 | import { AsyncAPIDocument, LAST_SPEC_VERSION, SpecsEnum } from '../interfaces'; 6 | import { ProblemException } from '../exceptions/problem.exception'; 7 | 8 | import type { ConvertVersion } from '@asyncapi/converter'; 9 | 10 | /** 11 | * Service providing `@asyncapi/converter` functionality. 12 | */ 13 | export class ConvertService { 14 | /** 15 | * Convert the given spec to the desired version and format. 16 | * @param spec AsyncAPI spec 17 | * @param language Language to convert to, YAML or JSON 18 | * @param version AsyncAPI spec version 19 | * @returns converted spec 20 | */ 21 | public async convert( 22 | spec: string | AsyncAPIDocument, 23 | version: SpecsEnum = LAST_SPEC_VERSION as SpecsEnum, 24 | language?: 'json' | 'yaml' | 'yml' 25 | ): Promise { 26 | if (version === 'latest') { 27 | version = LAST_SPEC_VERSION as SpecsEnum; 28 | } 29 | 30 | try { 31 | const asyncapiSpec = 32 | typeof spec === 'object' ? JSON.stringify(spec) : spec; 33 | const convertedSpec = convert(asyncapiSpec, version as ConvertVersion); 34 | 35 | if (!language) { 36 | return convertedSpec; 37 | } 38 | return this.convertToFormat(convertedSpec, language); 39 | } catch (err) { 40 | if (err instanceof ProblemException) { 41 | throw err; 42 | } 43 | 44 | throw new ProblemException({ 45 | type: 'internal-converter-error', 46 | title: 'Could not convert document', 47 | status: 422, 48 | detail: (err as Error).message, 49 | }); 50 | } 51 | } 52 | 53 | private convertToFormat( 54 | spec: string | Record, 55 | language: 'json' | 'yaml' | 'yml' 56 | ) { 57 | if (typeof spec === 'object') { 58 | spec = JSON.stringify(spec, undefined, 2); 59 | } 60 | 61 | try { 62 | if (language === 'json') { 63 | return this.convertToJSON(spec); 64 | } 65 | return this.convertToYaml(spec); 66 | } catch (err) { 67 | throw new ProblemException({ 68 | type: 'converter-output-format', 69 | title: `Could not transform output to ${language}`, 70 | status: 422, 71 | detail: (err as Error).message, 72 | }); 73 | } 74 | } 75 | 76 | private convertToJSON(spec: string) { 77 | // JSON or YAML String -> JS object 78 | const jsonContent = YAML.load(spec); 79 | // JS Object -> pretty JSON string 80 | return JSON.stringify(jsonContent, undefined, 2); 81 | } 82 | 83 | private convertToYaml(spec: string) { 84 | // Editor content -> JS object -> YAML string 85 | const jsonContent = YAML.load(spec); 86 | return YAML.dump(jsonContent); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/utils/parser.ts: -------------------------------------------------------------------------------- 1 | import { registerSchemaParser, parse, ParserError } from '@asyncapi/parser'; 2 | import { Request } from 'express'; 3 | import ramlDtParser from '@asyncapi/raml-dt-schema-parser'; 4 | import openapiSchemaParser from '@asyncapi/openapi-schema-parser'; 5 | import avroSchemaParser from '@asyncapi/avro-schema-parser'; 6 | 7 | import { ProblemException } from '../exceptions/problem.exception'; 8 | 9 | registerSchemaParser(openapiSchemaParser); 10 | registerSchemaParser(ramlDtParser); 11 | registerSchemaParser(avroSchemaParser); 12 | 13 | function prepareParserConfig(req?: Request) { 14 | if (!req) { 15 | return { 16 | resolve: { 17 | file: false, 18 | }, 19 | }; 20 | } 21 | 22 | return { 23 | resolve: { 24 | file: false, 25 | http: { 26 | headers: { 27 | Cookie: req.header('Cookie'), 28 | }, 29 | withCredentials: true, 30 | }, 31 | }, 32 | path: 33 | req.header('x-asyncapi-base-url') || 34 | req.header('referer') || 35 | req.header('origin'), 36 | }; 37 | } 38 | 39 | const TYPES_400 = [ 40 | 'null-or-falsey-document', 41 | 'impossible-to-convert-to-json', 42 | 'invalid-document-type', 43 | 'invalid-json', 44 | 'invalid-yaml', 45 | ]; 46 | 47 | /** 48 | * Some error types have to be treated as 400 HTTP Status Code, another as 422. 49 | */ 50 | function retrieveStatusCode(type: string): number { 51 | if (TYPES_400.includes(type)) { 52 | return 400; 53 | } 54 | return 422; 55 | } 56 | 57 | /** 58 | * Merges fields from ParserError to ProblemException. 59 | */ 60 | function mergeParserError(error: ProblemException, parserError: any): ProblemException { 61 | if (parserError.detail) { 62 | error.set('detail', parserError.detail); 63 | } 64 | if (parserError.validationErrors) { 65 | error.set('validationErrors', parserError.validationErrors); 66 | } 67 | if (parserError.parsedJSON) { 68 | error.set('parsedJSON', parserError.parsedJSON); 69 | } 70 | if (parserError.location) { 71 | error.set('location', parserError.location); 72 | } 73 | if (parserError.refs) { 74 | error.set('refs', parserError.refs); 75 | } 76 | return error; 77 | } 78 | 79 | function tryConvertToProblemException(err: any) { 80 | let error = err; 81 | if (error instanceof ParserError) { 82 | const typeName = err.type.replace( 83 | 'https://github.com/asyncapi/parser-js/', 84 | '' 85 | ); 86 | error = new ProblemException({ 87 | type: typeName, 88 | title: err.title, 89 | status: retrieveStatusCode(typeName), 90 | }); 91 | mergeParserError(error, err); 92 | } 93 | 94 | return error; 95 | } 96 | 97 | export { 98 | prepareParserConfig, 99 | parse, 100 | mergeParserError, 101 | retrieveStatusCode, 102 | tryConvertToProblemException, 103 | }; 104 | -------------------------------------------------------------------------------- /src/controllers/tests/help.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | import { App } from '../../app'; 3 | import { HelpController } from '../help.controller'; 4 | import { getAppOpenAPI } from '../../utils/app-openapi'; 5 | 6 | jest.mock('../../utils/app-openapi', () => ({ 7 | getAppOpenAPI: jest.fn(), 8 | })); 9 | 10 | describe('HelpController', () => { 11 | let app; 12 | beforeAll(async () => { 13 | app = new App([new HelpController()]); 14 | await app.init(); 15 | }); 16 | 17 | describe('[GET] /help', () => { 18 | it('should return all commands', async () => { 19 | (getAppOpenAPI as jest.Mock).mockResolvedValue({ 20 | paths: { 21 | '/validate': {}, 22 | '/parse': {}, 23 | '/generate': {}, 24 | '/convert': {}, 25 | '/bundle': {}, 26 | '/help': {}, 27 | '/diff': {} 28 | } 29 | }); 30 | 31 | const response = await request(app.getServer()) 32 | .get('/v1/help') 33 | .expect(200); 34 | 35 | expect(response.body).toEqual([ 36 | { 37 | command: 'validate', 38 | url: '/help/validate' 39 | }, 40 | { 41 | command: 'parse', 42 | url: '/help/parse' 43 | }, 44 | { 45 | command: 'generate', 46 | url: '/help/generate' 47 | }, 48 | { 49 | command: 'convert', 50 | url: '/help/convert' 51 | }, 52 | { 53 | command: 'bundle', 54 | url: '/help/bundle' 55 | }, 56 | { 57 | command: 'help', 58 | url: '/help/help' 59 | }, 60 | { 61 | command: 'diff', 62 | url: '/help/diff' 63 | } 64 | ]); 65 | }); 66 | 67 | it('should return 404 error for an invalid command', async () => { 68 | const response = await request(app.getServer()) 69 | .get('/v1/help/invalidCommand') 70 | .expect(404); 71 | 72 | expect(response.body).toEqual({ 73 | type: 'https://api.asyncapi.com/problem/invalid-asyncapi-command', 74 | title: 'Invalid AsyncAPI Command', 75 | status: 404, 76 | detail: 'The given AsyncAPI command is not valid.' 77 | }); 78 | }); 79 | 80 | it('should return 404 error for a command without a method', async () => { 81 | (getAppOpenAPI as jest.Mock).mockResolvedValue({ 82 | paths: { 83 | '/someCommand': {} 84 | } 85 | }); 86 | 87 | const response = await request(app.getServer()) 88 | .get('/v1/help/someCommand') 89 | .expect(404); 90 | 91 | expect(response.body).toEqual({ 92 | type: 'https://api.asyncapi.com/problem/invalid-asyncapi-command', 93 | title: 'Invalid AsyncAPI Command', 94 | status: 404, 95 | detail: 'The given AsyncAPI command is not valid.' 96 | }); 97 | }); 98 | }); 99 | }); -------------------------------------------------------------------------------- /.github/workflows/if-docker-pr-testing.yml: -------------------------------------------------------------------------------- 1 | #This action is centrally managed in https://github.com/asyncapi/.github/ 2 | #Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | #It does magic only if there is a Dockerfile in the root of the project 4 | name: PR testing - if Docker 5 | 6 | on: 7 | pull_request: 8 | types: [opened, reopened, synchronize, ready_for_review] 9 | 10 | env: 11 | IMAGE_NAME: ${{ github.repository }} 12 | 13 | jobs: 14 | test-docker-pr: 15 | name: Test Docker build 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - if: > 20 | !github.event.pull_request.draft && !( 21 | (github.actor == 'asyncapi-bot' && ( 22 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 23 | startsWith(github.event.pull_request.title, 'chore(release):') 24 | )) || 25 | (github.actor == 'asyncapi-bot-eve' && ( 26 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 27 | startsWith(github.event.pull_request.title, 'chore(release):') 28 | )) || 29 | (github.actor == 'allcontributors[bot]' && 30 | startsWith(github.event.pull_request.title, 'docs: add') 31 | ) 32 | ) 33 | id: should_run 34 | name: Should Run 35 | run: echo "shouldrun=true" >> $GITHUB_OUTPUT 36 | 37 | - if: steps.should_run.outputs.shouldrun == 'true' 38 | name: Checkout repository 39 | uses: actions/checkout@v4 40 | 41 | - if: steps.should_run.outputs.shouldrun == 'true' 42 | name: Check if project has a Dockerfile 43 | id: docker 44 | run: test -e ./Dockerfile && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 45 | shell: bash 46 | 47 | - if: steps.docker.outputs.exists == 'true' 48 | name: Set up Docker Buildx 49 | uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # use 3.10.0 https://github.com/docker/setup-buildx-action/releases/tag/v2.5.0 50 | 51 | - if: steps.docker.outputs.exists == 'true' 52 | name: Extract metadata for Docker 53 | id: meta 54 | uses: docker/metadata-action@902fa8ec7d6ecbf8d84d538b9b233a880e428804 # use 5.7.0 https://github.com/docker/metadata-action/releases/tag/v4.3.0 55 | with: 56 | images: ${{ env.IMAGE_NAME }} 57 | 58 | - if: steps.docker.outputs.exists == 'true' 59 | name: Build Docker image 60 | uses: docker/build-push-action@471d1dc4e07e5cdedd4c2171150001c434f0b7a4 # use 6.15.0 https://github.com/docker/build-push-action/releases/tag/v4.0.0 61 | with: 62 | context: . 63 | push: false 64 | tags: ${{ steps.meta.outputs.tags }} 65 | labels: ${{ steps.meta.outputs.labels }} 66 | cache-from: type=gha 67 | cache-to: type=gha,mode=max 68 | -------------------------------------------------------------------------------- /.github/workflows/scripts/mailchimp/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This code is centrally managed in https://github.com/asyncapi/.github/ 3 | * Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 4 | */ 5 | const mailchimp = require('@mailchimp/mailchimp_marketing'); 6 | const core = require('@actions/core'); 7 | const htmlContent = require('./htmlContent.js'); 8 | 9 | /** 10 | * Sending API request to mailchimp to schedule email to subscribers 11 | * Input is the URL to issue/discussion or other resource 12 | */ 13 | module.exports = async (link, title) => { 14 | 15 | let newCampaign; 16 | 17 | mailchimp.setConfig({ 18 | apiKey: process.env.MAILCHIMP_API_KEY, 19 | server: 'us12' 20 | }); 21 | 22 | /* 23 | * First we create campaign 24 | */ 25 | try { 26 | newCampaign = await mailchimp.campaigns.create({ 27 | type: 'regular', 28 | recipients: { 29 | list_id: '6e3e437abe', 30 | segment_opts: { 31 | match: 'any', 32 | conditions: [{ 33 | condition_type: 'Interests', 34 | field: 'interests-2801e38b9f', 35 | op: 'interestcontains', 36 | value: ['f7204f9b90'] 37 | }] 38 | } 39 | }, 40 | settings: { 41 | subject_line: `TSC attention required: ${ title }`, 42 | preview_text: 'Check out the latest topic that TSC members have to be aware of', 43 | title: `New topic info - ${ new Date(Date.now()).toUTCString()}`, 44 | from_name: 'AsyncAPI Initiative', 45 | reply_to: 'info@asyncapi.io', 46 | } 47 | }); 48 | } catch (error) { 49 | return core.setFailed(`Failed creating campaign: ${ JSON.stringify(error) }`); 50 | } 51 | 52 | /* 53 | * Content of the email is added separately after campaign creation 54 | */ 55 | try { 56 | await mailchimp.campaigns.setContent(newCampaign.id, { html: htmlContent(link, title) }); 57 | } catch (error) { 58 | return core.setFailed(`Failed adding content to campaign: ${ JSON.stringify(error) }`); 59 | } 60 | 61 | /* 62 | * We schedule an email to send it immediately 63 | */ 64 | try { 65 | //schedule for next hour 66 | //so if this code was created by new issue creation at 9:46, the email is scheduled for 10:00 67 | //is it like this as schedule has limitiations and you cannot schedule email for 9:48 68 | const scheduleDate = new Date(Date.parse(new Date(Date.now()).toISOString()) + 1 * 1 * 60 * 60 * 1000); 69 | scheduleDate.setUTCMinutes(00); 70 | 71 | await mailchimp.campaigns.schedule(newCampaign.id, { 72 | schedule_time: scheduleDate.toISOString(), 73 | }); 74 | } catch (error) { 75 | return core.setFailed(`Failed scheduling email: ${ JSON.stringify(error) }`); 76 | } 77 | 78 | core.info(`New email campaign created`); 79 | } -------------------------------------------------------------------------------- /.github/workflows/automerge-orphans.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: 'Notify on failing automerge' 5 | 6 | on: 7 | schedule: 8 | - cron: "0 0 * * *" 9 | 10 | jobs: 11 | identify-orphans: 12 | if: startsWith(github.repository, 'asyncapi/') 13 | name: Find orphans and notify 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Checkout repository 17 | uses: actions/checkout@v4 18 | - name: Get list of orphans 19 | uses: actions/github-script@v7 20 | id: orphans 21 | with: 22 | github-token: ${{ secrets.GITHUB_TOKEN }} 23 | script: | 24 | const query = `query($owner:String!, $name:String!) { 25 | repository(owner:$owner, name:$name){ 26 | pullRequests(first: 100, states: OPEN){ 27 | nodes{ 28 | title 29 | url 30 | author { 31 | resourcePath 32 | } 33 | } 34 | } 35 | } 36 | }`; 37 | const variables = { 38 | owner: context.repo.owner, 39 | name: context.repo.repo 40 | }; 41 | const { repository: { pullRequests: { nodes } } } = await github.graphql(query, variables); 42 | 43 | let orphans = nodes.filter( (pr) => pr.author.resourcePath === '/asyncapi-bot' || pr.author.resourcePath === '/apps/dependabot') 44 | 45 | if (orphans.length) { 46 | core.setOutput('found', 'true'); 47 | //Yes, this is very naive approach to assume there is just one PR causing issues, there can be a case that more PRs are affected the same day 48 | //The thing is that handling multiple PRs will increase a complexity in this PR that in my opinion we should avoid 49 | //The other PRs will be reported the next day the action runs, or person that checks first url will notice the other ones 50 | core.setOutput('url', orphans[0].url); 51 | core.setOutput('title', orphans[0].title); 52 | } 53 | - if: steps.orphans.outputs.found == 'true' 54 | name: Convert markdown to slack markdown 55 | # This workflow is from our own org repo and safe to reference by 'master'. 56 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 57 | id: issuemarkdown 58 | with: 59 | markdown: "-> [${{steps.orphans.outputs.title}}](${{steps.orphans.outputs.url}})" 60 | - if: steps.orphans.outputs.found == 'true' 61 | name: Send info about orphan to slack 62 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 63 | env: 64 | SLACK_WEBHOOK: ${{secrets.SLACK_CI_FAIL_NOTIFY}} 65 | SLACK_TITLE: 🚨 Not merged PR that should be automerged 🚨 66 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}} 67 | MSG_MINIMAL: true -------------------------------------------------------------------------------- /.github/workflows/add-good-first-issue-labels.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this workflow is to enable anyone to label issue with 'Good First Issue' and 'area/*' with a single command. 5 | name: Add 'Good First Issue' and 'area/*' labels # if proper comment added 6 | 7 | on: 8 | issue_comment: 9 | types: 10 | - created 11 | 12 | jobs: 13 | add-labels: 14 | if: ${{(!github.event.issue.pull_request && github.event.issue.state != 'closed' && github.actor != 'asyncapi-bot') && (contains(github.event.comment.body, '/good-first-issue') || contains(github.event.comment.body, '/gfi' ))}} 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Add label 18 | uses: actions/github-script@v7 19 | with: 20 | github-token: ${{ secrets.GH_TOKEN }} 21 | script: | 22 | const areas = ['javascript', 'typescript', 'java' , 'go', 'docs', 'ci-cd', 'design']; 23 | const words = context.payload.comment.body.trim().split(" "); 24 | const areaIndex = words.findIndex((word)=> word === '/gfi' || word === '/good-first-issue') + 1 25 | let area = words[areaIndex]; 26 | switch(area){ 27 | case 'ts': 28 | area = 'typescript'; 29 | break; 30 | case 'js': 31 | area = 'javascript'; 32 | break; 33 | case 'markdown': 34 | area = 'docs'; 35 | break; 36 | } 37 | if(!areas.includes(area)){ 38 | const message = `Hey @${context.payload.sender.login}, your message doesn't follow the requirements, you can try \`/help\`.` 39 | 40 | await github.rest.issues.createComment({ 41 | issue_number: context.issue.number, 42 | owner: context.repo.owner, 43 | repo: context.repo.repo, 44 | body: message 45 | }) 46 | } else { 47 | 48 | // remove area if there is any before adding new labels. 49 | const currentLabels = (await github.rest.issues.listLabelsOnIssue({ 50 | issue_number: context.issue.number, 51 | owner: context.repo.owner, 52 | repo: context.repo.repo, 53 | })).data.map(label => label.name); 54 | 55 | const shouldBeRemoved = currentLabels.filter(label => (label.startsWith('area/') && !label.endsWith(area))); 56 | shouldBeRemoved.forEach(label => { 57 | github.rest.issues.deleteLabel({ 58 | owner: context.repo.owner, 59 | repo: context.repo.repo, 60 | name: label, 61 | }); 62 | }); 63 | 64 | // Add new labels. 65 | github.rest.issues.addLabels({ 66 | issue_number: context.issue.number, 67 | owner: context.repo.owner, 68 | repo: context.repo.repo, 69 | labels: ['good first issue', `area/${area}`] 70 | }); 71 | } 72 | -------------------------------------------------------------------------------- /src/controllers/help.controller.ts: -------------------------------------------------------------------------------- 1 | import { Router, Request, Response, NextFunction } from 'express'; 2 | import { Controller } from '../interfaces'; 3 | import { ProblemException } from '../exceptions/problem.exception'; 4 | import { getAppOpenAPI } from '../utils/app-openapi'; 5 | 6 | const getCommandsFromRequest = (req: Request): string[] => { 7 | return req.params.command ? req.params.command.split('/').filter(cmd => cmd.trim()) : []; 8 | }; 9 | 10 | const isKeyValid = (key: string, obj: any): boolean => { 11 | return Object.keys(obj).includes(key); 12 | }; 13 | 14 | const getPathKeysMatchingCommands = (commands: string[], pathKeys: string[]): string | undefined => { 15 | if (!Array.isArray(pathKeys) || !pathKeys.every(key => typeof key === 'string')) { 16 | return undefined; 17 | } 18 | return pathKeys.find(pathKey => { 19 | const pathParts = pathKey.split('/').filter(part => part !== ''); 20 | return pathParts.every((pathPart, i) => { 21 | const command = commands[Number(i)]; 22 | return pathPart === command || pathPart.startsWith('{'); 23 | }); 24 | }); 25 | }; 26 | 27 | const getFullRequestBodySpec = (operationDetails: any) => { 28 | return isKeyValid('requestBody', operationDetails) ? operationDetails.requestBody.content['application/json'].schema : null; 29 | }; 30 | 31 | const buildResponseObject = (matchedPathKey: string, method: string, operationDetails: any, requestBodySchema: any) => { 32 | return { 33 | command: matchedPathKey, 34 | method: method.toUpperCase(), 35 | summary: operationDetails.summary || '', 36 | requestBody: requestBodySchema 37 | }; 38 | }; 39 | 40 | export class HelpController implements Controller { 41 | public basepath = '/help'; 42 | 43 | public async boot(): Promise { 44 | const router: Router = Router(); 45 | 46 | router.get('/help/:command*?', async (req: Request, res: Response, next: NextFunction) => { 47 | const commands = getCommandsFromRequest(req); 48 | let openapiSpec: any; 49 | 50 | try { 51 | openapiSpec = await getAppOpenAPI(); 52 | } catch (err) { 53 | return next(err); 54 | } 55 | 56 | if (commands.length === 0) { 57 | const routes = isKeyValid('paths', openapiSpec) ? Object.keys(openapiSpec.paths).map(path => ({ command: path.replace(/^\//, ''), url: `${this.basepath}${path}` })) : []; 58 | return res.json(routes); 59 | } 60 | 61 | const pathKeys = isKeyValid('paths', openapiSpec) ? Object.keys(openapiSpec.paths) : []; 62 | const matchedPathKey = getPathKeysMatchingCommands(commands, pathKeys); 63 | 64 | if (!matchedPathKey) { 65 | return next(new ProblemException({ 66 | type: 'invalid-asyncapi-command', 67 | title: 'Invalid AsyncAPI Command', 68 | status: 404, 69 | detail: 'The given AsyncAPI command is not valid.' 70 | })); 71 | } 72 | 73 | const pathInfo = isKeyValid(matchedPathKey, openapiSpec.paths) ? openapiSpec.paths[String(matchedPathKey)] : undefined; 74 | const method = commands.length > 1 ? 'get' : 'post'; 75 | const operationDetails = isKeyValid(method, pathInfo) ? pathInfo[String(method)] : undefined; 76 | if (!operationDetails) { 77 | return next(new ProblemException({ 78 | type: 'invalid-asyncapi-command', 79 | title: 'Invalid AsyncAPI Command', 80 | status: 404, 81 | detail: 'The given AsyncAPI command is not valid.' 82 | })); 83 | } 84 | 85 | const requestBodySchema = getFullRequestBodySpec(operationDetails); 86 | 87 | return res.json(buildResponseObject(matchedPathKey, method, operationDetails, requestBodySchema)); 88 | }); 89 | 90 | return router; 91 | } 92 | } -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | env: 2 | es6: true 3 | node: true 4 | 5 | parser: "@typescript-eslint/parser" 6 | 7 | plugins: 8 | - "@typescript-eslint" 9 | - sonarjs 10 | - security 11 | 12 | extends: 13 | - eslint:recommended 14 | - plugin:@typescript-eslint/eslint-recommended 15 | - plugin:@typescript-eslint/recommended 16 | - plugin:sonarjs/recommended 17 | - plugin:security/recommended 18 | 19 | parserOptions: 20 | ecmaVersion: 2018 21 | sourceType: module 22 | ecmaFeatures: 23 | jsx: true 24 | settings: 25 | react: 26 | version: detect 27 | 28 | rules: 29 | # Ignore Rules 30 | strict: 0 31 | no-underscore-dangle: 0 32 | no-mixed-requires: 0 33 | no-process-exit: 0 34 | no-warning-comments: 0 35 | curly: 0 36 | no-multi-spaces: 0 37 | no-alert: 0 38 | consistent-return: 0 39 | consistent-this: [0, self] 40 | func-style: 0 41 | max-nested-callbacks: 0 42 | camelcase: 0 43 | 44 | # Warnings 45 | no-debugger: 1 46 | no-empty: 1 47 | no-invalid-regexp: 1 48 | no-unused-expressions: 0 49 | no-native-reassign: 1 50 | no-fallthrough: 1 51 | sonarjs/cognitive-complexity: 1 52 | 53 | # Errors 54 | eqeqeq: 2 55 | no-undef: 2 56 | no-dupe-keys: 2 57 | no-empty-character-class: 2 58 | no-self-compare: 2 59 | valid-typeof: 2 60 | no-unused-vars: [2, { "args": "none" }] 61 | handle-callback-err: 2 62 | no-shadow-restricted-names: 2 63 | no-new-require: 2 64 | no-mixed-spaces-and-tabs: 2 65 | block-scoped-var: 2 66 | no-else-return: 2 67 | no-throw-literal: 2 68 | no-void: 2 69 | radix: 2 70 | wrap-iife: [2, outside] 71 | no-shadow: 0 72 | no-path-concat: 2 73 | valid-jsdoc: [0, {requireReturn: false, requireParamDescription: false, requireReturnDescription: false}] 74 | 75 | # stylistic errors 76 | no-spaced-func: 2 77 | semi-spacing: 2 78 | quotes: [2, 'single'] 79 | key-spacing: [2, { beforeColon: false, afterColon: true }] 80 | indent: [2, 2] 81 | no-lonely-if: 2 82 | no-floating-decimal: 2 83 | brace-style: [2, 1tbs, { allowSingleLine: true }] 84 | comma-style: [2, last] 85 | no-multiple-empty-lines: [2, {max: 1}] 86 | no-nested-ternary: 2 87 | operator-assignment: [2, always] 88 | padded-blocks: [2, never] 89 | quote-props: [2, as-needed] 90 | keyword-spacing: [2, {'before': true, 'after': true, 'overrides': {}}] 91 | space-before-blocks: [2, always] 92 | array-bracket-spacing: [2, never] 93 | computed-property-spacing: [2, never] 94 | space-in-parens: [2, never] 95 | space-unary-ops: [2, {words: true, nonwords: false}] 96 | wrap-regex: 2 97 | linebreak-style: 0 98 | semi: [2, always] 99 | arrow-spacing: [2, {before: true, after: true}] 100 | no-class-assign: 2 101 | no-const-assign: 2 102 | no-dupe-class-members: 2 103 | no-this-before-super: 2 104 | no-var: 2 105 | object-shorthand: [2, always] 106 | prefer-arrow-callback: 2 107 | prefer-const: 2 108 | prefer-spread: 2 109 | prefer-template: 2 110 | 111 | # Security 112 | "security/detect-non-literal-fs-filename": off 113 | 114 | # TypeScript 115 | "@typescript-eslint/no-empty-interface": "off" 116 | # disable JS rule 117 | no-use-before-define: "off" 118 | "@typescript-eslint/no-use-before-define": ["error"] 119 | "@typescript-eslint/no-empty-function": "off" 120 | "@typescript-eslint/ban-ts-comment": "off" 121 | "@typescript-eslint/no-explicit-any": "off" 122 | "@typescript-eslint/explicit-module-boundary-types": "off" 123 | "@typescript-eslint/no-this-alias": "off" 124 | 125 | overrides: 126 | - files: 127 | - "*.spec.ts" 128 | - "*.test.ts" 129 | rules: 130 | no-undef: "off" 131 | no-console: "off" 132 | prefer-arrow-callback: 0 133 | sonarjs/no-duplicate-string: 0 134 | security/detect-object-injection: 0 -------------------------------------------------------------------------------- /.github/workflows/if-nodejs-pr-testing.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It does magic only if there is package.json file in the root of the project 5 | name: PR testing - if Node project 6 | 7 | on: 8 | pull_request: 9 | types: [opened, reopened, synchronize, ready_for_review] 10 | 11 | jobs: 12 | test-nodejs-pr: 13 | name: Test NodeJS PR - ${{ matrix.os }} 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [ubuntu-latest, macos-latest, windows-latest] 18 | steps: 19 | - if: > 20 | !github.event.pull_request.draft && !( 21 | (github.actor == 'asyncapi-bot' && ( 22 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 23 | startsWith(github.event.pull_request.title, 'chore(release):') 24 | )) || 25 | (github.actor == 'asyncapi-bot-eve' && ( 26 | startsWith(github.event.pull_request.title, 'ci: update of files from global .github repo') || 27 | startsWith(github.event.pull_request.title, 'chore(release):') 28 | )) || 29 | (github.actor == 'allcontributors[bot]' && 30 | startsWith(github.event.pull_request.title, 'docs: add') 31 | ) 32 | ) 33 | id: should_run 34 | name: Should Run 35 | run: echo "shouldrun=true" >> $GITHUB_OUTPUT 36 | shell: bash 37 | - if: steps.should_run.outputs.shouldrun == 'true' 38 | name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 39 | run: | 40 | git config --global core.autocrlf false 41 | git config --global core.eol lf 42 | shell: bash 43 | - if: steps.should_run.outputs.shouldrun == 'true' 44 | name: Checkout repository 45 | uses: actions/checkout@v4 46 | - if: steps.should_run.outputs.shouldrun == 'true' 47 | name: Check if Node.js project and has package.json 48 | id: packagejson 49 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 50 | shell: bash 51 | - if: steps.packagejson.outputs.exists == 'true' 52 | name: Check package-lock version 53 | # This workflow is from our own org repo and safe to reference by 'master'. 54 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master # //NOSONAR 55 | id: lockversion 56 | - if: steps.packagejson.outputs.exists == 'true' 57 | name: Setup Node.js 58 | uses: actions/setup-node@v4 59 | with: 60 | node-version: "${{ steps.lockversion.outputs.version }}" 61 | - if: steps.lockversion.outputs.version == '18' && matrix.os == 'windows-latest' 62 | #npm cli 10 is buggy because of some cache issue 63 | name: Install npm cli 8 64 | shell: bash 65 | run: npm install -g npm@8.19.4 66 | - if: steps.packagejson.outputs.exists == 'true' 67 | name: Install dependencies 68 | shell: bash 69 | run: npm ci 70 | - if: steps.packagejson.outputs.exists == 'true' 71 | name: Test 72 | run: npm test --if-present 73 | - if: steps.packagejson.outputs.exists == 'true' && matrix.os == 'ubuntu-latest' 74 | #linting should run just one and not on all possible operating systems 75 | name: Run linter 76 | run: npm run lint --if-present 77 | - if: steps.packagejson.outputs.exists == 'true' 78 | name: Run release assets generation to make sure PR does not break it 79 | shell: bash 80 | run: npm run generate:assets --if-present 81 | -------------------------------------------------------------------------------- /.github/workflows/help-command.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Create help comment 5 | 6 | on: 7 | issue_comment: 8 | types: 9 | - created 10 | 11 | jobs: 12 | create_help_comment_pr: 13 | if: ${{ github.event.issue.pull_request && startsWith(github.event.comment.body, '/help') && github.actor != 'asyncapi-bot' }} 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Add comment to PR 17 | uses: actions/github-script@v7 18 | env: 19 | ACTOR: ${{ github.actor }} 20 | with: 21 | github-token: ${{ secrets.GH_TOKEN }} 22 | script: | 23 | //Yes to add comment to PR the same endpoint is use that we use to create a comment in issue 24 | //For more details http://developer.github.com/v3/issues/comments/ 25 | //Also proved by this action https://github.com/actions-ecosystem/action-create-comment/blob/main/src/main.ts 26 | github.rest.issues.createComment({ 27 | issue_number: context.issue.number, 28 | owner: context.repo.owner, 29 | repo: context.repo.repo, 30 | body: `Hello, @${process.env.ACTOR}! 👋🏼 31 | 32 | I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand! 33 | 34 | At the moment the following comments are supported in pull requests: 35 | 36 | - \`/please-take-a-look\` or \`/ptal\` - This comment will add a comment to the PR asking for attention from the reviewrs who have not reviewed the PR yet. 37 | - \`/ready-to-merge\` or \`/rtm\` - This comment will trigger automerge of PR in case all required checks are green, approvals in place and do-not-merge label is not added 38 | - \`/do-not-merge\` or \`/dnm\` - This comment will block automerging even if all conditions are met and ready-to-merge label is added 39 | - \`/autoupdate\` or \`/au\` - This comment will add \`autoupdate\` label to the PR and keeps your PR up-to-date to the target branch's future changes. Unless there is a merge conflict or it is a draft PR. (Currently only works for upstream branches.) 40 | - \`/update\` or \`/u\` - This comment will update the PR with the latest changes from the target branch. Unless there is a merge conflict or it is a draft PR. NOTE: this only updates the PR once, so if you need to update again, you need to call the command again.` 41 | }) 42 | 43 | create_help_comment_issue: 44 | if: ${{ !github.event.issue.pull_request && startsWith(github.event.comment.body, '/help') && github.actor != 'asyncapi-bot' }} 45 | runs-on: ubuntu-latest 46 | steps: 47 | - name: Add comment to Issue 48 | uses: actions/github-script@v7 49 | env: 50 | ACTOR: ${{ github.actor }} 51 | with: 52 | github-token: ${{ secrets.GH_TOKEN }} 53 | script: | 54 | github.rest.issues.createComment({ 55 | issue_number: context.issue.number, 56 | owner: context.repo.owner, 57 | repo: context.repo.repo, 58 | body: `Hello, @${process.env.ACTOR}! 👋🏼 59 | 60 | I'm 🧞🧞🧞 Genie 🧞🧞🧞 from the magic lamp. Looks like somebody needs a hand! 61 | 62 | At the moment the following comments are supported in issues: 63 | 64 | - \`/good-first-issue {js | ts | java | go | docs | design | ci-cd}\` or \`/gfi {js | ts | java | go | docs | design | ci-cd}\` - label an issue as a \`good first issue\`. 65 | example: \`/gfi js\` or \`/good-first-issue ci-cd\` 66 | - \`/transfer-issue {repo-name}\` or \`/ti {repo-name}\` - transfer issue from the source repository to the other repository passed by the user. example: \`/ti cli\` or \`/transfer-issue cli\`.` 67 | }) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@asyncapi/server-api", 3 | "version": "0.16.23", 4 | "description": "Server API providing official AsyncAPI tools", 5 | "license": "Apache-2.0", 6 | "homepage": "https://github.com/asyncapi/server-api", 7 | "bugs": { 8 | "url": "https://github.com/asyncapi/server-api/issues" 9 | }, 10 | "engines": { 11 | "node": ">=14" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git://github.com/asyncapi/server-api.git" 16 | }, 17 | "keywords": [ 18 | "server", 19 | "api", 20 | "asyncapi", 21 | "generator", 22 | "tooling" 23 | ], 24 | "author": { 25 | "name": "The AsyncAPI maintainers" 26 | }, 27 | "scripts": { 28 | "start:dev": "npm run build:dev && cross-env NODE_ENV=development node dist/server.js", 29 | "start:prod": "npm run build:prod && cross-env NODE_ENV=production node dist/server.js", 30 | "start:docker": "NODE_ENV=production node dist/server.js", 31 | "dev": "cross-env NODE_ENV=development nodemon", 32 | "build:dev": "tsc", 33 | "build:prod": "tsc", 34 | "test": "cross-env NODE_ENV=test jest", 35 | "lint": "eslint --max-warnings 0 --config .eslintrc .", 36 | "lint:fix": "eslint --max-warnings 0 --config .eslintrc . --fix", 37 | "generate:assets": "npm run generate:readme:toc", 38 | "generate:readme:toc": "markdown-toc -i README.md", 39 | "docker:build": "docker build --tag asyncapi/server-api .", 40 | "bump:version": "npm --no-git-tag-version --allow-same-version version $VERSION" 41 | }, 42 | "dependencies": { 43 | "@apidevtools/json-schema-ref-parser": "^10.1.0", 44 | "@asyncapi/avro-schema-parser": "^1.1.0", 45 | "@asyncapi/bundler": "^0.4.0", 46 | "@asyncapi/converter": "1.4.17", 47 | "@asyncapi/diff": "^0.4.1", 48 | "@asyncapi/dotnet-nats-template": "^0.12.1", 49 | "@asyncapi/generator": "^1.9.18", 50 | "@asyncapi/go-watermill-template": "^0.2.74", 51 | "@asyncapi/html-template": "^0.28.4", 52 | "@asyncapi/java-spring-cloud-stream-template": "^0.13.4", 53 | "@asyncapi/java-spring-template": "^1.5.0", 54 | "@asyncapi/java-template": "^0.2.0", 55 | "@asyncapi/markdown-template": "^1.4.0", 56 | "@asyncapi/nodejs-template": "^2.0.1", 57 | "@asyncapi/nodejs-ws-template": "^0.9.33", 58 | "@asyncapi/openapi-schema-parser": "^2.0.3", 59 | "@asyncapi/parser": "^1.18.1", 60 | "@asyncapi/problem": "^1.0.0", 61 | "@asyncapi/python-paho-template": "^0.2.13", 62 | "@asyncapi/raml-dt-schema-parser": "^2.0.1", 63 | "@asyncapi/specs": "^4.2.1", 64 | "@asyncapi/ts-nats-template": "^0.10.3", 65 | "ajv": "^8.8.2", 66 | "ajv-formats": "^2.1.1", 67 | "archiver": "^5.3.0", 68 | "body-parser": "^1.19.0", 69 | "compression": "^1.7.4", 70 | "config": "^3.3.6", 71 | "cors": "^2.8.5", 72 | "express": "^4.17.1", 73 | "helmet": "^6.0.1", 74 | "js-yaml": "^4.1.0", 75 | "redoc-express": "^1.0.0", 76 | "types": "^0.1.1", 77 | "uuid": "^8.3.2", 78 | "winston": "^3.3.3" 79 | }, 80 | "devDependencies": { 81 | "@types/archiver": "^5.1.1", 82 | "@types/body-parser": "^1.19.1", 83 | "@types/compression": "^1.7.2", 84 | "@types/config": "0.0.40", 85 | "@types/cookie-parser": "^1.4.2", 86 | "@types/cors": "^2.8.12", 87 | "@types/express": "^4.17.13", 88 | "@types/jest": "^27.0.3", 89 | "@types/js-yaml": "^4.0.5", 90 | "@types/node": "^16.18.126", 91 | "@types/supertest": "^2.0.11", 92 | "@types/uuid": "^8.3.1", 93 | "@typescript-eslint/eslint-plugin": "^5.7.0", 94 | "@typescript-eslint/parser": "^5.7.0", 95 | "cross-env": "^7.0.3", 96 | "eslint": "^8.4.1", 97 | "eslint-plugin-security": "^1.4.0", 98 | "eslint-plugin-sonarjs": "^0.11.0", 99 | "jest": "^27.4.1", 100 | "markdown-toc": "^1.2.0", 101 | "nodemon": "^2.0.13", 102 | "supertest": "^6.1.6", 103 | "ts-jest": "^27.0.7", 104 | "ts-node": "^10.2.1", 105 | "typescript": "^4.4.3" 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /.github/workflows/if-nodejs-version-bump.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It does magic only if there is package.json file in the root of the project 5 | name: Version bump - if Node.js project 6 | 7 | on: 8 | release: 9 | types: 10 | - published 11 | 12 | jobs: 13 | version_bump: 14 | name: Generate assets and bump NodeJS 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v4 19 | with: 20 | # target branch of release. More info https://docs.github.com/en/rest/reference/repos#releases 21 | # in case release is created from release branch then we need to checkout from given branch 22 | # if @semantic-release/github is used to publish, the minimum version is 7.2.0 for proper working 23 | ref: ${{ github.event.release.target_commitish }} 24 | - name: Check if Node.js project and has package.json 25 | id: packagejson 26 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 27 | - if: steps.packagejson.outputs.exists == 'true' 28 | name: Check package-lock version 29 | # This workflow is from our own org repo and safe to reference by 'master'. 30 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master # //NOSONAR 31 | id: lockversion 32 | - if: steps.packagejson.outputs.exists == 'true' 33 | name: Setup Node.js 34 | uses: actions/setup-node@v4 35 | with: 36 | node-version: "${{ steps.lockversion.outputs.version }}" 37 | cache: 'npm' 38 | cache-dependency-path: '**/package-lock.json' 39 | - if: steps.packagejson.outputs.exists == 'true' 40 | name: Install dependencies 41 | run: npm ci 42 | - if: steps.packagejson.outputs.exists == 'true' 43 | name: Assets generation 44 | run: npm run generate:assets --if-present 45 | - if: steps.packagejson.outputs.exists == 'true' 46 | name: Bump version in package.json 47 | # There is no need to substract "v" from the tag as version script handles it 48 | # When adding "bump:version" script in package.json, make sure no tags are added by default (--no-git-tag-version) as they are already added by release workflow 49 | # When adding "bump:version" script in package.json, make sure --allow-same-version is set in case someone forgot and updated package.json manually and we want to avoide this action to fail and raise confusion 50 | env: 51 | VERSION: ${{github.event.release.tag_name}} 52 | run: npm run bump:version 53 | - if: steps.packagejson.outputs.exists == 'true' 54 | name: Create Pull Request with updated asset files including package.json 55 | uses: peter-evans/create-pull-request@38e0b6e68b4c852a5500a94740f0e535e0d7ba54 # use 4.2.4 https://github.com/peter-evans/create-pull-request/releases/tag/v4.2.4 56 | env: 57 | RELEASE_TAG: ${{github.event.release.tag_name}} 58 | RELEASE_URL: ${{github.event.release.html_url}} 59 | with: 60 | token: ${{ secrets.GH_TOKEN }} 61 | commit-message: 'chore(release): ${{ env.RELEASE_TAG }}' 62 | committer: asyncapi-bot 63 | author: asyncapi-bot 64 | title: 'chore(release): ${{ env.RELEASE_TAG }}' 65 | body: 'Version bump in package.json for release [${{ env.RELEASE_TAG }}](${{ env.RELEASE_URL }})' 66 | branch: version-bump/${{ env.RELEASE_TAG }} 67 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 68 | name: Report workflow run status to Slack 69 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 70 | with: 71 | status: ${{ job.status }} 72 | fields: repo,action,workflow 73 | text: 'Unable to bump the version in package.json after the release' 74 | env: 75 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} -------------------------------------------------------------------------------- /.github/workflows/issues-prs-notifications.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # This action notifies community on slack whenever there is a new issue, PR or discussion started in given repository 5 | name: Notify slack 6 | 7 | on: 8 | issues: 9 | types: [opened, reopened] 10 | 11 | pull_request_target: 12 | types: [opened, reopened, ready_for_review] 13 | 14 | discussion: 15 | types: [created] 16 | 17 | jobs: 18 | issue: 19 | if: github.event_name == 'issues' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]' 20 | name: Notify slack on every new issue 21 | runs-on: ubuntu-latest 22 | steps: 23 | - name: Convert markdown to slack markdown for issue 24 | # This workflow is from our own org repo and safe to reference by 'master'. 25 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 26 | id: issuemarkdown 27 | env: 28 | ISSUE_TITLE: ${{github.event.issue.title}} 29 | ISSUE_URL: ${{github.event.issue.html_url}} 30 | ISSUE_BODY: ${{github.event.issue.body}} 31 | with: 32 | markdown: "[${{ env.ISSUE_TITLE }}](${{ env.ISSUE_URL }}) \n ${{ env.ISSUE_BODY }}" 33 | - name: Send info about issue 34 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 35 | env: 36 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}} 37 | SLACK_TITLE: 🐛 New Issue in ${{github.repository}} 🐛 38 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}} 39 | MSG_MINIMAL: true 40 | 41 | pull_request: 42 | if: github.event_name == 'pull_request_target' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]' 43 | name: Notify slack on every new pull request 44 | runs-on: ubuntu-latest 45 | steps: 46 | - name: Convert markdown to slack markdown for pull request 47 | # This workflow is from our own org repo and safe to reference by 'master'. 48 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 49 | id: prmarkdown 50 | env: 51 | PR_TITLE: ${{github.event.pull_request.title}} 52 | PR_URL: ${{github.event.pull_request.html_url}} 53 | PR_BODY: ${{github.event.pull_request.body}} 54 | with: 55 | markdown: "[${{ env.PR_TITLE }}](${{ env.PR_URL }}) \n ${{ env.PR_BODY }}" 56 | - name: Send info about pull request 57 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 58 | env: 59 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}} 60 | SLACK_TITLE: 💪 New Pull Request in ${{github.repository}} 💪 61 | SLACK_MESSAGE: ${{steps.prmarkdown.outputs.text}} 62 | MSG_MINIMAL: true 63 | 64 | discussion: 65 | if: github.event_name == 'discussion' && github.actor != 'asyncapi-bot' && github.actor != 'dependabot[bot]' && github.actor != 'dependabot-preview[bot]' 66 | name: Notify slack on every new pull request 67 | runs-on: ubuntu-latest 68 | steps: 69 | - name: Convert markdown to slack markdown for pull request 70 | # This workflow is from our own org repo and safe to reference by 'master'. 71 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 72 | id: discussionmarkdown 73 | env: 74 | DISCUSSION_TITLE: ${{github.event.discussion.title}} 75 | DISCUSSION_URL: ${{github.event.discussion.html_url}} 76 | DISCUSSION_BODY: ${{github.event.discussion.body}} 77 | with: 78 | markdown: "[${{ env.DISCUSSION_TITLE }}](${{ env.DISCUSSION_URL }}) \n ${{ env.DISCUSSION_BODY }}" 79 | - name: Send info about pull request 80 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 81 | env: 82 | SLACK_WEBHOOK: ${{secrets.SLACK_GITHUB_NEWISSUEPR}} 83 | SLACK_TITLE: 💬 New Discussion in ${{github.repository}} 💬 84 | SLACK_MESSAGE: ${{steps.discussionmarkdown.outputs.text}} 85 | MSG_MINIMAL: true 86 | -------------------------------------------------------------------------------- /.github/workflows/automerge-for-humans-merging.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this workflow is to allow people to merge PR without a need of maintainer doing it. If all checks are in place (including maintainers approval) - JUST MERGE IT! 5 | name: Automerge For Humans 6 | 7 | on: 8 | pull_request_target: 9 | types: 10 | - labeled 11 | - unlabeled 12 | - synchronize 13 | - opened 14 | - edited 15 | - ready_for_review 16 | - reopened 17 | - unlocked 18 | 19 | jobs: 20 | automerge-for-humans: 21 | # it runs only if PR actor is not a bot, at least not a bot that we know 22 | if: | 23 | github.event.pull_request.draft == false && 24 | (github.event.pull_request.user.login != 'asyncapi-bot' || 25 | github.event.pull_request.user.login != 'dependabot[bot]' || 26 | github.event.pull_request.user.login != 'dependabot-preview[bot]') 27 | runs-on: ubuntu-latest 28 | steps: 29 | - name: Get PR authors 30 | id: authors 31 | uses: actions/github-script@v7 32 | with: 33 | script: | 34 | // Get paginated list of all commits in the PR 35 | try { 36 | const commitOpts = github.rest.pulls.listCommits.endpoint.merge({ 37 | owner: context.repo.owner, 38 | repo: context.repo.repo, 39 | pull_number: context.issue.number 40 | }); 41 | 42 | const commits = await github.paginate(commitOpts); 43 | 44 | if (commits.length === 0) { 45 | core.setFailed('No commits found in the PR'); 46 | return ''; 47 | } 48 | 49 | // Get unique authors from the commits list 50 | const authors = commits.reduce((acc, commit) => { 51 | const username = commit.author?.login || commit.commit.author?.name; 52 | if (username && !acc[username]) { 53 | acc[username] = { 54 | name: commit.commit.author?.name, 55 | email: commit.commit.author?.email, 56 | } 57 | } 58 | 59 | return acc; 60 | }, {}); 61 | 62 | return authors; 63 | } catch (error) { 64 | core.setFailed(error.message); 65 | return []; 66 | } 67 | 68 | - name: Create commit message 69 | id: create-commit-message 70 | uses: actions/github-script@v7 71 | with: 72 | script: | 73 | const authors = ${{ steps.authors.outputs.result }}; 74 | 75 | if (Object.keys(authors).length === 0) { 76 | core.setFailed('No authors found in the PR'); 77 | return ''; 78 | } 79 | 80 | // Create a string of the form "Co-authored-by: Name " 81 | // ref: https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors 82 | const coAuthors = Object.values(authors).map(author => { 83 | return `Co-authored-by: ${author.name} <${author.email}>`; 84 | }).join('\n'); 85 | 86 | core.debug(coAuthors);; 87 | 88 | return coAuthors; 89 | 90 | - name: Automerge PR 91 | uses: pascalgn/automerge-action@22948e0bc22f0aa673800da838595a3e7347e584 #v0.15.6 https://github.com/pascalgn/automerge-action/releases/tag/v0.15.6 92 | env: 93 | GITHUB_TOKEN: "${{ secrets.GH_TOKEN }}" 94 | MERGE_LABELS: "!do-not-merge,ready-to-merge" 95 | MERGE_METHOD: "squash" 96 | # Using the output of the previous step (`Co-authored-by: ...` lines) as commit description. 97 | # Important to keep 2 empty lines as https://docs.github.com/en/pull-requests/committing-changes-to-your-project/creating-and-editing-commits/creating-a-commit-with-multiple-authors#creating-co-authored-commits-on-the-command-line mentions 98 | MERGE_COMMIT_MESSAGE: "{pullRequest.title} (#{pullRequest.number})\n\n\n${{ fromJSON(steps.create-commit-message.outputs.result) }}" 99 | MERGE_RETRIES: "20" 100 | MERGE_RETRY_SLEEP: "30000" 101 | -------------------------------------------------------------------------------- /src/controllers/tests/diff.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { DiffController } from '../../controllers/diff.controller'; 7 | 8 | describe('DiffController', () => { 9 | describe('[POST] /diff', () => { 10 | it('should diff AsyncAPI documents', async () => { 11 | const app = new App([new DiffController()]); 12 | await app.init(); 13 | 14 | await request(app.getServer()) 15 | .post('/v1/diff') 16 | .send({ 17 | asyncapis: [ 18 | { 19 | asyncapi: '2.3.0', 20 | info: { 21 | title: 'Super test', 22 | version: '1.0.0' 23 | }, 24 | channels: { 25 | 'test-channel-1': { 26 | publish: { 27 | message: { 28 | payload: { 29 | type: 'object', 30 | }, 31 | }, 32 | } 33 | }, 34 | }, 35 | }, 36 | { 37 | asyncapi: '2.3.0', 38 | info: { 39 | title: 'Changed super test', 40 | version: '1.1.0' 41 | }, 42 | channels: { 43 | 'test-channel-1': { 44 | publish: { 45 | message: { 46 | payload: { 47 | type: 'object', 48 | }, 49 | }, 50 | } 51 | }, 52 | }, 53 | }, 54 | ], 55 | }) 56 | .expect(200, { 57 | diff: { 58 | changes: [ 59 | { 60 | action: 'edit', 61 | path: '/info/version', 62 | before: '1.0.0', 63 | after: '1.1.0', 64 | type: 'breaking', 65 | }, 66 | { 67 | action: 'edit', 68 | path: '/info/title', 69 | before: 'Super test', 70 | after: 'Changed super test', 71 | type: 'non-breaking', 72 | }, 73 | ], 74 | } 75 | }); 76 | }); 77 | 78 | it('should throw error with invalid AsyncAPI document', async () => { 79 | const app = new App([new DiffController()]); 80 | await app.init(); 81 | 82 | await request(app.getServer()) 83 | .post('/v1/diff') 84 | .send({ 85 | asyncapis: [ 86 | { 87 | asyncapi: '2.2.0', 88 | info: { 89 | title: 'Test Service', 90 | version: '1.0.0', 91 | }, 92 | channels: { 93 | 'test-channel-2': { 94 | publish: { 95 | message: { 96 | payload: { 97 | type: 'object', 98 | }, 99 | }, 100 | } 101 | }, 102 | }, 103 | }, 104 | { 105 | asyncapi: '2.2.0', 106 | info: { 107 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 108 | version: '1.0.0' 109 | }, 110 | channels: {}, 111 | } 112 | ], 113 | }) 114 | .expect(422, { 115 | type: ProblemException.createType('validation-errors'), 116 | title: 'There were errors validating the AsyncAPI document.', 117 | status: 422, 118 | validationErrors: [ 119 | { 120 | title: '/info should NOT have additional properties', 121 | location: { 122 | jsonPointer: '/info' 123 | } 124 | }, 125 | { 126 | title: '/info should have required property \'title\'', 127 | location: { 128 | jsonPointer: '/info' 129 | } 130 | } 131 | ], 132 | parsedJSON: { 133 | asyncapi: '2.2.0', 134 | info: { 135 | tite: 'My API', 136 | version: '1.0.0' 137 | }, 138 | channels: {} 139 | } 140 | }); 141 | }); 142 | }); 143 | }); 144 | -------------------------------------------------------------------------------- /src/controllers/tests/generate.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { GenerateController } from '../generate.controller'; 7 | 8 | describe('GeneratorController', () => { 9 | describe('[POST] /generate', () => { 10 | it('should generate template ', async () => { 11 | const app = new App([new GenerateController()]); 12 | await app.init(); 13 | 14 | return request(app.getServer()) 15 | .post('/v1/generate') 16 | .send({ 17 | asyncapi: { 18 | asyncapi: '2.2.0', 19 | info: { 20 | title: 'Test Service', 21 | version: '1.0.0', 22 | }, 23 | channels: {}, 24 | }, 25 | template: '@asyncapi/html-template', 26 | parameters: { 27 | version: '2.1.37', 28 | } 29 | }) 30 | .expect(200); 31 | }); 32 | 33 | it('should pass when sent template parameters are empty', async () => { 34 | const app = new App([new GenerateController()]); 35 | await app.init(); 36 | 37 | return request(app.getServer()) 38 | .post('/v1/generate') 39 | .send({ 40 | asyncapi: { 41 | asyncapi: '2.2.0', 42 | info: { 43 | title: 'Test Service', 44 | version: '1.0.0', 45 | }, 46 | channels: {}, 47 | }, 48 | template: '@asyncapi/html-template', 49 | }) 50 | .expect(200); 51 | }); 52 | 53 | it('should throw error when sent template parameters are invalid', async () => { 54 | const app = new App([new GenerateController()]); 55 | await app.init(); 56 | 57 | return request(app.getServer()) 58 | .post('/v1/generate') 59 | .send({ 60 | asyncapi: { 61 | asyncapi: '2.2.0', 62 | info: { 63 | title: 'Test Service', 64 | version: '1.0.0', 65 | }, 66 | channels: {}, 67 | }, 68 | template: '@asyncapi/html-template', 69 | parameters: { 70 | customParameter: 'customValue', 71 | } 72 | }) 73 | .expect(422, { 74 | type: ProblemException.createType('invalid-template-parameters'), 75 | title: 'Invalid Generator Template parameters', 76 | status: 422, 77 | validationErrors: [ 78 | { 79 | instancePath: '', 80 | schemaPath: '#/additionalProperties', 81 | keyword: 'additionalProperties', 82 | params: { 83 | additionalProperty: 'customParameter' 84 | }, 85 | message: 'must NOT have additional properties' 86 | } 87 | ] 88 | }); 89 | }); 90 | 91 | it('should throw error when required parameter is not sent', async () => { 92 | const app = new App([new GenerateController()]); 93 | await app.init(); 94 | 95 | return request(app.getServer()) 96 | .post('/v1/generate') 97 | .send({ 98 | asyncapi: { 99 | asyncapi: '2.2.0', 100 | info: { 101 | title: 'Test Service', 102 | version: '1.0.0', 103 | }, 104 | channels: {}, 105 | }, 106 | template: '@asyncapi/nodejs-template', 107 | parameters: { 108 | invalidServer: 'invalidServer', 109 | } 110 | }) 111 | .expect(422, { 112 | type: ProblemException.createType('invalid-template-parameters'), 113 | title: 'Invalid Generator Template parameters', 114 | status: 422, 115 | validationErrors: [ 116 | { 117 | instancePath: '', 118 | schemaPath: '#/required', 119 | keyword: 'required', 120 | params: { missingProperty: 'server' }, 121 | message: 'must have required property \'server\'' 122 | }, 123 | { 124 | instancePath: '', 125 | schemaPath: '#/additionalProperties', 126 | keyword: 'additionalProperties', 127 | params: { additionalProperty: 'invalidServer' }, 128 | message: 'must NOT have additional properties' 129 | } 130 | ] 131 | }); 132 | }); 133 | }); 134 | }); 135 | -------------------------------------------------------------------------------- /src/controllers/tests/convert.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | import { ALL_SPECS } from '../../interfaces'; 6 | 7 | import { ConvertController } from '../convert.controller'; 8 | 9 | const validJsonAsyncAPI2_0_0 = { 10 | asyncapi: '2.0.0', 11 | info: { 12 | title: 'Super test', 13 | version: '1.0.0' 14 | }, 15 | channels: {} 16 | }; 17 | 18 | const validJsonAsyncAPI2_1_0 = { 19 | asyncapi: '2.1.0', 20 | info: { 21 | title: 'Super test', 22 | version: '1.0.0' 23 | }, 24 | channels: {} 25 | }; 26 | 27 | const validYamlAsyncAPI2_4_0 = ` 28 | asyncapi: 2.4.0 29 | info: 30 | title: Super test 31 | version: 1.0.0 32 | channels: {} 33 | `; 34 | 35 | describe('ConvertController', () => { 36 | describe('[POST] /convert', () => { 37 | it('should throw error with invalid version', async () => { 38 | const app = new App([new ConvertController()]); 39 | await app.init(); 40 | 41 | return request(app.getServer()) 42 | .post('/v1/convert') 43 | .send({ 44 | asyncapi: { 45 | asyncapi: '2.2.0', 46 | info: { 47 | title: 'Test Service', 48 | version: '1.0.0', 49 | }, 50 | channels: {}, 51 | }, 52 | version: '1' 53 | }) 54 | .expect(422, { 55 | type: ProblemException.createType('invalid-request-body'), 56 | title: 'Invalid Request Body', 57 | status: 422, 58 | validationErrors: [ 59 | { 60 | instancePath: '/version', 61 | schemaPath: '#/properties/version/enum', 62 | keyword: 'enum', 63 | params: { 64 | allowedValues: [...ALL_SPECS, 'latest'], 65 | }, 66 | message: 'must be equal to one of the allowed values' 67 | } 68 | ] 69 | }); 70 | }); 71 | 72 | it('should throw error that the converter cannot convert to a lower version', async () => { 73 | const app = new App([new ConvertController()]); 74 | await app.init(); 75 | 76 | return request(app.getServer()) 77 | .post('/v1/convert') 78 | .send({ 79 | asyncapi: validJsonAsyncAPI2_1_0, 80 | version: '2.0.0' 81 | }) 82 | .expect(422, { 83 | type: 'https://api.asyncapi.com/problem/internal-converter-error', 84 | title: 'Could not convert document', 85 | status: 422, 86 | detail: 'Cannot downgrade from 2.1.0 to 2.0.0.', 87 | }); 88 | }); 89 | 90 | it('should pass when converting to 2.4.0 version', async () => { 91 | const app = new App([new ConvertController()]); 92 | await app.init(); 93 | 94 | return request(app.getServer()) 95 | .post('/v1/convert') 96 | .send({ 97 | asyncapi: validJsonAsyncAPI2_0_0, 98 | version: '2.4.0' 99 | }) 100 | .expect(200, { 101 | converted: { 102 | asyncapi: '2.4.0', 103 | info: { 104 | title: 'Super test', 105 | version: '1.0.0' 106 | }, 107 | channels: {}, 108 | }, 109 | }); 110 | }); 111 | 112 | it('should pass when converting to latest version', async () => { 113 | const app = new App([new ConvertController()]); 114 | await app.init(); 115 | 116 | return request(app.getServer()) 117 | .post('/v1/convert') 118 | .send({ 119 | asyncapi: validJsonAsyncAPI2_0_0, 120 | }) 121 | .expect(200, { 122 | converted: { 123 | asyncapi: '2.6.0', 124 | info: { 125 | title: 'Super test', 126 | version: '1.0.0' 127 | }, 128 | channels: {}, 129 | }, 130 | }); 131 | }); 132 | 133 | it('should correctly convert JSON to YAML', async () => { 134 | const app = new App([new ConvertController()]); 135 | await app.init(); 136 | 137 | return request(app.getServer()) 138 | .post('/v1/convert') 139 | .send({ 140 | asyncapi: validJsonAsyncAPI2_0_0, 141 | version: '2.4.0', 142 | language: 'yaml' 143 | }) 144 | .expect(200, { 145 | converted: validYamlAsyncAPI2_4_0.trimStart(), 146 | }); 147 | }); 148 | }); 149 | }); 150 | -------------------------------------------------------------------------------- /.github/workflows/welcome-first-time-contrib.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: Welcome first time contributors 5 | 6 | on: 7 | pull_request_target: 8 | types: 9 | - opened 10 | issues: 11 | types: 12 | - opened 13 | 14 | jobs: 15 | welcome: 16 | name: Post welcome message 17 | if: ${{ !contains(fromJson('["asyncapi-bot", "dependabot[bot]", "dependabot-preview[bot]", "allcontributors[bot]"]'), github.actor) }} 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/github-script@v7 21 | with: 22 | github-token: ${{ secrets.GITHUB_TOKEN }} 23 | script: | 24 | const issueMessage = `Welcome to AsyncAPI. Thanks a lot for reporting your first issue. Please check out our [contributors guide](https://github.com/asyncapi/community/blob/master/CONTRIBUTING.md) and the instructions about a [basic recommended setup](https://github.com/asyncapi/community/blob/master/git-workflow.md) useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out [this issue](https://github.com/asyncapi/asyncapi/issues/115).`; 25 | const prMessage = `Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our [contributors guide](https://github.com/asyncapi/community/blob/master/CONTRIBUTING.md) useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out [this issue](https://github.com/asyncapi/asyncapi/issues/115).`; 26 | if (!issueMessage && !prMessage) { 27 | throw new Error('Action must have at least one of issue-message or pr-message set'); 28 | } 29 | const isIssue = !!context.payload.issue; 30 | let isFirstContribution; 31 | if (isIssue) { 32 | const query = `query($owner:String!, $name:String!, $contributer:String!) { 33 | repository(owner:$owner, name:$name){ 34 | issues(first: 1, filterBy: {createdBy:$contributer}){ 35 | totalCount 36 | } 37 | } 38 | }`; 39 | const variables = { 40 | owner: context.repo.owner, 41 | name: context.repo.repo, 42 | contributer: context.payload.sender.login 43 | }; 44 | const { repository: { issues: { totalCount } } } = await github.graphql(query, variables); 45 | isFirstContribution = totalCount === 1; 46 | } else { 47 | const query = `query($qstr: String!) { 48 | search(query: $qstr, type: ISSUE, first: 1) { 49 | issueCount 50 | } 51 | }`; 52 | const variables = { 53 | "qstr": `repo:${context.repo.owner}/${context.repo.repo} type:pr author:${context.payload.sender.login}`, 54 | }; 55 | const { search: { issueCount } } = await github.graphql(query, variables); 56 | isFirstContribution = issueCount === 1; 57 | } 58 | 59 | if (!isFirstContribution) { 60 | console.log(`Not the users first contribution.`); 61 | return; 62 | } 63 | const message = isIssue ? issueMessage : prMessage; 64 | // Add a comment to the appropriate place 65 | if (isIssue) { 66 | const issueNumber = context.payload.issue.number; 67 | console.log(`Adding message: ${message} to issue #${issueNumber}`); 68 | await github.rest.issues.createComment({ 69 | owner: context.payload.repository.owner.login, 70 | repo: context.payload.repository.name, 71 | issue_number: issueNumber, 72 | body: message 73 | }); 74 | } 75 | else { 76 | const pullNumber = context.payload.pull_request.number; 77 | console.log(`Adding message: ${message} to pull request #${pullNumber}`); 78 | await github.rest.pulls.createReview({ 79 | owner: context.payload.repository.owner.login, 80 | repo: context.payload.repository.name, 81 | pull_number: pullNumber, 82 | body: message, 83 | event: 'COMMENT' 84 | }); 85 | } 86 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to AsyncAPI 2 | We love your input! We want to make contributing to this project as easy and transparent as possible. 3 | 4 | ## Contribution recogniton 5 | 6 | We use [All Contributors](https://allcontributors.org/docs/en/specification) specification to handle recognitions. For more details read [this](https://www.asyncapi.com/docs/community/010-contribution-guidelines/recognize-contributors#main-content) document. 7 | 8 | 9 | 10 | 11 | ## Summary of the contribution flow 12 | 13 | The following is a summary of the ideal contribution flow. Please, note that Pull Requests can also be rejected by the maintainers when appropriate. 14 | 15 | ``` 16 | ┌───────────────────────┐ 17 | │ │ 18 | │ Open an issue │ 19 | │ (a bug report or a │ 20 | │ feature request) │ 21 | │ │ 22 | └───────────────────────┘ 23 | ⇩ 24 | ┌───────────────────────┐ 25 | │ │ 26 | │ Open a Pull Request │ 27 | │ (only after issue │ 28 | │ is approved) │ 29 | │ │ 30 | └───────────────────────┘ 31 | ⇩ 32 | ┌───────────────────────┐ 33 | │ │ 34 | │ Your changes will │ 35 | │ be merged and │ 36 | │ published on the next │ 37 | │ release │ 38 | │ │ 39 | └───────────────────────┘ 40 | ``` 41 | 42 | ## Code of Conduct 43 | AsyncAPI has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](./CODE_OF_CONDUCT.md) so that you can understand what sort of behaviour is expected. 44 | 45 | ## Our Development Process 46 | We use Github to host code, to track issues and feature requests, as well as accept pull requests. 47 | 48 | ## Issues 49 | [Open an issue](https://github.com/asyncapi/asyncapi/issues/new) **only** if you want to report a bug or a feature. Don't open issues for questions or support, instead join our [Slack workspace](https://www.asyncapi.com/slack-invite) and ask there. Don't forget to follow our [Slack Etiquette](https://www.asyncapi.com/docs/community/060-meetings-and-communication/slack-etiquette) while interacting with community members! It's more likely you'll get help, and much faster! 50 | 51 | ## Bug Reports and Feature Requests 52 | 53 | Please use our issues templates that provide you with hints on what information we need from you to help you out. 54 | 55 | ## Pull Requests 56 | 57 | **Please, make sure you open an issue before starting with a Pull Request, unless it's a typo or a really obvious error.** Pull requests are the best way to propose changes to the specification. Get familiar with our document that explains [Git workflow](https://www.asyncapi.com/docs/community/010-contribution-guidelines/git-workflow) used in our repositories. 58 | 59 | ## Conventional commits 60 | 61 | Our repositories follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/#summary) specification. Releasing to GitHub and NPM is done with the support of [semantic-release](https://semantic-release.gitbook.io/semantic-release/). 62 | 63 | Pull requests should have a title that follows the specification, otherwise, merging is blocked. If you are not familiar with the specification simply ask maintainers to modify. You can also use this cheatsheet if you want: 64 | 65 | - `fix: ` prefix in the title indicates that PR is a bug fix and PATCH release must be triggered. 66 | - `feat: ` prefix in the title indicates that PR is a feature and MINOR release must be triggered. 67 | - `docs: ` prefix in the title indicates that PR is only related to the documentation and there is no need to trigger release. 68 | - `chore: ` prefix in the title indicates that PR is only related to cleanup in the project and there is no need to trigger release. 69 | - `test: ` prefix in the title indicates that PR is only related to tests and there is no need to trigger release. 70 | - `refactor: ` prefix in the title indicates that PR is only related to refactoring and there is no need to trigger release. 71 | 72 | What about MAJOR release? just add `!` to the prefix, like `fix!: ` or `refactor!: ` 73 | 74 | Prefix that follows specification is not enough though. Remember that the title must be clear and descriptive with usage of [imperative mood](https://chris.beams.io/posts/git-commit/#imperative). 75 | 76 | Happy contributing :heart: 77 | 78 | ## License 79 | When you submit changes, your submissions are understood to be under the same [Apache 2.0 License](https://github.com/asyncapi/asyncapi/blob/master/LICENSE) that covers the project. Feel free to [contact the maintainers](https://www.asyncapi.com/slack-invite) if that's a concern. 80 | 81 | ## References 82 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/master/CONTRIBUTING.md). 83 | -------------------------------------------------------------------------------- /.github/workflows/update-pr.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # This workflow will run on every comment with /update or /u. And will create merge-commits for the PR. 5 | # This also works with forks, not only with branches in the same repository/organization. 6 | # Currently, does not work with forks in different organizations. 7 | 8 | # This workflow will be distributed to all repositories in the AsyncAPI organization 9 | 10 | name: Update PR branches from fork 11 | 12 | on: 13 | issue_comment: 14 | types: [created] 15 | 16 | jobs: 17 | update-pr: 18 | if: > 19 | startsWith(github.repository, 'asyncapi/') && 20 | github.event.issue.pull_request && 21 | github.event.issue.state != 'closed' && ( 22 | contains(github.event.comment.body, '/update') || 23 | contains(github.event.comment.body, '/u') 24 | ) 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Get Pull Request Details 28 | id: pr 29 | uses: actions/github-script@v7 30 | with: 31 | github-token: ${{ secrets.GH_TOKEN || secrets.GITHUB_TOKEN }} 32 | previews: 'merge-info-preview' # https://docs.github.com/en/graphql/overview/schema-previews#merge-info-preview-more-detailed-information-about-a-pull-requests-merge-state-preview 33 | script: | 34 | const prNumber = context.payload.issue.number; 35 | core.debug(`PR Number: ${prNumber}`); 36 | const { data: pr } = await github.rest.pulls.get({ 37 | owner: context.repo.owner, 38 | repo: context.repo.repo, 39 | pull_number: prNumber 40 | }); 41 | 42 | // If the PR has conflicts, we don't want to update it 43 | const updateable = ['behind', 'blocked', 'unknown', 'draft', 'clean'].includes(pr.mergeable_state); 44 | console.log(`PR #${prNumber} is ${pr.mergeable_state} and is ${updateable ? 'updateable' : 'not updateable'}`); 45 | core.setOutput('updateable', updateable); 46 | 47 | core.debug(`Updating PR #${prNumber} with head ${pr.head.sha}`); 48 | 49 | return { 50 | id: pr.node_id, 51 | number: prNumber, 52 | head: pr.head.sha, 53 | } 54 | - name: Update the Pull Request 55 | if: steps.pr.outputs.updateable == 'true' 56 | uses: actions/github-script@v7 57 | with: 58 | github-token: ${{ secrets.GH_TOKEN || secrets.GITHUB_TOKEN }} 59 | script: | 60 | const mutation = `mutation update($input: UpdatePullRequestBranchInput!) { 61 | updatePullRequestBranch(input: $input) { 62 | pullRequest { 63 | mergeable 64 | } 65 | } 66 | }`; 67 | 68 | const pr_details = ${{ steps.pr.outputs.result }}; 69 | 70 | try { 71 | const { data } = await github.graphql(mutation, { 72 | input: { 73 | pullRequestId: pr_details.id, 74 | expectedHeadOid: pr_details.head, 75 | } 76 | }); 77 | } catch (GraphQLError) { 78 | core.debug(GraphQLError); 79 | if ( 80 | GraphQLError.name === 'GraphqlResponseError' && 81 | GraphQLError.errors.some( 82 | error => error.type === 'FORBIDDEN' || error.type === 'UNAUTHORIZED' 83 | ) 84 | ) { 85 | // Add comment to PR if the bot doesn't have permissions to update the PR 86 | const comment = `Hi @${context.actor}. Update of PR has failed. It can be due to one of the following reasons: 87 | - I don't have permissions to update this PR. To update your fork with upstream using bot you need to enable [Allow edits from maintainers](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) option in the PR. 88 | - The fork is located in an organization, not under your personal profile. No solution for that. You are on your own with manual update. 89 | - There may be a conflict in the PR. Please resolve the conflict and try again.`; 90 | 91 | await github.rest.issues.createComment({ 92 | owner: context.repo.owner, 93 | repo: context.repo.repo, 94 | issue_number: context.issue.number, 95 | body: comment 96 | }); 97 | 98 | core.setFailed('Bot does not have permissions to update the PR'); 99 | } else { 100 | core.setFailed(GraphQLError.message); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/middlewares/validation.middleware.ts: -------------------------------------------------------------------------------- 1 | import { Request, Response, NextFunction } from 'express'; 2 | import { AsyncAPIDocument } from '@asyncapi/parser'; 3 | 4 | import { ProblemException } from '../exceptions/problem.exception'; 5 | import { createAjvInstance } from '../utils/ajv'; 6 | import { getAppOpenAPI } from '../utils/app-openapi'; 7 | import { 8 | parse, 9 | prepareParserConfig, 10 | tryConvertToProblemException, 11 | } from '../utils/parser'; 12 | 13 | import type { ValidateFunction } from 'ajv'; 14 | 15 | export interface ValidationMiddlewareOptions { 16 | path: string; 17 | method: 18 | | 'all' 19 | | 'get' 20 | | 'post' 21 | | 'put' 22 | | 'delete' 23 | | 'patch' 24 | | 'options' 25 | | 'head'; 26 | documents?: Array; 27 | version?: 'v1'; 28 | } 29 | 30 | const ajvInstance = createAjvInstance(); 31 | 32 | /** 33 | * Create AJV's validator function for given path in the OpenAPI document. 34 | */ 35 | async function compileAjv(options: ValidationMiddlewareOptions) { 36 | const appOpenAPI = await getAppOpenAPI(); 37 | const paths = appOpenAPI.paths || {}; 38 | 39 | const pathName = options.path; 40 | const path = paths[String(pathName)]; 41 | if (!path) { 42 | throw new Error( 43 | `Path "${pathName}" doesn't exist in the OpenAPI document.` 44 | ); 45 | } 46 | 47 | const methodName = options.method; 48 | const method = path[String(methodName)]; 49 | if (!method) { 50 | throw new Error( 51 | `Method "${methodName}" for "${pathName}" path doesn't exist in the OpenAPI document.` 52 | ); 53 | } 54 | 55 | const requestBody = method.requestBody; 56 | if (!requestBody) return; 57 | 58 | let schema = requestBody.content['application/json'].schema; 59 | if (!schema) return; 60 | 61 | schema = { ...schema }; 62 | schema['$schema'] = 'http://json-schema.org/draft-07/schema'; 63 | 64 | if (options.documents && schema.properties) { 65 | schema.properties = { ...schema.properties }; 66 | options.documents.forEach((field) => { 67 | if (schema.properties[String(field)].items) { 68 | schema.properties[String(field)] = { 69 | ...schema.properties[String(field)], 70 | }; 71 | schema.properties[String(field)].items = true; 72 | } else { 73 | schema.properties[String(field)] = true; 74 | } 75 | }); 76 | } 77 | 78 | return ajvInstance.compile(schema); 79 | } 80 | 81 | async function validateRequestBody(validate: ValidateFunction, body: any) { 82 | const valid = validate(body); 83 | const errors = validate.errors && [...validate.errors]; 84 | 85 | if (valid === false) { 86 | throw new ProblemException({ 87 | type: 'invalid-request-body', 88 | title: 'Invalid Request Body', 89 | status: 422, 90 | validationErrors: errors as any, 91 | }); 92 | } 93 | } 94 | 95 | async function validateSingleDocument( 96 | asyncapi: string | AsyncAPIDocument, 97 | parserConfig: ReturnType 98 | ) { 99 | if (typeof asyncapi === 'object') { 100 | asyncapi = JSON.parse(JSON.stringify(asyncapi)); 101 | } 102 | return parse(asyncapi, parserConfig); 103 | } 104 | 105 | async function validateListDocuments( 106 | asyncapis: Array, 107 | parserConfig: ReturnType 108 | ) { 109 | const parsedDocuments: Array = []; 110 | for (const asyncapi of asyncapis) { 111 | const parsed = await validateSingleDocument(asyncapi, parserConfig); 112 | parsedDocuments.push(parsed); 113 | } 114 | return parsedDocuments; 115 | } 116 | 117 | /** 118 | * Validate RequestBody and sent AsyncAPI document(s) for given path and method based on the OpenAPI Document. 119 | */ 120 | export async function validationMiddleware( 121 | options: ValidationMiddlewareOptions 122 | ) { 123 | options.version = options.version || 'v1'; 124 | const validate = await compileAjv(options); 125 | const documents = options.documents; 126 | 127 | return async function (req: Request, _: Response, next: NextFunction) { 128 | // validate request body 129 | try { 130 | await validateRequestBody(validate, req.body); 131 | } catch (err: unknown) { 132 | return next(err); 133 | } 134 | 135 | // validate AsyncAPI document(s) 136 | const parserConfig = prepareParserConfig(req); 137 | try { 138 | req.asyncapi = req.asyncapi || {}; 139 | for (const field of documents) { 140 | const body = req.body[String(field)]; 141 | if (Array.isArray(body)) { 142 | const parsed = await validateListDocuments(body, parserConfig); 143 | req.asyncapi.parsedDocuments = parsed; 144 | } else { 145 | const parsed = await validateSingleDocument(body, parserConfig); 146 | req.asyncapi.parsedDocument = parsed; 147 | } 148 | } 149 | 150 | next(); 151 | } catch (err: unknown) { 152 | return next(tryConvertToProblemException(err)); 153 | } 154 | }; 155 | } 156 | -------------------------------------------------------------------------------- /.github/workflows/bounty-program-commands.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed at https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repository, as they will be overwritten with 3 | # changes made to the same file in the abovementioned repository. 4 | 5 | # The purpose of this workflow is to allow Bounty Team members 6 | # (https://github.com/orgs/asyncapi/teams/bounty_team) to issue commands to the 7 | # organization's global AsyncAPI bot related to the Bounty Program, while at the 8 | # same time preventing unauthorized users from misusing them. 9 | 10 | name: Bounty Program commands 11 | 12 | on: 13 | issue_comment: 14 | types: 15 | - created 16 | 17 | env: 18 | BOUNTY_PROGRAM_LABELS_JSON: | 19 | [ 20 | {"name": "bounty", "color": "0e8a16", "description": "Participation in the Bounty Program"} 21 | ] 22 | 23 | jobs: 24 | guard-against-unauthorized-use: 25 | if: > 26 | github.actor != ('aeworxet' || 'thulieblack') && 27 | ( 28 | startsWith(github.event.comment.body, '/bounty' ) 29 | ) 30 | 31 | runs-on: ubuntu-latest 32 | 33 | steps: 34 | - name: ❌ @${{github.actor}} made an unauthorized attempt to use a Bounty Program's command 35 | uses: actions/github-script@v7 36 | env: 37 | ACTOR: ${{ github.actor }} 38 | with: 39 | github-token: ${{ secrets.GH_TOKEN }} 40 | script: | 41 | const commentText = `❌ @${process.env.ACTOR} is not authorized to use the Bounty Program's commands. 42 | These commands can only be used by members of the [Bounty Team](https://github.com/orgs/asyncapi/teams/bounty_team).`; 43 | 44 | console.log(`❌ @${process.env.ACTOR} made an unauthorized attempt to use a Bounty Program's command.`); 45 | github.rest.issues.createComment({ 46 | issue_number: context.issue.number, 47 | owner: context.repo.owner, 48 | repo: context.repo.repo, 49 | body: commentText 50 | }) 51 | 52 | add-label-bounty: 53 | if: > 54 | github.actor == ('aeworxet' || 'thulieblack') && 55 | ( 56 | startsWith(github.event.comment.body, '/bounty' ) 57 | ) 58 | 59 | runs-on: ubuntu-latest 60 | 61 | steps: 62 | - name: Add label `bounty` 63 | uses: actions/github-script@v7 64 | with: 65 | github-token: ${{ secrets.GH_TOKEN }} 66 | script: | 67 | const BOUNTY_PROGRAM_LABELS = JSON.parse(process.env.BOUNTY_PROGRAM_LABELS_JSON); 68 | let LIST_OF_LABELS_FOR_REPO = await github.rest.issues.listLabelsForRepo({ 69 | owner: context.repo.owner, 70 | repo: context.repo.repo, 71 | }); 72 | 73 | LIST_OF_LABELS_FOR_REPO = LIST_OF_LABELS_FOR_REPO.data.map(key => key.name); 74 | 75 | if (!LIST_OF_LABELS_FOR_REPO.includes(BOUNTY_PROGRAM_LABELS[0].name)) { 76 | await github.rest.issues.createLabel({ 77 | owner: context.repo.owner, 78 | repo: context.repo.repo, 79 | name: BOUNTY_PROGRAM_LABELS[0].name, 80 | color: BOUNTY_PROGRAM_LABELS[0].color, 81 | description: BOUNTY_PROGRAM_LABELS[0].description 82 | }); 83 | } 84 | 85 | console.log('Adding label `bounty`...'); 86 | github.rest.issues.addLabels({ 87 | issue_number: context.issue.number, 88 | owner: context.repo.owner, 89 | repo: context.repo.repo, 90 | labels: [BOUNTY_PROGRAM_LABELS[0].name] 91 | }) 92 | 93 | remove-label-bounty: 94 | if: > 95 | github.actor == ('aeworxet' || 'thulieblack') && 96 | ( 97 | startsWith(github.event.comment.body, '/unbounty' ) 98 | ) 99 | 100 | runs-on: ubuntu-latest 101 | 102 | steps: 103 | - name: Remove label `bounty` 104 | uses: actions/github-script@v7 105 | with: 106 | github-token: ${{ secrets.GH_TOKEN }} 107 | script: | 108 | const BOUNTY_PROGRAM_LABELS = JSON.parse(process.env.BOUNTY_PROGRAM_LABELS_JSON); 109 | let LIST_OF_LABELS_FOR_ISSUE = await github.rest.issues.listLabelsOnIssue({ 110 | owner: context.repo.owner, 111 | repo: context.repo.repo, 112 | issue_number: context.issue.number, 113 | }); 114 | 115 | LIST_OF_LABELS_FOR_ISSUE = LIST_OF_LABELS_FOR_ISSUE.data.map(key => key.name); 116 | 117 | if (LIST_OF_LABELS_FOR_ISSUE.includes(BOUNTY_PROGRAM_LABELS[0].name)) { 118 | console.log('Removing label `bounty`...'); 119 | github.rest.issues.removeLabel({ 120 | issue_number: context.issue.number, 121 | owner: context.repo.owner, 122 | repo: context.repo.repo, 123 | name: [BOUNTY_PROGRAM_LABELS[0].name] 124 | }) 125 | } 126 | -------------------------------------------------------------------------------- /src/controllers/tests/validate.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { ValidateController } from '../validate.controller'; 7 | 8 | const validJSONAsyncAPI = { 9 | asyncapi: '2.2.0', 10 | info: { 11 | title: 'Account Service', 12 | version: '1.0.0', 13 | description: 'This service is in charge of processing user signups' 14 | }, 15 | channels: { 16 | 'user/signedup': { 17 | subscribe: { 18 | message: { 19 | $ref: '#/components/messages/UserSignedUp' 20 | } 21 | } 22 | } 23 | }, 24 | components: { 25 | messages: { 26 | UserSignedUp: { 27 | payload: { 28 | type: 'object', 29 | properties: { 30 | displayName: { 31 | type: 'string', 32 | description: 'Name of the user' 33 | }, 34 | email: { 35 | type: 'string', 36 | format: 'email', 37 | description: 'Email of the user' 38 | } 39 | } 40 | } 41 | } 42 | } 43 | } 44 | }; 45 | const validYAMLAsyncAPI = ` 46 | asyncapi: '2.2.0' 47 | info: 48 | title: Account Service 49 | version: 1.0.0 50 | description: This service is in charge of processing user signups 51 | channels: 52 | user/signedup: 53 | subscribe: 54 | message: 55 | $ref: '#/components/messages/UserSignedUp' 56 | components: 57 | messages: 58 | UserSignedUp: 59 | payload: 60 | type: object 61 | properties: 62 | displayName: 63 | type: string 64 | description: Name of the user 65 | email: 66 | type: string 67 | format: email 68 | description: Email of the user 69 | `; 70 | const invalidJSONAsyncAPI = { 71 | asyncapi: '2.0.0', 72 | info: { 73 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 74 | version: '1.0.0' 75 | }, 76 | channels: {} 77 | }; 78 | 79 | describe('ValidateController', () => { 80 | describe('[POST] /validate', () => { 81 | it('should validate AsyncAPI document in JSON', async () => { 82 | const app = new App([new ValidateController()]); 83 | await app.init(); 84 | 85 | return request(app.getServer()) 86 | .post('/v1/validate') 87 | .send({ 88 | asyncapi: validJSONAsyncAPI 89 | }) 90 | .expect(204); 91 | }); 92 | 93 | it('should validate AsyncAPI document in YAML', async () => { 94 | const app = new App([new ValidateController()]); 95 | await app.init(); 96 | 97 | return request(app.getServer()) 98 | .post('/v1/validate') 99 | .send({ 100 | asyncapi: validYAMLAsyncAPI 101 | }) 102 | .expect(204); 103 | }); 104 | 105 | it('should throw error when sent an empty document', async () => { 106 | const app = new App([new ValidateController()]); 107 | await app.init(); 108 | 109 | return request(app.getServer()) 110 | .post('/v1/validate') 111 | .send({}) 112 | .expect(422, { 113 | type: ProblemException.createType('invalid-request-body'), 114 | title: 'Invalid Request Body', 115 | status: 422, 116 | validationErrors: [ 117 | { 118 | instancePath: '', 119 | schemaPath: '#/required', 120 | keyword: 'required', 121 | params: { 122 | missingProperty: 'asyncapi' 123 | }, 124 | message: 'must have required property \'asyncapi\'' 125 | } 126 | ] 127 | }); 128 | }); 129 | 130 | it('should throw error when sent an invalid AsyncAPI document', async () => { 131 | const app = new App([new ValidateController()]); 132 | await app.init(); 133 | 134 | return request(app.getServer()) 135 | .post('/v1/validate') 136 | .send({ 137 | asyncapi: invalidJSONAsyncAPI 138 | }) 139 | .expect(422, { 140 | type: ProblemException.createType('validation-errors'), 141 | title: 'There were errors validating the AsyncAPI document.', 142 | status: 422, 143 | validationErrors: [ 144 | { 145 | title: '/info should NOT have additional properties', 146 | location: { 147 | jsonPointer: '/info' 148 | } 149 | }, 150 | { 151 | title: '/info should have required property \'title\'', 152 | location: { 153 | jsonPointer: '/info' 154 | } 155 | } 156 | ], 157 | parsedJSON: { 158 | asyncapi: '2.0.0', 159 | info: { 160 | tite: 'My API', 161 | version: '1.0.0' 162 | }, 163 | channels: {} 164 | } 165 | }); 166 | }); 167 | }); 168 | }); 169 | -------------------------------------------------------------------------------- /.github/workflows/release-announcements.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | name: 'Announce releases in different channels' 5 | 6 | on: 7 | release: 8 | types: 9 | - published 10 | 11 | jobs: 12 | 13 | slack-announce: 14 | name: Slack - notify on every release 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout repository 18 | uses: actions/checkout@v4 19 | - name: Convert markdown to slack markdown for issue 20 | # This workflow is from our own org repo and safe to reference by 'master'. 21 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 22 | id: markdown 23 | env: 24 | RELEASE_TAG: ${{github.event.release.tag_name}} 25 | RELEASE_URL: ${{github.event.release.html_url}} 26 | RELEASE_BODY: ${{ github.event.release.body }} 27 | with: 28 | markdown: "[${{ env.RELEASE_TAG }}](${{ env.RELEASE_URL }}) \n ${{ env.RELEASE_BODY }}" 29 | - name: Send info about release to Slack 30 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 31 | env: 32 | SLACK_WEBHOOK: ${{ secrets.SLACK_RELEASES }} 33 | SLACK_TITLE: Release ${{ env.RELEASE_TAG }} for ${{ env.REPO_NAME }} is out in the wild 😱💪🍾🎂 34 | SLACK_MESSAGE: ${{steps.markdown.outputs.text}} 35 | MSG_MINIMAL: true 36 | RELEASE_TAG: ${{github.event.release.tag_name}} 37 | REPO_NAME: ${{github.repository}} 38 | 39 | twitter-announce: 40 | name: Twitter - notify on minor and major releases 41 | runs-on: ubuntu-latest 42 | steps: 43 | - name: Checkout repo 44 | uses: actions/checkout@v4 45 | - name: Get version of last and previous release 46 | uses: actions/github-script@v7 47 | id: versions 48 | with: 49 | github-token: ${{ secrets.GITHUB_TOKEN }} 50 | script: | 51 | const query = `query($owner:String!, $name:String!) { 52 | repository(owner:$owner, name:$name){ 53 | releases(first: 2, orderBy: {field: CREATED_AT, direction: DESC}) { 54 | nodes { 55 | name 56 | } 57 | } 58 | } 59 | }`; 60 | const variables = { 61 | owner: context.repo.owner, 62 | name: context.repo.repo 63 | }; 64 | const { repository: { releases: { nodes } } } = await github.graphql(query, variables); 65 | core.setOutput('lastver', nodes[0].name); 66 | // In case of first release in the package, there is no such thing as previous error, so we set info about previous version only once we have it 67 | // We should tweet about the release no matter of the type as it is initial release 68 | if (nodes.length != 1) core.setOutput('previousver', nodes[1].name); 69 | - name: Identify release type 70 | id: releasetype 71 | # if previousver is not provided then this steps just logs information about missing version, no errors 72 | env: 73 | PREV_VERSION: ${{steps.versions.outputs.previousver}} 74 | LAST_VERSION: ${{steps.versions.outputs.lastver}} 75 | run: echo "type=$(npx -q -p semver-diff-cli semver-diff "$PREV_VERSION" "$LAST_VERSION")" >> $GITHUB_OUTPUT 76 | - name: Get name of the person that is behind the newly released version 77 | id: author 78 | run: | 79 | AUTHOR_NAME=$(git log -1 --pretty=format:'%an') 80 | printf 'name=%s\n' "$AUTHOR_NAME" >> $GITHUB_OUTPUT 81 | - name: Publish information about the release to Twitter # tweet only if detected version change is not a patch 82 | # tweet goes out even if the type is not major or minor but "You need provide version number to compare." 83 | # it is ok, it just means we did not identify previous version as we are tweeting out information about the release for the first time 84 | if: steps.releasetype.outputs.type != 'null' && steps.releasetype.outputs.type != 'patch' # null means that versions are the same 85 | uses: m1ner79/Github-Twittction@d1e508b6c2170145127138f93c49b7c46c6ff3a7 # using 2.0.0 https://github.com/m1ner79/Github-Twittction/releases/tag/v2.0.0 86 | env: 87 | RELEASE_TAG: ${{github.event.release.tag_name}} 88 | REPO_NAME: ${{github.repository}} 89 | AUTHOR_NAME: ${{ steps.author.outputs.name }} 90 | RELEASE_URL: ${{github.event.release.html_url}} 91 | with: 92 | twitter_status: "Release ${{ env.RELEASE_TAG }} for ${{ env.REPO_NAME }} is out in the wild 😱💪🍾🎂\n\nThank you for the contribution ${{ env.AUTHOR_NAME }} ${{ env.RELEASE_URL }}" 93 | twitter_consumer_key: ${{ secrets.TWITTER_CONSUMER_KEY }} 94 | twitter_consumer_secret: ${{ secrets.TWITTER_CONSUMER_SECRET }} 95 | twitter_access_token_key: ${{ secrets.TWITTER_ACCESS_TOKEN_KEY }} 96 | twitter_access_token_secret: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} -------------------------------------------------------------------------------- /.github/workflows/automerge-for-humans-add-ready-to-merge-or-do-not-merge-label.yml: -------------------------------------------------------------------------------- 1 | # This workflow is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # Purpose of this workflow is to enable anyone to label PR with the following labels: 5 | # `ready-to-merge` and `do-not-merge` labels to get stuff merged or blocked from merging 6 | # `autoupdate` to keep a branch up-to-date with the target branch 7 | 8 | name: Label PRs # if proper comment added 9 | 10 | on: 11 | issue_comment: 12 | types: 13 | - created 14 | 15 | jobs: 16 | add-ready-to-merge-label: 17 | if: > 18 | github.event.issue.pull_request && 19 | github.event.issue.state != 'closed' && 20 | github.actor != 'asyncapi-bot' && 21 | ( 22 | contains(github.event.comment.body, '/ready-to-merge') || 23 | contains(github.event.comment.body, '/rtm' ) 24 | ) 25 | 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: Add ready-to-merge label 29 | uses: actions/github-script@v7 30 | env: 31 | GITHUB_ACTOR: ${{ github.actor }} 32 | with: 33 | github-token: ${{ secrets.GH_TOKEN }} 34 | script: | 35 | const prDetailsUrl = context.payload.issue.pull_request.url; 36 | const { data: pull } = await github.request(prDetailsUrl); 37 | const { draft: isDraft} = pull; 38 | if(!isDraft) { 39 | console.log('adding ready-to-merge label...'); 40 | github.rest.issues.addLabels({ 41 | issue_number: context.issue.number, 42 | owner: context.repo.owner, 43 | repo: context.repo.repo, 44 | labels: ['ready-to-merge'] 45 | }) 46 | } 47 | 48 | const { data: comparison } = 49 | await github.rest.repos.compareCommitsWithBasehead({ 50 | owner: pull.head.repo.owner.login, 51 | repo: pull.head.repo.name, 52 | basehead: `${pull.base.label}...${pull.head.label}`, 53 | }); 54 | if (comparison.behind_by !== 0 && pull.mergeable_state === 'behind') { 55 | console.log(`This branch is behind the target by ${comparison.behind_by} commits`) 56 | console.log('adding out-of-date comment...'); 57 | github.rest.issues.createComment({ 58 | issue_number: context.issue.number, 59 | owner: context.repo.owner, 60 | repo: context.repo.repo, 61 | body: `Hello, @${process.env.GITHUB_ACTOR}! 👋🏼 62 | This PR is not up to date with the base branch and can't be merged. 63 | Please update your branch manually with the latest version of the base branch. 64 | PRO-TIP: To request an update from the upstream branch, simply comment \`/u\` or \`/update\` and our bot will handle the update operation promptly. 65 | 66 | The only requirement for this to work is to enable [Allow edits from maintainers](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) option in your PR. Also the update will not work if your fork is located in an organization, not under your personal profile. 67 | Thanks 😄` 68 | }) 69 | } 70 | 71 | add-do-not-merge-label: 72 | if: > 73 | github.event.issue.pull_request && 74 | github.event.issue.state != 'closed' && 75 | github.actor != 'asyncapi-bot' && 76 | ( 77 | contains(github.event.comment.body, '/do-not-merge') || 78 | contains(github.event.comment.body, '/dnm' ) 79 | ) 80 | runs-on: ubuntu-latest 81 | steps: 82 | - name: Add do-not-merge label 83 | uses: actions/github-script@v7 84 | with: 85 | github-token: ${{ secrets.GH_TOKEN }} 86 | script: | 87 | github.rest.issues.addLabels({ 88 | issue_number: context.issue.number, 89 | owner: context.repo.owner, 90 | repo: context.repo.repo, 91 | labels: ['do-not-merge'] 92 | }) 93 | add-autoupdate-label: 94 | if: > 95 | github.event.issue.pull_request && 96 | github.event.issue.state != 'closed' && 97 | github.actor != 'asyncapi-bot' && 98 | ( 99 | contains(github.event.comment.body, '/autoupdate') || 100 | contains(github.event.comment.body, '/au' ) 101 | ) 102 | runs-on: ubuntu-latest 103 | steps: 104 | - name: Add autoupdate label 105 | uses: actions/github-script@v7 106 | with: 107 | github-token: ${{ secrets.GH_TOKEN }} 108 | script: | 109 | github.rest.issues.addLabels({ 110 | issue_number: context.issue.number, 111 | owner: context.repo.owner, 112 | repo: context.repo.repo, 113 | labels: ['autoupdate'] 114 | }) 115 | -------------------------------------------------------------------------------- /src/controllers/generate.controller.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { NextFunction, Request, Response, Router } from 'express'; 4 | import Ajv from 'ajv'; 5 | 6 | import { Controller } from '../interfaces'; 7 | 8 | import { validationMiddleware } from '../middlewares/validation.middleware'; 9 | 10 | import { ArchiverService } from '../services/archiver.service'; 11 | import { GeneratorService } from '../services/generator.service'; 12 | 13 | import { ProblemException } from '../exceptions/problem.exception'; 14 | import { prepareParserConfig } from '../utils/parser'; 15 | 16 | /** 17 | * Controller which exposes the Generator functionality 18 | */ 19 | export class GenerateController implements Controller { 20 | public basepath = '/generate'; 21 | 22 | private archiverService = new ArchiverService(); 23 | private generatorService = new GeneratorService(); 24 | private ajv: Ajv; 25 | 26 | private async generate(req: Request, res: Response, next: NextFunction) { 27 | try { 28 | await this.validateTemplateParameters(req); 29 | } catch (err) { 30 | return next(err); 31 | } 32 | 33 | const zip = this.archiverService.createZip(res); 34 | 35 | let tmpDir: string; 36 | try { 37 | tmpDir = await this.archiverService.createTempDirectory(); 38 | const { asyncapi, template, parameters } = req.body; 39 | 40 | try { 41 | await this.generatorService.generate( 42 | asyncapi, 43 | template, 44 | parameters, 45 | tmpDir, 46 | prepareParserConfig(req) 47 | ); 48 | } catch (genErr: unknown) { 49 | return next( 50 | new ProblemException({ 51 | type: 'internal-generator-error', 52 | title: 'Internal Generator error', 53 | status: 500, 54 | detail: (genErr as Error).message, 55 | }) 56 | ); 57 | } 58 | 59 | this.archiverService.appendDirectory(zip, tmpDir, 'template'); 60 | this.archiverService.appendAsyncAPIDocument(zip, asyncapi); 61 | 62 | res.status(200); 63 | return await this.archiverService.finalize(zip); 64 | } catch (err: unknown) { 65 | return next( 66 | new ProblemException({ 67 | type: 'internal-server-error', 68 | title: 'Internal server error', 69 | status: 500, 70 | detail: (err as Error).message, 71 | }) 72 | ); 73 | } finally { 74 | this.archiverService.removeTempDirectory(tmpDir); 75 | } 76 | } 77 | 78 | private async validateTemplateParameters(req: Request) { 79 | const { template, parameters } = req.body; 80 | 81 | const validate = await this.getAjvValidator(template); 82 | const valid = validate(parameters || {}); 83 | const errors = validate.errors && [...validate.errors]; 84 | 85 | if (valid === false) { 86 | throw new ProblemException({ 87 | type: 'invalid-template-parameters', 88 | title: 'Invalid Generator Template parameters', 89 | status: 422, 90 | validationErrors: errors as any, 91 | }); 92 | } 93 | } 94 | 95 | /** 96 | * Retrieve proper AJV's validator function, create or reuse it. 97 | */ 98 | public async getAjvValidator(templateName: string) { 99 | let validate = this.ajv.getSchema(templateName); 100 | if (!validate) { 101 | this.ajv.addSchema( 102 | await this.serializeTemplateParameters(templateName), 103 | templateName 104 | ); 105 | validate = this.ajv.getSchema(templateName); 106 | } 107 | return validate; 108 | } 109 | 110 | /** 111 | * Serialize template parameters. Read all parameters from template's package.json and create a proper JSON Schema for validating parameters. 112 | */ 113 | public async serializeTemplateParameters( 114 | templateName: string 115 | ): Promise { 116 | const pathToPackageJSON = path.join( 117 | __dirname, 118 | `../../node_modules/${templateName}/package.json` 119 | ); 120 | const packageJSONContent = await fs.promises.readFile( 121 | pathToPackageJSON, 122 | 'utf-8' 123 | ); 124 | const packageJSON = JSON.parse(packageJSONContent); 125 | if (!packageJSON) { 126 | return; 127 | } 128 | 129 | const generator = packageJSON.generator; 130 | if (!generator || !generator.parameters) { 131 | return; 132 | } 133 | 134 | const parameters = generator.parameters || {}; 135 | const required: string[] = []; 136 | for (const parameter in parameters) { 137 | // at the moment all parameters have to be passed to the Generator instance as string 138 | parameters[String(parameter)].type = 'string'; 139 | if (parameters[String(parameter)].required) { 140 | required.push(parameter); 141 | } 142 | delete parameters[String(parameter)].required; 143 | } 144 | 145 | return { 146 | $schema: 'http://json-schema.org/draft-07/schema#', 147 | type: 'object', 148 | properties: parameters, 149 | required, 150 | // don't allow non supported properties 151 | additionalProperties: false, 152 | }; 153 | } 154 | 155 | public async boot(): Promise { 156 | this.ajv = new Ajv({ 157 | inlineRefs: true, 158 | allErrors: true, 159 | schemaId: 'id', 160 | logger: false, 161 | }); 162 | const router = Router(); 163 | 164 | router.post( 165 | `${this.basepath}`, 166 | await validationMiddleware({ 167 | path: this.basepath, 168 | method: 'post', 169 | documents: ['asyncapi'], 170 | }), 171 | this.generate.bind(this) 172 | ); 173 | 174 | return router; 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /.github/workflows/if-nodejs-release.yml: -------------------------------------------------------------------------------- 1 | # This action is centrally managed in https://github.com/asyncapi/.github/ 2 | # Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo 3 | 4 | # It does magic only if there is package.json file in the root of the project 5 | name: Release - if Node project 6 | 7 | on: 8 | push: 9 | branches: 10 | - master 11 | # below lines are not enough to have release supported for these branches 12 | # make sure configuration of `semantic-release` package mentions these branches 13 | - next-spec 14 | - next-major 15 | - next-major-spec 16 | - beta 17 | - alpha 18 | - next 19 | 20 | jobs: 21 | 22 | test-nodejs: 23 | # We just check the message of first commit as there is always just one commit because we squash into one before merging 24 | # "commits" contains array of objects where one of the properties is commit "message" 25 | # Release workflow will be skipped if release conventional commits are not used 26 | if: | 27 | startsWith( github.repository, 'asyncapi/' ) && 28 | (startsWith( github.event.commits[0].message , 'fix:' ) || 29 | startsWith( github.event.commits[0].message, 'fix!:' ) || 30 | startsWith( github.event.commits[0].message, 'feat:' ) || 31 | startsWith( github.event.commits[0].message, 'feat!:' )) 32 | name: Test NodeJS release on ${{ matrix.os }} 33 | runs-on: ${{ matrix.os }} 34 | strategy: 35 | matrix: 36 | os: [ubuntu-latest, macos-latest, windows-latest] 37 | steps: 38 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 39 | run: | 40 | git config --global core.autocrlf false 41 | git config --global core.eol lf 42 | shell: bash 43 | - name: Checkout repository 44 | uses: actions/checkout@v4 45 | - name: Check if Node.js project and has package.json 46 | id: packagejson 47 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 48 | shell: bash 49 | - if: steps.packagejson.outputs.exists == 'true' 50 | name: Check package-lock version 51 | # This workflow is from our own org repo and safe to reference by 'master'. 52 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master # //NOSONAR 53 | id: lockversion 54 | - if: steps.packagejson.outputs.exists == 'true' 55 | name: Setup Node.js 56 | uses: actions/setup-node@v4 57 | with: 58 | node-version: "${{ steps.lockversion.outputs.version }}" 59 | - if: steps.lockversion.outputs.version == '18' && matrix.os == 'windows-latest' 60 | name: Install npm cli 8 61 | shell: bash 62 | #npm cli 10 is buggy because of some cache issues 63 | run: npm install -g npm@8.19.4 64 | - if: steps.packagejson.outputs.exists == 'true' 65 | name: Install dependencies 66 | shell: bash 67 | run: npm ci 68 | - if: steps.packagejson.outputs.exists == 'true' 69 | name: Run test 70 | run: npm test --if-present 71 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 72 | name: Report workflow run status to Slack 73 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 74 | with: 75 | status: ${{ job.status }} 76 | fields: repo,action,workflow 77 | text: 'Release workflow failed in testing job' 78 | env: 79 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} 80 | 81 | release: 82 | needs: [test-nodejs] 83 | name: Publish to any of NPM, Github, or Docker Hub 84 | runs-on: ubuntu-latest 85 | steps: 86 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 87 | run: | 88 | git config --global core.autocrlf false 89 | git config --global core.eol lf 90 | - name: Checkout repository 91 | uses: actions/checkout@v4 92 | - name: Check if Node.js project and has package.json 93 | id: packagejson 94 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 95 | shell: bash 96 | - if: steps.packagejson.outputs.exists == 'true' 97 | name: Check package-lock version 98 | # This workflow is from our own org repo and safe to reference by 'master'. 99 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master # //NOSONAR 100 | id: lockversion 101 | - if: steps.packagejson.outputs.exists == 'true' 102 | name: Setup Node.js 103 | uses: actions/setup-node@v4 104 | with: 105 | node-version: "${{ steps.lockversion.outputs.version }}" 106 | - if: steps.packagejson.outputs.exists == 'true' 107 | name: Install dependencies 108 | shell: bash 109 | run: npm ci 110 | - if: steps.packagejson.outputs.exists == 'true' 111 | name: Add plugin for conventional commits for semantic-release 112 | run: npm install --save-dev conventional-changelog-conventionalcommits@5.0.0 113 | - if: steps.packagejson.outputs.exists == 'true' 114 | name: Publish to any of NPM, Github, and Docker Hub 115 | id: release 116 | env: 117 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 118 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 119 | DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} 120 | DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} 121 | GIT_AUTHOR_NAME: asyncapi-bot 122 | GIT_AUTHOR_EMAIL: info@asyncapi.io 123 | GIT_COMMITTER_NAME: asyncapi-bot 124 | GIT_COMMITTER_EMAIL: info@asyncapi.io 125 | run: npx semantic-release@19.0.4 126 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 127 | name: Report workflow run status to Slack 128 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 129 | with: 130 | status: ${{ job.status }} 131 | fields: repo,action,workflow 132 | text: 'Release workflow failed in release job' 133 | env: 134 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} 135 | -------------------------------------------------------------------------------- /src/controllers/tests/bundle.controller.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | 6 | import { BundleController } from '../bundle.controller'; 7 | 8 | describe('BundleController', () => { 9 | describe('[POST] /bundle', () => { 10 | it('should bundle files', async () => { 11 | const app = new App([new BundleController()]); 12 | await app.init(); 13 | 14 | await request(app.getServer()) 15 | .post('/v1/bundle') 16 | .send({ 17 | asyncapis: [{ 18 | asyncapi: '2.2.0', 19 | info: { 20 | title: 'Test Service', 21 | version: '1.0.0', 22 | }, 23 | channels: { 24 | 'test-channel-2': { 25 | publish: { 26 | message: { 27 | payload: { 28 | type: 'object', 29 | }, 30 | }, 31 | } 32 | }, 33 | }, 34 | }], 35 | base: { 36 | asyncapi: '2.2.0', 37 | info: { 38 | title: 'Merged test service', 39 | version: '1.2.0', 40 | }, 41 | channels: { 42 | 'test-channel-1': { 43 | publish: { 44 | message: { 45 | payload: { 46 | type: 'object', 47 | }, 48 | }, 49 | } 50 | }, 51 | }, 52 | } 53 | }) 54 | .expect(200, { 55 | bundled: { 56 | asyncapi: '2.2.0', 57 | info: { title: 'Merged test service', version: '1.2.0' }, 58 | channels: { 59 | 'test-channel-1': { 60 | publish: { 61 | message: { 62 | payload: { 63 | type: 'object', 64 | }, 65 | }, 66 | } 67 | }, 68 | 'test-channel-2': { 69 | publish: { 70 | message: { 71 | payload: { 72 | type: 'object', 73 | }, 74 | }, 75 | } 76 | }, 77 | } 78 | } 79 | }); 80 | }); 81 | 82 | it('should throw error with invalid AsyncAPI document in the `base` list', async () => { 83 | const app = new App([new BundleController()]); 84 | await app.init(); 85 | 86 | await request(app.getServer()) 87 | .post('/v1/bundle') 88 | .send({ 89 | asyncapis: [{ 90 | asyncapi: '2.2.0', 91 | info: { 92 | title: 'Test Service', 93 | version: '1.0.0', 94 | }, 95 | channels: { 96 | 'test-channel-2': { 97 | publish: { 98 | message: { 99 | payload: { 100 | type: 'object', 101 | }, 102 | }, 103 | } 104 | }, 105 | }, 106 | }], 107 | base: { 108 | asyncapi: '2.2.0', 109 | info: { 110 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 111 | version: '1.0.0' 112 | }, 113 | channels: {} 114 | } 115 | }) 116 | .expect(422, { 117 | type: ProblemException.createType('validation-errors'), 118 | title: 'There were errors validating the AsyncAPI document.', 119 | status: 422, 120 | validationErrors: [ 121 | { 122 | title: '/info should NOT have additional properties', 123 | location: { 124 | jsonPointer: '/info' 125 | } 126 | }, 127 | { 128 | title: '/info should have required property \'title\'', 129 | location: { 130 | jsonPointer: '/info' 131 | } 132 | } 133 | ], 134 | parsedJSON: { 135 | asyncapi: '2.2.0', 136 | info: { 137 | tite: 'My API', 138 | version: '1.0.0' 139 | }, 140 | channels: {} 141 | } 142 | }); 143 | }); 144 | 145 | it('should throw error with invalid AsyncAPI document in the `asyncapis` list', async () => { 146 | const app = new App([new BundleController()]); 147 | await app.init(); 148 | 149 | await request(app.getServer()) 150 | .post('/v1/bundle') 151 | .send({ 152 | asyncapis: [{ 153 | asyncapi: '2.2.0', 154 | info: { 155 | tite: 'My API', // spelled wrong on purpose to throw an error in the test 156 | version: '1.0.0' 157 | }, 158 | channels: {} 159 | }], 160 | base: { 161 | asyncapi: '2.2.0', 162 | info: { 163 | title: 'Merged test service', 164 | version: '1.2.0', 165 | }, 166 | channels: { 167 | 'test-channel-1': { 168 | publish: { 169 | message: { 170 | payload: { 171 | type: 'object', 172 | }, 173 | }, 174 | } 175 | }, 176 | }, 177 | } 178 | }) 179 | .expect(422, { 180 | type: ProblemException.createType('validation-errors'), 181 | title: 'There were errors validating the AsyncAPI document.', 182 | status: 422, 183 | validationErrors: [ 184 | { 185 | title: '/info should NOT have additional properties', 186 | location: { 187 | jsonPointer: '/info' 188 | } 189 | }, 190 | { 191 | title: '/info should have required property \'title\'', 192 | location: { 193 | jsonPointer: '/info' 194 | } 195 | } 196 | ], 197 | parsedJSON: { 198 | asyncapi: '2.2.0', 199 | info: { 200 | tite: 'My API', 201 | version: '1.0.0' 202 | }, 203 | channels: {} 204 | } 205 | }); 206 | }); 207 | }); 208 | }); -------------------------------------------------------------------------------- /src/middlewares/tests/validation.middleware.test.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import { App } from '../../app'; 4 | import { ProblemException } from '../../exceptions/problem.exception'; 5 | import { validationMiddleware } from '../validation.middleware'; 6 | 7 | import { createTestController } from '../../../tests/test.controller'; 8 | import { getAppOpenAPI } from '../../utils/app-openapi'; 9 | 10 | // test /generate route to check validation of custom requestBody 11 | describe('validationMiddleware', () => { 12 | it('should pass when request body is valid', async () => { 13 | const TestController = createTestController({ 14 | path: '/generate', 15 | method: 'post', 16 | callback: (_, res) => { 17 | res.status(200).send({ success: true }); 18 | }, 19 | middlewares: [ 20 | await validationMiddleware({ 21 | path: '/generate', 22 | method: 'post', 23 | documents: ['asyncapi'], 24 | }), 25 | ], 26 | }); 27 | const app = new App([new TestController()]); 28 | await app.init(); 29 | 30 | return await request(app.getServer()) 31 | .post('/v1/generate') 32 | .send({ 33 | asyncapi: { 34 | asyncapi: '2.2.0', 35 | info: { 36 | title: 'Test Service', 37 | version: '1.0.0', 38 | }, 39 | channels: {}, 40 | }, 41 | template: '@asyncapi/html-template' 42 | }) 43 | .expect(200, { 44 | success: true, 45 | }); 46 | }); 47 | 48 | it('should throw error when request body is invalid', async () => { 49 | const TestController = createTestController({ 50 | path: '/generate', 51 | method: 'post', 52 | callback: (_, res) => { 53 | res.status(200).send({ success: true }); 54 | }, 55 | middlewares: [ 56 | await validationMiddleware({ 57 | path: '/generate', 58 | method: 'post', 59 | documents: ['asyncapi'], 60 | }), 61 | ], 62 | }); 63 | const app = new App([new TestController()]); 64 | await app.init(); 65 | 66 | const openApi = await getAppOpenAPI(); 67 | const availableTemplates = openApi.components.schemas.GenerateRequest.properties.template.enum; 68 | 69 | return await request(app.getServer()) 70 | .post('/v1/generate') 71 | .send({ 72 | asyncapi: { 73 | asyncapi: '2.2.0', 74 | info: { 75 | title: 'Test Service', 76 | version: '1.0.0', 77 | }, 78 | channels: {}, 79 | }, 80 | template: 'custom template' 81 | }) 82 | .expect(422, { 83 | type: ProblemException.createType('invalid-request-body'), 84 | title: 'Invalid Request Body', 85 | status: 422, 86 | validationErrors: [ 87 | { 88 | instancePath: '/template', 89 | schemaPath: '#/properties/template/enum', 90 | keyword: 'enum', 91 | params: { 92 | allowedValues: availableTemplates, 93 | }, 94 | message: 'must be equal to one of the allowed values' 95 | } 96 | ] 97 | }); 98 | }); 99 | 100 | it('should pass when `asyncapi` field is defined as valid AsyncAPI document', async () => { 101 | const TestController = createTestController({ 102 | path: '/generate', 103 | method: 'post', 104 | callback: (_, res) => { 105 | res.status(200).send({ success: true }); 106 | }, 107 | middlewares: [ 108 | await validationMiddleware({ 109 | path: '/generate', 110 | method: 'post', 111 | documents: ['asyncapi'], 112 | }), 113 | ], 114 | }); 115 | const app = new App([new TestController()]); 116 | await app.init(); 117 | 118 | return await request(app.getServer()) 119 | .post('/v1/generate') 120 | .send({ 121 | template: '@asyncapi/html-template', 122 | asyncapi: { 123 | asyncapi: '2.2.0', 124 | info: { 125 | title: 'Account Service', 126 | version: '1.0.0', 127 | description: 'This service is in charge of processing user signups' 128 | }, 129 | channels: { 130 | 'user/signedup': { 131 | subscribe: { 132 | message: { 133 | $ref: '#/components/messages/UserSignedUp' 134 | } 135 | } 136 | } 137 | }, 138 | components: { 139 | messages: { 140 | UserSignedUp: { 141 | payload: { 142 | type: 'object', 143 | properties: { 144 | displayName: { 145 | type: 'string', 146 | description: 'Name of the user' 147 | }, 148 | email: { 149 | type: 'string', 150 | format: 'email', 151 | description: 'Email of the user' 152 | } 153 | } 154 | } 155 | } 156 | } 157 | } 158 | } 159 | }) 160 | .expect(200, { 161 | success: true, 162 | }); 163 | }); 164 | 165 | it('should throw error when `asyncapi` field is defined as invalid AsyncAPI document', async () => { 166 | const TestController = createTestController({ 167 | path: '/generate', 168 | method: 'post', 169 | callback: (_, res) => { 170 | res.status(200).send({ success: true }); 171 | }, 172 | middlewares: [ 173 | await validationMiddleware({ 174 | path: '/generate', 175 | method: 'post', 176 | documents: ['asyncapi'], 177 | }), 178 | ], 179 | }); 180 | const app = new App([new TestController()]); 181 | await app.init(); 182 | 183 | return await request(app.getServer()) 184 | .post('/v1/generate') 185 | .send({ 186 | template: '@asyncapi/html-template', 187 | // without title, version and channels 188 | asyncapi: { 189 | asyncapi: '2.2.0', 190 | info: { 191 | description: 'This service is in charge of processing user signups' 192 | } 193 | } 194 | }) 195 | .expect(422, { 196 | type: ProblemException.createType('validation-errors'), 197 | title: 'There were errors validating the AsyncAPI document.', 198 | status: 422, 199 | validationErrors: [ 200 | { 201 | title: '/info should have required property \'title\'', 202 | location: { jsonPointer: '/info' } 203 | }, 204 | { 205 | title: '/info should have required property \'version\'', 206 | location: { jsonPointer: '/info' } 207 | }, 208 | { 209 | title: '/ should have required property \'channels\'', 210 | location: { jsonPointer: '/' } 211 | } 212 | ], 213 | parsedJSON: { 214 | asyncapi: '2.2.0', 215 | info: { 216 | description: 'This service is in charge of processing user signups', 217 | }, 218 | } 219 | }); 220 | }); 221 | }); 222 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | ## :loudspeaker: ATTENTION: 4 | 5 | This repo has been archived as code is moved to https://github.com/asyncapi/cli/tree/master/src/apps/api. 6 | 7 | ## :loudspeaker: ATTENTION: 8 | --- 9 | 10 | 11 | [![AsyncAPI Server API](./.github/assets/banner.png)](https://www.asyncapi.com) 12 | 13 | Server API providing official AsyncAPI tools. 14 | 15 | 16 | [![All Contributors](https://img.shields.io/badge/all_contributors-6-orange.svg?style=flat-square)](#contributors-) 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | - [Requirements](#requirements) 26 | - [Using it locally](#using-it-locally) 27 | - [Using it via Docker](#using-it-via-docker) 28 | - [Development](#development) 29 | - [Deployment](#deployment) 30 | * [How the GitHub workflow works](#how-the-github-workflow-works) 31 | - [Contribution](#contribution) 32 | - [Supported by](#supported-by) 33 | - [Contributors](#contributors) 34 | 35 | 36 | 37 | ## Requirements 38 | 39 | - [NodeJS](https://nodejs.org/en/) >= 14 40 | 41 | ## Using it locally 42 | 43 | Run: 44 | 45 | ```bash 46 | npm install 47 | npm run start:prod 48 | ``` 49 | 50 | server is ready to use on [http://localhost:80](http://localhost:80). 51 | 52 | ## Using it via Docker 53 | 54 | Run: 55 | 56 | ```bash 57 | docker run -it -p 80:80 asyncapi/server-api 58 | ``` 59 | 60 | server is ready to use on [http://localhost:80](http://localhost:80). 61 | 62 | ## Development 63 | 64 | 1. Setup project by installing dependencies `npm install` 65 | 2. Write code and tests. 66 | 3. Make sure all tests pass `npm test` 67 | 68 | ## Deployment 69 | 70 | This project is deployed to [DigitalOcean App Platform](https://www.digitalocean.com/products/app-platform/) using [Terraform](https://www.terraform.io/) and [GitHub Actions](https://www.github.com/digitalocean/app_action/). To deploy it to your own account, follow these steps: 71 | 72 | 1. Fork this repository. 73 | 2. Create a [DigitalOcean Personal Access Token](https://cloud.digitalocean.com/account/api/tokens) with `read` and `write` permissions. For more information, see [DigitalOcean's documentation](https://docs.digitalocean.com/reference/api/create-personal-access-token/). 74 | 3. Run `terraform init` to initialize the Terraform project as can be seen [here](./deployments/apps/main.tf). This should be run being located at ./deployments/apps directory preferably. 75 | 4. Run `terraform apply` to create the necessary infrastructure. 76 | 77 | > [!NOTE] 78 | > You need to export the following environment variables before running `terraform apply`: 79 | > - `DIGITALOCEAN_ACCESS_TOKEN`: Your DigitalOcean Personal Access Token. 80 | 81 | 82 | ### How the GitHub workflow works 83 | 84 | The [GitHub workflow](./.github/workflows/release-docker.yml) is triggered when a new tag is pushed to the repository. It will build a new Docker image and push it to the [Docker Hub](https://hub.docker.com/r/asyncapi/server-api) repository. Then the [DigitalOcean App Platform GitHub Action](https://www.github.com/digitalocean/app_action/) updates the application with the new image. 85 | 86 | ## Contribution 87 | 88 | Read [CONTRIBUTING](https://github.com/asyncapi/.github/blob/master/CONTRIBUTING.md) guide. 89 | 90 | ## Supported by 91 | 92 |

93 | 94 | 95 | 96 |

97 | 98 | ## Contributors 99 | 100 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 |
Maciej Urbańczyk
Maciej Urbańczyk

🚧 💻 📖 🐛 🤔 👀 ⚠️ 🚇 🧑‍🏫
David Pereira
David Pereira

🚧 💻 📖 🐛 🤔 👀 ⚠️ 🚇 🧑‍🏫
Sergio Moya
Sergio Moya

🚧 💻 📖 🐛 🤔 👀 ⚠️ 🚇 🧑‍🏫
Ritik Rawal
Ritik Rawal

💻 📖
Everly Precia Suresh
Everly Precia Suresh

💻 📖
Ashish Padhy
Ashish Padhy

📖 🚇
117 | 118 | 119 | 120 | 121 | 122 | 123 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! 124 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant 3.0 Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We pledge to make our community welcoming, safe, and equitable for all. 7 | 8 | We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant. 9 | 10 | ## Encouraged Behaviors 11 | 12 | While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language. 13 | 14 | With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including: 15 | 16 | 1. Respecting the **purpose of our community**, our activities, and our ways of gathering. 17 | 2. Engaging **kindly and honestly** with others. 18 | 3. Respecting **different viewpoints** and experiences. 19 | 4. **Taking responsibility** for our actions and contributions. 20 | 5. Gracefully giving and accepting **constructive feedback**. 21 | 6. Committing to **repairing harm** when it occurs. 22 | 7. Behaving in other ways that promote and sustain the **well-being of our community**. 23 | 24 | 25 | ## Restricted Behaviors 26 | 27 | We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct. 28 | 29 | 1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop. 30 | 2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people. 31 | 3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits. 32 | 4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community. 33 | 5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission. 34 | 6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group. 35 | 7. Behaving in other ways that **threaten the well-being** of our community. 36 | 37 | ### Other Restrictions 38 | 39 | 1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions. 40 | 2. **Failing to credit sources.** Not properly crediting the sources of content you contribute. 41 | 3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community. 42 | 4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors. 43 | 44 | 45 | ## Reporting an Issue 46 | 47 | Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm. 48 | 49 | When an incident does occur, it is important to report it promptly. To report a possible violation, here are a few simple ways to do it: 50 | 51 | - Join our [AsyncAPI Slack](https://asyncapi.com/slack-invite) and share your report in the `#coc` channel. 52 | - Reach out directly to any member of the [Code of Conduct Committee](https://github.com/orgs/asyncapi/teams/code_of_conduct). 53 | - Or, if you’d prefer, just send us an email at **conduct@asyncapi.com**. 54 | 55 | Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution. 56 | 57 | 58 | ## Addressing and Repairing Harm 59 | 60 | **** 61 | 62 | If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped. 63 | 64 | 1) Warning 65 | 1) Event: A violation involving a single incident or series of incidents. 66 | 2) Consequence: A private, written warning from the Community Moderators. 67 | 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations. 68 | 2) Temporarily Limited Activities 69 | 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation. 70 | 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members. 71 | 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over. 72 | 3) Temporary Suspension 73 | 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation. 74 | 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions. 75 | 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted. 76 | 4) Permanent Ban 77 | 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member. 78 | 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior. 79 | 3) Repair: There is no possible repair in cases of this severity. 80 | 81 | This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community. 82 | 83 | 84 | ## Scope 85 | 86 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 87 | 88 | 89 | ## Attribution 90 | 91 | This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/). 92 | 93 | Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/) 94 | 95 | For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion). --------------------------------------------------------------------------------