> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# CLIs from OpenAPI in TypeScript

> Install an API an OpenAPI 3 spec describes as one CLI.

An OpenAPI 3 spec's operations become one CLI: each operation is a
subcommand that takes its parameters and body as one flat JSON object.
Profiles, network rules and snapshots apply to it as to any CLI.

## Register an API

`openapiCli` reads the spec and returns a `CLI`; install it with
`registerCli`, passing the same config:

GitHub publishes its REST API as an OpenAPI spec; this installs the
`licenses` and `meta` parts, which need no token:

```ts theme={null}
import { Workspace, openapiCli } from '@struktoai/mirage-node'

const config = {
  spec: 'https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json',
  base_url: 'https://api.github.com',
  tags: ['licenses', 'meta'],
  headers: { 'User-Agent': 'my-agent' },
}
const ws = new Workspace({})
ws.registerCli('github', await openapiCli(config), config)
```

```bash theme={null}
github --help
github licenses-get --help
github licenses-get '{"license": "mit"}' | jq -c '{key, name}'
github meta-get-zen
```

With a token in `auth`, select the parts you need, such as `tags: [pulls]`.
The whole GitHub spec has more than 1024 operations and is refused; see
[What a spec must hold](#what-a-spec-must-hold).

| Config | Meaning |
| - | - |
| `spec` | the spec's http(s) URL; in YAML also a path to a JSON or YAML file, read beside the YAML file when relative. A YAML spec is read on Node and in the browser; a Cloudflare Worker reads JSON specs unless it [gives a YAML reader](#yaml-specs-on-cloudflare) |
| `base_url` | every request goes here plus the operation's path; the spec's `servers` are never used |
| `tags`, `operations` | select the operations with any of these tags, and those named here (operationId or command name); without either, every operation |
| `headers` | headers every call carries, such as a `User-Agent`; values may be credential pointers |
| `auth` | how requests authenticate; leave it out for a public API |

To build from a spec already in memory, pass it second:
`await openapiCli(config, spec)`.

## How an API becomes a CLI

One spec is one CLI, and each operation in it one subcommand. GitHub's
spec describes `GET /licenses/{license}` as:

```yaml theme={null}
/licenses/{license}:
  get:
    operationId: licenses/get
    tags: [licenses]
    summary: Get a license
    description: Gets information about a specific license. ...
    parameters:
      - name: license
        in: path
        required: true
        schema: {type: string}
```

| In the spec | In the CLI |
| - | - |
| `operationId: licenses/get` | the subcommand `licenses-get`: the operationId in lower-case words joined by dashes. Without an operationId, the method and path: `get-licenses-license` |
| `summary` | its line in `github --help` |
| `description` | the text of `github licenses-get --help` |
| `parameters` and the request body's properties | the keys of its one JSON object, whose schema `--help` shows |
| `tags` | what the `tags` config selects |

```
$ github licenses-get --help
usage: github licenses-get [-h] [JSON]

Get a license

positional arguments:
  JSON  the operation's arguments as one object

options:
  -h, --help  Show this help and exit

Gets information about a specific license. For more information, see ...

JSON arguments (schema):
{"type":"object","properties":{"license":{"type":"string"}},"required":["license"]}

$ github licenses-get '{"license": "mit"}' | jq -c '{key, name}'
{"key":"mit","name":"MIT License"}
```

The object holds every path, query and header parameter by name, and the
body's top-level properties beside them. A parameter whose name another
parameter or a body property also uses is spelled `<name>__<in>`
(`id__path`); a body that is not an object of fixed properties (one open
to more keys, nullable, or composed with `allOf`, `oneOf` or `anyOf`) goes
under `body`. `Accept`,
`Content-Type` and `Authorization` header parameters are left to the
client. A schema longer than 16,384 characters is cut in `--help`, and the
heading says where.

## Coverage

| Part of a spec | Supported |
| - | - |
| Versions | OpenAPI 3.0 and 3.1; convert a Swagger 2.0 spec first |
| Request bodies | JSON (`application/json`, any `+json` type) and `application/x-www-form-urlencoded`, each field in its `encoding` (by default a list repeats its key; `deepObject` writes brackets); not multipart, binary, XML or plain text |
| Parameters | path, query and header; query styles `form`, `deepObject`, `spaceDelimited` and `pipeDelimited`; path and header style `simple`; not cookie parameters, `content` parameters, or the `label` and `matrix` styles |
| `$ref` | inside the document only, path items included; a cycle is cut |
| Auth | bearer, a header, a query parameter or basic; not OAuth2 flows |
| Servers | not read: every call goes to `base_url`; an operation that names servers of its own is refused |
| Responses | printed as received, one call per command; pagination is not followed |

An API whose spec uses something outside this list still installs when
`tags` or `operations` leave those operations out.

## What a spec must hold

An agent learns what a command does from its description, so every
selected operation needs one; a summary alone is not enough. Twilio's main
spec has 47 operations without one, and installing all of it is refused,
naming each:

```
OpenAPISpecError: operations that cannot become commands: list-address (no
description), create-address (no description), ...
```

Selecting operations that have one installs:
`operations: [ListCall, CreateCall, FetchCall]` gives `list-call`,
`create-call` and `fetch-call`.

The whole spec is refused, with `OpenAPISpecError` naming every operation
at fault, when any selected operation:

* has no description;
* sends a body other than JSON or `application/x-www-form-urlencoded`, or
  takes a cookie parameter;
* has a path that does not start with `/`;
* is a `TRACE`, or sends a body on `GET` or `HEAD`, which fetch cannot
  send;
* names servers of its own, other than the spec's;
* gives a form field an encoding other than the default while the form
  goes under `body` whole;
* has a parameter without a name, or one not in the path, query, header or
  cookie.

`openapiCli` also rejects with `OpenAPISpecError` when the spec cannot be read,
is not OpenAPI 3 (convert a Swagger 2.0 spec first), names a tag or an
operation it doesn't have, selects no operation or more than 1024, has a
path item or operation that is not a mapping, has a `$ref` outside the
document or to nothing, or has two operations that become one command. Narrow the selection with `tags`
or `operations` to leave an operation out.

## YAML specs on Cloudflare

Node and the browser read specs written in YAML. A Cloudflare Worker reads
JSON specs and carries no YAML parser, so its upload stays small; given a
YAML spec it refuses with `the spec is not JSON, and this host reads no
YAML; give the spec as JSON`. To read YAML specs there, install
[`yaml`](https://www.npmjs.com/package/yaml) and give it to core in the
Worker's entry, which adds about 100 KB to the Worker:

```ts src/worker.ts theme={null}
import { readYamlWith } from '@struktoai/mirage-core/core/openapi/spec'
import { parse } from 'yaml'

readYamlWith(parse)
```

## Authentication

| `auth` | Sent |
| - | - |
| `{ type: 'bearer', token: T }` | `Authorization: Bearer T` |
| `{ type: 'header', name: N, token: T }` | header `N: T` |
| `{ type: 'query', name: N, token: T }` | query parameter `N=T` |
| `{ type: 'basic', username: U, token: T }` | basic auth `U:T` |

Credentials go only to `base_url`: a call whose URL would leave its origin
is refused, and a redirect from the API is never followed. The spec is
fetched without them, following redirects unless it carries `headers`.
`base_url` must be an http(s) URL with a host and no query, fragment or
credentials, and https whenever `auth` or `headers` are set, unless the
host is local (`localhost`, `127.0.0.1`, `::1`). A basic `username` cannot
hold `:`. The token is redacted in snapshots.

`headers` adds headers to every call, for an API that wants a `User-Agent`
naming the caller, a version header or a tenant ID. The spec fetch carries
them too when the spec is on `base_url`'s origin. Auth wins over a header of
the same name; values are checked like the token and redacted in snapshots.

```ts theme={null}
const config = {
  spec: 'https://en.wikipedia.org/api/rest_v1/?spec',
  base_url: 'https://en.wikipedia.org/api/rest_v1',
  headers: { 'User-Agent': 'my-agent/1.0 (ops@example.com)' },
}
```

## Register from YAML

An API is a `clis:` entry with `cli: openapi`:

```yaml workspace.yaml theme={null}
mounts:
  /:
    vfs: ram
clis:
  github:
    cli: openapi
    machine: in_process
    config:
      spec: https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json
      base_url: https://api.github.com
      tags: [pulls]
      auth:
        type: bearer
        token:
          from: env
          key: GITHUB_TOKEN
```

`mirage workspace create workspace.yaml` builds it on the server, and
`configToWorkspaceArgs` reads each spec as it loads the file.

A config's `network:` also holds fetching the spec.

## Call an operation

| Call | Result |
| - | - |
| `github licenses-get '{"license": "mit"}'` | the response body on stdout, exit 0 |
| the API answers 400 or above | `licenses-get: HTTP <status>: <body>` on stderr, exit 1 |
| the API cannot be reached | `licenses-get: request failed: <reason>`, exit 1 |
| the API answers a redirect | `licenses-get: HTTP 302: redirect to <url> not followed`, exit 1 (in a browser, `HTTP 0` without the URL) |
| the operand is not one JSON object | `invalid JSON`, `JSON must be an object` or `takes one JSON object`, exit 2, nothing sent |
| a key no parameter or property takes, or a path value missing, empty, `.` or `..` | `unknown argument 'k'`, `missing 'k'` or `'k' cannot be '..'`, exit 2, nothing sent |
| a non-object value for a form body | `a form body must be an object`, exit 2, nothing sent |

A path value is percent-encoded whole, a list repeats its query parameter,
a `null` query or header value is left out, and a `null` body property is
sent as `null`, so a PATCH can clear a field; `{"body": null}` sends a
`null` body, while leaving `body` out sends none. A form field follows its
`encoding`: by default a list repeats its key (`tags=a&tags=b`) and an
object spreads its keys; `deepObject` writes brackets
(`metadata[plan]=pro`, as Stripe declares).

## Flags instead of a JSON string

With `flags: true` in its config, each subcommand takes one flag per
argument instead of a single JSON string, and sends the same request:

```
$ github licenses-get --license mit | jq -c '{key, name}'
{"key":"mit","name":"MIT License"}
```

| In the schema | The option |
| - | - |
| a property | `--` and its name in lower-case words joined by dashes: `pull_number` and `pullNumber` read `--pull-number`, `owner__path` reads `--owner-path`, a body taken whole is `--body`. Where two properties would read as one option, each keeps its own name (`--linodeId`, `--linode_id`) |
| a string, integer or number | `--x VALUE`; an integer or number is checked before anything is sent |
| an enum of strings | `--x {a,b}`, its choices checked |
| a type or `null` (`type: [T, "null"]`, or `anyOf`/`oneOf` of `T` and `null`) | the option of `T`; a plain option cannot send `null`, a JSON one can |
| a boolean | `--x` sends `true` and `--no-x` sends `false`; the last one typed wins. Where another property holds `--no-x`, `--x {true,false}` |
| a list of strings or numbers | the option repeats: `--tags a --tags b`; it cannot send an empty list |
| anything else: an object, a list of objects, or a union of several types | `--x JSON`, one JSON value, `null` included |
| a required property | a required option; a required boolean, `--x` or `--no-x` |

`--help` lists each option with its description's first line and default,
and ends with the schema of the JSON options. A long option is never
abbreviated. An option left out is not sent, and a plain option cannot send
`null`. An option the CLI refuses (unknown, missing its value, a required
one left out, a value outside its choices or not a number) and any operand
exit 2 with nothing sent. A snapshot keeps the setting.

## Profiles

A profile names an operation the way it names any CLI subcommand. `GET`,
`HEAD`, `OPTIONS` and `TRACE` operations run as reads; every other counts
as a write.

## Snapshots

A snapshot keeps the selected operations, so loading one rebuilds the CLI
without the spec. The token is redacted, so pass the config again:

```ts theme={null}
const ws = await Workspace.load('snap.tar', {}, {}, { github: config })
```

## Example

`examples/typescript/cli/openapi/` installs GitHub's REST API from its
published spec, runs reads that need no token, shows the whole spec
refused, and writes the same CLI out as a module with
`openapi_to_mirage.ts`. Run from `examples/typescript`:

```bash theme={null}
npx tsx cli/openapi/demo.ts
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.