AsyncAPI CLI

repository·master·Indexed 42 days ago

https://github.com/asyncapi/cli

An all-in-one command-line interface and REST API server for working with AsyncAPI specification files. Version 6.1.0 provides tools for validation, conversion, bundling, and code generation, as well as configuration management and integration as a GitHub Action.

Tokens
39.8K
Snippets
171
Records
215
Agent score
49%

What's inside AsyncAPI CLI

  1. Overview of AsyncAPI CLI features

    master

    The AsyncAPI CLI is a command-line tool designed to manage the lifecycle of AsyncAPI documents. It provides capabilities for creating, validating, converting, and manipulating these documents to ensure they conform to the AsyncAPI specification.

    Key capabilities include:

    • Creation: Generate new AsyncAPI documents from scratch.
    • Validation: Use the AsyncAPI Parser to ensure documents conform to the specification and catch errors early.
    • Conversion: Migrate AsyncAPI documents between different specification versions.
    • Difference: Compare two AsyncAPI documents to identify changes or differences between versions.
    • Generation: Leverage the AsyncAPI Generator and Modelina to produce documentation, applications, and models in various programming languages.
    • Optimize: Use the Optimizer to restructure AsyncAPI specifications, making them smaller and removing repetition.
    • Bundling: Combine multiple files into a single AsyncAPI document.
    • Studio: Start a local instance of AsyncAPI Studio for visual editing, viewing, and testing. Note: Studio is not bundled; the CLI will install it on-demand (~450MB) upon first use.
  2. What is the Context concept in AsyncAPI CLI?

    master

    The context feature allows you to create aliases for AsyncAPI documents. This is particularly useful in large, event-driven architectures where a single project contains multiple services, each with its own AsyncAPI specification file located in different directories.

    Instead of providing the full file path every time you run a command (e.g., asyncapi validate ./services/auth/asyncapi.yaml), you can define a context name (e.g., auth) that points to that path. You can then simply run asyncapi validate auth.

    Contexts can be:

    • Global: Stored in your home directory for use across multiple repositories.
    • Project-specific: Stored in a .asyncapi-cli file within your project directory, allowing you to share context configurations with your team via version control.
  3. Overview of AsyncAPI CLI Architecture

    master

    The AsyncAPI CLI is a dual-purpose tool built with oclif and Express. It provides two primary entry points for interacting with AsyncAPI specifications:

    1. CLI Application: A command-line interface for local operations like validation, conversion, and code generation.
    2. API Server: A REST API server that exposes the same core logic via HTTP endpoints.

    Both entry points rely on a shared layer of Domain Services (business logic like validation and generation) and Domain Models (data structures like Specifications and Contexts).

  4. Understand the AsyncAPI CLI command structure

    master

    The CLI follows specific naming patterns for commands and arguments to ensure a consistent user experience:

    1. verb + noun (e.g., asyncapi validate <spec-file-path>)
    2. namespace + noun + [verb] (e.g., asyncapi config context add <context-name> <spec-file-path>)

    All CLI development should comply with the Command Line Interface Guideline.

    # Example of verb + noun pattern
    asyncapi validate <spec-file-path>
    
    # Example of namespace + noun + verb pattern
    asyncapi config context add <context-name> <spec-file-path>
  5. Understand what metrics are collected

    master

    The CLI collects two primary types of metrics for tool improvement:

    1. asyncapi_adoption.action.invoked: A counter that tracks when a command is invoked, regardless of whether it succeeds or fails.
    2. asyncapi_adoption.action.finished: A counter that tracks when a command completes, including metadata such as validation_result, success, asyncapi_version, and counts for asyncapi_servers, asyncapi_channels, asyncapi_messages, etc.

    Note: Metrics are automatically skipped in CI environments or when the CI environment variable is set to true.

  6. Understand the AsyncAPI CLI execution flow

    master

    The AsyncAPI CLI operates on a command-based execution model. When you issue a command (e.g., validate, generate, or start), the CLI processes the operation and returns the results.

    If an operation fails but is recoverable, the CLI will display an error message along with suggested next steps. You can then follow these suggestions to correct your input and reissue the command.

  7. Understand the AsyncAPI CLI release flow

    master

    The release process is automated via GitHub Actions and follows these steps:

    1. Add a Changeset: Create a markdown file in .changeset specifying the package and change level (major, minor, or patch).
    2. Open a Pull Request: Merge your changes. The changeset file communicates the change type to the CI.
    3. CI Processes Changeset: A dedicated GitHub Action reads the .changeset files and automatically creates a new Pull Request that updates the package versions (e.g., from 2.0.1 to 3.0.1) and includes the change descriptions. The AsyncAPI bot automatically merges these release PRs.
    4. Release the Package: Once the version-update PR is merged, the CI/CD pipeline triggers again. It detects the version difference and executes the publish command to release the updated package.
  8. Run the AsyncAPI CLI GitHub Action locally via Docker

    master

    You can test the GitHub Action locally using Docker. First, build the action's Docker image, then run it using docker run with the necessary environment variables and volume mounts to simulate the GitHub workspace.

    # 1. Build the docker image
    npm run action:docker:build
    
    # 2. Execute the docker image
    docker run -e GITHUB_WORKSPACE="" --workdir /action -v "/home/{user}/path/to/repo":"/action" asyncapi/github-action-for-cli "" "generate" "github-action/test/asyncapi.yml" "@asyncapi/markdown-template@2.0.0" "" "output" "" ""
  9. Write unit and integration tests

    master

    The project uses chai for assertions and @oclif/test for CLI integration testing.

    Unit Test Structure

    Unit tests should be located in test/unit/ and follow the pattern: test/unit/<category>/<name>.test.ts.

    import { expect } from 'chai';
    import { MyService } from '../../../src/domains/services/my.service';
    
    describe('MyService', () => {
      let service: MyService;
    
      beforeEach(() => {
        service = new MyService();
      });
    
      describe('methodName', () => {
        it('should do something when given valid input', async () => {
          const input = { /* test data */ };
          const result = await service.methodName(input);
          expect(result.success).to.be.true;
        });
      });
    });

    Integration Test Structure (CLI Commands)

    Integration tests for CLI commands should be located in test/integration/.

    import { expect, test } from '@oclif/test';
    import path from 'path';
    
    const validSpec = path.resolve(__dirname, '../fixtures/specification.yml');
    
    describe('mycommand', () => {
      test
        .stdout()
        .command(['mycommand', validSpec])
        .it('should succeed with valid specification', (ctx) => {
          expect(ctx.stdout).to.contain('Success');
        });
    });
  10. Run AsyncAPI CLI using Docker

    master

    You can run the CLI using a Docker container. The image includes Chromium (enabling PDF generation with @asyncapi/html-template) but does not bundle Studio.

    Build the image:

    docker build -t asyncapi/cli:latest .

    Run the image: You must mount your AsyncAPI specification file and a directory for generated output using volumes (-v).

    Example (Template Generation):

    docker run --rm -it \
       --user=root \
       -v ${PWD}/test/integration/fixtures/asyncapi_v1.yml:/app/asyncapi.yml \
       -v ${PWD}/output:/app/output \
       asyncapi/cli generate fromTemplate -o /app/output /app/asyncapi.yml @asyncapi/html-template --force-write

    Note for Studio in Docker: If running asyncapi start studio inside a container, you must publish the port (e.g., -p 3210:3210) to access the web server from your host. Use --yes or ASYNCAPI_STUDIO_AUTO_INSTALL=1 to install Studio without a prompt inside the container.

  11. Install AsyncAPI CLI on macOS

    master

    You can install the CLI on macOS using Homebrew or via .pkg installers.

    Using Homebrew:

    brew install asyncapi

    Using .pkg files:

    1. Download the appropriate package for your architecture (x64 or arm64) from the releases page.
    2. Install the package using installer:
    sudo installer -pkg asyncapi.pkg -target /
  12. Install AsyncAPI CLI on Linux

    master

    Installation methods vary by distribution.

    Debian-based (Ubuntu, etc.): Download and install the .deb package:

    curl -OL https://github.com/asyncapi/cli/releases/latest/download/asyncapi.deb
    # Then use dpkg to install

    Other Linux distributions (glibc-based): Download and untar the tar.gz archive:

    curl -OL https://github.com/asyncapi/cli/releases/latest/download/asyncapi.tar.gz
    tar -xzf asyncapi.tar.gz

    Alpine Linux (musl-based): Important: Use the -alpine.tar.gz version to avoid compatibility issues.

    curl -OL https://github.com/asyncapi/cli/releases/latest/download/asyncapi-alpine.tar.gz
    tar -xzf asyncapi-alpine.tar.gz

    Setting up the symlink (for tar.gz/tar.xz installs): To run asyncapi from any directory, create a symlink in your local bin directory:

    cd asyncapi
    pwd
    # Replace <absolute-path> with the output of pwd
    ln -s <absolute-path>/bin/asyncapi /user/local/bin/asyncapi
    ln -s <absolute-path>/bin/asyncapi /user/local/bin/asyncapi