Plugin Factory
UsecreatePlugin to build type-safe plugins:
Plugin Structure
A plugin is an object with a name and optional lifecycle hooks:Type-Safe Store
Define a typed store for shared state:Plugin Factory with Options
Create configurable plugins using factory functions:Complete Plugin Example
Here’s a complete plugin that tracks command metrics:packages/examples/metrics-plugin.ts
Plugin Lifecycle
1. Setup Phase
Called once during CLI initialization:2. Config Resolved Phase
Called after all plugins have run setup and config is finalized:3. Before Command Phase
Called before each command execution:4. After Command Phase
Called after command execution completes:Testing Plugins
Use built-in testing utilities:Mock Contexts
Create mock contexts for unit testing:Test Plugin Factory
Quickly create test plugins:Error Handling
Usebetter-result for type-safe error handling:
Best Practices
Plugin Naming
- Use descriptive names:
@scope/plugin-featureormy-cli-plugin - Include version for debugging
- Follow npm package naming conventions
Store Design
- Keep store lightweight - avoid large objects
- Use methods for complex operations
- Never use
Object.freeze()- breaks Zod validation - Prefer flat structures over deep nesting
Hook Performance
- Keep
beforeCommandfast - runs on every command - Use
setupfor expensive initialization - Avoid blocking I/O in hot paths
- Consider lazy loading for heavy dependencies
Type Safety
- Always type the store:
createPlugin<MyStore>() - Use
as constfor plugin arrays - Export store types for consumers
- Leverage TypeScript’s inference
Next Steps
Plugin Hooks
Deep dive into lifecycle hooks
Plugin Store
Master type-safe shared state
Official Plugins
Study real plugin implementations
API Reference
Complete plugin API documentation