CLI Architecture Overview
Relevant source files
The following files were used as context for generating this wiki page:
The Resend CLI provides a terminal-based interface for interacting with the Resend platform, enabling users to send emails, manage domains, and configure account resources. It is built using the commander library and supports both interactive terminal usage and automated environments like CI/CD pipelines. The architecture prioritizes secure credential handling, flexible output formatting (plain text vs. JSON), and robust error reporting.
The CLI serves as an orchestrator that resolves authentication, parses user input via subcommands, executes requests against the Resend API, and formats the response according to the environment's capabilities. It includes specific protocols for non-TTY environments to ensure silent failures do not occur during automated tasks.
Sources: src/cli.ts, skills/resend-cli/SKILL.md
Command Execution and Routing
The CLI utilizes a hierarchical command structure where a main program routes requests to specific modules. Each major feature set (e.g., emails, domains, templates) is organized into command groups. The src/cli.ts file acts as the entry point, registering all available commands and global options.
Global Options and Hooks
The program configures global behavior through options that modify output and storage behavior:
--api-key <key>: Overrides stored credentials for a single command.--profile <name>: Selects a specific authentication profile.--json: Forces output in JSON format.--quiet/-q: Suppresses visual progress indicators and implies JSON output.
A preAction hook extracts these flags and sets environment variables or configuration values before the specific command logic executes. For instance, if the --quiet flag is detected, the program automatically enables JSON mode to maintain compatibility with scripting.
Sources: src/cli.ts:46-64, src/cli.ts:74-98
Lifecycle Flow
The following diagram illustrates the lifecycle of a typical command execution from initialization to completion.
The diagram shows the sequence of operations within the CLI, highlighting the global hooks and the standard action flow.
Sources: src/cli.ts:133-176, src/lib/cli-exit.ts
Authentication Subsystem
Authentication is managed through a resolution hierarchy that prioritizes immediate user input over persisted data. The CLI supports standard API keys and OAuth2 flows with PKCE.
Credential Resolution Logic
The system resolves credentials in the following order:
- Command Flags: Explicit
--api-keypassed during execution. - Environment Variables:
RESEND_API_KEYdefined in the shell. - Persisted Configuration: Credentials stored in
credentials.jsonor secure system storage (keychain).
Sources: src/commands/whoami.ts:42-46, skills/resend-cli/SKILL.md:61-63
OAuth and Token Management
For browser-based login, the CLI implements an OAuth2 flow. It starts a local HTTP server to capture the callback code and uses PKCE (Proof Key for Code Exchange) to secure the exchange.
| Component | Function |
|---|---|
generatePKCE() | Generates codeVerifier, codeChallenge, and state. |
createCallbackServer() | Spawns a temporary http server on 127.0.0.1 to listen for the redirect. |
refreshOAuthGrant() | Checks JWT expiration and performs a refresh_token grant if the token is near expiry. |
exchangeAuthorizationCode() | Exchanges the capture code for access and refresh tokens via the /oauth/token endpoint. |
Sources: src/lib/oauth.ts:107-133, src/lib/oauth.ts:172-181, src/lib/oauth.ts:271-290
This sequence details the PKCE-secured OAuth flow used during resend login.
Sources: src/lib/oauth.ts:200-269
Health and Diagnostic System
The CLI includes built-in diagnostics to verify the local environment and API connectivity. This is primarily handled by the doctor and whoami commands.
The Doctor Command
The doctor command performs a series of checks to ensure the CLI is functional. It returns a structured report containing the status (pass, warn, or fail) of various components.
| Check Name | Logic | Source |
|---|---|---|
| CLI Version | Fetches the latest release from GitHub to check for updates. | checkCliVersion |
| API Key | Verifies a key exists in environment or config without making network calls. | checkApiKeyPresence |
| Credential Storage | Identifies if credentials are in secure storage or a plaintext file. | doctorCommand.action |
| API Validation | Exercises the key by attempting to list domains from the Resend API. | checkApiValidationAndDomains |
Sources: src/commands/doctor.ts:43-91, src/commands/doctor.ts:133-149, src/commands/doctor.ts:245-271
User Identity (whoami)
The whoami command provides a local-only view of the current session. It identifies the active profile, the source of the API key, and the configuration file path. It specifically avoids network calls to remain functional in offline environments.
Sources: src/commands/whoami.ts:39-71
Output and Interaction Patterns
The CLI dynamically adjusts its interaction model based on whether the output stream is a TTY (terminal).
Output Formatting
- TTY (Interactive): Uses spinners (via
clack/prompts), colorized text (viapicocolors), and interactive prompts for missing required flags. - Non-TTY / JSON Mode: Suppresses all decorative elements. Success responses are written to
stdoutas JSON, while errors are written tostderras JSON.
Sources: src/cli.ts:178-185, skills/resend-cli/SKILL.md:43-52
Input Processing Logic
Commands like emails send and templates create share common input resolution patterns:
- Flag Parsing: Read direct command-line arguments.
- File Reading: Read content from paths provided in flags (e.g.,
--html-file). - Stdin Support: Use
"-"as a file path to read content from the standard input stream. - React Email Bundling: If
--react-emailis provided, the CLI bundles and renders the.tsxfile into HTML before sending.
Sources: src/commands/emails/send.ts:223-239, src/commands/templates/create.ts:109-118
Error Handling
The CLI uses a centralized exit handler to manage process termination. Errors are categorized by codes (e.g., auth_error, missing_body, send_error) to allow agents and scripts to programmatically handle failures.
Sources: src/lib/cli-exit.ts, src/commands/emails/send.ts:100-116
The architecture of resend-cli ensures that every command follows a predictable path of authentication, validation, and standardized output, making it suitable for both human developers and automated systems.
Sources: src/cli.ts, skills/resend-cli/SKILL.md