The @axinom/mosaic-cli is a command line utility that provides several commands that could be useful when developing an Axinom Mosaic solution

@axinom/mosaic-cli

The @axinom/mosaic-cli is a command-line utility that provides several commands for developing an Axinom Mosaic solution.

You can find a list of all available CLI commands by running npx mosaic --help. If you run the command npx mosaic <command-name> --help you will find a description of the specific command and the available parameters and examples.

A note on environment variables and CLI parameters

Some parameters to the CLI commands can be provided via environment variables. These parameters have similar names to the environment variables defined in the .env files, for example --clientId and SERVICE_ACCOUNT_CLIENT_ID.

With a library like env-cmd you can easily load environment variables from your .env file and use them in your package.json scripts. For example

{
  "scripts": {
    "get-token": "env-cmd -f .env mosaic get-access-token -f ./path/to/permissions.json"
  }
}

Commands

mosaic apply-templates

Creates a local copy of each *.template file. A diff and confirmation prompt will be displayed before any changes are made.

Env (.env) files have special treatment…​ the value for each key defined in the target file will be kept in these cases: a. A value for the key is not defined, or is blank, in the template b. The value in the template looks like <a_{placeholder}> c. The line from the template is included in the .env file and commented out

When a .env file is created from a template, an extra line will be prefixed in the form "#@TEMPLATE = {template-file}". This directive will then be used to match the output file to the original template even after renaming the output file. This simplifies management of .env files when multiple template files are provided for alternative environments.

mosaic get-access-token

Requests a long living access token for development purposes.

Options:
      --version                             Show version number        [boolean]
      --help                                Show help                  [boolean]
  -f, --permissionsFile                     A JSON file containing the wanted
                                            permission structure.
                                            JSON Format:
                                            {"serviceId" : string,
                                            "permissions": string[]}[]
                                                             [string] [required]
  -i, --clientId,                           The service account client id.
  --devServiceAccountClientId               Required permission:
                                            ID SERVICE -> 'Dev Generate User
                                            Access Token With Permissions'
                                                             [string] [required]
  -s, --clientSecret,                       The service account client secret.
  --devServiceAccountClientSecret                            [string] [required]
  -a, --authEndpoint,                       The authentication service endpoint
  --idServiceAuthBaseUrl                    url.             [string] [required]
  -e, --userEmail                           The email of a user that exists on
                                            the environment. If unspecified, a
                                            pseudo-user will be used to generate
                                            the token for.              [string]
  -u, --failOnUnknownPermission             Fails if an unknown permission is
                                            requested.[boolean] [default: false]
  -x, --expiration                          Token expiration time in seconds.
                                                     [number] [default: 2592000]

This allows you to call GraphQL APIs or test specific scenarios without the need to assign all the needed permissions to some user and to refresh the token every few minutes.

To declare which permissions should be included in the token, you must create a JSON file listing the permissions. The format of the file looks like this:

permissions.json
[
  {
    "serviceId": "service-1",
    "permissions": ["permission-1", "permission-2"]
  },
  {
    "serviceId": "ax-image-service",
    "permissions": ["ADMIN"]
  }
]

Then pass it to the CLI command to receive a JWT for the desired user:

npx mosaic get-access-token -i <client-id> -s <client-secret> -a <auth-endpoint> -f permissions.json
Note

You must provide the CLI a client ID and client secret of a service account of your environment. This service account must have the permission Dev Generate User Access Token With Permissions. In addition, you need to provide the URL to the user authentication endpoint (e.g. https://id.service.eu.axinom.net).

mosaic publish-schema-to-db

Tool to generate the initial database schema for a catalog-like service from publish format definitions.

mosaic pg-dump

Development command that uses a default PostgreSQL pg_dump utility to create a schema dump file of a specific database based on an existing docker-compose.yml file.

Options:
      --version            Show version number                         [boolean]
      --help               Show help                                   [boolean]
  -c, --composeFolderPath  Relative path to docker-compose.yml file, e.g.
                           `infra` or `scripts/infra`. Script will look for such
                           directory starting from current project, traversing
                           directories closer to root, so no need to specify a
                           path like `../../../infra`[string] [default: "infra"]
  -d, --dumpPath           Relative path from working directory to a schema SQL
                           file which will be created by pg_dump utility, e.g.
                           `src/generated/db/schema.sql`
                               [string] [default: "src/generated/db/schema.sql"]
  -e, --excludeSchemas     A comma-separated string of database schema names
                           that should be excluded from pg_dump, e.g.
                           `schema_one,schema_two`
                          [string] [default: "graphile_migrate,graphile_worker"]
  -s, --connectionString   The connection string to the database to be used to
                           take a schema dump. Can be omitted if
                           database-related environment variables are preloaded
                                                                        [string]
Note
You need to provide the CLI the database with a connection string that has permissions to create a dump file.

mosaic msg-codegen

Generates code from an AsyncAPI document.

Options:
      --version      Show version number                               [boolean]
      --help         Show help                                         [boolean]
  -i, --inputDir     Path to input directory - AsyncAPI document root.
                                                             [string] [required]
  -p, --filePattern  Regular expression that matches suitable input files.
                           [string] [default: "^.*(-asyncapi).(json|yaml|yml)$"]
  -o, --outputDir    Path to output directory - output root.
                                             [string] [default: "src/generated"]
      --lint         Run the Spectral linter on message schemas.
                                                      [boolean] [default: false]
  -r, --rulesetPath  Path to a Spectral ruleset file for linting.       [string]

mosaic msg-diff

Compares two versions of an AsyncAPI document and raises an error if there are breaking changes.

Options:
      --version         Show version number                            [boolean]
      --help            Show help                                      [boolean]
  -i, --inputDir        Path to input directory - AsyncAPI document root.
                                                             [string] [required]
  -p, --filePattern     Regular expression used to include suitable input files.
                           [string] [default: "^.*(-asyncapi).(json|yaml|yml)$"]
  -e, --excludePattern  Exclude input files matching a regular expression.
                        Exclusion takes precedence over inclusion.      [string]
  -b, --branch          Git branch or commit identifier to compare to.
                                             [string] [default: "origin/master"]
  -v, --verbose         Verbose output including non-breaking changes.
                                                      [boolean] [default: false]

mosaic create-extension-config

Creates Mosaic CLI configuration file, that allows to access commands from all installed Mosaic libraries through mosaic script.

mosaic graphql-diff

Compares graphql schema(s) with git for breaking changes.

Options:
      --version  Show version number                                   [boolean]
      --help     Show help                                             [boolean]
  -f, --files    The .graphql file(s) to check. Each will be checked against
                 git.                                         [array] [required]
  -b, --branch   Git branch or commit identifier to compare to.
                                             [string] [default: "origin/master"]
  -v, --verbose  Verbose output including non-breaking changes
                                                      [boolean] [default: false]

mosaic hosting pilet register

Register a pilet in Mosaic Micro Frontend Service.

Options:
      --version                      Show version number               [boolean]
      --help                         Show help                         [boolean]
  -i, --serviceId                    Service ID the pilet should be registered
                                     to                                 [string]
  -c, --mosaicHostingClientId        Client ID to authenticate          [string]
  -s, --mosaicHostingClientSecret    Client Secret to authenticate      [string]
  -t, --tenantId                     Tenant ID                          [string]
  -e, --environmentId                Environment ID                     [string]
  -p, --piletArtifactPath            Pilet Artifact Path                [string]
  -a, --idServiceAuthBaseURL         ID Service Authentication Endpoint Base URL
                                                                        [string]
  -m, --microFrontendServiceBaseURL  Micro Frontend Service Base URL    [string]
  -o, --overrideRegistration         Override registration
                                                      [boolean] [default: false]

mosaic hosting pilet manifest upload

Upload a Deployment Manifest against a Service ID to the Hosting Service.

Options:
      --version                    Show version number                 [boolean]
      --help                       Show help                           [boolean]
  -n, --name                       Name of the Deployment Manifest
                                                             [string] [required]
  -i, --serviceId                  Service ID the Deployment Manifest should be
                                   registered to                        [string]
  -c, --mosaicHostingClientId      Service Account Client ID to authenticate
                                                                        [string]
  -s, --mosaicHostingClientSecret  Service Account Client Secret to authenticate
                                                                        [string]
  -p, --deploymentManifestPath     Deployment Manifest Path
                 [string] [default: "./mosaic-hosting-deployment-manifest.yaml"]
  -a, --idServiceAuthBaseURL       ID Service Authentication Endpoint Base URL
                                                                        [string]
  -h, --hostingServiceBaseURL      Hosting Service Base URL             [string]

mosaic service sync-permissions

Synchronize permissions of a Mosaic Service with ID Service.

Options:
      --version                      Show version number               [boolean]
      --help                         Show help                         [boolean]
  -i, --serviceId                    Service ID the permissions must be synchronized
                                     for                                [string]
  -c, --clientId                     Client ID to authenticate          [string]
  -s, --clientSecret                 Client Secret to authenticate      [string]
  -p, --permissionDefinitionJsonPath Permission Definition JSON Path    [string]
  -a, --idServiceAuthBaseURL         ID Service Authentication Endpoint Base URL
                                                                        [string]

mosaic service delete-permissions

Delete all permissions for a given Service ID.

Options:
      --version                      Show version number               [boolean]
      --help                         Show help                         [boolean]
  -i, --serviceId                    Service ID the permissions must be deleted
                                                                        [string]
  -c, --clientId                     Client ID to authenticate          [string]
  -s, --clientSecret                 Client Secret to authenticate      [string]
  -a, --idServiceAuthBaseURL         ID Service Authentication Endpoint Base URL
                                                                        [string]

mosaic generate-vscode-sql-snippets

Note
Extension from @axinom/mosaic-db-common.

Creates or updates a mosaic sql snippets file, providing an easier way to write database migrations.

Options:
      --version                           Show version number          [boolean]
      --help                              Show help                    [boolean]
  -f, --snippetsFileNameWithoutExtension  Overrides default snippets file name
                                          with a custom value. Extension
                                          `code-snippets` will be attached to
                                          this value.
                                     [string] [default: "mosaic-sql-migrations"]

Call npx mosaic generate-vscode-sql-snippets from monorepo root to create or update a .code-snippets file with all currently supported SQL snippets. The file is created inside of the .vscode folder and is only relevant if VSCode IDE is used.

Having this file enables custom mosaic code snippets for .sql files, especially useful when writing migrations in the current.sql file to help discover existing ax_utils and ax_define helpers, as well as common pieces of database migration code.

It is recommended to run this command after previously described generate-define-func-migration command was used, to make sure that both ax_define and SQL snippets are updated at the same time.

The default name of the generated snippets file is mosaic-sql-migrations.code-snippets, but it can be adjusted using the -f parameter.

mosaic generate-define-func-migration

Note
Extension from @axinom/mosaic-db-common.

Updates a current.sql migrations file with latest ax_define helper function definitions.

Options:
      --version                     Show version number                [boolean]
      --help                        Show help                          [boolean]
  -p, --currentMigrationFolderPath  Relative path from working directory to a
                                    folder containing current.sql file, which
                                    will be updated with latest ax_define
                                    function definitions.
                                                [string] [default: "migrations"]

We use graphile-migrate, where you write migrations with SQL. To make the process of writing migrations easier, we expose a lot of helper functions, which are located in dedicated ax_utils and ax_define PostgreSQL schemas. Unlike ax_utils functions, which are automatically updated whenever a new migration is applied, ax_define functions require manual updates from time to time, and this command is introduced to simplify the process.

Important
We strongly advise keeping the functions as they are provided to ensure that future updates will work as intended.

Call npx mosaic generate-define-func-migration from the root of the project that supports graphile-migrate migrations. This will update the current.sql with a migration code that is ready to be committed. It drops all existing ax_define functions and then initializes them again. This does not affect previously committed migrations. They will continue using previous versions of ax_define helpers since they are also defined in the context of committed migrations.

In case you are using a custom project structure and the migrations folder is not located in the root of the project, then this path can be specified using -p parameter.

Apply environment file templates

In the local development environment, the environment variables are read from .env files. Those files can contain configuration values that are secret (e.g. passwords). Therefore, and as they can be customized in every local development environment, they are not committed to source control.

The Mosaic solutions contain instead a .env.template file in every project. Only the template files go into source control. The CLI command mosaic apply-templates takes all *.template files and creates a copy of them as a .env file. The provided variables inside of the template files offer already good defaults that work for your local development. But you can adjust all those values to your needs.

You can decide if existing .env files should be overwritten by providing the -r parameter. And you can provide a glob pattern to run the command only for a specific folder pattern (-o <glob-pattern>).

Extending Mosaic CLI

Mosaic CLI can be extended with modular commands, that are not originally part of the @axinom/mosaic-cli and are exported by other mosaic packages.

To create an extension, you need to create a mosaic package that exports an object named cliExtension, a yargs CommandModule object.

import * as yargs from 'yargs';
import {
  extensionCommand1,
  extensionCommand2,
} from './commands';

export const cliExtension = (): yargs.CommandModule<any, any>[] => [
  extensionCommand1,
  extensionCommand2,
];

Loading extensions

To enable modular commands, run npx mosaic create-extension-config. This will generate a .mosaic text file with a list of package names from which mosaic CLI will get extra commands. Run this command again after installing new mosaic packages or updating existing ones to update the list of packages that extend the Mosaic CLI.

Note
The extensions mechanism currently only works with mosaic packages, i.e. packages that have @axinom/mosaic- prefix.