├── .sonarcloud.properties ├── src ├── Utils │ ├── index.ts │ └── Helpers.ts ├── index.ts ├── Reporters │ ├── index.ts │ ├── RemoveComponents.ts │ ├── ReuseComponents.ts │ ├── moveAllToComponents.ts │ └── moveDuplicatesToComponents.ts ├── types.ts ├── ComponentProvider.ts └── Optimizer.ts ├── .gitignore ├── .eslintignore ├── assets └── readme-banner.png ├── .prettierrc ├── NOTICE ├── .github └── 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 │ ├── bump.yml │ ├── automerge.yml │ ├── please-take-a-look-command.yml │ ├── transfer-issue.yml │ ├── lint-pr-title.yml │ ├── stale-issues-prs.yml │ ├── automerge-orphans.yml │ ├── add-good-first-issue-labels.yml │ ├── if-nodejs-pr-testing.yml │ ├── help-command.yml │ ├── issues-prs-notifications.yml │ ├── if-nodejs-version-bump.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 │ ├── update-maintainers.yml │ └── notify-tsc-members-mention.yml ├── .npmignore ├── CODEOWNERS ├── jest.config.js ├── .releaserc ├── tsconfig.json ├── examples ├── index.js ├── output.yaml └── input.yaml ├── test ├── ComponentProvider.spec.ts ├── Utils │ └── Helpers.spec.ts ├── Reporters │ └── Reporters.spec.ts └── Optimizer.spec.ts ├── package.json ├── .eslintrc ├── CONTRIBUTING.md ├── README.md ├── API.md ├── CODE_OF_CONDUCT.md └── LICENSE /.sonarcloud.properties: -------------------------------------------------------------------------------- 1 | sonar.exclusions=test/**/* 2 | -------------------------------------------------------------------------------- /src/Utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Helpers'; 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode 3 | .idea 4 | coverage 5 | lib 6 | *.DS_Store -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode 3 | .idea 4 | coverage 5 | lib 6 | *.DS_Store 7 | examples 8 | -------------------------------------------------------------------------------- /assets/readme-banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asyncapi/optimizer/HEAD/assets/readme-banner.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "trailingComma": "es5", 5 | "printWidth": 100 6 | } 7 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { Optimizer, Output } from './Optimizer' 2 | export type { Report, ReportElement, Options } from './types' 3 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2016-2025 AsyncAPI Initiative 2 | 3 | This product includes software developed at 4 | AsyncAPI Initiative (http://www.asyncapi.com/). -------------------------------------------------------------------------------- /src/Reporters/index.ts: -------------------------------------------------------------------------------- 1 | export * from './moveAllToComponents' 2 | export * from './moveDuplicatesToComponents' 3 | export * from './RemoveComponents' 4 | export * from './ReuseComponents' 5 | -------------------------------------------------------------------------------- /.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. -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .github 2 | examples 3 | node_nodules 4 | src 5 | test 6 | .eslintignore 7 | .eslintrc 8 | .gitignore 9 | API.md 10 | CODEOWNERS 11 | jest.config.js 12 | package-lock.json 13 | tsconfig.json 14 | -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /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 | * @khudadad414 @aeworxet @asyncapi-bot-eve 9 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line no-undef 2 | module.exports = { 3 | coverageReporters: [ 4 | 'json-summary', 5 | 'lcov', 6 | 'text' 7 | ], 8 | preset: 'ts-jest', 9 | // The root of your source code, typically /src 10 | // `` is a token Jest substitutes 11 | roots: [''], 12 | 13 | // Test spec file resolution pattern 14 | // Matches parent folder `__tests__` and filename 15 | // should contain `test` or `spec`. 16 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$', 17 | // Module file extensions for importing 18 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 19 | testTimeout: 10000 20 | }; 21 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./lib", 4 | "baseUrl": "./src", 5 | "declaration": true, 6 | "target": "es6", 7 | "lib": [ 8 | "esnext" 9 | ], 10 | "sourceMap": true, 11 | "allowJs": true, 12 | "skipLibCheck": true, 13 | "esModuleInterop": true, 14 | "allowSyntheticDefaultImports": true, 15 | "strict": true, 16 | "forceConsistentCasingInFileNames": true, 17 | "noFallthroughCasesInSwitch": true, 18 | "module": "commonjs", 19 | "moduleResolution": "node", 20 | "resolveJsonModule": true, 21 | "isolatedModules": true 22 | }, 23 | "include": [ 24 | "src/**/*.ts", 25 | ], 26 | "exclude": ["node_modules", "lib", "examples"] 27 | } 28 | -------------------------------------------------------------------------------- /examples/index.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line @typescript-eslint/no-var-requires 2 | const { Optimizer } = require('../lib/Optimizer') 3 | const fs = require('fs') 4 | const path = require('path') 5 | 6 | // Construct absolute paths to input and output files 7 | const inputFilePath = path.join(__dirname, 'input.yaml') 8 | const outputFilePath = path.join(__dirname, 'output.yaml') 9 | 10 | // Read input.yaml file synchronously and store it as a string 11 | const input = fs.readFileSync(inputFilePath, 'utf8') 12 | const optimizer = new Optimizer(input) 13 | 14 | optimizer.getReport().then((report) => { 15 | console.log(report) 16 | const optimizedDocument = optimizer.getOptimizedDocument({ 17 | output: 'YAML', 18 | rules: { 19 | reuseComponents: true, 20 | removeComponents: true, 21 | moveAllToComponents: true, 22 | moveDuplicatesToComponents: false, 23 | }, 24 | disableOptimizationFor: { 25 | schema: false, 26 | }, 27 | }) 28 | 29 | // Store optimizedDocument to output.yaml 30 | fs.writeFileSync(outputFilePath, optimizedDocument) 31 | }) 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 | -------------------------------------------------------------------------------- /src/Reporters/RemoveComponents.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '../Optimizer' 2 | import { OptimizableComponentGroup, ReportElement, Reporter } from '../types' 3 | import { createReport, isInComponents } from '../Utils' 4 | import Debug from 'debug' 5 | const debug = Debug('reporter:removeComponents') 6 | 7 | const findUnusedComponents = (componentsGroup: OptimizableComponentGroup): ReportElement[] => { 8 | const allComponents = componentsGroup.components 9 | const insideComponentsSection = new Set([...allComponents].filter(isInComponents)) 10 | const outsideComponentsSection = new Set( 11 | allComponents 12 | .filter((component) => !insideComponentsSection.has(component)) 13 | .map((component) => component.component) 14 | ) 15 | const unusedComponents = [...insideComponentsSection].filter( 16 | (component) => !outsideComponentsSection.has(component.component) 17 | ) 18 | debug( 19 | 'unused %s inside components section: %O', 20 | componentsGroup.type, 21 | unusedComponents.map((component) => component.path) 22 | ) 23 | return unusedComponents.map((component) => ({ path: component.path, action: Action.Remove })) 24 | } 25 | 26 | export const removeComponents: Reporter = (optimizeableComponents) => { 27 | return createReport(findUnusedComponents, optimizeableComponents, 'removeComponents') 28 | } 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 | -------------------------------------------------------------------------------- /test/ComponentProvider.spec.ts: -------------------------------------------------------------------------------- 1 | import { asyncapiYAMLWithoutComponents, inputYAML } from './fixtures' 2 | import { Parser } from '@asyncapi/parser' 3 | import { isInComponents } from '../src/Utils' 4 | import { getOptimizableComponents } from '../src/ComponentProvider' 5 | 6 | describe('ComponentProvider', () => { 7 | it('should not contain any component from components section', async () => { 8 | const asyncapiDocument = await new Parser().parse(asyncapiYAMLWithoutComponents, { 9 | applyTraits: false, 10 | }) 11 | const componentProviderWithoutComponents = getOptimizableComponents(asyncapiDocument.document!) 12 | for (const componentsGroup of componentProviderWithoutComponents) { 13 | for (const component of componentsGroup.components) { 14 | expect(isInComponents(component)).toBe(false) 15 | } 16 | } 17 | }) 18 | 19 | it('should contain some components from components section', async () => { 20 | const asyncapiDocument = await new Parser().parse(inputYAML) 21 | const componentProviderWithComponents = getOptimizableComponents(asyncapiDocument.document!) 22 | let inComponentsCounter = 0 23 | 24 | for (const componentsGroup of componentProviderWithComponents) { 25 | for (const component of componentsGroup.components) { 26 | if (isInComponents(component)) { 27 | inComponentsCounter++ 28 | } 29 | } 30 | } 31 | expect(inComponentsCounter).toBeGreaterThan(0) 32 | }) 33 | }) 34 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import type { Action, Output } from './Optimizer' 2 | 3 | export interface ReportElement { 4 | path: string 5 | action: Action 6 | target?: string 7 | } 8 | export type OptimizableComponent = { 9 | path: string 10 | component: any 11 | } 12 | export type OptimizableComponentGroup = { 13 | type: string 14 | components: OptimizableComponent[] 15 | } 16 | 17 | //Keeping this format for compatibility reasons. (we can remove this in the next major version) 18 | export interface Report { 19 | reuseComponents?: ReportElement[] 20 | removeComponents?: ReportElement[] 21 | moveAllToComponents?: ReportElement[] 22 | moveDuplicatesToComponents?: ReportElement[] 23 | } 24 | 25 | //In the next major version we can rename this to `Report` and use this format instead. 26 | export interface NewReport { 27 | type: string 28 | elements: ReportElement[] 29 | } 30 | 31 | export type Reporter = (optimizeableComponents: OptimizableComponentGroup[]) => NewReport 32 | 33 | interface Rules { 34 | reuseComponents?: boolean 35 | removeComponents?: boolean 36 | moveAllToComponents?: boolean 37 | moveDuplicatesToComponents?: boolean 38 | } 39 | 40 | export interface DisableOptimizationFor { 41 | schema?: boolean 42 | } 43 | export interface Options { 44 | rules?: Rules 45 | output?: Output 46 | disableOptimizationFor?: DisableOptimizationFor // non-approved type 47 | } 48 | 49 | export interface IOptimizer { 50 | getReport: () => ReportElement[] 51 | } 52 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/Reporters/ReuseComponents.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '../Optimizer' 2 | import { 3 | OptimizableComponent, 4 | OptimizableComponentGroup, 5 | ReportElement, 6 | Reporter, 7 | } from '../types' 8 | import { createReport, isEqual, isInChannels, isInComponents } from '../Utils' 9 | import Debug from 'debug' 10 | const debug = Debug('reporter:reuseComponents') 11 | 12 | const isChannelToComponent = ( 13 | component1: OptimizableComponent, 14 | component2: OptimizableComponent 15 | ): boolean => { 16 | return isInChannels(component1) && isInComponents(component2) 17 | } 18 | 19 | const findDuplicateComponents = ( 20 | optimizableComponent: OptimizableComponentGroup 21 | ): ReportElement[] => { 22 | const elements = [] 23 | //compare components together and push a record in elements if a duplicated is found. 24 | for (const component1 of optimizableComponent.components) { 25 | for (const component2 of optimizableComponent.components) { 26 | if (component1.path === component2.path || !isChannelToComponent(component1, component2)) { 27 | continue 28 | } 29 | if (isEqual(component1.component, component2.component, false)) { 30 | const element: ReportElement = { 31 | path: component1.path, 32 | action: Action.Reuse, 33 | target: component2.path, 34 | } 35 | elements.push(element) 36 | break 37 | } 38 | } 39 | } 40 | for (const element of elements) { 41 | debug('%s can reuse %s', element.path, element.target) 42 | } 43 | 44 | return elements 45 | } 46 | 47 | export const reuseComponents: Reporter = (optimizeableComponents) => { 48 | return createReport(findDuplicateComponents, optimizeableComponents, 'reuseComponents') 49 | } 50 | -------------------------------------------------------------------------------- /src/Reporters/moveAllToComponents.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '../Optimizer' 2 | import { createReport, isEqual, isInComponents, getComponentName } from '../Utils' 3 | import { OptimizableComponent, OptimizableComponentGroup, ReportElement, Reporter } from 'types' 4 | import Debug from 'debug' 5 | const debug = Debug('reporter:moveAllToComponents') 6 | /** 7 | * 8 | * @param optimizableComponentGroup all AsyncAPI Specification-valid components. 9 | * @returns A list of optimization report elements. 10 | */ 11 | const findAllComponents = ( 12 | optimizableComponentGroup: OptimizableComponentGroup 13 | ): ReportElement[] => { 14 | const allComponents = optimizableComponentGroup.components 15 | const insideComponentsSection = allComponents.filter(isInComponents) 16 | const outsideComponentsSection = getOutsideComponents(allComponents, insideComponentsSection) 17 | 18 | const resultElements: ReportElement[] = [] 19 | 20 | for (const component of outsideComponentsSection.values()) { 21 | const existingResult = resultElements.filter( 22 | (reportElement) => component.path === reportElement.path 23 | )[0] 24 | if (!existingResult) { 25 | const componentName = getComponentName(component) 26 | const target = `components.${optimizableComponentGroup.type}.${componentName}` 27 | resultElements.push({ 28 | path: component.path, 29 | action: Action.Move, 30 | target, 31 | }) 32 | } 33 | } 34 | debug( 35 | 'all %s: %O', 36 | optimizableComponentGroup.type, 37 | resultElements.map((element) => element.path) 38 | ) 39 | return resultElements 40 | } 41 | 42 | export const moveAllToComponents: Reporter = (optimizableComponentsGroup) => { 43 | return createReport(findAllComponents, optimizableComponentsGroup, 'moveAllToComponents') 44 | } 45 | 46 | function getOutsideComponents( 47 | allComponents: OptimizableComponent[], 48 | insideComponentsSection: OptimizableComponent[] 49 | ) { 50 | return allComponents.filter( 51 | (component) => 52 | !isInComponents(component) && 53 | insideComponentsSection.filter((inCSC) => isEqual(component.component, inCSC.component, true)) 54 | .length === 0 55 | ) 56 | } 57 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@asyncapi/optimizer", 3 | "version": "1.0.4", 4 | "description": "This library will optimize the AsyncAPI specification file.", 5 | "main": "./lib/index.js", 6 | "types": "./lib/index.d.ts", 7 | "files": [ 8 | "/lib", 9 | "./README.md", 10 | "./LICENSE" 11 | ], 12 | "scripts": { 13 | "test": "jest --coverage", 14 | "test:watch": "jest --watch", 15 | "build": "tsc", 16 | "dev": "tsc --watch", 17 | "docs": "jsdoc2md lib/Optimizer.js -f lib/**/*.js > API.md", 18 | "example": "tsc && node examples/index.js", 19 | "lint": "eslint --max-warnings 0 --config .eslintrc .", 20 | "get:version": "echo $npm_package_version", 21 | "get:name": "echo $npm_package_name", 22 | "generate:readme:toc": "markdown-toc -i README.md", 23 | "generate:assets": "npm run build && npm run docs && npm run generate:readme:toc", 24 | "bump:version": "npm --no-git-tag-version --allow-same-version version $VERSION", 25 | "prepublishOnly": "npm run build" 26 | }, 27 | "repository": { 28 | "type": "git", 29 | "url": "git+https://github.com/asyncapi/optimizer.git" 30 | }, 31 | "author": "Khuda Dad Nomani", 32 | "license": "Apache-2.0", 33 | "bugs": { 34 | "url": "https://github.com/asyncapi/optimizer/issues" 35 | }, 36 | "homepage": "https://github.com/asyncapi/optimizer#readme", 37 | "devDependencies": { 38 | "@types/jest": "^26.0.23", 39 | "@types/js-yaml": "^4.0.3", 40 | "@types/lodash": "^4.14.171", 41 | "@types/merge-deep": "^3.0.0", 42 | "@types/node": "^15.12.1", 43 | "@typescript-eslint/eslint-plugin": "^4.26.0", 44 | "@typescript-eslint/parser": "^4.26.0", 45 | "eslint": "^7.28.0", 46 | "eslint-plugin-github": "^4.1.3", 47 | "eslint-plugin-security": "^1.4.0", 48 | "eslint-plugin-sonarjs": "^0.8.0-125", 49 | "jest": "^29.6.1", 50 | "jsdoc-to-markdown": "^7.0.1", 51 | "markdown-toc": "^1.2.0", 52 | "ts-jest": "^29.1.1", 53 | "typescript": "^4.3.2" 54 | }, 55 | "publishConfig": { 56 | "access": "public" 57 | }, 58 | "dependencies": { 59 | "@asyncapi/parser": "^3.2.2", 60 | "@types/debug": "^4.1.8", 61 | "debug": "^4.3.4", 62 | "js-yaml": "^4.1.0", 63 | "jsonpath-plus": "^10.1.0", 64 | "lodash": "^4.17.21", 65 | "merge-deep": "^3.0.3", 66 | "yaml": "^2.3.1" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /test/Utils/Helpers.spec.ts: -------------------------------------------------------------------------------- 1 | import YAML from 'yaml' 2 | import _ from 'lodash' 3 | import { compareComponents, isEqual, isInComponents, isInChannels, toJS } from '../../src/Utils' 4 | 5 | describe('Helpers', () => { 6 | const testObject1 = { 7 | streetlightId: { schema: { type: 'string', 'x-extension': 'different_value' } }, 8 | } 9 | const testObject1_copy = { streetlightId: { schema: { type: 'string', 'x-extension': 'value' } } } 10 | const testObject2 = { streetlightId: { schema: { type: 'number' } } } 11 | const testObject2_reference = testObject2 12 | 13 | describe('compareComponents', () => { 14 | test('should return true.', () => { 15 | expect(compareComponents(testObject1, testObject1_copy)).toEqual(true) 16 | }) 17 | 18 | test('should return false.', () => { 19 | expect(compareComponents(testObject1, testObject2)).toEqual(false) 20 | }) 21 | }) 22 | describe('isEqual', () => { 23 | test('should return true.', () => { 24 | expect(isEqual(testObject2, testObject2_reference, true)).toEqual(true) 25 | expect(isEqual(testObject1, testObject1_copy, true)).toEqual(true) 26 | expect(isEqual(testObject1, testObject1_copy, false)).toEqual(true) 27 | }) 28 | 29 | test('should return false.', () => { 30 | expect(isEqual(testObject2, testObject2_reference, false)).toEqual(false) 31 | }) 32 | }) 33 | 34 | describe('isInComponents', () => { 35 | test('should return true.', () => { 36 | expect(isInComponents({ component: {}, path: 'components.messages.message1' })).toEqual(true) 37 | }) 38 | 39 | test('should return false.', () => { 40 | expect(isInComponents({ component: {}, path: 'channels.channel1.message' })).toEqual(false) 41 | }) 42 | }) 43 | 44 | describe('toJS', () => { 45 | const json_object = { 46 | components: { 47 | messages: { 48 | unusedMessage: { name: 'unusedMessage', title: 'Thismessageisnotusedinanychannel.' }, 49 | }, 50 | }, 51 | } 52 | const json_string = JSON.stringify(json_object) 53 | const yaml_string = YAML.stringify(json_object) 54 | test('should convert all input types to Object.', () => { 55 | expect(_.isEqual(toJS(json_object), json_object)).toEqual(true) 56 | expect(_.isEqual(toJS(json_string), json_object)).toEqual(true) 57 | expect(_.isEqual(toJS(yaml_string), json_object)).toEqual(true) 58 | }) 59 | }) 60 | describe('isInChannels', () => { 61 | test('should return true.', () => { 62 | expect(isInChannels({ component: {}, path: 'channels.channel1.message' })).toEqual(true) 63 | }) 64 | 65 | test('should return false.', () => { 66 | expect(isInChannels({ component: {}, path: 'components.messages.message1' })).toEqual(false) 67 | }) 68 | }) 69 | }) 70 | -------------------------------------------------------------------------------- /.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/Reporters/moveDuplicatesToComponents.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '../Optimizer' 2 | import { createReport, isEqual, isInComponents, getComponentName } from '../Utils' 3 | import { OptimizableComponent, OptimizableComponentGroup, ReportElement, Reporter } from 'types' 4 | import Debug from 'debug' 5 | const debug = Debug('reporter:moveDuplicatesToComponents') 6 | /** 7 | * 8 | * @param optimizableComponentGroup all AsyncAPI Specification-valid components that you want to analyze for duplicates. 9 | * @returns A list of optimization report elements. 10 | */ 11 | const findDuplicateComponents = ( 12 | optimizableComponentGroup: OptimizableComponentGroup 13 | ): ReportElement[] => { 14 | const allComponents = optimizableComponentGroup.components 15 | const insideComponentsSection = allComponents.filter(isInComponents) 16 | const outsideComponentsSection = getOutsideComponents(allComponents, insideComponentsSection) 17 | 18 | const resultElements: ReportElement[] = [] 19 | 20 | for (const [index, component] of outsideComponentsSection.entries()) { 21 | for (const compareComponent of outsideComponentsSection.slice(index + 1)) { 22 | if (isEqual(component.component, compareComponent.component, false)) { 23 | const existingResult = resultElements.filter( 24 | (reportElement) => component.path === reportElement.path 25 | )[0] 26 | if (!existingResult) { 27 | const componentName = getComponentName(component) 28 | const target = `components.${optimizableComponentGroup.type}.${componentName}` 29 | resultElements.push({ 30 | path: component.path, 31 | action: Action.Move, 32 | target, 33 | }) 34 | resultElements.push({ 35 | path: compareComponent.path, 36 | action: Action.Reuse, 37 | target, 38 | }) 39 | } else { 40 | resultElements.push({ 41 | path: component.path, 42 | action: Action.Reuse, 43 | target: existingResult.target, 44 | }) 45 | } 46 | } 47 | } 48 | } 49 | debug( 50 | 'duplicte %s: %O', 51 | optimizableComponentGroup.type, 52 | resultElements.map((element) => element.path) 53 | ) 54 | return resultElements 55 | } 56 | 57 | export const moveDuplicatesToComponents: Reporter = (optimizableComponentsGroup) => { 58 | return createReport( 59 | findDuplicateComponents, 60 | optimizableComponentsGroup, 61 | 'moveDuplicatesToComponents' 62 | ) 63 | } 64 | 65 | function getOutsideComponents( 66 | allComponents: OptimizableComponent[], 67 | insideComponentsSection: OptimizableComponent[] 68 | ) { 69 | return allComponents.filter( 70 | (component) => 71 | !isInComponents(component) && 72 | insideComponentsSection.filter((inCSC) => isEqual(component.component, inCSC.component, true)) 73 | .length === 0 74 | ) 75 | } 76 | -------------------------------------------------------------------------------- /.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/ComponentProvider.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 2 | /* eslint-disable security/detect-object-injection */ 3 | import type { AsyncAPIDocumentInterface } from '@asyncapi/parser' 4 | import { OptimizableComponentGroup, OptimizableComponent } from 'types' 5 | 6 | import { JSONPath } from 'jsonpath-plus' 7 | import _ from 'lodash' 8 | 9 | export const toLodashPath = (jsonPointer: string): string => { 10 | // Remove leading slash if present 11 | if (jsonPointer.startsWith('/')) { 12 | jsonPointer = jsonPointer.slice(1) 13 | } 14 | 15 | // Split the JSON Pointer into tokens 16 | const tokens = jsonPointer.split('/') 17 | 18 | // Unescape the special characters and transform into Lodash path 19 | return tokens 20 | .map((token) => { 21 | // Replace tilde representations 22 | token = token.replace(/~1/g, '/') 23 | token = token.replace(/~0/g, '~') 24 | 25 | // Check if token can be treated as an array index (non-negative integer) 26 | if (/^\d+$/.test(token)) { 27 | return `[${token}]` 28 | } 29 | // For nested properties, use dot notation 30 | return token 31 | }) 32 | .join('.') 33 | } 34 | 35 | export const parseComponentsFromPath = ( 36 | asyncAPIDocument: AsyncAPIDocumentInterface, 37 | paths: string[] 38 | ): OptimizableComponent[] => { 39 | return _.chain(paths) 40 | .map((path) => { 41 | return JSONPath({ 42 | resultType: 'all', 43 | json: asyncAPIDocument.json(), 44 | path, 45 | }) 46 | }) 47 | .flatten() 48 | .map((component) => ({ 49 | path: toLodashPath(component.path), 50 | component: component.value, 51 | })) 52 | .value() 53 | } 54 | 55 | export const getOptimizableComponents = ( 56 | asyncAPIDocument: AsyncAPIDocumentInterface, 57 | ): OptimizableComponentGroup[] => { 58 | const optimizeableComponents: OptimizableComponentGroup[] = [] 59 | const getAllComponents = (type: string) => { 60 | // @ts-ignore 61 | if (typeof asyncAPIDocument[type] !== 'function') return [] 62 | // @ts-ignore 63 | return asyncAPIDocument[type]().all().concat(asyncAPIDocument.components()[type]().all()) 64 | } 65 | const optimizableComponents = { 66 | servers: getAllComponents('servers'), 67 | messages: getAllComponents('messages'), 68 | channels: getAllComponents('channels'), 69 | schemas: getAllComponents('schemas'), 70 | operations: getAllComponents('operations'), 71 | securitySchemes: getAllComponents('securitySchemes'), 72 | serverVariables: getAllComponents('serverVariables'), 73 | parameters: getAllComponents('parameters'), 74 | correlationIds: getAllComponents('correlationIds'), 75 | replies: getAllComponents('replies'), 76 | replyAddresses: getAllComponents('replyAddresses'), 77 | externalDocs: getAllComponents('externalDocs'), 78 | tags: getAllComponents('tags'), 79 | operationTraits: getAllComponents('operationTraits'), 80 | messageTraits: getAllComponents('messageTraits'), 81 | serverBindings: getAllComponents('serverBindings'), 82 | channelBindings: getAllComponents('channelBindings'), 83 | operationBindings: getAllComponents('operationBindings'), 84 | messageBindings: getAllComponents('messageBindings'), 85 | } 86 | for (const [type, components] of Object.entries(optimizableComponents)) { 87 | if (components.length === 0) continue 88 | optimizeableComponents.push({ 89 | type, 90 | components: components.map((component: any) => ({ 91 | path: toLodashPath(component.jsonPath()), 92 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 93 | // @ts-ignore 94 | component: component.json(), 95 | })), 96 | }) 97 | } 98 | return optimizeableComponents 99 | } 100 | -------------------------------------------------------------------------------- /.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: Determine what node version to use 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 | with: 56 | node-version: ${{ vars.NODE_VERSION }} 57 | id: lockversion 58 | - if: steps.packagejson.outputs.exists == 'true' 59 | name: Setup Node.js 60 | uses: actions/setup-node@v4 61 | with: 62 | node-version: "${{ steps.lockversion.outputs.version }}" 63 | - if: steps.lockversion.outputs.version == '18' && matrix.os == 'windows-latest' 64 | #npm cli 10 is buggy because of some cache issue 65 | name: Install npm cli 8 66 | shell: bash 67 | run: npm install -g npm@8.19.4 68 | - if: steps.packagejson.outputs.exists == 'true' 69 | name: Install dependencies 70 | shell: bash 71 | run: npm ci 72 | - if: steps.packagejson.outputs.exists == 'true' 73 | name: Test 74 | run: npm test --if-present 75 | - if: steps.packagejson.outputs.exists == 'true' && matrix.os == 'ubuntu-latest' 76 | #linting should run just one and not on all possible operating systems 77 | name: Run linter 78 | run: npm run lint --if-present 79 | - if: steps.packagejson.outputs.exists == 'true' 80 | name: Run release assets generation to make sure PR does not break it 81 | shell: bash 82 | run: npm run generate:assets --if-present 83 | -------------------------------------------------------------------------------- /.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 | }) -------------------------------------------------------------------------------- /.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/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: Determine what node version to use 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 | with: 32 | node-version: ${{ vars.NODE_VERSION }} 33 | id: lockversion 34 | - if: steps.packagejson.outputs.exists == 'true' 35 | name: Setup Node.js 36 | uses: actions/setup-node@v4 37 | with: 38 | node-version: "${{ steps.lockversion.outputs.version }}" 39 | cache: 'npm' 40 | cache-dependency-path: '**/package-lock.json' 41 | - if: steps.packagejson.outputs.exists == 'true' 42 | name: Install dependencies 43 | run: npm ci 44 | - if: steps.packagejson.outputs.exists == 'true' 45 | name: Assets generation 46 | run: npm run generate:assets --if-present 47 | - if: steps.packagejson.outputs.exists == 'true' 48 | name: Bump version in package.json 49 | # There is no need to substract "v" from the tag as version script handles it 50 | # 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 51 | # 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 52 | env: 53 | VERSION: ${{github.event.release.tag_name}} 54 | run: npm run bump:version 55 | - if: steps.packagejson.outputs.exists == 'true' 56 | name: Create Pull Request with updated asset files including package.json 57 | uses: peter-evans/create-pull-request@38e0b6e68b4c852a5500a94740f0e535e0d7ba54 # use 4.2.4 https://github.com/peter-evans/create-pull-request/releases/tag/v4.2.4 58 | env: 59 | RELEASE_TAG: ${{github.event.release.tag_name}} 60 | RELEASE_URL: ${{github.event.release.html_url}} 61 | with: 62 | token: ${{ secrets.GH_TOKEN }} 63 | commit-message: 'chore(release): ${{ env.RELEASE_TAG }}' 64 | committer: asyncapi-bot 65 | author: asyncapi-bot 66 | title: 'chore(release): ${{ env.RELEASE_TAG }}' 67 | body: 'Version bump in package.json for release [${{ env.RELEASE_TAG }}](${{ env.RELEASE_URL }})' 68 | branch: version-bump/${{ env.RELEASE_TAG }} 69 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 70 | name: Report workflow run status to Slack 71 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 72 | with: 73 | status: ${{ job.status }} 74 | fields: repo,action,workflow 75 | text: 'Unable to bump the version in package.json after the release' 76 | env: 77 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "plugins": ["@typescript-eslint", "sonarjs", "security", "github"], 4 | "extends": [ 5 | "eslint:recommended", 6 | "plugin:@typescript-eslint/recommended", 7 | "plugin:sonarjs/recommended", 8 | "plugin:security/recommended" 9 | ], 10 | "rules": { 11 | "@typescript-eslint/no-unused-vars": ["error"], 12 | "strict": 0, 13 | "object-curly-spacing": ["error", "always"], 14 | "comma-spacing": ["error", { "before": false, "after": true }], 15 | "github/array-foreach": 2, 16 | "eol-last": ["error", "always"], 17 | "@typescript-eslint/no-explicit-any": 0, 18 | "require-await": "error", 19 | "@typescript-eslint/explicit-module-boundary-types": [ 20 | "error", 21 | { "allowArgumentsExplicitlyTypedAsAny": true } 22 | ], 23 | "sonarjs/no-small-switch": "off", 24 | "no-underscore-dangle": "error", 25 | "no-process-exit": "error", 26 | "no-warning-comments": "error", 27 | "no-loop-func": "error", 28 | "no-multi-spaces": "error", 29 | "consistent-return": 0, 30 | "consistent-this": [0, "self"], 31 | "func-style": 0, 32 | "max-nested-callbacks": ["error", 3], 33 | "camelcase": 0, 34 | "no-debugger": 1, 35 | "no-empty": 1, 36 | "no-invalid-regexp": 1, 37 | "no-unused-expressions": 1, 38 | "no-native-reassign": 1, 39 | "no-fallthrough": 1, 40 | "sonarjs/cognitive-complexity": 1, 41 | "eqeqeq": 2, 42 | "no-undef": 2, 43 | "no-dupe-keys": 2, 44 | "no-empty-character-class": 2, 45 | "no-self-compare": 2, 46 | "valid-typeof": 2, 47 | "no-unused-vars": [ 48 | 2, 49 | { 50 | "args": "none" 51 | } 52 | ], 53 | "handle-callback-err": 2, 54 | "no-shadow-restricted-names": 2, 55 | "no-new-require": 2, 56 | "no-mixed-spaces-and-tabs": 2, 57 | "block-scoped-var": 2, 58 | "no-else-return": 2, 59 | "no-throw-literal": 2, 60 | "no-void": 2, 61 | "radix": 2, 62 | "wrap-iife": [2, "outside"], 63 | "no-shadow": 0, 64 | "no-use-before-define": [2, "nofunc"], 65 | "no-path-concat": 2, 66 | "valid-jsdoc": [ 67 | 0, 68 | { 69 | "requireReturn": false, 70 | "requireParamDescription": false, 71 | "requireReturnDescription": false 72 | } 73 | ], 74 | "no-spaced-func": 2, 75 | "semi-spacing": 2, 76 | "quotes": [2, "single"], 77 | "key-spacing": [ 78 | 2, 79 | { 80 | "beforeColon": false, 81 | "afterColon": true 82 | } 83 | ], 84 | "no-lonely-if": 2, 85 | "no-floating-decimal": 2, 86 | "brace-style": [ 87 | 2, 88 | "1tbs", 89 | { 90 | "allowSingleLine": true 91 | } 92 | ], 93 | "comma-style": [2, "last"], 94 | "no-multiple-empty-lines": [ 95 | 2, 96 | { 97 | "max": 1 98 | } 99 | ], 100 | "no-nested-ternary": 2, 101 | "operator-assignment": [2, "always"], 102 | "padded-blocks": [2, "never"], 103 | "quote-props": [2, "as-needed"], 104 | "keyword-spacing": [ 105 | 2, 106 | { 107 | "before": true, 108 | "after": true, 109 | "overrides": {} 110 | } 111 | ], 112 | "space-before-blocks": [2, "always"], 113 | "array-bracket-spacing": [2, "never"], 114 | "computed-property-spacing": [2, "never"], 115 | "space-in-parens": [2, "never"], 116 | "space-unary-ops": [ 117 | 2, 118 | { 119 | "words": true, 120 | "nonwords": false 121 | } 122 | ], 123 | "no-console": "error", 124 | "wrap-regex": 0, 125 | //"linebreak-style": ["error", "unix"], 126 | "linebreak-style": 0, 127 | "arrow-spacing": [ 128 | 2, 129 | { 130 | "before": true, 131 | "after": true 132 | } 133 | ], 134 | "no-class-assign": 2, 135 | "no-const-assign": 2, 136 | "no-this-before-super": 2, 137 | "no-var": 2, 138 | "object-shorthand": [2, "always"], 139 | "prefer-arrow-callback": 2, 140 | "prefer-const": 2, 141 | "prefer-spread": 2, 142 | "prefer-template": 2 143 | }, 144 | "overrides": [ 145 | { 146 | "files": "*.spec.ts", 147 | "rules": { 148 | "no-undef": "off", 149 | "security/detect-non-literal-fs-filename": "off", 150 | "sonarjs/no-duplicate-string": "off", 151 | "security/detect-object-injection": "off", 152 | "max-nested-callbacks": "off", 153 | "sonarjs/no-identical-functions": "off", 154 | "@typescript-eslint/no-non-null-assertion": "off", 155 | "@typescript-eslint/no-unused-vars": "off" 156 | } 157 | } 158 | ] 159 | } 160 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /test/Reporters/Reporters.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | moveAllToComponents, 3 | moveDuplicatesToComponents, 4 | reuseComponents, 5 | removeComponents, 6 | } from '../../src/Reporters' 7 | import { inputYAML } from '../fixtures' 8 | import { Parser } from '@asyncapi/parser' 9 | import { getOptimizableComponents } from '../../src/ComponentProvider' 10 | import { OptimizableComponentGroup } from '../../src/types' 11 | 12 | const moveAllToComponentsExpectedResult: any[] = [ 13 | { 14 | path: 'channels.withDuplicatedMessage1.messages.duped1', 15 | action: 'move', 16 | target: 'components.messages.duped1', 17 | }, 18 | { 19 | path: 'channels.withDuplicatedMessage2.messages.duped2', 20 | action: 'move', 21 | target: 'components.messages.duped2', 22 | }, 23 | { 24 | path: 'channels.withFullFormMessage.messages.canBeReused', 25 | action: 'move', 26 | target: 'components.messages.canBeReused', 27 | }, 28 | { 29 | path: 'channels.withDuplicatedMessage1', 30 | action: 'move', 31 | target: 'components.channels.withDuplicatedMessage1FromXOrigin', 32 | }, 33 | { 34 | path: 'channels.withDuplicatedMessage2', 35 | action: 'move', 36 | target: 'components.channels.withDuplicatedMessage2', 37 | }, 38 | { 39 | path: 'channels.withFullFormMessage', 40 | action: 'move', 41 | target: 'components.channels.withFullFormMessage', 42 | }, 43 | { 44 | path: 'channels.UserSignedUp1', 45 | action: 'move', 46 | target: 'components.channels.UserSignedUp1', 47 | }, 48 | { 49 | path: 'channels.UserSignedUp2', 50 | action: 'move', 51 | target: 'components.channels.UserSignedUp2', 52 | }, 53 | { 54 | path: 'channels.deleteAccount', 55 | action: 'move', 56 | target: 'components.channels.deleteAccount', 57 | }, 58 | { 59 | path: 'channels.withDuplicatedMessage1.messages.duped1.payload', 60 | action: 'move', 61 | target: 'components.schemas.payload', 62 | }, 63 | { 64 | path: 'channels.withDuplicatedMessage2.messages.duped2.payload', 65 | action: 'move', 66 | target: 'components.schemas.payload', 67 | }, 68 | { 69 | path: 'channels.UserSignedUp1.messages.myMessage.payload', 70 | action: 'move', 71 | target: 'components.schemas.payload', 72 | }, 73 | { 74 | path: 'channels.UserSignedUp1.messages.myMessage.payload.properties.displayName', 75 | action: 'move', 76 | target: 'components.schemas.displayName', 77 | }, 78 | { 79 | path: 'channels.UserSignedUp1.messages.myMessage.payload.properties.email', 80 | action: 'move', 81 | target: 'components.schemas.email', 82 | }, 83 | { 84 | path: 'channels.deleteAccount.messages.deleteUser.payload', 85 | action: 'move', 86 | target: 'components.schemas.payload', 87 | }, 88 | { 89 | path: 'operations.user/deleteAccount.subscribe', 90 | action: 'move', 91 | target: 'components.operations.subscribe', 92 | }, 93 | ] 94 | const moveDuplicatesToComponentsExpectedResult: any[] = [ 95 | { 96 | path: 'channels.withDuplicatedMessage1.messages.duped1', 97 | action: 'move', 98 | target: 'components.messages.duped1', 99 | }, 100 | { 101 | path: 'channels.withDuplicatedMessage2.messages.duped2', 102 | action: 'reuse', 103 | target: 'components.messages.duped1', 104 | }, 105 | { 106 | path: 'channels.UserSignedUp1', 107 | action: 'move', 108 | target: 'components.channels.UserSignedUp1', 109 | }, 110 | { 111 | path: 'channels.UserSignedUp2', 112 | action: 'reuse', 113 | target: 'components.channels.UserSignedUp1', 114 | }, 115 | { 116 | path: 'channels.withDuplicatedMessage1.messages.duped1.payload', 117 | action: 'move', 118 | target: 'components.schemas.payload', 119 | }, 120 | { 121 | path: 'channels.withDuplicatedMessage2.messages.duped2.payload', 122 | action: 'reuse', 123 | target: 'components.schemas.payload', 124 | }, 125 | ] 126 | const RemoveComponentsExpectedResult = [ 127 | { path: 'components.messages.unUsedMessage', action: 'remove' }, 128 | { path: 'components.channels.unUsedChannel', action: 'remove' }, 129 | { path: 'components.schemas.canBeReused', action: 'remove' }, 130 | ] 131 | const ReuseComponentsExpectedResult = [ 132 | { 133 | path: 'channels.withFullFormMessage.messages.canBeReused.payload', 134 | action: 'reuse', 135 | target: 'components.schemas.canBeReused', 136 | }, 137 | ] 138 | 139 | describe('Optimizers', () => { 140 | let optimizableComponents: OptimizableComponentGroup[] 141 | beforeAll(async () => { 142 | const asyncapiDocument = await new Parser().parse(inputYAML, { applyTraits: false }) 143 | optimizableComponents = getOptimizableComponents(asyncapiDocument.document!) 144 | }) 145 | describe('moveAllToComponents', () => { 146 | test('should contain the correct optimizations.', () => { 147 | const report = moveAllToComponents(optimizableComponents) 148 | expect(report.elements).toEqual(moveAllToComponentsExpectedResult) 149 | expect(report.type).toEqual('moveAllToComponents') 150 | }) 151 | }) 152 | 153 | describe('moveDuplicatesToComponents', () => { 154 | test('should contain the correct optimizations.', () => { 155 | const report = moveDuplicatesToComponents(optimizableComponents) 156 | expect(report.elements).toEqual(moveDuplicatesToComponentsExpectedResult) 157 | expect(report.type).toEqual('moveDuplicatesToComponents') 158 | }) 159 | }) 160 | 161 | describe('RemoveComponents', () => { 162 | test('should contain the correct optimizations.', () => { 163 | const report = removeComponents(optimizableComponents) 164 | expect(report.elements).toEqual(RemoveComponentsExpectedResult) 165 | expect(report.type).toEqual('removeComponents') 166 | }) 167 | }) 168 | 169 | describe('ReuseComponents', () => { 170 | test('should contain the correct optimizations.', () => { 171 | const report = reuseComponents(optimizableComponents) 172 | expect(report.elements).toEqual(ReuseComponentsExpectedResult) 173 | expect(report.type).toEqual('reuseComponents') 174 | }) 175 | }) 176 | }) 177 | -------------------------------------------------------------------------------- /src/Utils/Helpers.ts: -------------------------------------------------------------------------------- 1 | import * as _ from 'lodash' 2 | import YAML from 'js-yaml' 3 | import { OptimizableComponentGroup, NewReport, ReportElement, OptimizableComponent } from 'types' 4 | 5 | /** 6 | * Checks if a component's parent is a ref or not. 7 | */ 8 | export const hasParent = (reportElement: ReportElement, asyncapiFile: any): boolean => { 9 | const childPath = reportElement.path 10 | const parentPath = childPath.substring(0, childPath.lastIndexOf('.')) 11 | const parent = _.get(asyncapiFile, parentPath) 12 | return !_.has(parent, '$ref') 13 | } 14 | 15 | export const createReport = ( 16 | reportFn: (optimizableComponent: OptimizableComponentGroup) => ReportElement[], 17 | optimizeableComponents: OptimizableComponentGroup[], 18 | reporterType: string 19 | ): NewReport => { 20 | const elements = optimizeableComponents 21 | .map((optimizeableComponent) => reportFn(optimizeableComponent)) 22 | .flat() 23 | 24 | const type = reporterType 25 | return { type, elements } 26 | } 27 | 28 | export const sortReportElements = (report: NewReport): NewReport => { 29 | report.elements.sort((a, b) => a.action.length - b.action.length || b.path.length - a.path.length) 30 | return report 31 | } 32 | 33 | // Utility function to get all targets of reports with type 'reuseComponents' 34 | const getReuseComponentTargets = ( 35 | reports: { type: string; elements: ReportElement[] }[] 36 | ): Set => { 37 | const targets = new Set() 38 | for (const report of reports) { 39 | if (report.type === 'reuseComponents') { 40 | for (const element of report.elements) { 41 | if (element.target) { 42 | targets.add(element.target) 43 | } 44 | } 45 | } 46 | } 47 | return targets 48 | } 49 | 50 | // Main function to filter report elements 51 | export const filterReportElements = ( 52 | reports: { type: string; elements: ReportElement[] }[] 53 | ): NewReport[] => { 54 | const reuseTargets = getReuseComponentTargets(reports) 55 | 56 | return reports.map((report) => { 57 | if (report.type === 'removeComponents') { 58 | const filteredElements = report.elements.filter((element) => { 59 | return !reuseTargets.has(element.path) 60 | }) 61 | return { type: report.type, elements: filteredElements } 62 | } 63 | return report 64 | }) 65 | } 66 | 67 | const isExtension = (fieldName: string): boolean => { 68 | return fieldName.startsWith('x-') 69 | } 70 | 71 | const backwardsCheck = (x: any, y: any): boolean => { 72 | for (const p in y) { 73 | if (_.has(y, p) && !_.has(x, p)) { 74 | return false 75 | } 76 | } 77 | return true 78 | } 79 | 80 | const compareComponents = (x: any, y: any): boolean => { 81 | // if they are not strictly equal, they both need to be Objects 82 | if (!(x instanceof Object) || !(y instanceof Object)) { 83 | return false 84 | } 85 | for (const p in x) { 86 | //extensions have different values for objects that are equal (duplicated.) If you don't skip the extensions this function always returns false. 87 | if (isExtension(p)) { 88 | continue 89 | } 90 | if (!_.has(x, p)) { 91 | continue 92 | } 93 | 94 | // allows to compare x[ p ] and y[ p ] when set to undefined 95 | if (!_.has(y, p)) { 96 | return false 97 | } 98 | 99 | // if they have the same strict value or identity then they are equal 100 | if (x[String(p)] === y[String(p)]) { 101 | continue 102 | } 103 | 104 | // Numbers, Strings, Functions, Booleans must be strictly equal 105 | if (typeof x[String(p)] !== 'object') { 106 | return false 107 | } 108 | 109 | // Objects and Arrays must be tested recursively 110 | if (!compareComponents(x[String(p)], y[String(p)])) { 111 | return false 112 | } 113 | } 114 | return backwardsCheck(x, y) 115 | } 116 | 117 | /** 118 | * 119 | * @param component1 The first component that you want to compare with the second component. 120 | * @param component2 The second component. 121 | * @param referentialEqualityCheck If `true` the function will return true if the two components have referential equality OR they have the same structure. If `false` the it will only return true if they have the same structure but they are NOT referentially equal. 122 | * @returns whether the two components are equal. 123 | */ 124 | const isEqual = (component1: any, component2: any, referentialEqualityCheck: boolean): boolean => { 125 | if (referentialEqualityCheck) { 126 | return component1 === component2 || compareComponents(component1, component2) 127 | } 128 | return component1 !== component2 && compareComponents(component1, component2) 129 | } 130 | 131 | /** 132 | * checks if a component is located in `components` section of an asyncapi document. 133 | */ 134 | const isInComponents = (optimizableComponent: OptimizableComponent): boolean => { 135 | return optimizableComponent.path.startsWith('components.') 136 | } 137 | 138 | /** 139 | * checks if a component is located in `channels` section of an asyncapi document. 140 | */ 141 | const isInChannels = (component: OptimizableComponent): boolean => { 142 | return component.path.startsWith('channels.') 143 | } 144 | 145 | /** 146 | * Converts JSON or YAML string object. 147 | */ 148 | const toJS = (asyncapiYAMLorJSON: any): any => { 149 | if (asyncapiYAMLorJSON.constructor && asyncapiYAMLorJSON.constructor.name === 'Object') { 150 | //NOTE: this approach can have problem with circular references between object and JSON.stringify doesn't support it. 151 | //more info: https://github.com/asyncapi/parser-js/issues/293 152 | return JSON.parse(JSON.stringify(asyncapiYAMLorJSON)) 153 | } 154 | if (typeof asyncapiYAMLorJSON === 'string') { 155 | return YAML.load(asyncapiYAMLorJSON) 156 | } 157 | throw new Error( 158 | 'Unknown input: Please make sure that your input is an Object/String of a valid AsyncAPI specification document.' 159 | ) 160 | } 161 | 162 | const getComponentName = (component: OptimizableComponent): string => { 163 | let componentName 164 | if (component.component['x-origin']) { 165 | componentName = String(component.component['x-origin']).split('/').reverse()[0] 166 | } else { 167 | componentName = String(component.path).split('.').reverse()[0] 168 | } 169 | return componentName 170 | } 171 | 172 | export { compareComponents, isEqual, isInComponents, isInChannels, toJS, getComponentName } 173 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![AsyncAPI Optimizer](./assets/readme-banner.png)](https://www.asyncapi.com) 2 | 3 | AsyncAPI offers many ways to reuse certain parts of the document like messages or schemas definitions or references to external files, not to even mention the traits. Purpose of **AsyncAPI Optimizer** is to enable different ways to optimize AsyncAPI files. It is a library that can be used in UIs and CLIs. 4 | 5 | ![npm](https://img.shields.io/npm/v/@asyncapi/optimizer?style=for-the-badge) ![npm](https://img.shields.io/npm/dt/@asyncapi/optimizer?style=for-the-badge) 6 | 7 | 8 | 9 | 10 | 11 | - [Testing](#testing) 12 | - [Usage](#usage) 13 | * [Node.js](#nodejs) 14 | * [Generating report](#generating-report) 15 | * [Applying the suggested changes](#applying-the-suggested-changes) 16 | - [API documentation](#api-documentation) 17 | 18 | 19 | 20 | ## Testing 21 | 22 | 1. Clone the project 23 | `git clone https://github.com/asyncapi/optimizer.git` 24 | 2. Install the dependencies 25 | `npm i` 26 | 3. for a quick check you can run `npm run example`. You can open `examples/index.js` modify it or add your own AsyncAPI document for optimization. 27 | 28 | ## Usage 29 | 30 | ### Node.js 31 | 32 | ```typescript 33 | import { Optimizer } from '@asyncapi/optimizer' 34 | import type { Report } from '@asyncapi/optimizer' 35 | 36 | const yaml = ` 37 | asyncapi: 3.0.0 38 | info: 39 | title: Example Service 40 | version: 1.0.0 41 | description: Example Service. 42 | servers: 43 | production: 44 | host: 'test.mosquitto.org:{port}' 45 | protocol: mqtt 46 | description: Test broker 47 | variables: 48 | port: 49 | description: Secure connection (TLS) is available through port 8883. 50 | default: '1883' 51 | enum: 52 | - '1883' 53 | - '8883' 54 | operations: 55 | user/deleteAccount.subscribe: 56 | action: send 57 | channel: 58 | $ref: '#/channels/commentLikedChannel' 59 | channels: 60 | commentLikedChannel: 61 | address: comment/liked 62 | messages: 63 | commentLikedMessage: 64 | description: Message that is being sent when a comment has been liked by someone. 65 | payload: 66 | type: object 67 | title: commentLikedPayload 68 | properties: 69 | commentId: 70 | type: string 71 | description: an id object 72 | x-origin: ./schemas.yaml#/schemas/idSchema 73 | x-origin: ./schemas.yaml#/schemas/commentLikedSchema 74 | x-origin: ./messages.yaml#/messages/commentLikedMessage 75 | x-origin: ./channels.yaml#/channels/commentLikedChannel` 76 | 77 | const optimizer = new Optimizer(yaml) 78 | ``` 79 | 80 | ### Generating report 81 | 82 | ```typescript 83 | const report: Report = await optimizer.getReport() 84 | /* 85 | the report value will be: 86 | { 87 | removeComponents: [], 88 | reuseComponents: [], 89 | moveAllToComponents: [ 90 | { 91 | path: 'channels.commentLikedChannel.messages.commentLikedMessage.payload.properties.commentId', 92 | action: 'move', 93 | target: 'components.schemas.idSchema' 94 | }, 95 | { 96 | path: 'channels.commentLikedChannel.messages.commentLikedMessage.payload', 97 | action: 'move', 98 | target: 'components.schemas.commentLikedSchema' 99 | }, 100 | { 101 | path: 'channels.commentLikedChannel.messages.commentLikedMessage', 102 | action: 'move', 103 | target: 'components.messages.commentLikedMessage' 104 | }, 105 | { 106 | path: 'operations.user/deleteAccount.subscribe', 107 | action: 'move', 108 | target: 'components.operations.subscribe' 109 | }, 110 | { 111 | path: 'channels.commentLikedChannel', 112 | action: 'move', 113 | target: 'components.channels.commentLikedChannel' 114 | }, 115 | { 116 | path: 'servers.production', 117 | action: 'move', 118 | target: 'components.servers.production' 119 | } 120 | ], 121 | moveDuplicatesToComponents: [] 122 | } 123 | */ 124 | ``` 125 | 126 | ### Applying the suggested changes 127 | 128 | ```typescript 129 | const optimizedDocument = optimizer.getOptimizedDocument({ 130 | output: 'YAML', 131 | rules: { 132 | reuseComponents: true, 133 | removeComponents: true, 134 | moveAllToComponents: true, 135 | moveDuplicatesToComponents: false, 136 | }, 137 | disableOptimizationFor: { 138 | schema: false, 139 | }, 140 | }) 141 | /* 142 | the optimizedDocument value will be: 143 | 144 | asyncapi: 3.0.0 145 | info: 146 | title: Example Service 147 | version: 1.0.0 148 | description: Example Service. 149 | servers: 150 | production: 151 | $ref: '#/components/servers/production' 152 | operations: 153 | user/deleteAccount.subscribe: 154 | action: send 155 | channel: 156 | $ref: '#/channels/commentLikedChannel' 157 | user/deleteAccount: 158 | subscribe: 159 | $ref: '#/components/operations/subscribe' 160 | channels: 161 | commentLikedChannel: 162 | $ref: '#/components/channels/commentLikedChannel' 163 | components: 164 | schemas: 165 | idSchema: 166 | type: string 167 | description: an id object 168 | x-origin: ./schemas.yaml#/schemas/idSchema 169 | commentLikedSchema: 170 | type: object 171 | title: commentLikedPayload 172 | properties: 173 | commentId: 174 | $ref: '#/components/schemas/idSchema' 175 | x-origin: ./schemas.yaml#/schemas/commentLikedSchema 176 | messages: 177 | commentLikedMessage: 178 | description: Message that is being sent when a comment has been liked by someone. 179 | payload: 180 | $ref: '#/components/schemas/commentLikedSchema' 181 | x-origin: ./messages.yaml#/messages/commentLikedMessage 182 | operations: {} 183 | channels: 184 | commentLikedChannel: 185 | address: comment/liked 186 | messages: 187 | commentLikedMessage: 188 | $ref: '#/components/messages/commentLikedMessage' 189 | x-origin: ./channels.yaml#/channels/commentLikedChannel 190 | servers: 191 | production: 192 | host: test.mosquitto.org:{port} 193 | protocol: mqtt 194 | description: Test broker 195 | variables: 196 | port: 197 | description: Secure connection (TLS) is available through port 8883. 198 | default: '1883' 199 | enum: 200 | - '1883' 201 | - '8883' 202 | */ 203 | ``` 204 | 205 | ## API documentation 206 | 207 | For using the optimizer to optimize file you just need to import the `Optimizer` class. Use its two methods to get the report (`getReport()`) and get the optimized document (`getOptimizedDocument()`). 208 | 209 | See [API documentation](./API.md) for more example and full API reference information. 210 | -------------------------------------------------------------------------------- /.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 | permissions: 21 | contents: write # to be able to publish a GitHub release 22 | issues: write # to be able to comment on released issues 23 | pull-requests: write # to be able to comment on released pull requests 24 | id-token: write # to enable use of OIDC for trusted publishing and npm provenance 25 | 26 | jobs: 27 | 28 | test-nodejs: 29 | # We just check the message of first commit as there is always just one commit because we squash into one before merging 30 | # "commits" contains array of objects where one of the properties is commit "message" 31 | # Release workflow will be skipped if release conventional commits are not used 32 | if: | 33 | startsWith( github.repository, 'asyncapi/' ) && 34 | (startsWith( github.event.commits[0].message , 'fix:' ) || 35 | startsWith( github.event.commits[0].message, 'fix!:' ) || 36 | startsWith( github.event.commits[0].message, 'feat:' ) || 37 | startsWith( github.event.commits[0].message, 'feat!:' )) 38 | name: Test NodeJS release on ${{ matrix.os }} 39 | runs-on: ${{ matrix.os }} 40 | strategy: 41 | matrix: 42 | os: [ubuntu-latest, macos-latest, windows-latest] 43 | steps: 44 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 45 | run: | 46 | git config --global core.autocrlf false 47 | git config --global core.eol lf 48 | shell: bash 49 | - name: Checkout repository 50 | uses: actions/checkout@v4 51 | - name: Check if Node.js project and has package.json 52 | id: packagejson 53 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 54 | shell: bash 55 | - if: steps.packagejson.outputs.exists == 'true' 56 | name: Determine what node version to use 57 | # This workflow is from our own org repo and safe to reference by 'master'. 58 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master # //NOSONAR 59 | with: 60 | node-version: ${{ vars.NODE_VERSION }} 61 | id: lockversion 62 | - if: steps.packagejson.outputs.exists == 'true' 63 | name: Setup Node.js 64 | uses: actions/setup-node@v4 65 | with: 66 | node-version: "${{ steps.lockversion.outputs.version }}" 67 | - if: steps.lockversion.outputs.version == '18' && matrix.os == 'windows-latest' 68 | name: Install npm cli 8 69 | shell: bash 70 | #npm cli 10 is buggy because of some cache issues 71 | run: npm install -g npm@8.19.4 72 | - if: steps.packagejson.outputs.exists == 'true' 73 | name: Install dependencies 74 | shell: bash 75 | run: npm ci 76 | - if: steps.packagejson.outputs.exists == 'true' 77 | name: Run test 78 | run: npm test --if-present 79 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 80 | name: Report workflow run status to Slack 81 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 82 | with: 83 | status: ${{ job.status }} 84 | fields: repo,action,workflow 85 | text: 'Release workflow failed in testing job' 86 | env: 87 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} 88 | 89 | release: 90 | needs: [test-nodejs] 91 | name: Publish to any of NPM, Github, or Docker Hub 92 | runs-on: ubuntu-latest 93 | steps: 94 | - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows 95 | run: | 96 | git config --global core.autocrlf false 97 | git config --global core.eol lf 98 | - name: Checkout repository 99 | uses: actions/checkout@v4 100 | - name: Check if Node.js project and has package.json 101 | id: packagejson 102 | run: test -e ./package.json && echo "exists=true" >> $GITHUB_OUTPUT || echo "exists=false" >> $GITHUB_OUTPUT 103 | shell: bash 104 | - if: steps.packagejson.outputs.exists == 'true' 105 | name: Determine what node version to use 106 | # This workflow is from our own org repo and safe to reference by 'master'. 107 | uses: asyncapi/.github/.github/actions/get-node-version-from-package-lock@master # //NOSONAR 108 | with: 109 | node-version: ${{ vars.NODE_VERSION }} 110 | id: lockversion 111 | - if: steps.packagejson.outputs.exists == 'true' 112 | name: Setup Node.js 113 | uses: actions/setup-node@v4 114 | with: 115 | node-version: "${{ steps.lockversion.outputs.version }}" 116 | registry-url: "https://registry.npmjs.org" 117 | - if: steps.packagejson.outputs.exists == 'true' 118 | name: Install dependencies 119 | shell: bash 120 | run: npm ci 121 | - if: steps.packagejson.outputs.exists == 'true' 122 | name: Add plugin for conventional commits for semantic-release 123 | run: npm install --save-dev conventional-changelog-conventionalcommits@9.1.0 124 | - if: steps.packagejson.outputs.exists == 'true' 125 | name: Publish to any of NPM, Github, and Docker Hub 126 | id: release 127 | env: 128 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 129 | DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} 130 | DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} 131 | GIT_AUTHOR_NAME: asyncapi-bot 132 | GIT_AUTHOR_EMAIL: info@asyncapi.io 133 | GIT_COMMITTER_NAME: asyncapi-bot 134 | GIT_COMMITTER_EMAIL: info@asyncapi.io 135 | run: npx semantic-release@25.0.2 136 | - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel 137 | name: Report workflow run status to Slack 138 | uses: 8398a7/action-slack@28ba43ae48961b90635b50953d216767a6bea486 #using https://github.com/8398a7/action-slack/releases/tag/v3.16.2 139 | with: 140 | status: ${{ job.status }} 141 | fields: repo,action,workflow 142 | text: 'Release workflow failed in release job' 143 | env: 144 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} 145 | -------------------------------------------------------------------------------- /API.md: -------------------------------------------------------------------------------- 1 | ## Classes 2 | 3 |
4 |
Optimizer
5 |

this class is the starting point of the library. 6 | user will only interact with this class. here we generate different kind of reports using optimizers, apply changes and return the results to the user.

7 |
8 |
9 | 10 | ## Functions 11 | 12 |
13 |
findAllComponents(optimizableComponentGroup)
14 |
15 |
findDuplicateComponents(optimizableComponentGroup)
16 |
17 |
hasParent()
18 |

Checks if a component's parent is a ref or not.

19 |
20 |
isEqual(component1, component2, referentialEqualityCheck)
21 |
22 |
isInComponents()
23 |

checks if a component is located in components section of an asyncapi document.

24 |
25 |
isInChannels()
26 |

checks if a component is located in channels section of an asyncapi document.

27 |
28 |
toJS()
29 |

Converts JSON or YAML string object.

30 |
31 |
32 | 33 | ## Typedefs 34 | 35 |
36 |
Rules : Object
37 |
38 |
DisableOptimizationFor : Object
39 |
40 |
Options : Object
41 |
42 |
43 | 44 | 45 | 46 | ## Optimizer 47 | this class is the starting point of the library. 48 | user will only interact with this class. here we generate different kind of reports using optimizers, apply changes and return the results to the user. 49 | 50 | **Kind**: global class 51 | **Access**: public 52 | 53 | * [Optimizer](#Optimizer) 54 | * [new Optimizer(YAMLorJSON)](#new_Optimizer_new) 55 | * [.getReport()](#Optimizer+getReport) ⇒ Report 56 | * [.getOptimizedDocument([Options])](#Optimizer+getOptimizedDocument) ⇒ string 57 | 58 | 59 | 60 | ### new Optimizer(YAMLorJSON) 61 | 62 | | Param | Type | Description | 63 | | --- | --- | --- | 64 | | YAMLorJSON | any | YAML or JSON document that you want to optimize. You can pass Object, YAML or JSON version of your AsyncAPI document here. | 65 | 66 | 67 | 68 | ### optimizer.getReport() ⇒ Report 69 | **Kind**: instance method of [Optimizer](#Optimizer) 70 | **Returns**: Report - an object containing all of the optimizations that the library can do. 71 | 72 | 73 | ### optimizer.getOptimizedDocument([Options]) ⇒ string 74 | This function is used to get the optimized document after seeing the report. 75 | 76 | **Kind**: instance method of [Optimizer](#Optimizer) 77 | **Returns**: string - returns an stringified version of the YAML output. 78 | 79 | | Param | Type | Description | 80 | | --- | --- | --- | 81 | | [Options] | [Options](#Options) | the options are a way to customize the final output. | 82 | 83 | 84 | 85 | ## findAllComponents(optimizableComponentGroup) ⇒ 86 | **Kind**: global function 87 | **Returns**: A list of optimization report elements. 88 | 89 | | Param | Description | 90 | | --- | --- | 91 | | optimizableComponentGroup | all AsyncAPI Specification-valid components. | 92 | 93 | 94 | 95 | ## findDuplicateComponents(optimizableComponentGroup) ⇒ 96 | **Kind**: global function 97 | **Returns**: A list of optimization report elements. 98 | 99 | | Param | Description | 100 | | --- | --- | 101 | | optimizableComponentGroup | all AsyncAPI Specification-valid components that you want to analyze for duplicates. | 102 | 103 | 104 | 105 | ## hasParent() 106 | Checks if a component's parent is a ref or not. 107 | 108 | **Kind**: global function 109 | 110 | 111 | ## isEqual(component1, component2, referentialEqualityCheck) ⇒ 112 | **Kind**: global function 113 | **Returns**: whether the two components are equal. 114 | 115 | | Param | Description | 116 | | --- | --- | 117 | | component1 | The first component that you want to compare with the second component. | 118 | | component2 | The second component. | 119 | | referentialEqualityCheck | If `true` the function will return true if the two components have referential equality OR they have the same structure. If `false` the it will only return true if they have the same structure but they are NOT referentially equal. | 120 | 121 | 122 | 123 | ## isInComponents() 124 | checks if a component is located in `components` section of an asyncapi document. 125 | 126 | **Kind**: global function 127 | 128 | 129 | ## isInChannels() 130 | checks if a component is located in `channels` section of an asyncapi document. 131 | 132 | **Kind**: global function 133 | 134 | 135 | ## toJS() 136 | Converts JSON or YAML string object. 137 | 138 | **Kind**: global function 139 | 140 | 141 | ## Rules : Object 142 | **Kind**: global typedef 143 | **Properties** 144 | 145 | | Name | Type | Description | 146 | | --- | --- | --- | 147 | | [reuseComponents] | Boolean | whether to reuse components from `components` section or not. Defaults to `true`. | 148 | | [removeComponents] | Boolean | whether to remove un-used components from `components` section or not. Defaults to `true`. | 149 | | [moveAllToComponents] | Boolean | whether to move all AsyncAPI Specification-valid components to the `components` section or not. Defaults to `true`. | 150 | | [moveDuplicatesToComponents] | Boolean | whether to move duplicated components to the `components` section or not. Defaults to `false`. | 151 | 152 | 153 | 154 | ## DisableOptimizationFor : Object 155 | **Kind**: global typedef 156 | **Properties** 157 | 158 | | Name | Type | Description | 159 | | --- | --- | --- | 160 | | [schema] | Boolean | whether object `schema` should be excluded from the process of optimization (`true` instructs **not** to add calculated `schemas` to the optimized AsyncAPI Document.) | 161 | 162 | 163 | 164 | ## Options : Object 165 | **Kind**: global typedef 166 | **Properties** 167 | 168 | | Name | Type | Description | 169 | | --- | --- | --- | 170 | | [rules] | [Rules](#Rules) | the list of rules that specifies which type of optimizations should be applied. | 171 | | [output] | String | specifies which type of output user wants, `'JSON'` or `'YAML'`. Defaults to `'YAML'`; | 172 | | [disableOptimizationFor] | [DisableOptimizationFor](#DisableOptimizationFor) | the list of objects that should be excluded from the process of optimization. | 173 | 174 | -------------------------------------------------------------------------------- /.github/workflows/update-maintainers.yml: -------------------------------------------------------------------------------- 1 | name: Update MAINTAINERS.yaml in community repo 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | paths: 8 | - 'CODEOWNERS' 9 | 10 | jobs: 11 | update-maintainers: 12 | runs-on: ubuntu-latest 13 | env: 14 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 15 | steps: 16 | - name: Checkout main branch 17 | uses: actions/checkout@v3 18 | with: 19 | ref: master 20 | path: current_state 21 | 22 | - name: Checkout one commit before last one 23 | uses: actions/checkout@v3 24 | with: 25 | fetch-depth: 2 26 | ref: master 27 | path: previous_state 28 | 29 | - run: cd previous_state && git checkout HEAD^ 30 | 31 | - name: Checkout community repo 32 | uses: actions/checkout@v3 33 | with: 34 | repository: asyncapi/community 35 | token: ${{ env.GITHUB_TOKEN }} 36 | path: community 37 | 38 | - name: Setup Node.js 39 | uses: actions/setup-node@v3 40 | with: 41 | node-version: '16' 42 | 43 | - name: Install js-yaml 44 | run: npm install js-yaml@3.14.1 45 | 46 | - name: Compare CODEOWNERS 47 | id: compare-codeowners 48 | env: 49 | GH_TOKEN: ${{ env.GITHUB_TOKEN }} 50 | uses: actions/github-script@v6 51 | with: 52 | script: | 53 | const fs = require('fs'); 54 | const yaml = require('js-yaml'); 55 | 56 | // Get repository name 57 | const repoName = context.repo.repo; 58 | 59 | function extractGitHubUsernames(content) { 60 | // Remove lines starting with # 61 | content = content.replace(/^#.*$/mg, ""); 62 | 63 | const regex = /@([a-zA-Z0-9_-]+)/g; 64 | const matches = content.match(regex); 65 | if (!matches) { 66 | return []; 67 | } 68 | return matches.map(match => match.substr(1)); 69 | } 70 | 71 | const currentCodeowners = fs.readFileSync('./current_state/CODEOWNERS', 'utf8'); 72 | const previousCodeowners = fs.readFileSync('./previous_state/CODEOWNERS', 'utf8'); 73 | 74 | const currentUsernames = extractGitHubUsernames(currentCodeowners); 75 | const previousUsernames = extractGitHubUsernames(previousCodeowners); 76 | 77 | const addedUsernames = currentUsernames.filter(username => !previousUsernames.includes(username)); 78 | const removedUsernames = previousUsernames.filter(username => !currentUsernames.includes(username)); 79 | 80 | core.info('Added Usernames:', addedUsernames); 81 | core.info('Removed Usernames:', removedUsernames); 82 | core.info(`ADDED_USERNAMES=${addedUsernames.join(', ')}`); 83 | core.info(`REMOVED_USERNAMES=${removedUsernames.join(', ')}`); 84 | 85 | // Update MAINTAINERS.yaml 86 | const maintainersFile = './community/MAINTAINERS.yaml'; 87 | const maintainers = yaml.safeLoad(fs.readFileSync(maintainersFile, 'utf8')); 88 | 89 | 90 | // Update for added usernames 91 | for (const username of addedUsernames) { 92 | // Exclude bot accounts 93 | if (username === 'asyncapi-bot' || username === 'asyncapi-bot-eve') { 94 | core.info('Skipping bot account:', username); 95 | continue; // Skip the iteration for bot accounts 96 | } 97 | 98 | const maintainer = maintainers.find(maintainer => maintainer.github === username.toLowerCase()); 99 | if (!maintainer) { 100 | const { data } = await github.rest.users.getByUsername({ username }); 101 | const twitterUsername = data.twitter_username; 102 | const newMaintainer = { 103 | github: username, 104 | isTscMember: false, 105 | repos: [repoName] 106 | }; 107 | if (twitterUsername) { 108 | newMaintainer.twitter = twitterUsername; 109 | } 110 | maintainers.push(newMaintainer); 111 | core.info('Added maintainer:', username); 112 | } else { 113 | // If the maintainer already exists, check if the current repo is in their list 114 | if (!maintainer.repos.includes(repoName)) { 115 | maintainer.repos.push(repoName); 116 | core.info('Added repository to existing maintainer:', username); 117 | } else { 118 | core.info(`Maintainer ${username} already exists and already has the repo. Skipping addition.`); 119 | } 120 | } 121 | } 122 | 123 | // Update for removed usernames 124 | for (const username of removedUsernames) { 125 | const index = maintainers.findIndex(maintainer => maintainer.github === username); 126 | if (index !== -1) { 127 | const maintainer = maintainers[index]; 128 | const repoIndex = maintainer.repos.findIndex(repo => repo === repoName); 129 | 130 | if (repoIndex !== -1) { 131 | maintainer.repos.splice(repoIndex, 1); 132 | core.info(`Removed repository ${repoName} from maintainer ${username}`); 133 | if (maintainer.repos.length === 0) { 134 | maintainers.splice(index, 1); 135 | core.info(`Removed maintainer ${username} as they have no other repositories`); 136 | } 137 | } else { 138 | core.info(`Repository ${repoName} not found for maintainer ${username}`); 139 | } 140 | } else { 141 | core.info(`Maintainer ${username} does not exist. Skipping removal.`); 142 | } 143 | } 144 | 145 | // Write updated MAINTAINERS.yaml file 146 | const updatedMaintainers = yaml.safeDump(maintainers); 147 | fs.writeFileSync(maintainersFile, updatedMaintainers); 148 | core.info('Updated MAINTAINERS.yaml:', updatedMaintainers); 149 | 150 | - name: Create new branch 151 | working-directory: ./community 152 | run: | 153 | git checkout -b update-maintainers-${{ github.run_id }} 154 | 155 | - name: Commit and push 156 | working-directory: ./community 157 | run: | 158 | git config --global user.email "info@asyncapi.io" 159 | git config --global user.name "asyncapi-bot" 160 | git add . 161 | git commit -m "Update MAINTAINERS.yaml" 162 | git push https://${{ env.GITHUB_TOKEN }}@github.com/asyncapi/community 163 | 164 | - name: Create PR 165 | working-directory: ./community 166 | run: | 167 | gh pr create --title "docs(community): update latest maintainers list" --body "Updated Maintainers list is available and this PR introduces changes with latest information about Maintainers" --head update-maintainers-${{ github.run_id }} 168 | 169 | 170 | - name: Report workflow run status to Slack 171 | if: failure() # Only, on failure, send a message on the slack channel 172 | uses: rtCamp/action-slack-notify@v2 173 | env: 174 | SLACK_WEBHOOK: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} 175 | SLACK_TITLE: 🚨 Update maintainers list action failed 🚨 176 | SLACK_MESSAGE: Failed to update the maintainers list. 177 | MSG_MINIMAL: true -------------------------------------------------------------------------------- /src/Optimizer.ts: -------------------------------------------------------------------------------- 1 | import { 2 | NewReport, 3 | Report, 4 | ReportElement, 5 | Options, 6 | OptimizableComponentGroup, 7 | Reporter, 8 | } from './types' 9 | import { Parser } from '@asyncapi/parser' 10 | import { 11 | removeComponents, 12 | reuseComponents, 13 | moveAllToComponents, 14 | moveDuplicatesToComponents, 15 | } from './Reporters' 16 | import YAML from 'js-yaml' 17 | import merge from 'merge-deep' 18 | import * as _ from 'lodash' 19 | import { getOptimizableComponents } from './ComponentProvider' 20 | import { filterReportElements, hasParent, sortReportElements, toJS } from './Utils' 21 | import Debug from 'debug' 22 | 23 | export enum Action { 24 | Move = 'move', 25 | Remove = 'remove', 26 | Reuse = 'reuse', 27 | } 28 | 29 | export enum Output { 30 | JSON = 'JSON', 31 | YAML = 'YAML', 32 | } 33 | /** 34 | * this class is the starting point of the library. 35 | * user will only interact with this class. here we generate different kind of reports using optimizers, apply changes and return the results to the user. 36 | * 37 | * @public 38 | */ 39 | export class Optimizer { 40 | private components!: OptimizableComponentGroup[] 41 | private reporters: Reporter[] 42 | private reports: NewReport[] | undefined 43 | private outputObject = {} 44 | 45 | /** 46 | * @param {any} YAMLorJSON - YAML or JSON document that you want to optimize. You can pass Object, YAML or JSON version of your AsyncAPI document here. 47 | */ 48 | constructor(private YAMLorJSON: any) { 49 | this.outputObject = toJS(this.YAMLorJSON) 50 | this.reporters = [ 51 | removeComponents, 52 | reuseComponents, 53 | moveAllToComponents, 54 | moveDuplicatesToComponents, 55 | ] 56 | } 57 | 58 | /** 59 | * @returns {Report} an object containing all of the optimizations that the library can do. 60 | * 61 | */ 62 | async getReport(): Promise { 63 | const parser = new Parser() 64 | const parsedDocument = await parser.parse(this.YAMLorJSON, { applyTraits: false }) 65 | if (!parsedDocument.document) { 66 | // eslint-disable-next-line no-undef, no-console 67 | console.error(parsedDocument.diagnostics) 68 | throw new Error('Parsing failed.') 69 | } 70 | this.components = getOptimizableComponents(parsedDocument.document) 71 | const rawReports = this.reporters.map((reporter) => reporter(this.components)) 72 | const reportsWithParents = rawReports.map((report) => ({ 73 | type: report.type, 74 | elements: report.elements.filter((reportElement) => 75 | hasParent(reportElement, this.outputObject) 76 | ), 77 | })) 78 | 79 | const filteredReports = filterReportElements(reportsWithParents) 80 | const sortedReports = filteredReports.map((report) => sortReportElements(report)) 81 | this.reports = sortedReports 82 | 83 | // since changing the report format is considered a breaking change, we are going to return the report in the old format. 84 | return convertToReportFormat(this.reports) 85 | } 86 | 87 | /** 88 | * @typedef {Object} Rules 89 | * @property {Boolean=} reuseComponents - whether to reuse components from `components` section or not. Defaults to `true`. 90 | * @property {Boolean=} removeComponents - whether to remove un-used components from `components` section or not. Defaults to `true`. 91 | * @property {Boolean=} moveAllToComponents - whether to move all AsyncAPI Specification-valid components to the `components` section or not. Defaults to `true`. 92 | * @property {Boolean=} moveDuplicatesToComponents - whether to move duplicated components to the `components` section or not. Defaults to `false`. 93 | */ 94 | /** 95 | * @typedef {Object} DisableOptimizationFor 96 | * @property {Boolean=} schema - whether object `schema` should be excluded from the process of optimization (`true` instructs **not** to add calculated `schemas` to the optimized AsyncAPI Document.) 97 | */ 98 | /** 99 | * @typedef {Object} Options 100 | * @property {Rules=} rules - the list of rules that specifies which type of optimizations should be applied. 101 | * @property {String=} output - specifies which type of output user wants, `'JSON'` or `'YAML'`. Defaults to `'YAML'`; 102 | * @property {DisableOptimizationFor=} disableOptimizationFor - the list of objects that should be excluded from the process of optimization. 103 | */ 104 | /** 105 | * This function is used to get the optimized document after seeing the report. 106 | * 107 | * @param {Options=} Options - the options are a way to customize the final output. 108 | * @returns {string } returns an stringified version of the YAML output. 109 | * 110 | */ 111 | getOptimizedDocument(options?: Options): string { 112 | const defaultOptions = { 113 | rules: { 114 | reuseComponents: true, 115 | removeComponents: true, 116 | moveAllToComponents: true, 117 | moveDuplicatesToComponents: false, // there is no need to move duplicates if `moveAllToComponents` is `true` 118 | }, 119 | output: Output.YAML, 120 | disableOptimizationFor: { 121 | schema: false, 122 | }, 123 | } 124 | options = merge(defaultOptions, options) 125 | if (!this.reports) { 126 | throw new Error( 127 | 'No report has been generated. please first generate a report by calling getReport method.' 128 | ) 129 | } 130 | for (const report of this.reports) { 131 | if (options.disableOptimizationFor?.schema === true) { 132 | report.elements = report.elements.filter( 133 | (element) => !element.target?.includes('.schemas.') 134 | ) 135 | } 136 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 137 | // @ts-ignore 138 | if (options.rules[report.type] === true) { 139 | this.applyReport(report.elements) 140 | } 141 | } 142 | 143 | if (options.output === Output.JSON) { 144 | return JSON.stringify(this.outputObject) 145 | } 146 | return YAML.dump(this.outputObject) 147 | } 148 | 149 | private removeEmptyParent(childPath: string): void { 150 | const parentPath = childPath.substring(0, childPath.lastIndexOf('.')) 151 | const parent = _.get(this.outputObject, parentPath) 152 | if (_.isEmpty(parent)) { 153 | _.unset(this.outputObject, parentPath) 154 | } 155 | } 156 | 157 | private applyReport(changes: ReportElement[]): void { 158 | const debug = Debug('optimizer:applyReport') 159 | for (const change of changes) { 160 | switch (change.action) { 161 | case Action.Move: 162 | _.set(this.outputObject, change.target as string, _.get(this.outputObject, change.path)) 163 | _.set(this.outputObject, change.path, { 164 | $ref: `#/${change.target?.replace(/\./g, '/')}`, 165 | }) 166 | debug('moved %s to %s', change.path, change.target) 167 | break 168 | 169 | case Action.Reuse: 170 | if (_.get(this.outputObject, change.target as string)) { 171 | _.set(this.outputObject, change.path, { 172 | $ref: `#/${change.target?.replace(/\./g, '/')}`, 173 | }) 174 | } 175 | debug('%s reused %s', change.path, change.target) 176 | break 177 | 178 | case Action.Remove: 179 | _.unset(this.outputObject, change.path) 180 | //if parent becomes empty after removing, parent should be removed as well. 181 | this.removeEmptyParent(change.path) 182 | debug('removed %s', change.path) 183 | break 184 | } 185 | } 186 | } 187 | } 188 | function convertToReportFormat(reports: NewReport[]): Report { 189 | const result = {} 190 | for (const report of reports) { 191 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 192 | //@ts-ignore 193 | result[report.type] = report.elements 194 | } 195 | return result as Report 196 | } 197 | -------------------------------------------------------------------------------- /examples/output.yaml: -------------------------------------------------------------------------------- 1 | asyncapi: 3.0.0 2 | info: 3 | title: Streetlights MQTT API 4 | version: 1.0.0 5 | description: > 6 | The Smartylighting Streetlights API allows you to remotely manage the city 7 | lights. 8 | 9 | 10 | ### Check out its awesome features: 11 | 12 | 13 | * Turn a specific streetlight on/off 🌃 14 | 15 | * Dim a specific streetlight 😎 16 | 17 | * Receive real-time information about environmental lighting conditions 📈 18 | license: 19 | name: Apache 2.0 20 | url: https://www.apache.org/licenses/LICENSE-2.0 21 | defaultContentType: application/json 22 | servers: 23 | production: 24 | host: test.mosquitto.org:{port} 25 | protocol: mqtt 26 | description: Test broker 27 | variables: 28 | port: 29 | description: Secure connection (TLS) is available through port 8883. 30 | default: '1883' 31 | enum: 32 | - '1883' 33 | - '8883' 34 | security: 35 | - $ref: '#/components/securitySchemes/apiKey' 36 | - type: oauth2 37 | description: Flows to support OAuth 2.0 38 | flows: 39 | implicit: 40 | authorizationUrl: https://authserver.example/auth 41 | availableScopes: 42 | streetlights:on: Ability to switch lights on 43 | streetlights:off: Ability to switch lights off 44 | streetlights:dim: Ability to dim the lights 45 | password: 46 | tokenUrl: https://authserver.example/token 47 | availableScopes: 48 | streetlights:on: Ability to switch lights on 49 | streetlights:off: Ability to switch lights off 50 | streetlights:dim: Ability to dim the lights 51 | clientCredentials: 52 | tokenUrl: https://authserver.example/token 53 | availableScopes: 54 | streetlights:on: Ability to switch lights on 55 | streetlights:off: Ability to switch lights off 56 | streetlights:dim: Ability to dim the lights 57 | authorizationCode: 58 | authorizationUrl: https://authserver.example/auth 59 | tokenUrl: https://authserver.example/token 60 | refreshUrl: https://authserver.example/refresh 61 | availableScopes: 62 | streetlights:on: Ability to switch lights on 63 | streetlights:off: Ability to switch lights off 64 | streetlights:dim: Ability to dim the lights 65 | scopes: 66 | - streetlights:on 67 | - streetlights:off 68 | - streetlights:dim 69 | - $ref: '#/components/securitySchemes/openIdConnectWellKnown' 70 | tags: 71 | - name: env:production 72 | description: This environment is meant for production use case 73 | - name: kind:remote 74 | description: This server is a remote server. Not exposed by the application 75 | - name: visibility:public 76 | description: This resource is public and available to everyone 77 | channels: 78 | lightingMeasured: 79 | address: smartylighting/streetlights/1/0/event/{streetlightId}/lighting/measured 80 | messages: 81 | lightMeasured: 82 | $ref: '#/components/messages/lightMeasured' 83 | description: The topic on which measured values may be produced and consumed. 84 | parameters: 85 | streetlightId: 86 | $ref: '#/components/schemas/schema-1' 87 | lightTurnOn: 88 | address: smartylighting/streetlights/1/0/action/{streetlightId}/turn/on 89 | messages: 90 | turnOn: 91 | $ref: '#/components/messages/turnOnOff' 92 | parameters: 93 | streetlightId: 94 | $ref: '#/components/schemas/schema-1' 95 | lightTurnOff: 96 | address: smartylighting/streetlights/1/0/action/{streetlightId}/turn/off 97 | messages: 98 | turnOff: 99 | $ref: '#/components/messages/turnOnOff' 100 | parameters: 101 | streetlightId: 102 | $ref: '#/components/schemas/schema-2' 103 | lightsDim: 104 | address: smartylighting/streetlights/1/0/action/{streetlightId}/dim 105 | messages: 106 | dimLight: 107 | $ref: '#/components/messages/dimLight' 108 | parameters: 109 | streetlightId: 110 | $ref: '#/components/schemas/schema-2' 111 | operations: 112 | receiveLightMeasurement: 113 | action: receive 114 | channel: 115 | $ref: '#/channels/lightingMeasured' 116 | summary: >- 117 | Inform about environmental lighting conditions of a particular 118 | streetlight. 119 | traits: 120 | - $ref: '#/components/operationTraits/mqtt' 121 | messages: 122 | - $ref: '#/channels/lightingMeasured/messages/lightMeasured' 123 | turnOn: 124 | action: send 125 | channel: 126 | $ref: '#/channels/lightTurnOn' 127 | traits: 128 | - $ref: '#/components/operationTraits/mqtt' 129 | messages: 130 | - $ref: '#/channels/lightTurnOn/messages/turnOn' 131 | turnOff: 132 | action: send 133 | channel: 134 | $ref: '#/channels/lightTurnOff' 135 | traits: 136 | - $ref: '#/components/operationTraits/mqtt' 137 | messages: 138 | - $ref: '#/channels/lightTurnOff/messages/turnOff' 139 | dimLight: 140 | action: send 141 | channel: 142 | $ref: '#/channels/lightsDim' 143 | traits: 144 | - $ref: '#/components/operationTraits/mqtt' 145 | messages: 146 | - $ref: '#/channels/lightsDim/messages/dimLight' 147 | components: 148 | messages: 149 | lightMeasured: 150 | name: lightMeasured 151 | title: Light measured 152 | summary: >- 153 | Inform about environmental lighting conditions of a particular 154 | streetlight. 155 | contentType: application/json 156 | traits: 157 | - $ref: '#/components/messageTraits/commonHeaders' 158 | payload: 159 | $ref: '#/components/schemas/lightMeasuredPayload' 160 | turnOnOff: 161 | name: turnOnOff 162 | title: Turn on/off 163 | summary: Command a particular streetlight to turn the lights on or off. 164 | traits: 165 | - $ref: '#/components/messageTraits/commonHeaders' 166 | payload: 167 | $ref: '#/components/schemas/turnOnOffPayload' 168 | dimLight: 169 | name: dimLight 170 | title: Dim light 171 | summary: Command a particular streetlight to dim the lights. 172 | traits: 173 | - $ref: '#/components/messageTraits/commonHeaders' 174 | payload: 175 | $ref: '#/components/schemas/dimLightPayload' 176 | schemas: 177 | lightMeasuredPayload: 178 | type: object 179 | properties: 180 | lumens: 181 | type: integer 182 | minimum: 0 183 | description: Light intensity measured in lumens. 184 | sentAt: 185 | $ref: '#/components/schemas/sentAt' 186 | turnOnOffPayload: 187 | type: object 188 | properties: 189 | command: 190 | type: string 191 | enum: 192 | - 'on' 193 | - 'off' 194 | description: Whether to turn on or off the light. 195 | sentAt: 196 | $ref: '#/components/schemas/sentAt' 197 | dimLightPayload: 198 | type: object 199 | properties: 200 | percentage: 201 | type: integer 202 | description: Percentage to which the light should be dimmed to. 203 | minimum: 0 204 | maximum: 100 205 | sentAt: 206 | $ref: '#/components/schemas/sentAt' 207 | sentAt: 208 | type: string 209 | format: date-time 210 | description: Date and time when the message was sent. 211 | schema-1: 212 | $ref: '#/components/parameters/streetlightId' 213 | schema-2: 214 | $ref: '#/components/parameters/streetlightId' 215 | parameters: 216 | streetlightId: 217 | description: The ID of the streetlight. 218 | messageTraits: 219 | commonHeaders: 220 | headers: 221 | type: object 222 | properties: 223 | my-app-header: 224 | type: integer 225 | minimum: 0 226 | maximum: 100 227 | operationTraits: 228 | mqtt: 229 | bindings: 230 | mqtt: 231 | qos: 1 232 | -------------------------------------------------------------------------------- /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). -------------------------------------------------------------------------------- /examples/input.yaml: -------------------------------------------------------------------------------- 1 | asyncapi: 3.0.0 2 | info: 3 | title: Streetlights MQTT API 4 | version: 1.0.0 5 | description: "The Smartylighting Streetlights API allows you to remotely manage the city lights.\n\n### Check out its awesome features:\n\n* Turn a specific streetlight on/off \U0001F303\n* Dim a specific streetlight \U0001F60E\n* Receive real-time information about environmental lighting conditions \U0001F4C8\n" 6 | license: 7 | name: Apache 2.0 8 | url: 'https://www.apache.org/licenses/LICENSE-2.0' 9 | defaultContentType: application/json 10 | servers: 11 | production: 12 | host: 'test.mosquitto.org:{port}' 13 | protocol: mqtt 14 | description: Test broker 15 | variables: 16 | port: 17 | description: Secure connection (TLS) is available through port 8883. 18 | default: '1883' 19 | enum: 20 | - '1883' 21 | - '8883' 22 | security: 23 | - $ref: '#/components/securitySchemes/apiKey' 24 | - type: oauth2 25 | description: Flows to support OAuth 2.0 26 | flows: 27 | implicit: 28 | authorizationUrl: 'https://authserver.example/auth' 29 | availableScopes: 30 | 'streetlights:on': Ability to switch lights on 31 | 'streetlights:off': Ability to switch lights off 32 | 'streetlights:dim': Ability to dim the lights 33 | password: 34 | tokenUrl: 'https://authserver.example/token' 35 | availableScopes: 36 | 'streetlights:on': Ability to switch lights on 37 | 'streetlights:off': Ability to switch lights off 38 | 'streetlights:dim': Ability to dim the lights 39 | clientCredentials: 40 | tokenUrl: 'https://authserver.example/token' 41 | availableScopes: 42 | 'streetlights:on': Ability to switch lights on 43 | 'streetlights:off': Ability to switch lights off 44 | 'streetlights:dim': Ability to dim the lights 45 | authorizationCode: 46 | authorizationUrl: 'https://authserver.example/auth' 47 | tokenUrl: 'https://authserver.example/token' 48 | refreshUrl: 'https://authserver.example/refresh' 49 | availableScopes: 50 | 'streetlights:on': Ability to switch lights on 51 | 'streetlights:off': Ability to switch lights off 52 | 'streetlights:dim': Ability to dim the lights 53 | scopes: 54 | - 'streetlights:on' 55 | - 'streetlights:off' 56 | - 'streetlights:dim' 57 | - $ref: '#/components/securitySchemes/openIdConnectWellKnown' 58 | tags: 59 | - name: 'env:production' 60 | description: This environment is meant for production use case 61 | - name: 'kind:remote' 62 | description: This server is a remote server. Not exposed by the application 63 | - name: 'visibility:public' 64 | description: This resource is public and available to everyone 65 | channels: 66 | lightingMeasured: 67 | address: 'smartylighting/streetlights/1/0/event/{streetlightId}/lighting/measured' 68 | messages: 69 | lightMeasured: 70 | $ref: '#/components/messages/lightMeasured' 71 | description: The topic on which measured values may be produced and consumed. 72 | parameters: 73 | streetlightId: 74 | $ref: '#/components/parameters/streetlightId' 75 | lightTurnOn: 76 | address: 'smartylighting/streetlights/1/0/action/{streetlightId}/turn/on' 77 | messages: 78 | turnOn: 79 | $ref: '#/components/messages/turnOnOff' 80 | parameters: 81 | streetlightId: 82 | $ref: '#/components/parameters/streetlightId' 83 | lightTurnOff: 84 | address: 'smartylighting/streetlights/1/0/action/{streetlightId}/turn/off' 85 | messages: 86 | turnOff: 87 | $ref: '#/components/messages/turnOnOff' 88 | parameters: 89 | streetlightId: 90 | $ref: '#/components/parameters/streetlightId' 91 | lightsDim: 92 | address: 'smartylighting/streetlights/1/0/action/{streetlightId}/dim' 93 | messages: 94 | dimLight: 95 | $ref: '#/components/messages/dimLight' 96 | parameters: 97 | streetlightId: 98 | $ref: '#/components/parameters/streetlightId' 99 | operations: 100 | receiveLightMeasurement: 101 | action: receive 102 | channel: 103 | $ref: '#/channels/lightingMeasured' 104 | summary: >- 105 | Inform about environmental lighting conditions of a particular 106 | streetlight. 107 | traits: 108 | - $ref: '#/components/operationTraits/mqtt' 109 | messages: 110 | - $ref: '#/channels/lightingMeasured/messages/lightMeasured' 111 | turnOn: 112 | action: send 113 | channel: 114 | $ref: '#/channels/lightTurnOn' 115 | traits: 116 | - $ref: '#/components/operationTraits/mqtt' 117 | messages: 118 | - $ref: '#/channels/lightTurnOn/messages/turnOn' 119 | turnOff: 120 | action: send 121 | channel: 122 | $ref: '#/channels/lightTurnOff' 123 | traits: 124 | - $ref: '#/components/operationTraits/mqtt' 125 | messages: 126 | - $ref: '#/channels/lightTurnOff/messages/turnOff' 127 | dimLight: 128 | action: send 129 | channel: 130 | $ref: '#/channels/lightsDim' 131 | traits: 132 | - $ref: '#/components/operationTraits/mqtt' 133 | messages: 134 | - $ref: '#/channels/lightsDim/messages/dimLight' 135 | components: 136 | messages: 137 | lightMeasured: 138 | name: lightMeasured 139 | title: Light measured 140 | summary: >- 141 | Inform about environmental lighting conditions of a particular 142 | streetlight. 143 | contentType: application/json 144 | traits: 145 | - $ref: '#/components/messageTraits/commonHeaders' 146 | payload: 147 | $ref: '#/components/schemas/lightMeasuredPayload' 148 | turnOnOff: 149 | name: turnOnOff 150 | title: Turn on/off 151 | summary: Command a particular streetlight to turn the lights on or off. 152 | traits: 153 | - $ref: '#/components/messageTraits/commonHeaders' 154 | payload: 155 | $ref: '#/components/schemas/turnOnOffPayload' 156 | dimLight: 157 | name: dimLight 158 | title: Dim light 159 | summary: Command a particular streetlight to dim the lights. 160 | traits: 161 | - $ref: '#/components/messageTraits/commonHeaders' 162 | payload: 163 | $ref: '#/components/schemas/dimLightPayload' 164 | schemas: 165 | lightMeasuredPayload: 166 | type: object 167 | properties: 168 | lumens: 169 | type: integer 170 | minimum: 0 171 | description: Light intensity measured in lumens. 172 | sentAt: 173 | $ref: '#/components/schemas/sentAt' 174 | turnOnOffPayload: 175 | type: object 176 | properties: 177 | command: 178 | type: string 179 | enum: 180 | - 'on' 181 | - 'off' 182 | description: Whether to turn on or off the light. 183 | sentAt: 184 | $ref: '#/components/schemas/sentAt' 185 | dimLightPayload: 186 | type: object 187 | properties: 188 | percentage: 189 | type: integer 190 | description: Percentage to which the light should be dimmed to. 191 | minimum: 0 192 | maximum: 100 193 | sentAt: 194 | $ref: '#/components/schemas/sentAt' 195 | sentAt: 196 | type: string 197 | format: date-time 198 | description: Date and time when the message was sent. 199 | securitySchemes: 200 | apiKey: 201 | type: apiKey 202 | in: user 203 | description: Provide your API key as the user and leave the password empty. 204 | supportedOauthFlows: 205 | type: oauth2 206 | description: Flows to support OAuth 2.0 207 | flows: 208 | implicit: 209 | authorizationUrl: 'https://authserver.example/auth' 210 | availableScopes: 211 | 'streetlights:on': Ability to switch lights on 212 | 'streetlights:off': Ability to switch lights off 213 | 'streetlights:dim': Ability to dim the lights 214 | password: 215 | tokenUrl: 'https://authserver.example/token' 216 | availableScopes: 217 | 'streetlights:on': Ability to switch lights on 218 | 'streetlights:off': Ability to switch lights off 219 | 'streetlights:dim': Ability to dim the lights 220 | clientCredentials: 221 | tokenUrl: 'https://authserver.example/token' 222 | availableScopes: 223 | 'streetlights:on': Ability to switch lights on 224 | 'streetlights:off': Ability to switch lights off 225 | 'streetlights:dim': Ability to dim the lights 226 | authorizationCode: 227 | authorizationUrl: 'https://authserver.example/auth' 228 | tokenUrl: 'https://authserver.example/token' 229 | refreshUrl: 'https://authserver.example/refresh' 230 | availableScopes: 231 | 'streetlights:on': Ability to switch lights on 232 | 'streetlights:off': Ability to switch lights off 233 | 'streetlights:dim': Ability to dim the lights 234 | openIdConnectWellKnown: 235 | type: openIdConnect 236 | openIdConnectUrl: 'https://authserver.example/.well-known' 237 | parameters: 238 | streetlightId: 239 | description: The ID of the streetlight. 240 | messageTraits: 241 | commonHeaders: 242 | headers: 243 | type: object 244 | properties: 245 | my-app-header: 246 | type: integer 247 | minimum: 0 248 | maximum: 100 249 | operationTraits: 250 | mqtt: 251 | bindings: 252 | mqtt: 253 | qos: 1 -------------------------------------------------------------------------------- /test/Optimizer.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | inputJSON, 3 | inputYAML, 4 | outputJSON_mATCFalse_mDTCTrue_schemaFalse, 5 | outputYAML_mATCFalse_mDTCTrue_schemaFalse, 6 | outputYAML_mATCTrue_mDTCFalse_schemaFalse, 7 | outputJSON_mATCTrue_mDTCFalse_schemaFalse, 8 | outputYAML_mATCFalse_mDTCTrue_schemaTrue, 9 | outputJSON_mATCFalse_mDTCTrue_schemaTrue, 10 | outputYAML_mATCTrue_mDTCFalse_schemaTrue, 11 | outputJSON_mATCTrue_mDTCFalse_schemaTrue, 12 | } from './fixtures' 13 | import { Optimizer } from '../src' 14 | import { Output } from '../src/Optimizer' 15 | 16 | describe('Optimizer', () => { 17 | it('should produce the correct optimized file with YAML input and `{ moveAllToComponents: false, moveDuplicatesToComponents: true }, disableOptimizationFor: { schema: false } }`.', async () => { 18 | const optimizer = new Optimizer(inputYAML) 19 | await optimizer.getReport() 20 | expect( 21 | optimizer 22 | .getOptimizedDocument({ 23 | output: Output.YAML, 24 | rules: { 25 | reuseComponents: true, 26 | removeComponents: true, 27 | moveAllToComponents: false, 28 | moveDuplicatesToComponents: true, 29 | }, 30 | disableOptimizationFor: { 31 | schema: false, 32 | }, 33 | }) 34 | .trim() 35 | ).toEqual(outputYAML_mATCFalse_mDTCTrue_schemaFalse.trim()) 36 | }) 37 | 38 | it('should produce the correct optimized file with JSON input and `{ moveAllToComponents: false, moveDuplicatesToComponents: true }, disableOptimizationFor: { schema: false } }`.', async () => { 39 | const optimizer = new Optimizer(inputJSON) 40 | await optimizer.getReport() 41 | expect( 42 | optimizer 43 | .getOptimizedDocument({ 44 | output: Output.YAML, 45 | rules: { 46 | reuseComponents: true, 47 | removeComponents: true, 48 | moveAllToComponents: false, 49 | moveDuplicatesToComponents: true, 50 | }, 51 | disableOptimizationFor: { 52 | schema: false, 53 | }, 54 | }) 55 | .trim() 56 | ).toEqual(outputYAML_mATCFalse_mDTCTrue_schemaFalse.trim()) 57 | }) 58 | 59 | it('should produce the correct JSON output and `{ moveAllToComponents: false, moveDuplicatesToComponents: true }, disableOptimizationFor: { schema: false } }`.', async () => { 60 | const optimizer = new Optimizer(inputYAML) 61 | await optimizer.getReport() 62 | expect( 63 | optimizer 64 | .getOptimizedDocument({ 65 | output: Output.JSON, 66 | rules: { 67 | reuseComponents: true, 68 | removeComponents: true, 69 | moveAllToComponents: false, 70 | moveDuplicatesToComponents: true, 71 | }, 72 | disableOptimizationFor: { 73 | schema: false, 74 | }, 75 | }) 76 | .trim() 77 | ).toEqual(outputJSON_mATCFalse_mDTCTrue_schemaFalse.trim()) 78 | }) 79 | 80 | it('should produce the correct optimized file with YAML input and `{ moveAllToComponents: true, moveDuplicatesToComponents: false }, disableOptimizationFor: { schema: false } }`.', async () => { 81 | const optimizer = new Optimizer(inputYAML) 82 | await optimizer.getReport() 83 | expect( 84 | optimizer 85 | .getOptimizedDocument({ 86 | output: Output.YAML, 87 | rules: { 88 | reuseComponents: true, 89 | removeComponents: true, 90 | moveAllToComponents: true, 91 | moveDuplicatesToComponents: false, 92 | }, 93 | disableOptimizationFor: { 94 | schema: false, 95 | }, 96 | }) 97 | .trim() 98 | ).toEqual(outputYAML_mATCTrue_mDTCFalse_schemaFalse.trim()) 99 | }) 100 | 101 | it('should produce the correct optimized file with JSON input and `{ moveAllToComponents: true, moveDuplicatesToComponents: false }, disableOptimizationFor: { schema: false } }`.', async () => { 102 | const optimizer = new Optimizer(inputJSON) 103 | await optimizer.getReport() 104 | expect( 105 | optimizer 106 | .getOptimizedDocument({ 107 | output: Output.YAML, 108 | rules: { 109 | reuseComponents: true, 110 | removeComponents: true, 111 | moveAllToComponents: true, 112 | moveDuplicatesToComponents: false, 113 | }, 114 | disableOptimizationFor: { 115 | schema: false, 116 | }, 117 | }) 118 | .trim() 119 | ).toEqual(outputYAML_mATCTrue_mDTCFalse_schemaFalse.trim()) 120 | }) 121 | 122 | it('should produce the correct JSON output and `{ moveAllToComponents: true, moveDuplicatesToComponents: false }, disableOptimizationFor: { schema: false } }`.', async () => { 123 | const optimizer = new Optimizer(inputYAML) 124 | await optimizer.getReport() 125 | expect( 126 | optimizer 127 | .getOptimizedDocument({ 128 | output: Output.JSON, 129 | rules: { 130 | reuseComponents: true, 131 | removeComponents: true, 132 | moveAllToComponents: true, 133 | moveDuplicatesToComponents: false, 134 | }, 135 | disableOptimizationFor: { 136 | schema: false, 137 | }, 138 | }) 139 | .trim() 140 | ).toEqual(outputJSON_mATCTrue_mDTCFalse_schemaFalse.trim()) 141 | }) 142 | 143 | it('should produce the correct optimized file with YAML input and `{ moveAllToComponents: false, moveDuplicatesToComponents: true }, disableOptimizationFor: { schema: true } }`.', async () => { 144 | const optimizer = new Optimizer(inputYAML) 145 | await optimizer.getReport() 146 | expect( 147 | optimizer 148 | .getOptimizedDocument({ 149 | output: Output.YAML, 150 | rules: { 151 | reuseComponents: true, 152 | removeComponents: true, 153 | moveAllToComponents: false, 154 | moveDuplicatesToComponents: true, 155 | }, 156 | disableOptimizationFor: { 157 | schema: true, 158 | }, 159 | }) 160 | .trim() 161 | ).toEqual(outputYAML_mATCFalse_mDTCTrue_schemaTrue.trim()) 162 | }) 163 | 164 | it('should produce the correct optimized file with JSON input and `{ moveAllToComponents: false, moveDuplicatesToComponents: true }, disableOptimizationFor: { schema: true } }`.', async () => { 165 | const optimizer = new Optimizer(inputJSON) 166 | await optimizer.getReport() 167 | expect( 168 | optimizer 169 | .getOptimizedDocument({ 170 | output: Output.YAML, 171 | rules: { 172 | reuseComponents: true, 173 | removeComponents: true, 174 | moveAllToComponents: false, 175 | moveDuplicatesToComponents: true, 176 | }, 177 | disableOptimizationFor: { 178 | schema: true, 179 | }, 180 | }) 181 | .trim() 182 | ).toEqual(outputYAML_mATCFalse_mDTCTrue_schemaTrue.trim()) 183 | }) 184 | 185 | it('should produce the correct JSON output and `{ moveAllToComponents: false, moveDuplicatesToComponents: true }, disableOptimizationFor: { schema: true } }`.', async () => { 186 | const optimizer = new Optimizer(inputYAML) 187 | await optimizer.getReport() 188 | expect( 189 | optimizer 190 | .getOptimizedDocument({ 191 | output: Output.JSON, 192 | rules: { 193 | reuseComponents: true, 194 | removeComponents: true, 195 | moveAllToComponents: false, 196 | moveDuplicatesToComponents: true, 197 | }, 198 | disableOptimizationFor: { 199 | schema: true, 200 | }, 201 | }) 202 | .trim() 203 | ).toEqual(outputJSON_mATCFalse_mDTCTrue_schemaTrue.trim()) 204 | }) 205 | 206 | it('should produce the correct optimized file with YAML input and `{ moveAllToComponents: true, moveDuplicatesToComponents: false }, disableOptimizationFor: { schema: true } }`.', async () => { 207 | const optimizer = new Optimizer(inputYAML) 208 | await optimizer.getReport() 209 | expect( 210 | optimizer 211 | .getOptimizedDocument({ 212 | output: Output.YAML, 213 | rules: { 214 | reuseComponents: true, 215 | removeComponents: true, 216 | moveAllToComponents: true, 217 | moveDuplicatesToComponents: false, 218 | }, 219 | disableOptimizationFor: { 220 | schema: true, 221 | }, 222 | }) 223 | .trim() 224 | ).toEqual(outputYAML_mATCTrue_mDTCFalse_schemaTrue.trim()) 225 | }) 226 | 227 | it('should produce the correct optimized file with JSON input and `{ moveAllToComponents: true, moveDuplicatesToComponents: false }, disableOptimizationFor: { schema: true } }`.', async () => { 228 | const optimizer = new Optimizer(inputJSON) 229 | await optimizer.getReport() 230 | expect( 231 | optimizer 232 | .getOptimizedDocument({ 233 | output: Output.YAML, 234 | rules: { 235 | reuseComponents: true, 236 | removeComponents: true, 237 | moveAllToComponents: true, 238 | moveDuplicatesToComponents: false, 239 | }, 240 | disableOptimizationFor: { 241 | schema: true, 242 | }, 243 | }) 244 | .trim() 245 | ).toEqual(outputYAML_mATCTrue_mDTCFalse_schemaTrue.trim()) 246 | }) 247 | 248 | it('should produce the correct JSON output and `{ moveAllToComponents: true, moveDuplicatesToComponents: false }, disableOptimizationFor: { schema: true } }`.', async () => { 249 | const optimizer = new Optimizer(inputYAML) 250 | await optimizer.getReport() 251 | expect( 252 | optimizer 253 | .getOptimizedDocument({ 254 | output: Output.JSON, 255 | rules: { 256 | reuseComponents: true, 257 | removeComponents: true, 258 | moveAllToComponents: true, 259 | moveDuplicatesToComponents: false, 260 | }, 261 | disableOptimizationFor: { 262 | schema: true, 263 | }, 264 | }) 265 | .trim() 266 | ).toEqual(outputJSON_mATCTrue_mDTCFalse_schemaTrue.trim()) 267 | }) 268 | }) 269 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /.github/workflows/notify-tsc-members-mention.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 and email subscribers whenever TSC members are mentioned in GitHub 6 | 7 | on: 8 | issue_comment: 9 | types: 10 | - created 11 | 12 | discussion_comment: 13 | types: 14 | - created 15 | 16 | issues: 17 | types: 18 | - opened 19 | 20 | pull_request_target: 21 | types: 22 | - opened 23 | 24 | discussion: 25 | types: 26 | - created 27 | 28 | jobs: 29 | issue: 30 | if: github.event_name == 'issues' && contains(github.event.issue.body, '@asyncapi/tsc_members') 31 | name: TSC notification on every new issue 32 | runs-on: ubuntu-latest 33 | steps: 34 | - name: Checkout repository 35 | uses: actions/checkout@v4 36 | - name: Setup Node.js 37 | uses: actions/setup-node@v4 38 | with: 39 | node-version: 16 40 | cache: 'npm' 41 | cache-dependency-path: '**/package-lock.json' 42 | ######### 43 | # Handling Slack notifications 44 | ######### 45 | - name: Convert markdown to slack markdown 46 | # This workflow is from our own org repo and safe to reference by 'master'. 47 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 48 | id: issuemarkdown 49 | with: 50 | markdown: "[${{github.event.issue.title}}](${{github.event.issue.html_url}}) \n ${{github.event.issue.body}}" 51 | - name: Send info about issue 52 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 53 | env: 54 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}} 55 | SLACK_TITLE: 🆘 New issue that requires TSC Members attention 🆘 56 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}} 57 | MSG_MINIMAL: true 58 | ######### 59 | # Handling Mailchimp notifications 60 | ######### 61 | - name: Install deps 62 | run: npm install 63 | working-directory: ./.github/workflows/scripts/mailchimp 64 | - name: Send email with MailChimp 65 | uses: actions/github-script@v7 66 | env: 67 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }} 68 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }} 69 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }} 70 | TITLE: ${{ github.event.issue.title }} 71 | with: 72 | script: | 73 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js'); 74 | sendEmail('${{github.event.issue.html_url}}', process.env.TITLE); 75 | 76 | pull_request: 77 | if: github.event_name == 'pull_request_target' && contains(github.event.pull_request.body, '@asyncapi/tsc_members') 78 | name: TSC notification on every new pull request 79 | runs-on: ubuntu-latest 80 | steps: 81 | - name: Checkout repository 82 | uses: actions/checkout@v4 83 | - name: Setup Node.js 84 | uses: actions/setup-node@v4 85 | with: 86 | node-version: 16 87 | cache: 'npm' 88 | cache-dependency-path: '**/package-lock.json' 89 | ######### 90 | # Handling Slack notifications 91 | ######### 92 | - name: Convert markdown to slack markdown 93 | # This workflow is from our own org repo and safe to reference by 'master'. 94 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 95 | id: prmarkdown 96 | with: 97 | markdown: "[${{github.event.pull_request.title}}](${{github.event.pull_request.html_url}}) \n ${{github.event.pull_request.body}}" 98 | - name: Send info about pull request 99 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 100 | env: 101 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}} 102 | SLACK_TITLE: 🆘 New PR that requires TSC Members attention 🆘 103 | SLACK_MESSAGE: ${{steps.prmarkdown.outputs.text}} 104 | MSG_MINIMAL: true 105 | ######### 106 | # Handling Mailchimp notifications 107 | ######### 108 | - name: Install deps 109 | run: npm install 110 | working-directory: ./.github/workflows/scripts/mailchimp 111 | - name: Send email with MailChimp 112 | uses: actions/github-script@v7 113 | env: 114 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }} 115 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }} 116 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }} 117 | TITLE: ${{ github.event.pull_request.title }} 118 | with: 119 | script: | 120 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js'); 121 | sendEmail('${{github.event.pull_request.html_url}}', process.env.TITLE); 122 | 123 | discussion: 124 | if: github.event_name == 'discussion' && contains(github.event.discussion.body, '@asyncapi/tsc_members') 125 | name: TSC notification on every new discussion 126 | runs-on: ubuntu-latest 127 | steps: 128 | - name: Checkout repository 129 | uses: actions/checkout@v4 130 | - name: Setup Node.js 131 | uses: actions/setup-node@v4 132 | with: 133 | node-version: 16 134 | cache: 'npm' 135 | cache-dependency-path: '**/package-lock.json' 136 | ######### 137 | # Handling Slack notifications 138 | ######### 139 | - name: Convert markdown to slack markdown 140 | # This workflow is from our own org repo and safe to reference by 'master'. 141 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 142 | id: discussionmarkdown 143 | with: 144 | markdown: "[${{github.event.discussion.title}}](${{github.event.discussion.html_url}}) \n ${{github.event.discussion.body}}" 145 | - name: Send info about pull request 146 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 147 | env: 148 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}} 149 | SLACK_TITLE: 🆘 New discussion that requires TSC Members attention 🆘 150 | SLACK_MESSAGE: ${{steps.discussionmarkdown.outputs.text}} 151 | MSG_MINIMAL: true 152 | ######### 153 | # Handling Mailchimp notifications 154 | ######### 155 | - name: Install deps 156 | run: npm install 157 | working-directory: ./.github/workflows/scripts/mailchimp 158 | - name: Send email with MailChimp 159 | uses: actions/github-script@v7 160 | env: 161 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }} 162 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }} 163 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }} 164 | TITLE: ${{ github.event.discussion.title }} 165 | with: 166 | script: | 167 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js'); 168 | sendEmail('${{github.event.discussion.html_url}}', process.env.TITLE); 169 | 170 | issue_comment: 171 | if: ${{ github.event_name == 'issue_comment' && !github.event.issue.pull_request && contains(github.event.comment.body, '@asyncapi/tsc_members') }} 172 | name: TSC notification on every new comment in issue 173 | runs-on: ubuntu-latest 174 | steps: 175 | - name: Checkout repository 176 | uses: actions/checkout@v4 177 | - name: Setup Node.js 178 | uses: actions/setup-node@v4 179 | with: 180 | node-version: 16 181 | cache: 'npm' 182 | cache-dependency-path: '**/package-lock.json' 183 | ######### 184 | # Handling Slack notifications 185 | ######### 186 | - name: Convert markdown to slack markdown 187 | # This workflow is from our own org repo and safe to reference by 'master'. 188 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 189 | id: issuemarkdown 190 | with: 191 | markdown: "[${{github.event.issue.title}}](${{github.event.comment.html_url}}) \n ${{github.event.comment.body}}" 192 | - name: Send info about issue comment 193 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 194 | env: 195 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}} 196 | SLACK_TITLE: 🆘 New comment under existing issue that requires TSC Members attention 🆘 197 | SLACK_MESSAGE: ${{steps.issuemarkdown.outputs.text}} 198 | MSG_MINIMAL: true 199 | ######### 200 | # Handling Mailchimp notifications 201 | ######### 202 | - name: Install deps 203 | run: npm install 204 | working-directory: ./.github/workflows/scripts/mailchimp 205 | - name: Send email with MailChimp 206 | uses: actions/github-script@v7 207 | env: 208 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }} 209 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }} 210 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }} 211 | TITLE: ${{ github.event.issue.title }} 212 | with: 213 | script: | 214 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js'); 215 | sendEmail('${{github.event.comment.html_url}}', process.env.TITLE); 216 | 217 | pr_comment: 218 | if: github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '@asyncapi/tsc_members') 219 | name: TSC notification on every new comment in pr 220 | runs-on: ubuntu-latest 221 | steps: 222 | - name: Checkout repository 223 | uses: actions/checkout@v4 224 | - name: Setup Node.js 225 | uses: actions/setup-node@v4 226 | with: 227 | node-version: 16 228 | cache: 'npm' 229 | cache-dependency-path: '**/package-lock.json' 230 | ######### 231 | # Handling Slack notifications 232 | ######### 233 | - name: Convert markdown to slack markdown 234 | # This workflow is from our own org repo and safe to reference by 'master'. 235 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 236 | id: prmarkdown 237 | with: 238 | markdown: "[${{github.event.issue.title}}](${{github.event.comment.html_url}}) \n ${{github.event.comment.body}}" 239 | - name: Send info about PR comment 240 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 241 | env: 242 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}} 243 | SLACK_TITLE: 🆘 New comment under existing PR that requires TSC Members attention 🆘 244 | SLACK_MESSAGE: ${{steps.prmarkdown.outputs.text}} 245 | MSG_MINIMAL: true 246 | ######### 247 | # Handling Mailchimp notifications 248 | ######### 249 | - name: Install deps 250 | run: npm install 251 | working-directory: ./.github/workflows/scripts/mailchimp 252 | - name: Send email with MailChimp 253 | uses: actions/github-script@v7 254 | env: 255 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }} 256 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }} 257 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }} 258 | TITLE: ${{ github.event.issue.title }} 259 | with: 260 | script: | 261 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js'); 262 | sendEmail('${{github.event.comment.html_url}}', process.env.TITLE); 263 | 264 | discussion_comment: 265 | if: github.event_name == 'discussion_comment' && contains(github.event.comment.body, '@asyncapi/tsc_members') 266 | name: TSC notification on every new comment in discussion 267 | runs-on: ubuntu-latest 268 | steps: 269 | - name: Checkout repository 270 | uses: actions/checkout@v4 271 | - name: Setup Node.js 272 | uses: actions/setup-node@v4 273 | with: 274 | node-version: 16 275 | cache: 'npm' 276 | cache-dependency-path: '**/package-lock.json' 277 | ######### 278 | # Handling Slack notifications 279 | ######### 280 | - name: Convert markdown to slack markdown 281 | # This workflow is from our own org repo and safe to reference by 'master'. 282 | uses: asyncapi/.github/.github/actions/slackify-markdown@master # //NOSONAR 283 | id: discussionmarkdown 284 | with: 285 | markdown: "[${{github.event.discussion.title}}](${{github.event.comment.html_url}}) \n ${{github.event.comment.body}}" 286 | - name: Send info about discussion comment 287 | uses: rtCamp/action-slack-notify@c33737706dea87cd7784c687dadc9adf1be59990 # Using v2.3.2 288 | env: 289 | SLACK_WEBHOOK: ${{secrets.SLACK_TSC_MEMBERS_NOTIFY}} 290 | SLACK_TITLE: 🆘 New comment under existing discussion that requires TSC Members attention 🆘 291 | SLACK_MESSAGE: ${{steps.discussionmarkdown.outputs.text}} 292 | MSG_MINIMAL: true 293 | ######### 294 | # Handling Mailchimp notifications 295 | ######### 296 | - name: Install deps 297 | run: npm install 298 | working-directory: ./.github/workflows/scripts/mailchimp 299 | - name: Send email with MailChimp 300 | uses: actions/github-script@v7 301 | env: 302 | CALENDAR_ID: ${{ secrets.CALENDAR_ID }} 303 | CALENDAR_SERVICE_ACCOUNT: ${{ secrets.CALENDAR_SERVICE_ACCOUNT }} 304 | MAILCHIMP_API_KEY: ${{ secrets.MAILCHIMP_API_KEY }} 305 | TITLE: ${{ github.event.discussion.title }} 306 | with: 307 | script: | 308 | const sendEmail = require('./.github/workflows/scripts/mailchimp/index.js'); 309 | sendEmail('${{github.event.comment.html_url}}', process.env.TITLE); 310 | --------------------------------------------------------------------------------