### Full Ace Application Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md A comprehensive example demonstrating Ace kernel setup, including defining flags, adding aliases, configuring loaders, setting metadata, and using hooks. ```typescript // main.ts import { Kernel } from '@adonisjs/ace' import { FsLoader } from '@adonisjs/ace' async function main() { const kernel = Kernel.create() // Setup kernel.defineFlag('debug', { type: 'boolean', description: 'Enable debug mode' }) kernel.addAlias('m', 'make:model') kernel.addAlias('mig', 'migrate:run') // Loaders kernel.addLoader(new FsLoader('./build/commands')) // Metadata kernel.info.set('appName', 'My CLI') kernel.info.set('appVersion', '1.0.0') // Hooks kernel.executed((instance) => { if (instance.error) { console.error('Command failed') } }) // Run await kernel.handle(process.argv.slice(2)) process.exit(kernel.exitCode ?? 0) } main().catch((error) => { console.error(error) process.exit(1) }) ``` -------------------------------- ### Minimum Example: Greet Command Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/overview.md A basic example demonstrating how to create a command with a string argument, register it with the kernel, and handle CLI input. This showcases the core components of an Ace command. ```typescript import { Kernel, BaseCommand, args } from '@adonisjs/ace' class GreetCommand extends BaseCommand { static commandName = 'greet' static description = 'Greet someone' @args.string() declare name: string async run() { this.logger.info(`Hello, ${this.name}!`) } } const kernel = Kernel.create() kernel.addLoader({ getMetaData: () => [GreetCommand.serialize()], getCommand: () => GreetCommand }) await kernel.handle(process.argv.slice(2)) process.exit(kernel.exitCode ?? 0) ``` -------------------------------- ### Basic Ace Kernel Setup Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md This snippet shows the basic setup for an Ace kernel, including adding command loaders and handling incoming arguments. The default ExceptionHandler is automatically used. ```typescript import { Kernel } from '@adonisjs/ace' import { FsLoader } from '@adonisjs/ace' const kernel = Kernel.create() kernel.addLoader(new FsLoader('./commands')) await kernel.handle(process.argv.slice(2)) process.exit(kernel.exitCode ?? 0) ``` -------------------------------- ### Listen for Command Execution Start Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Registers a callback to be executed just before a command's execution begins. Useful for pre-execution setup or logging. ```typescript kernel.executing((instance) => { console.log(`Executing: ${instance.commandName}`) }) ``` -------------------------------- ### ListCommand Usage Examples Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/commands.md Demonstrates how to invoke the ListCommand to view all available commands, either by default or explicitly. ```bash # Show all commands node ace # Explicitly run list command node ace list # Show help for list command node ace help list ``` -------------------------------- ### Instantiate BaseCommand Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Example of creating a new command instance using the constructor with necessary dependencies. ```typescript const instance = new MyCommand(kernel, parsed, ui, prompt) ``` -------------------------------- ### HelpCommand Usage Examples Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/commands.md Illustrates how to invoke the HelpCommand to view help for specific commands or the default command. ```bash # View help for specific command node ace help make:model node ace make:model --help node ace make:model -h # View help for the default command node ace help ``` -------------------------------- ### Example Output: Command Not Found with Suggestions Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md Shows the console output when a command is not found, including suggestions for similar commands. ```text ERROR Command "mak:model" is not defined Did you mean one of the following? make:model make:migration ``` -------------------------------- ### Kernel Integration Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md Shows how the Ace kernel automatically uses an ExceptionHandler and how to customize it. ```typescript const kernel = Kernel.create() // Handler is set by default console.log(kernel.errorHandler instanceof ExceptionHandler) // true // Customize it kernel.errorHandler = new CustomExceptionHandler() // Used during handle() try { await kernel.handle(process.argv.slice(2)) } catch (error) { // Errors are rendered here by kernel } ``` -------------------------------- ### Rendering Example with Exception Handling Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md Illustrates how to use the ExceptionHandler to render errors caught during kernel command execution. ```typescript const handler = new ExceptionHandler() try { await kernel.handle(process.argv.slice(2)) } catch (error) { await handler.render(error, kernel) } ``` -------------------------------- ### commands.json Structure Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/index-generator.md Example of the JSON file generated by IndexGenerator, containing metadata for all commands. ```json { "version": 1, "commands": [ { "commandName": "make:model", "description": "Create a new model", "namespace": "make", "aliases": ["make:m", "m"], "args": [ { "name": "name", "argumentName": "name", "type": "string", "required": true, "description": "Model name" } ], "flags": [ { "name": "migration", "flagName": "migration", "type": "boolean", "default": false } ], "options": { "allowUnknownFlags": false }, "filePath": "make/model.js" } ] } ``` -------------------------------- ### Example Command Implementation Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Demonstrates overriding the run method in a subclass to define command logic, including argument handling and logging. ```typescript export class MakeCommand extends BaseCommand { @args.string() declare name: string async run() { this.logger.info(`Creating model: ${this.name}`) return { created: true } } } ``` -------------------------------- ### Example Output: Prompt Cancelled Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md Displays the console output when a user cancels an interactive prompt. ```text ERROR Prompt cancelled ``` -------------------------------- ### Example Output: Missing Required Argument Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md Illustrates the console output for a missing required argument error when handled by the ExceptionHandler. ```text ERROR Missing required argument "name" ``` -------------------------------- ### Combined AdonisJS ACE Command Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/decorators.md This example demonstrates a comprehensive AdonisJS ACE command using various decorators for arguments (string, spread) and flags (boolean, string, number, array). It shows how to define different types of inputs and access them within the command's `run` method. ```typescript import { BaseCommand } from '@adonisjs/ace' import { args } from '@adonisjs/ace' import { flags } from '@adonisjs/ace' export class GenerateCommand extends BaseCommand { static commandName = 'generate' static description = 'Generate scaffolding' // Positional arguments @args.string({ description: 'Type of thing to generate' }) declare type: string @args.string({ description: 'Name for the generated thing', required: false, default: 'default' }) declare name?: string @args.spread({ description: 'Additional files to generate', required: false }) declare files?: string[] // Named options @flags.boolean({ description: 'Skip confirmations', alias: 'f' }) declare force: boolean @flags.string({ description: 'Output directory', alias: 'o', default: './' }) declare output?: string @flags.number({ description: 'Number of items', default: 1 }) declare count: number @flags.array({ description: 'Tags to apply' }) declare tags?: string[] async run() { console.log(`Generating ${this.type}`) console.log(`Name: ${this.name}`) console.log(`Files: ${this.files}`) console.log(`Force: ${this.force}`) console.log(`Output: ${this.output}`) console.log(`Count: ${this.count}`) console.log(`Tags: ${this.tags}`) } } // Usage: node ace generate model User --name=User --force -o ./app/models --count=5 --tags=active --tags=admin ``` -------------------------------- ### ListLoader Constructor Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Creates a ListLoader by providing an array of command class constructors. This is useful for programmatic command registration. ```typescript import { ListLoader } from '@adonisjs/ace' import { MakeModelCommand } from './commands/make-model' import { MakeMigrationCommand } from './commands/make-migration' const loader = new ListLoader([ MakeModelCommand, MakeMigrationCommand ]) ``` -------------------------------- ### Organize Commands with Namespaces Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Illustrates how to structure command files within directories to create command namespaces. For example, `commands/make/model.ts` becomes the `make:model` command. ```text commands/ ├── make/ │ ├── model.ts → make:model │ └── migration.ts → make:migration ├── db/ │ ├── seed.ts → db:seed │ └── create.ts → db:create └── serve.ts → serve ``` -------------------------------- ### Define and Run a Simple Greet Command Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/README.md Defines a basic 'greet' command using BaseCommand and decorators, then configures the Kernel to load and execute it with provided arguments. Ensure you have @adonisjs/ace installed. ```typescript import { Kernel, BaseCommand, args } from '@adonisjs/ace' class GreetCommand extends BaseCommand { static commandName = 'greet' static description = 'Greet someone' @args.string({ description: 'Name' }) declare name: string async run() { this.logger.info(`Hello, ${this.name}!`) } } const kernel = Kernel.create() kernel.addLoader({ getMetaData: () => [GreetCommand.serialize()], getCommand: () => GreetCommand }) await kernel.handle(process.argv.slice(2)) process.exit(kernel.exitCode ?? 0) ``` ```bash node app.ts greet Alice # Output: Hello, Alice! ``` -------------------------------- ### FsLoader getMetaData Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Retrieves metadata for all discovered commands from the specified directory. Useful for listing available commands. ```typescript const loader = new FsLoader('./build/commands') const metadata = await loader.getMetaData() metadata.forEach(cmd => { console.log(`${cmd.commandName}: ${cmd.description}`) console.log(` File: ${cmd.filePath}`) }) ``` -------------------------------- ### Postbuild Script for Index Generation Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/index-generator.md Example of a package.json script and a corresponding Node.js file to generate command index artifacts after compilation. ```json { "scripts": { "build": "tsc", "postbuild": "node build-commands.js" } } ``` ```typescript import { IndexGenerator } from '@adonisjs/ace' const generator = new IndexGenerator('./build/commands') await generator.generate() console.log('Commands index generated successfully') ``` -------------------------------- ### Implement Custom Help Command Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/commands.md Create a custom 'help' command by extending `BaseCommand`. This example demonstrates how to access command information from the kernel and provide custom help output. Register the custom command with the Ace kernel to override the default behavior. ```typescript import { BaseCommand } from '@adonisjs/ace' export class MyHelpCommand extends BaseCommand { static commandName = 'help' static description = 'Custom help command' @args.string({ description: 'Command name' }) declare name: string async run() { // Custom help implementation const command = this.kernel.getCommand(this.name) if (!command) { this.logger.error(`Command "${this.name}" not found`) return } this.logger.info(`Help for: ${command.description}`) } } // Register with kernel instead of default const executor = Kernel.commandExecutor const kernel = new Kernel(MyHelpCommand, executor) ``` -------------------------------- ### Help Flag Integration Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/commands.md Explains the automatic integration of the --help/-h flag with the Ace kernel, showing how it triggers the HelpCommand to display command-specific help. ```typescript // User runs: node ace make:model --help // 1. Kernel detects --help flag // 2. Triggers help flag listener // 3. Converts to: node ace help make:model // 4. Executes HelpCommand // 5. Displays help for make:model ``` -------------------------------- ### Define String Argument Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Example of defining a required string argument for a command. ```typescript @args.string({ description: 'Name' }) declare name: string ``` -------------------------------- ### FsLoader getCommand Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Fetches a command class constructor based on its metadata. This is typically used after retrieving metadata to instantiate the command. ```typescript const loader = new FsLoader('./commands') const metadata = await loader.getMetaData() for (const meta of metadata) { const Command = await loader.getCommand(meta) if (Command) { const instance = new Command(kernel, parsed, ui, prompt) } } ``` -------------------------------- ### Instantiate Parser with Flags and Arguments Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/parser.md Create a new Parser instance by providing configuration for flags and arguments. This example shows how to define all flags, specify types (string, boolean, number), set aliases, provide default values, and use custom coercion functions for flags, alongside defining string and spread arguments with defaults. ```typescript const parser = new Parser({ flagsParserOptions: { all: ['connection', 'force', 'count'], string: ['connection'], boolean: ['force'], number: ['count'], alias: { connection: 'c' }, default: { force: false }, coerce: { count: (val) => parseInt(val) }, }, argumentsParserOptions: [ { type: 'string', default: 'User' }, { type: 'spread' }, ] }) ``` -------------------------------- ### FsLoader File Filtering Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Shows how to use a custom filter with FsLoader to ignore specific files, such as test files. ```typescript // Ignore test files const loader = new FsLoader('./commands', (filePath) => { return !filePath.includes('.test.') }) ``` -------------------------------- ### Spread Argument Parsing Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/decorators.md Demonstrates how a parser can interpret arguments, including a spread argument, with specified types and default values. ```javascript const parser = new Parser({ flagsParserOptions: { all: [] }, argumentsParserOptions: [ { type: 'string' }, { type: 'spread', default: [] } ] }) const result = parser.parse(['npm', 'lodash', 'axios', 'moment']) // result.args = ['npm', ['lodash', 'axios', 'moment']] ``` -------------------------------- ### FsLoader Specific Pattern Filtering Example Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Demonstrates filtering files with FsLoader to only load those matching a specific naming convention. ```typescript // Only load specific pattern const loader = new FsLoader('./commands', (filePath) => { return filePath.endsWith('.command.ts') || filePath.endsWith('.command.js') }) ``` -------------------------------- ### Boot Kernel and Get Commands Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Loads all commands from registered loaders and retrieves the list of loaded commands. Must be called before handling commands. ```typescript async boot(): Promise ``` ```typescript await kernel.boot() const commands = kernel.getCommands() ``` -------------------------------- ### Example Output: Unknown Error in Debug Mode Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md Demonstrates the detailed, pretty-printed error output using Youch when an unknown error occurs in debug mode. ```text TimeoutError: The operation timed out after 5000ms Stack Trace: 1. asyncFunction (/path/to/file.ts:123) 2. main (/path/to/main.ts:45) ``` -------------------------------- ### Example Trigger for E_MISSING_ARG Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/errors.md Shows a command definition that requires a 'name' argument and explains how running it without the argument triggers the E_MISSING_ARG error. ```typescript // Command definition export class MakeCommand extends BaseCommand { static commandName = 'make' @args.string({ description: 'Entity name', required: true }) declare name: string async run() {} } // ❌ User runs: node ace make // Throws: E_MISSING_ARG with message "Missing required argument 'name'" // ✅ Correct: node ace make User ``` -------------------------------- ### Enhancing Generated Command Metadata Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/index-generator.md This example shows how to programmatically enhance the generated `commands.json` file by adding custom metadata like 'hidden' or 'tags' to each command. This requires reading the JSON, modifying it, and writing it back. ```typescript const generator = new IndexGenerator('./build/commands') await generator.generate() // Then enhance commands.json import commands from './build/commands/commands.json' // Add custom metadata commands.commands.forEach(cmd => { cmd.hidden = false cmd.tags = [] }) // Write back import { writeFileSync } from 'node:fs' writeFileSync( './build/commands/commands.json', JSON.stringify(commands, null, 2) ) ``` -------------------------------- ### Example Trigger for E_MISSING_FLAG Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/errors.md Shows a command definition with a required 'connection' flag and explains how running the command without this flag triggers the E_MISSING_FLAG error. ```typescript export class MigrateCommand extends BaseCommand { @flags.boolean({ description: 'Connection', required: true }) declare connection: string async run() {} } // ❌ User runs: node ace migrate // Throws: E_MISSING_FLAG with message "Missing required option 'connection'" // ✅ Correct: node ace migrate --connection=mysql ``` -------------------------------- ### Initializing Kernel and Loading Commands Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exports-and-modules.md Demonstrates how to create a new Ace Kernel instance, add a file system loader for commands located in a specific directory, and handle incoming process arguments. ```typescript import { Kernel, FsLoader, BaseCommand, args, flags } from '@adonisjs/ace' const kernel = Kernel.create() kernel.addLoader(new FsLoader('./commands')) await kernel.handle(process.argv.slice(2)) ``` -------------------------------- ### boot() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Loads all registered commands from their respective loaders. This must be called before executing any commands. ```APIDOC ## boot() ### Description Load all commands from registered loaders. Must be called before handling commands. ### Returns A promise that resolves when all loaders have completed. ### Example ```typescript await kernel.boot() const commands = kernel.getCommands() ``` ``` -------------------------------- ### Define a Custom Ace Command Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Example of a custom Ace command that defines its name, description, arguments, and flags. It includes logic to log information based on provided arguments and flags during execution. ```typescript import { BaseCommand } from '@adonisjs/ace' import { args } from '@adonisjs/ace/decorators/args' import { flags } from '@adonisjs/ace/decorators/flags' export class MakeModelCommand extends BaseCommand { static commandName = 'make:model' static description = 'Create a new model' @args.string({ description: 'Model name' }) declare name: string @args.spread({ description: 'Additional files', required: false }) declare files?: string[] @flags.boolean({ description: 'Create migration', default: false }) declare migration: boolean @flags.string({ description: 'Database connection', alias: 'c' }) declare connection?: string async run() { this.logger.info(`Creating model: ${this.name}`) if (this.migration) { this.logger.info('Creating migration...') } if (this.connection) { this.logger.info(`Using connection: ${this.connection}`) } return { success: true } } } ``` -------------------------------- ### boot() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Initializes static properties on the command class. This method is automatically called during command definition. ```APIDOC ## boot() ### Description Initialize static properties on the command class. Called automatically during command definition. ### Method static ### Example ```typescript MyCommand.boot() ``` ``` -------------------------------- ### Get all registered commands Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getCommands` to retrieve an array of all registered commands, sorted alphabetically. Each command's metadata includes its name and description. ```typescript getCommands(): CommandMetaData[] ``` ```typescript const commands = kernel.getCommands() commands.forEach(cmd => { console.log(`${cmd.commandName}: ${cmd.description}`) }) ``` -------------------------------- ### Parse CLI Arguments Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/parser.md Parse command-line arguments using a configured Parser instance. This example demonstrates parsing arguments including boolean and string flags with aliases and default values, and positional arguments. The output object contains parsed arguments, flags, and unknown flags. ```typescript const parser = new Parser({ flagsParserOptions: { all: ['verbose', 'connection'], string: ['connection'], boolean: ['verbose'], alias: { verbose: 'v', connection: 'c' }, default: { verbose: false } }, argumentsParserOptions: [ { type: 'string' } ] }) const parsed = parser.parse(['--verbose', 'User', '--connection=mysql']) console.log(parsed) // { // args: ['User'], // flags: { verbose: true, connection: 'mysql' }, // unknownFlags: [], // _: [], // nodeArgs: [] // } ``` -------------------------------- ### Get default command Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getDefaultCommand` to retrieve the default command class. ```typescript getDefaultCommand(): Command ``` -------------------------------- ### Parse Simple Arguments and Flags Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/parser.md Parse command-line arguments with a single string argument and a boolean flag. This example shows basic configuration for flags and arguments, including setting a default value for the flag. ```typescript const parser = new Parser({ flagsParserOptions: { all: ['force'], boolean: ['force'], default: { force: false } }, argumentsParserOptions: [ { type: 'string' } ] }) const result = parser.parse(['MyModel', '--force']) console.log(result.args[0]) // 'MyModel' console.log(result.flags.force) // true ``` -------------------------------- ### constructor Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Creates a new command instance. It initializes the command with essential dependencies like the kernel, parsed input, UI primitives, and prompt utilities. ```APIDOC ## constructor ### Description Creates a new command instance. It initializes the command with essential dependencies like the kernel, parsed input, UI primitives, and prompt utilities. ### Parameters - **kernel** (Kernel) - The Ace kernel instance - **parsed** (ParsedOutput) - The parsed CLI input - **ui** (UIPrimitives) - UI primitives for output - **prompt** (Prompt) - Prompt utilities for user interaction ### Example ```typescript const instance = new MyCommand(kernel, parsed, ui, prompt) ``` ``` -------------------------------- ### constructor Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Initializes a Kernel instance with a specific default command and executor. ```APIDOC ## constructor ### Description Creates a new Kernel instance with a specific default command and executor. ### Parameters #### Parameters - **defaultCommand** (Command) - The command to run when no command is specified - **executor** (ExecutorContract) - Handler for creating and executing command instances ### Example ```typescript const kernel = new Kernel(ListCommand, customExecutor) ``` ``` -------------------------------- ### Define Array Flag Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Example of defining a flag that accepts multiple string values, which are collected into an array. ```typescript @flags.array({ description: 'Tags' }) declare tags?: string[] ``` -------------------------------- ### Define Boolean Flag with Alias Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Example of defining a boolean flag that can be set using a short alias. ```typescript @flags.boolean({ description: 'Force action', alias: 'f' }) declare force: boolean ``` -------------------------------- ### Define Optional String Argument with Default Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Example of defining an optional string argument with a default value. ```typescript @args.string({ description: 'Type', required: false, default: 'default' }) declare type?: string ``` -------------------------------- ### Create Basic CLI Application Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Sets up the Ace Kernel and adds a file system loader for commands. Handles command-line arguments and sets the exit code. ```typescript import { Kernel } from '@adonisjs/ace' import { FsLoader } from '@adonisjs/ace' const kernel = Kernel.create() kernel.addLoader(new FsLoader('./commands')) await kernel.handle(process.argv.slice(2)) process.exit(kernel.exitCode ?? 0) ``` -------------------------------- ### Get all registered namespaces Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getNamespaces` to retrieve an array of all registered namespace names, sorted alphabetically. ```typescript getNamespaces(): string[] ``` ```typescript const namespaces = kernel.getNamespaces() console.log(namespaces) // ['make', 'migration', 'test'] ``` -------------------------------- ### Get All Command Metadata Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Retrieves metadata for all registered commands. Useful for introspection or generating command lists. ```typescript async getMetaData(): Promise ``` ```typescript const loader = new ListLoader([Command1, Command2]) const metadata = await loader.getMetaData() // metadata will contain serialized info for both commands metadata.forEach(cmd => { console.log(cmd.commandName) }) ``` -------------------------------- ### Get namespace suggestions Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getNamespaceSuggestions` to find namespace suggestions for a given keyword using Levenshtein distance. ```typescript getNamespaceSuggestions(keyword: string): string[] ``` -------------------------------- ### E_MISSING_FLAG_VALUE Example Trigger Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/errors.md Demonstrates how a missing flag value triggers the E_MISSING_FLAG_VALUE error. Use this when a flag must have a value. ```typescript export class MakeCommand extends BaseCommand { @flags.string({ description: 'Template', allowEmptyValue: false }) declare template?: string async run() {} } // ❌ User runs: node ace make --template= // Throws: E_MISSING_FLAG_VALUE // ✅ Correct: node ace make --template=api // ✅ Or allow empty: @flags.string({ allowEmptyValue: true }) ``` -------------------------------- ### on Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Listens for specific CLI options (flags) and executes a callback when they are present. This is primarily for the main command. ```APIDOC ## on(option: string, callback: FlagListener) ### Description Listen for CLI options (flags) and execute an action. Only the main command triggers these listeners. ### Parameters #### Path Parameters - **option** (string) - The flag name - **callback** (FlagListener) - Handler to invoke when flag is present ### Returns - `this` - The kernel instance for method chaining. ### Example ```typescript kernel.on('help', async (Command, kernel, parsed) => { await new HelpCommand(kernel, parsed, kernel.ui, kernel.prompt).exec() return true }) ``` ``` -------------------------------- ### Create Kernel Instance Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/overview.md Initializes the Ace kernel. This is the first step in setting up the CLI application. ```typescript const kernel = Kernel.create() ``` -------------------------------- ### Kernel.create() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Creates a new Kernel instance with default settings. It includes a default executor and the ListCommand. ```APIDOC ## Kernel.create() ### Description Creates a kernel instance with default executor and default command (ListCommand). ### Returns A new Kernel instance ready for use. ### Example ```typescript const kernel = Kernel.create() kernel.addLoader(new FsLoader('./commands')) await kernel.handle(process.argv.slice(2)) ``` ``` -------------------------------- ### Get Command Metadata for an Alias Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Retrieves the metadata for a command associated with a specific alias. Returns null if the alias does not exist. ```typescript kernel.getAliasCommand('aliasName') ``` -------------------------------- ### Importing from Main Entry Point Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exports-and-modules.md Demonstrates importing the Kernel class from the main entry point of the '@adonisjs/ace' package. ```typescript // ✅ All exports from build/index.js import { Kernel } from '@adonisjs/ace' ``` -------------------------------- ### Get kernel state Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getState` to retrieve the current state of the kernel. The state can be 'idle', 'booted', 'running', or 'completed'. ```typescript getState(): 'idle' | 'booted' | 'running' | 'completed' ``` ```typescript const state = kernel.getState() if (state === 'idle') { await kernel.boot() } ``` -------------------------------- ### create() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Creates a command instance by parsing and validating arguments. This method does not execute the command. ```APIDOC ## create() ### Description Create a command instance by parsing and validating arguments. Does not execute it. ### Method async create(command: T, argv: string | string[]): Promise> ### Parameters #### Path Parameters - **command** (T) - Required - The command class to instantiate - **argv** (string|string[]) - Required - Command-line arguments to parse ### Response #### Success Response - **InstanceType** - The instantiated and hydrated command instance. ### Request Example ```typescript const instance = await kernel.create(MyCommand, ['arg1', '--flag=value']) console.log(instance.arg1) ``` ``` -------------------------------- ### Get Specific Command Constructor Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Retrieves the command class constructor based on its metadata. Returns null if the command is not found. ```typescript async getCommand(metaData: CommandMetaData): Promise ``` ```typescript const loader = new ListLoader([MyCommand]) const metadata = await loader.getMetaData() const Command = await loader.getCommand(metadata[0]) if (Command) { const instance = new Command(kernel, parsed, ui, prompt) } ``` -------------------------------- ### Viewing Command Help Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Use the `ace` command with `--help` or `-h` flags to view help for a specific command, or run `ace` without arguments to list all commands. ```bash # View help for command node ace help make:model node ace make:model --help node ace make:model -h # View all commands node ace node ace list ``` -------------------------------- ### Define Number Flag with Alias and Default Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Example of defining a number flag that can be set using a short alias and has a default value. ```typescript @flags.number({ description: 'Port', alias: 'p', default: 3000 }) declare port: number ``` -------------------------------- ### Catching Known Ace Errors Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/errors.md Provides an example of catching specific known errors like E_COMMAND_NOT_FOUND and E_MISSING_ARG during command execution. ```typescript import * as errors from '@adonisjs/ace' try { await kernel.handle(process.argv.slice(2)) } catch (error) { if (error instanceof errors.E_COMMAND_NOT_FOUND) { console.error(`Command "${error.commandName}" not found`) } else if (error instanceof errors.E_MISSING_ARG) { console.error(error.message) } else { throw error } } ``` -------------------------------- ### Create a Simple Greet Command Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Defines a command that greets a person, with options for a formal greeting. Includes argument and flag definitions. ```typescript import { BaseCommand } from '@adonisjs/ace' import { args } from '@adonisjs/ace' import { flags } from '@adonisjs/ace' export class GreetCommand extends BaseCommand { static commandName = 'greet' static description = 'Greet someone' @args.string({ description: 'Person to greet' }) declare name: string @flags.boolean({ description: 'Use formal greeting', alias: 'f' }) declare formal: boolean async run() { const greeting = this.formal ? 'Good day' : 'Hello' this.logger.info(`${greeting}, ${this.name}!`) } } ``` -------------------------------- ### Define String Flag with Alias and Default Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Example of defining a string flag that can be set using a short alias and has a default value. ```typescript @flags.string({ description: 'Database connection', alias: 'c', default: 'default' }) declare connection?: string ``` -------------------------------- ### run() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md The main command logic. This method should be overridden in command subclasses to define the behavior of a specific command. ```APIDOC ## run() ### Description The main command logic. Override this method in command subclasses. ### Parameters - **_ ** (any[]) - Additional arguments (not used in base) ### Returns Any value returned by the command. ### Example ```typescript export class MakeCommand extends BaseCommand { @args.string() declare name: string async run() { this.logger.info(`Creating model: ${this.name}`) return { created: true } } } ``` ``` -------------------------------- ### Command Logging and Output Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/quick-start.md Demonstrates how to use the logger for informational, warning, and error messages, including colored output and interactive prompts. ```typescript export class MyCommand extends BaseCommand { async run() { // Log messages this.logger.info('Information message') this.logger.warn('Warning message') this.logger.error('Error message') // Use colors this.logger.info(this.colors.green('Success!')) this.logger.error(this.colors.red('Failed!')) this.logger.info(this.colors.yellow('Warning')) // Interactive prompts const name = await this.prompt.ask('What is your name?') const email = await this.prompt.ask('Email', { default: 'user@example.com' }) const agree = await this.prompt.confirm('Do you agree?') this.logger.info(`Hello ${name}`) } } ``` -------------------------------- ### Create a command instance Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `create` to instantiate a command class by parsing and validating arguments. This method does not execute the command. ```typescript async create( command: T, argv: string | string[] ): Promise> ``` ```typescript const instance = await kernel.create(MyCommand, ['arg1', '--flag=value']) console.log(instance.arg1) ``` -------------------------------- ### Get Aliases for a Specific Command Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Fetches all registered aliases for a given command name. Useful for understanding shortcuts for a particular command. ```typescript const aliases = kernel.getCommandAliases('make:model') // ['m', 'make:m'] ``` -------------------------------- ### Get All Registered Alias Names Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Retrieves an array of all registered alias names for commands. Useful for inspecting available command shortcuts. ```typescript const aliases = kernel.getAliases() console.log(aliases) // ['m', 'migrate:fresh'] ``` -------------------------------- ### Get commands by namespace Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getNamespaceCommands` to retrieve commands filtered by a specific namespace. If no namespace is provided, it returns all non-namespaced commands. ```typescript getNamespaceCommands(namespace?: string): CommandMetaData[] ``` ```typescript const makeCommands = kernel.getNamespaceCommands('make') const rootCommands = kernel.getNamespaceCommands() ``` -------------------------------- ### Help Command Flag Listener Implementation Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/commands.md Shows how the Ace kernel automatically registers a listener for the --help/-h flag, which triggers the HelpCommand. ```typescript kernel.on('help', async (Command, kernel, parsed) => { parsed.args.unshift(Command.commandName) await new HelpCommand(kernel, parsed, kernel.ui, kernel.prompt).exec() return true }) kernel.defineFlag('help', { type: 'boolean', alias: 'h', description: 'Display help for the given command' }) ``` -------------------------------- ### Get specific command metadata Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getCommand` to retrieve metadata for a specific command by its name. Returns null if the command is not found. ```typescript getCommand(commandName: string): CommandMetaData | null ``` ```typescript const meta = kernel.getCommand('make:model') if (meta) { console.log(meta.description) } ``` -------------------------------- ### serialize() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Serializes the command into metadata, which is used for displaying help and list information. It includes command name, description, and flags. ```APIDOC ## serialize() ### Description Serialize the command to metadata for help/list display. ### Method static ### Returns CommandMetaData object with all command information. ### Throws `E_MISSING_COMMAND_NAME` if commandName is not defined. ### Example ```typescript const metadata = MyCommand.serialize() console.log(metadata.commandName) console.log(metadata.description) console.log(metadata.flags) ``` ``` -------------------------------- ### toJSON() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Gets a JSON representation of the command's execution state, including its name, options, arguments, flags, and any errors or results. ```APIDOC ## toJSON() ### Description Get JSON representation of command execution state. ### Returns Object containing command metadata and execution results. ### Example ```typescript const json = command.toJSON() console.log(JSON.stringify(json)) ``` ``` -------------------------------- ### Configure Single Filesystem Loader Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Sets up the Ace kernel to load commands from a specified directory on the filesystem. ```typescript import { Kernel } from '@adonisjs/ace' import { FsLoader } from '@adonisjs/ace' const kernel = Kernel.create() kernel.addLoader(new FsLoader('./build/commands')) await kernel.boot() ``` -------------------------------- ### E_UNKNOWN_FLAG Example Trigger Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/errors.md Illustrates the E_UNKNOWN_FLAG error when an unknown flag is provided to a command that does not allow them. Ensure all flags are defined or set allowUnknownFlags to true. ```typescript export class MyCommand extends BaseCommand { static commandName = 'my:command' static options = { allowUnknownFlags: false } @flags.boolean({ description: 'Verbose' }) declare verbose: boolean async run() {} } // ❌ User runs: node ace my:command --unknown=value // Throws: E_UNKNOWN_FLAG with message "Unknown flag 'unknown'" // ✅ Fix 1: Only use known flags node ace my:command --verbose // ✅ Fix 2: Allow unknown flags static options = { allowUnknownFlags: true } ``` -------------------------------- ### Full Build Process with TypeScript Compilation Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/index-generator.md This snippet demonstrates the complete process of compiling TypeScript files and then generating the command index using IndexGenerator. It's typically run as part of a build script. ```typescript import { execSync } from 'node:child_process' import { IndexGenerator } from '@adonisjs/ace' // Step 1: Compile TypeScript execSync('tsc', { stdio: 'inherit' }) // Step 2: Generate command index const generator = new IndexGenerator('./build/commands') await generator.generate() console.log('Build complete') ``` ```json { "scripts": { "build": "tsc && node scripts/generate-commands.js" } } ``` -------------------------------- ### Ace CLI Framework Architecture Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/overview.md Illustrates the flow of a CLI application built with Ace, from processing arguments to command execution, highlighting the roles of the Kernel, Loaders, Commands, and UI components. ```text ┌─────────────────────────────────────────────────────────┐ │ Your CLI App │ ├─────────────────────────────────────────────────────────┤ │ Process argv → Kernel → Parser → Command → Executor │ ├─────────────────────────────────────────────────────────┤ │ Loaders │ │ (FsLoader / ListLoader / Custom) │ ├─────────────────────────────────────────────────────────┤ │ Commands │ │ (BaseCommand subclasses with args & flags) │ ├─────────────────────────────────────────────────────────┤ │ UI, Prompts, Logging, Colors │ └─────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Get command suggestions Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Use `getCommandSuggestions` to find command and alias suggestions for a given keyword using Levenshtein distance (max distance 3). ```typescript getCommandSuggestions(keyword: string): string[] ``` ```typescript const suggestions = kernel.getCommandSuggestions('make:modle') // ['make:model', 'make:migration'] ``` -------------------------------- ### handle() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Handles process arguments and executes the main command. This method makes the kernel own the process and registers signal listeners. ```APIDOC ## handle() ### Description Handle process argv and execute the main command. Makes the kernel own the process and register signal listeners. ### Method async handle(argv: string[]): Promise ### Parameters #### Path Parameters - **argv** (string[]) - Array of command-line arguments from process.argv ### Response #### Success Response - **void** - A promise that resolves when command execution and cleanup is complete. ### Request Example ```typescript await kernel.handle(process.argv.slice(2)) process.exit(kernel.exitCode ?? 0) ``` ``` -------------------------------- ### Test Ace Command Execution Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/overview.md Demonstrates how to test a custom Ace command by creating a kernel instance, adding a command loader, and executing the command. Asserts that the command executed successfully. ```typescript import { Kernel } from '@adonisjs/ace' import { test } from '@japa/runner' test('command works', async () => { const kernel = Kernel.create() kernel.addLoader(new ListLoader([MyCommand])) const cmd = await kernel.create(MyCommand, ['arg']) await cmd.exec() cmd.assertSucceeded() }) ``` -------------------------------- ### Instantiate Kernel with Custom Executor Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Creates a Kernel instance with a specific default command and a custom executor. Useful for advanced customization. ```typescript constructor( defaultCommand: Command, executor: ExecutorContract ) ``` ```typescript const kernel = new Kernel(ListCommand, customExecutor) ``` -------------------------------- ### Search Documentation with Grep Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/README.md Use grep to search for method names within the documentation files. This is useful for quickly locating specific information across multiple markdown files. ```bash grep -r "method name" . ``` -------------------------------- ### E_INVALID_FLAG Example Trigger Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/errors.md Shows how the E_INVALID_FLAG error occurs when a flag's value does not match its expected data type. Ensure values are correctly formatted for the flag's type. ```typescript export class ServeCommand extends BaseCommand { @flags.number({ description: 'Port number' }) declare port?: number async run() {} } // ❌ User runs: node ace serve --port=abc // Throws: E_INVALID_FLAG with message "Invalid value. The 'port' flag accepts a 'numeric' value" // ✅ Correct: node ace serve --port=8080 ``` -------------------------------- ### Defining a Single Command File with Arguments and Flags Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exports-and-modules.md Shows how to define a custom command class extending BaseCommand, specifying its name, and using decorators for string arguments and boolean flags. ```typescript import { BaseCommand } from '@adonisjs/ace' import { args } from '@adonisjs/ace' import { flags } from '@adonisjs/ace' export class MyCommand extends BaseCommand { static commandName = 'my:command' @args.string() declare name: string @flags.boolean() declare force: boolean async run() { // ... } } ``` -------------------------------- ### Configure Multiple Ace Loaders Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Combines filesystem loading with programmatic registration of commands for the Ace kernel. ```typescript import { Kernel } from '@adonisjs/ace' import { FsLoader, ListLoader } from '@adonisjs/ace' import { CustomCommand } from './custom' const kernel = Kernel.create() // Load from filesystem kernel.addLoader(new FsLoader('./build/commands')) // Register additional commands programmatically kernel.addLoader(new ListLoader([CustomCommand])) await kernel.boot() ``` -------------------------------- ### Get Ace Command Parser Options Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Retrieve the parser configuration options for an Ace command using getParserOptions. This can be used to initialize a Parser instance with the command's defined flags and arguments. ```typescript const parserOptions = MyCommand.getParserOptions() ``` ```typescript const parser = new Parser(parserOptions) ``` -------------------------------- ### Custom Help Text for Commands Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/commands.md Shows how to define extended help text for a custom command using the static `help` property. This text is displayed by the HelpCommand. ```typescript export class MakeModelCommand extends BaseCommand { static commandName = 'make:model' static description = 'Create a new model' static help = [ 'Create a new model class with optional migration', '', 'Usage:', ' node ace make:model ', '', 'Examples:', ' node ace make:model User', ' node ace make:model Post --migration', ' node ace make:model Comment -c postgres', ] async run() {} } ``` -------------------------------- ### Initialize BaseCommand Static Properties Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Call the boot static method to initialize static properties on a command class. This is automatically invoked during command definition. ```typescript static boot(): void ``` ```typescript MyCommand.boot() ``` -------------------------------- ### Runtime Integration: Use Generated Loader Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/index-generator.md TypeScript code showing how to use the generated commands loader at runtime to initialize the Ace Kernel. ```typescript // main.ts - Use generated loader import { Kernel } from '@adonisjs/ace' import { commandsLoader } from './commands/main.js' const kernel = Kernel.create() kernel.addLoader(commandsLoader) await kernel.handle(process.argv.slice(2)) ``` -------------------------------- ### Using Custom Exception Handler Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/exception-handler.md Demonstrates how to instantiate and assign a custom exception handler to the Ace kernel. ```typescript // Use custom handler const handler = new CustomExceptionHandler() kernel.errorHandler = handler ``` -------------------------------- ### BaseCommand Constructor Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md Initializes a new BaseCommand instance with essential dependencies like the kernel, parsed input, UI primitives, and prompt utilities. ```typescript constructor( protected kernel: Kernel, protected parsed: ParsedOutput, public ui: UIPrimitives, public prompt: Prompt ) ``` -------------------------------- ### Build Time Integration: Generate Commands Index Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/index-generator.md TypeScript code demonstrating how to integrate IndexGenerator into build scripts to create command index artifacts. ```typescript // build.ts - Run during compilation import { IndexGenerator } from '@adonisjs/ace' export async function buildCommandsIndex() { const generator = new IndexGenerator('./build/commands') await generator.generate() } await buildCommandsIndex() ``` -------------------------------- ### BaseCommand Run Method Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/base-command.md The main entry point for command logic. Override this method in subclasses to implement custom command behavior. ```typescript async run(..._: any[]): Promise ``` -------------------------------- ### HelpCommand Class Overview Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/commands.md Defines the structure and metadata for the built-in HelpCommand. It includes the command name, description, and an argument for the command name. ```typescript export class HelpCommand extends BaseCommand { static commandName: string = 'help' static description: string = 'View help for a given command' @args.string({ description: 'Command name', argumentName: 'command' }) declare name: string } ``` -------------------------------- ### FsLoader Constructor with Directory Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/loaders.md Creates a new FsLoader instance to scan for command files within a specified directory. ```typescript const loader = new FsLoader('./commands') ``` -------------------------------- ### getCommands() Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Retrieves all registered commands, sorted alphabetically. ```APIDOC ## getCommands() ### Description Get all registered commands, sorted alphabetically. ### Method getCommands(): CommandMetaData[] ### Response #### Success Response - **CommandMetaData[]** - Array of command metadata. ### Request Example ```typescript const commands = kernel.getCommands() commands.forEach(cmd => { console.log(`${cmd.commandName}: ${cmd.description}`) }) ``` ``` -------------------------------- ### Listen for CLI Options (Flags) Source: https://github.com/adonisjs/ace/blob/14.x/_autodocs/kernel.md Registers a listener for specific CLI options (flags) on the main command. Executes a callback when the flag is present. ```typescript kernel.on('help', async (Command, kernel, parsed) => { await new HelpCommand(kernel, parsed, kernel.ui, kernel.prompt).exec() return true }) ```