### Run Ably Web CLI Example Source: https://github.com/ably/ably-cli/blob/main/examples/web-cli/README.md Navigate to the example directory and start the development server. Open the provided URL and enter your Ably API key when prompted. ```bash cd examples/web-cli pnpm dev ``` -------------------------------- ### Install @ably/react-web-cli Source: https://github.com/ably/ably-cli/blob/main/packages/react-web-cli/README.md Install the package using npm, yarn, or pnpm. ```bash # Using npm npm install @ably/react-web-cli # Using yarn yarn add @ably/react-web-cli # Using pnpm pnpm add @ably/react-web-cli ``` -------------------------------- ### Install Dependencies, Build, and Test Source: https://github.com/ably/ably-cli/blob/main/packages/react-web-cli/README.md Standard development commands for the package. Use `pnpm` for dependency management and building. ```bash pnpm install ``` ```bash pnpm build ``` ```bash pnpm test ``` -------------------------------- ### Debug Output Example Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Example of the comprehensive information displayed when debugging is enabled. ```bash === TEST DEBUG MODE ENABLED === Starting debug run at Wed Dec 18 10:30:45 PST 2024 Environment variables: E2E_DEBUG=true ABLY_CLI_TEST_SHOW_OUTPUT=true E2E_ABLY_API_KEY is configured ================================= === Test Execution Details === Test pattern: test/e2e/commands/rooms-e2e.test.ts Using Playwright: false Starting test execution at: Wed Dec 18 10:30:46 PST 2024 ============================== Cleaning up any existing processes... Process cleanup complete. ``` -------------------------------- ### Example: List Subcommands Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Shows how to use tab completion to list available subcommands for the 'accounts' command. ```bash # List all accounts subcommands ably accounts # Shows: current, list, login, logout, set ``` -------------------------------- ### Install Ably CLI Auto-completion Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Run this command to display installation instructions tailored to your shell. Follow the on-screen prompts to enable auto-completion. ```bash ably autocomplete ``` -------------------------------- ### Vercel CLI Deployment Source: https://github.com/ably/ably-cli/blob/main/examples/web-cli/DEPLOYMENT.md Navigate to the example directory and run the Vercel CLI to deploy. Follow the on-screen prompts to complete the deployment. ```bash cd examples/web-cli vercel ``` -------------------------------- ### Example: Complete Autocomplete Command Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Demonstrates how to use tab completion to finish typing the 'autocomplete' command. ```bash # Complete the autocomplete command ably autoc # Result: ably autocomplete ``` -------------------------------- ### Example: Navigate Nested Commands Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Demonstrates using tab completion to navigate through nested commands and discover available options. ```bash # Navigate nested commands ably inte rules # Result: ably integrations rules (and shows available subcommands) ``` -------------------------------- ### Install Ably CLI Source: https://github.com/ably/ably-cli/blob/main/README.md Install the Ably CLI globally using NPM. This command is required before using any Ably CLI functionalities. ```shell npm install -g @ably/cli ``` -------------------------------- ### Example: Complete a Flag Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Illustrates using tab completion to find and complete a flag for the 'channels publish' command. ```bash # Complete a flag ably channels publish --ch # Result: ably channels publish --channel-id ``` -------------------------------- ### Install Vercel CLI Source: https://github.com/ably/ably-cli/blob/main/examples/web-cli/DEPLOYMENT.md Install the Vercel Command Line Interface globally using npm. This is an optional prerequisite for deploying via CLI. ```bash npm i -g vercel ``` -------------------------------- ### Vercel Deployment Configuration Source: https://github.com/ably/ably-cli/blob/main/examples/web-cli/DEPLOYMENT.md Configuration file for Vercel deployment. Specifies build commands, output directory, install commands, framework, and rewrite rules for the Ably Web CLI example. ```json { "buildCommand": "cd ../.. && pnpm install && pnpm build:packages && cd examples/web-cli && pnpm build", "outputDirectory": "dist", "installCommand": "cd ../.. && pnpm install --frozen-lockfile", "framework": "vite", "rewrites": [ { "source": "/(.*)", "destination": "/index.html" } ] } ``` -------------------------------- ### Install Bash Auto-completion Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Execute this command to generate the bash completion script. Add the output to your `.bashrc` or `.bash_profile` to enable auto-completion for bash. ```bash ably autocomplete bash ``` -------------------------------- ### Install Zsh Auto-completion Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Run this command to generate the zsh completion script. Append the output to your `.zshrc` file to activate auto-completion for zsh. ```bash ably autocomplete zsh ``` -------------------------------- ### Install PowerShell Auto-completion Source: https://github.com/ably/ably-cli/blob/main/docs/Auto-completion.md Use this command to set up auto-completion for PowerShell. Follow the instructions provided to integrate the completion script into your PowerShell profile. ```powershell ably autocomplete powershell ``` -------------------------------- ### Start a Presence Command Process Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Initiate a presence command and wait for a confirmation message indicating the room entry. ```typescript import { startPresenceCommand } from '../../helpers/command-helpers.js'; const presenceRunner = await startPresenceCommand( ['rooms', 'presence', 'enter', 'my-room', '--client-id', 'user1'], /Entered room/, { timeoutMs: 20000 } ); // Process is ready when the promise resolves // Cleanup when done await presenceRunner.kill(); ``` -------------------------------- ### No App Specified Error Message Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Example of a direct output string for a common error condition when no application is specified. ```text 'No app specified. Use --app flag or select an app with "ably apps switch"' ``` -------------------------------- ### Define Product API Command Flags and Args Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Example of how to define arguments and flags for a Product API command. Imports necessary flag sets like `productApiFlags` and `clientIdFlag`. Use `Args.string` for the primary entity and include relevant flags based on command functionality. ```typescript import { productApiFlags, clientIdFlag, durationFlag, rewindFlag } from "../../flags.js"; static override args = { // entityName should always be camelCase for `Args.*`. entityName: Args.string({ description: "The primary entity being acted on", required: true, // or false if interactive fallback exists }), }; static override flags = { ...productApiFlags, ...clientIdFlag, // Only if command needs client identity ...durationFlag, // Only if long-running (subscribe/stream commands) ...rewindFlag, // Only if supports message replay // command-specific flags (modifiers only, NOT primary entity identifiers)... }; ``` -------------------------------- ### Start a Long-Running Subscriber Process Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Start a subscriber process, wait for a specific ready signal, and then wait for a particular message. ```typescript import { startSubscribeCommand, waitForOutput } from '../../helpers/command-helpers.js'; // Start a subscriber and wait for ready signal const subscriber = await startSubscribeCommand( ['channels', 'subscribe', 'my-channel', '--client-id', 'test-client'], /Connected to Ably and subscribed/, // Ready pattern { timeoutMs: 30000 } ); // Wait for specific output await waitForOutput(subscriber, 'Message received', 10000); // Cleanup await subscriber.kill(); ``` -------------------------------- ### Start Basic Interactive Mode Source: https://github.com/ably/ably-cli/blob/main/test/manual/interactive-mode-test.md Initiates the Ably CLI's interactive mode directly. Expect a welcome message, a command prompt, and inline command execution. Ctrl+C will display a warning, and 'exit' will quit. ```bash # Start interactive mode directly ./bin/run.js interactive ``` -------------------------------- ### Interactive Prompts in Wrapper Mode Source: https://github.com/ably/ably-cli/blob/main/test/manual/interactive-mode-test.md Tests interactive prompts (Y/N) within the bash wrapper mode. This example shows how to run a command like `apps create` that requires user confirmation and verifies that the input is processed correctly. ```bash # In wrapper mode ./bin/ably-interactive # Run a command that requires confirmation $ apps create test-app ``` -------------------------------- ### Start Interactive Mode with Bash Wrapper Source: https://github.com/ably/ably-cli/blob/main/test/manual/interactive-mode-test.md Launches the Ably CLI interactive mode using the bash wrapper for improved Ctrl+C handling. The welcome message appears only on the first run. Ctrl+C interrupts commands and restarts the CLI seamlessly without a welcome message. ```bash # Start with wrapper for seamless Ctrl+C handling ./bin/ably-interactive ``` -------------------------------- ### Implement Backend Signing Endpoint Source: https://github.com/ably/ably-cli/blob/main/packages/react-web-cli/README.md Example of a backend endpoint (Node.js/Express/Vercel) to generate signed credentials for the Ably Web CLI. Ensure your signing secret matches the terminal server's configuration. ```typescript import crypto from "crypto"; export default function handler(req, res) { const { apiKey } = req.body; const secret = process.env.SIGNING_SECRET; // From environment variable // Build config object const config = { apiKey, timestamp: Date.now(), }; // Sign it with HMAC-SHA256 const configString = JSON.stringify(config); const hmac = crypto.createHmac("sha256", secret); hmac.update(configString); const signature = hmac.digest("hex"); res.json({ signedConfig: configString, signature }); } ``` -------------------------------- ### Subscribe with message replay on attach Source: https://context7.com/ably/ably-cli/llms.txt When subscribing, replay the last N messages from the channel's history before starting to stream new messages. Useful for catching up on recent activity. ```bash # Replay the last 10 messages on attach, then listen for new ones ably channels subscribe --rewind 10 my-channel ``` -------------------------------- ### Define Control API Command Flags and Args Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Example of defining arguments and flags for a Control API command. Control API flags are automatically available via `ControlBaseCommand.globalFlags`. Use `Args.string` for the primary entity and add command-specific flags as needed. ```typescript // Control API command (apps, keys, queues, etc.) // controlApiFlags come from ControlBaseCommand.globalFlags automatically static args = { // entityName should always be camelCase for `Args.*` entityName: Args.string({ description: "The primary entity being acted on", required: true, }), }; static flags = { ...ControlBaseCommand.globalFlags, // command-specific flags (modifiers only, NOT primary entity identifiers)... }; ``` -------------------------------- ### Bash Wrapper for Interactive REPL Source: https://github.com/ably/ably-cli/blob/main/docs/Interactive-REPL.md A bash script that launches and manages the interactive Ably shell. It handles environment variable setup, auto-restarts on unexpected exits, and special exit code handling for user-initiated exits. ```bash #!/bin/bash # bin/ably-interactive # Configuration ABLY_BIN="$(dirname "$0")/run.js" ABLY_CONFIG_DIR="$HOME/.ably" HISTORY_FILE="$ABLY_CONFIG_DIR/history" EXIT_CODE_USER_EXIT=42 WELCOME_SHOWN=0 # Create config directory if it doesn't exist mkdir -p "$ABLY_CONFIG_DIR" 2>/dev/null || true # Initialize history file touch "$HISTORY_FILE" 2>/dev/null || true # Main loop while true; do # Run the CLI env ABLY_HISTORY_FILE="$HISTORY_FILE" \ ABLY_WRAPPER_MODE=1 \ ${ABLY_SUPPRESS_WELCOME:+ABLY_SUPPRESS_WELCOME=1} \ node "$ABLY_BIN" interactive EXIT_CODE=$? # Mark welcome as shown after first run WELCOME_SHOWN=1 export ABLY_SUPPRESS_WELCOME=1 # Check exit code case $EXIT_CODE in $EXIT_CODE_USER_EXIT) # User typed 'exit' break ;; 130) # SIGINT (Ctrl+C) - continue loop ;; 0) # Should not happen in interactive mode break ;; *) # Other error echo -e "\033[31m\nProcess exited unexpectedly (code: $EXIT_CODE)\033[0m" sleep 0.5 ;; esac done echo "Goodbye!" ``` -------------------------------- ### Set Up and Run E2E Ably CLI Tests Source: https://github.com/ably/ably-cli/blob/main/test/README.md Configure your Ably API key as an environment variable and then execute the end-to-end tests. Ensure the API key is in the correct format. ```bash # Set environment variable with your Ably API key export E2E_ABLY_API_KEY="your_app_id.your_key_id:your_key_secret" # Run E2E tests pnpm test test/e2e/ ``` -------------------------------- ### Display Ably CLI Help Source: https://github.com/ably/ably-cli/blob/main/README.md View a list of all available commands and their usage by running the help command. This is useful for discovering the CLI's capabilities. ```shell ably help ``` -------------------------------- ### Manage Multiple CLI Runners in a Test Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Start multiple CLI runners and ensure they are all cleaned up after the test logic, even if errors occur. ```typescript import { cleanupRunners } from '../../helpers/command-helpers.js'; const subscriber = await startSubscribeCommand([...]); const publisher = await startCli([...]); try { // Test logic here } finally { await cleanupRunners([subscriber, publisher]); } ``` -------------------------------- ### E2E Test Failure Debug Output Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Example of the detailed output provided automatically when an E2E test fails, including command details and captured output. ```text === E2E TEST FAILURE DEBUG === Test: should handle presence events Error: Timeout waiting for pattern "Action: enter" --- CLI Command: ably rooms presence subscribe my-room --client-id client1 --- STDOUT: Connecting to Ably... Connected to Ably Subscribing to presence events... STDERR: Warning: Connection took longer than expected Exit Code: null === END E2E TEST FAILURE DEBUG === ``` -------------------------------- ### New CLI Process Execution with Helper Functions Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Illustrates the new system's approach using helper functions for cleaner, promise-based process management and output waiting. This method avoids file I/O and race conditions. ```typescript const subscriber = await startSubscribeCommand( ['channels', 'subscribe', channelName], /Connected to Ably/, { timeoutMs: 15000 } ); // Clean, promise-based waiting await waitForOutput(subscriber, 'target event'); ``` -------------------------------- ### Updating TypeScript Type Definitions Source: https://github.com/ably/ably-cli/blob/main/docs/Troubleshooting.md Ensure your TypeScript type definitions are up to date by installing the latest `@types/node`. Use type assertions or add missing interface definitions when encountering type errors. ```typescript pnpm install @types/node@latest ``` ```typescript const result = (response as any).items as Item[] ``` ```typescript interface MyConfig { apiKey?: string controlHost?: string } ``` -------------------------------- ### Set Ably Credentials via Environment Variables Source: https://github.com/ably/ably-cli/blob/main/examples/web-cli/README.md Configure your Ably API key and access token by setting the `VITE_ABLY_API_KEY` and `VITE_ABLY_ACCESS_TOKEN` environment variables. ```bash VITE_ABLY_API_KEY=your-api-key VITE_ABLY_ACCESS_TOKEN=your-access-token ``` -------------------------------- ### JavaScript Initial Log Messages Source: https://github.com/ably/ably-cli/blob/main/test/manual/test-rate-limits.html Provides initial status messages and testing tips for the rate limit testing tool. Includes advice on using local or production WebSocket URLs and API key requirements. ```javascript // Initial log log('Rate limit testing tool ready', 'info'); log('Testing tips:', 'info'); log('- For localhost testing, use ws://localhost:8080 (rate limits are 50x higher)', 'info'); log('- For production testing, use wss://web-cli.ably.com', 'info'); log('- Provide a valid API key or the server will reject with code 4001', 'info'); log('', ''); log('Expected WebSoc' ``` -------------------------------- ### Ably CLI Quick Reference Commands Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Common commands for validating, testing, linting, and development within the Ably CLI project. ```bash # Full validation pnpm validate # Run specific test pnpm test test/unit/commands/interactive.test.ts # Lint specific file pnpm exec eslint src/commands/interactive.ts # Dev mode pnpm dev ``` -------------------------------- ### List Ably Apps as JSON Source: https://context7.com/ably/ably-cli/llms.txt Lists all Ably applications and returns the output in JSON format, suitable for programmatic processing. ```bash ably apps list --json ``` -------------------------------- ### List All Ably Apps Source: https://context7.com/ably/ably-cli/llms.txt Lists all Ably applications associated with the current account credentials. The currently selected app is highlighted in the output. ```bash ably apps list ``` -------------------------------- ### Configure Custom Ready Signal with RegEx Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Configure a custom ready signal for a CLI runner using a regular expression pattern. ```typescript // RegEx patterns const runner = await startCli(argv, outfile, { ready: { matcher: /Server started on port \d+/ } }); ``` -------------------------------- ### List Ably Apps with Limit Source: https://context7.com/ably/ably-cli/llms.txt Lists Ably applications, but limits the number of results returned to a specified quantity. ```bash ably apps list --limit 5 ``` -------------------------------- ### Linking the Ably CLI Locally Source: https://github.com/ably/ably-cli/blob/main/docs/Troubleshooting.md Link the Ably CLI globally to run it locally. Ensure the CLI is built using `pnpm prepare` before linking. ```bash pnpm link --global ``` ```bash pnpm prepare && pnpm link --global ``` -------------------------------- ### Unit Test Authentication - Correct Usage Source: https://github.com/ably/ably-cli/blob/main/docs/Testing.md Demonstrates the correct way to run unit tests without passing authentication flags, as MockConfigManager handles it automatically. Also shows how to access mock auth values. ```typescript // CORRECT — MockConfigManager handles it runCommand(["channels", "publish", "my-channel", "hello"]); // CORRECT — access mock auth values when needed import { getMockConfigManager } from "../../helpers/mock-config-manager.js"; const mockConfig = getMockConfigManager(); const apiKey = mockConfig.getApiKey()!; ``` -------------------------------- ### Fetch channel history with pagination info Source: https://context7.com/ably/ably-cli/llms.txt Fetches channel history in ascending order and outputs JSON with pagination information. Use `--direction forwards` for ascending order. ```bash ably channels history --direction forwards --json my-channel ``` -------------------------------- ### Use environment variable for API key during publish Source: https://context7.com/ably/ably-cli/llms.txt Demonstrates how to use the `ABLY_API_KEY` environment variable for authentication when publishing messages. This avoids needing to pass the key as a flag. ```bash # Use environment variable for the API key ABLY_API_KEY="YOUR_APP.KEY_ID:KEY_SECRET" \ ably channels publish my-channel '{"data":"env key used"}' ``` -------------------------------- ### Enable Debugging via Query String Source: https://github.com/ably/ably-cli/blob/main/packages/react-web-cli/README.md Add `?cliDebug=true` to the page URL to enable verbose logging before the component mounts. This flag can be combined with other query parameters. ```url http://localhost:5173/?cliDebug=true ``` -------------------------------- ### Configure Custom Ready Signal with JSON Path Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Configure a custom ready signal for a CLI runner using JSON path detection. ```typescript // JSON path detection const runner = await startCli(argv, outfile, { ready: { matcher: '{"status":"ready"}', jsonPath: 'status' } }); ``` -------------------------------- ### Run All Ably CLI Tests Source: https://github.com/ably/ably-cli/blob/main/test/README.md Execute all available test suites, including unit, integration, and end-to-end tests, with a single command. ```bash pnpm test ``` -------------------------------- ### Legacy CLI Process Execution Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Demonstrates the legacy method of running a background process and manually polling its output. This approach is prone to race conditions and errors. ```typescript const outputPath = await createTempOutputFile(); const processInfo = await runLongRunningBackgroundProcess( `bin/run.js channels subscribe ${channelName}`, outputPath, { readySignal: "Connected to Ably", timeoutMs: 15000 } ); // Manual polling for output for (let i = 0; i < 50; i++) { const output = await readProcessOutput(outputPath); if (output.includes('target event')) break; await new Promise(resolve => setTimeout(resolve, 200)); } ``` -------------------------------- ### Enable Debugging via Runtime Global Flag Source: https://github.com/ably/ably-cli/blob/main/packages/react-web-cli/README.md From the browser DevTools console, set `window.ABLY_CLI_DEBUG = true;` to enable verbose logging before the component mounts. Remove the flag or refresh without the query parameter to return to silent mode. ```javascript window.ABLY_CLI_DEBUG = true; ``` -------------------------------- ### `ably apps list` Source: https://context7.com/ably/ably-cli/llms.txt Lists all applications visible to the configured account credentials via the Ably Control API. The currently selected app is highlighted. ```APIDOC ## `ably apps list` — List all Ably apps in the current account ### Description Lists all applications visible to the configured account credentials via the Ably Control API. The currently selected app is highlighted. ### Usage Examples # List all apps ```bash ably apps list # Found 3 apps: # ▶ App ID: abc123 (current) # Name: Production # Status: enabled # ... ``` # List apps as JSON ```bash ably apps list --json # {"apps":[{"id":"abc123","name":"Production","status":"enabled","isCurrent":true,...}],"hasMore":false} ``` # Limit the result set ```bash ably apps list --limit 5 ``` ``` -------------------------------- ### Ably CLI Project Structure Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Overview of the Ably CLI npm package directory structure, built with the oclif framework. ```tree .\n├── src/ # CLI commands (oclif) │ ├── commands/ # Business logic │ ├── services/ # Utilities │ ├── utils/ # base-command.ts │ └── base-command.ts ├── test/ # Fast, mocked │ ├── unit/ # Multi-component, mocked external services │ ├── integration/ # Full scenarios against real Ably │ ├── e2e/ # runCommand(), MockConfigManager, etc. │ └── helpers/ # Project docs (Testing.md, Project-Structure.md, etc.) ├── docs/ # Scripts defined here └── package.json # ``` -------------------------------- ### Subscribe with delta compression enabled Source: https://context7.com/ably/ably-cli/llms.txt Enable delta compression (VCDIFF) for the subscription to reduce bandwidth usage. This is particularly useful for high-traffic channels or metered connections. ```bash # Enable delta compression to reduce bandwidth ably channels subscribe --delta my-channel ``` -------------------------------- ### AblyCliTerminalHandle Methods Source: https://context7.com/ably/ably-cli/llms.txt The `AblyCliTerminalHandle` interface provides methods for programmatic control over the terminal instance, such as managing split-screen functionality. ```APIDOC ## AblyCliTerminalHandle ### Description Interface for programmatic control of the `AblyCliTerminal` component. ### Methods - **enableSplitScreen()** - Description: Opens the secondary pane. Has no effect if the `enableSplitScreen` prop is `false`. - **disableSplitScreen()** - Description: Closes the secondary pane. - **toggleSplitScreen()** - Description: Toggles between a single-pane and split-pane view. - **setSplitPosition(percent: number)** - Description: Sets the divider position for the split screen. Accepts a percentage value between 0 and 100 (inclusive), which will be clamped to the valid range. - Parameters: - **percent** (number) - The desired split position percentage (0-100). - **getSplitState()** - Description: Returns the current state of the split screen. - Returns: `{ isSplit: boolean; splitPosition: number }` - **isSplit** (boolean) - Indicates if the terminal is currently in a split view. - **splitPosition** (number) - The current position of the split divider in percentage. ``` -------------------------------- ### Enable Diagnostics and Run Interactive Mode Source: https://github.com/ably/ably-cli/blob/main/test/manual/manual-test-instructions.md Enables diagnostic logging and runs the interactive CLI mode. Use this to test direct execution and observe errors when Ctrl+C is pressed during a wait command. ```bash # Enable diagnostics export TERMINAL_DIAGNOSTICS=1 export DEBUG_SIGINT=1 # Run interactive mode directly node bin/run.js interactive # When you see the prompt: # 1. Type: test:wait --duration 10 # 2. Press Ctrl+C while it's waiting # 3. Note any error messages ``` -------------------------------- ### Ably CLI Error Handling Flow Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Illustrates the flow of fatal errors through `this.fail()` and `this.error()`. `this.fail()` is the single entry point for all fatal errors, ensuring consistent behavior. ```text this.fail(): never ← the single funnel (logs event, emits JSON, exits) ↓ internally calls this.error() ← oclif exit (ONLY inside fail, nowhere else) ``` -------------------------------- ### Show CLI Command Output During Tests Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Use the --show-output flag to display CLI command output during E2E test execution. ```bash pnpm test:e2e --show-output ``` -------------------------------- ### Subscribe to a single Ably channel Source: https://context7.com/ably/ably-cli/llms.txt Attach to a channel using a Realtime connection and stream incoming messages to standard output. Press Ctrl+C to stop the subscription. The output includes timestamps and event details. ```bash # Subscribe to a single channel (Ctrl+C to stop) ably channels subscribe my-channel # ✓ Subscribed to channel: my-channel. # Listening for messages. # # [14:23:01.456] Channel: my-channel | Event: order.created # Data: {"orderId":"abc-123","total":49.99} ``` -------------------------------- ### Mocking WebSocket Connections for Tests Source: https://github.com/ably/ably-cli/blob/main/docs/Troubleshooting.md Properly mock WebSocket connections using `vi.fn()` and `global.WebSocket` to simulate connection behavior in tests. Remember to clean up by deleting the global mock after each test. ```typescript // Example of properly mocking a WebSocket connection beforeEach(() => { // Create a fake WebSocket implementation const fakeWebSocketInstance = { addEventListener: vi.fn(), removeEventListener: vi.fn(), send: vi.fn(), close: vi.fn(), } // Mock the WebSocket constructor global.WebSocket = vi.fn().mockReturnValue(fakeWebSocketInstance) as any }) afterEach(() => { // Clean up delete (global as any).WebSocket }) ``` -------------------------------- ### Show Output via Environment Variable Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Set the ABLY_CLI_TEST_SHOW_OUTPUT environment variable to true to display CLI command output during tests. ```bash ABLY_CLI_TEST_SHOW_OUTPUT=true ``` -------------------------------- ### Mandatory Workflow for Ably CLI Changes Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Run these commands in order for every change to ensure the work is complete and meets project standards. Skipping these steps means the work is not considered complete. ```bash pnpm prepare # 1. Build + update manifest pnpm generate-doc # 2. Regenerate docs (gitignored) pnpm exec eslint . # 3. Lint (MUST be 0 errors) pnpm test:unit # 4. Test (at minimum) pnpm test:tty # 5. TTY tests (local only, skip in CI) # 6. Update docs if needed ``` -------------------------------- ### Run Web CLI Ably Tests Source: https://github.com/ably/ably-cli/blob/main/test/README.md Execute all web CLI browser tests or run them in parallel groups for faster feedback. Specific groups like auth, session, or UI can be targeted. ```bash pnpm test:web-cli ``` ```bash pnpm test:web-cli:parallel # All groups ``` ```bash pnpm test:web-cli:parallel:auth # Auth tests only ``` ```bash pnpm test:web-cli:parallel:session # Session tests only ``` ```bash pnpm test:web-cli:parallel:ui # UI tests only ``` -------------------------------- ### Run Specific Ably CLI Test Files or Named Tests Source: https://github.com/ably/ably-cli/blob/main/test/README.md Execute a single test file using its path or run tests matching a specific name pattern using a grep filter. Specify the project if necessary. ```bash pnpm test:unit test/unit/commands/channels/list.test.ts ``` ```bash pnpm vitest --project unit --grep "should publish" ``` -------------------------------- ### Pass Ably Credentials via URL Parameters Source: https://github.com/ably/ably-cli/blob/main/examples/web-cli/README.md Authenticate by passing your Ably API key and access token directly as URL parameters when accessing the application. ```bash http://localhost:5173?apiKey=your-api-key&accessToken=your-access-token ``` -------------------------------- ### Handling Test Failures in Ably CLI Source: https://github.com/ably/ably-cli/blob/main/AGENTS.md Demonstrates the correct way to skip tests when they fail. Always document the reason for skipping. ```typescript // WRONG it.skip('test name', () => { // CORRECT - Document why it.skip('should handle Ctrl+C on empty prompt', function(done) { // SKIPPED: This test is flaky in non-TTY environments // The readline SIGINT handler doesn't work properly with piped stdio ``` -------------------------------- ### Publish Push Notification with JSON Output Source: https://context7.com/ably/ably-cli/llms.txt Publishes a push notification to a channel and outputs the result in JSON format. The `--force` flag is required when using `--channel` with `--json`. ```bash ably push publish --force --json \ --channel alerts \ --title "Alert" --body "See details in app" ``` -------------------------------- ### Rapid Ctrl+C Testing in Prompt Source: https://github.com/ably/ably-cli/blob/main/test/manual/interactive-mode-test.md Tests the stability of the interactive shell when Ctrl+C is pressed multiple times rapidly while at the prompt. The shell should remain stable without crashing or exiting unexpectedly, though multiple warning messages might appear. ```bash ./bin/ably-interactive # Press Ctrl+C multiple times rapidly at the prompt ``` -------------------------------- ### Debug CLI Locally with Node Inspector Source: https://github.com/ably/ably-cli/blob/main/docs/Debugging.md Run the Ably CLI with the Node.js inspector enabled to attach a debugger. This is useful for stepping through CLI execution and inspecting variables. ```bash node --inspect-brk bin/run.js [your command and flags] ``` -------------------------------- ### Enable Detailed Debugging Output Source: https://github.com/ably/ably-cli/blob/main/docs/E2E-Testing-CLI-Runner.md Use the --debug flag to enable detailed debugging output for E2E tests. ```bash pnpm test:e2e --debug ``` -------------------------------- ### Override Configuration with Environment Variables Source: https://github.com/ably/ably-cli/blob/main/docs/Debugging.md Temporarily override Ably CLI configuration, such as the API key, using environment variables for testing purposes. This avoids modifying the actual configuration file. ```bash ABLY_API_KEY=your_key ably channels list ``` -------------------------------- ### `ably auth issue-ably-token` Source: https://context7.com/ably/ably-cli/llms.txt Creates an Ably Token (not a Token Request) from the configured API key. Supports custom capability scopes, TTL, and an optional client ID. The `--token-only` flag prints just the token string, making it easy to pipe into other commands. ```APIDOC ## `ably auth issue-ably-token` — Create a short-lived Ably Token ### Description Creates an Ably Token (not a Token Request) from the configured API key. Supports custom capability scopes, TTL, and an optional client ID. The `--token-only` flag prints just the token string, making it easy to pipe into other commands. ### Usage ```bash # Issue a token valid for 1 hour with full wildcard capability (default) ably auth issue-ably-token # Issue a scoped token for specific channels, valid 24 hours ably auth issue-ably-token \ --capability '{"orders:*":["publish","subscribe"],"status":["subscribe"]}' \ --ttl 86400 # Issue a token for a known client, output only the token string ably auth issue-ably-token --client-id "user-42" --token-only # Pipe the token into a publish command ABLY_TOKEN="$(ably auth issue-ably-token --token-only)" \ ably channels publish my-channel "Sent with a token" # Issue a token without a client ID and output JSON ably auth issue-ably-token --client-id "none" --json ``` ### Example Output (JSON) ```json {"token":{"value":"...","issuedAt":"...","expiresAt":"...","capability":{"*":["*"]}}} ``` ``` -------------------------------- ### Additional Debugging Commands for Terminal and Node.js Source: https://github.com/ably/ably-cli/blob/main/test/manual/manual-test-instructions.md A collection of utility commands for debugging terminal and Node.js environments. Includes commands to clean up processes, reset the terminal, check Node.js version, and verify the terminal type. ```bash # Clean up any stale processes pkill -f "ably-interactive" # Reset terminal if corrupted reset # Check Node.js version node --version # Check terminal type echo $TERM ``` -------------------------------- ### Publish a plain-text message to an Ably channel Source: https://context7.com/ably/ably-cli/llms.txt Use this command to send a simple string message to a specified channel. The output confirms the message was published and provides its serial number. ```bash # Publish a plain-text message ably channels publish my-channel "Hello World" # Expected output: # ✓ Message published to channel: my-channel. # Serial: 108TEejKCdL... ``` -------------------------------- ### Run Interactive Mode with Wrapper Script Source: https://github.com/ably/ably-cli/blob/main/test/manual/manual-test-instructions.md Executes the interactive CLI using a wrapper script with diagnostics enabled. This test focuses on observing the 'setRawMode EIO' error when the wrapper attempts to restart after a Ctrl+C interruption. ```bash # Keep diagnostics enabled export TERMINAL_DIAGNOSTICS=1 export DEBUG_SIGINT=1 # Run with wrapper bin/ably-interactive # When you see the prompt: # 1. Type: test:wait --duration 10 # 2. Press Ctrl+C while it's waiting # 3. Watch for "setRawMode EIO" error when wrapper tries to restart ```