npm package: @seedts/cli
Description: Command-line interface for SeedTS
Author: SeedTS Contributors
Latest version: 0.1.1

# @seedts/cli

> Command-line interface for SeedTS

The CLI package provides a command-line interface for running, listing, validating, and generating database seeds. It offers a streamlined developer experience for managing seeds in your project.

## Installation

```bash
# Install as a dev dependency
pnpm add -D @seedts/cli

# Or with npm
npm install --save-dev @seedts/cli

# Or with yarn
yarn add -D @seedts/cli
```

## Quick Start

### 1. Add CLI scripts to package.json

```json
{
  "scripts": {
    "seed": "seedts run",
    "seed:list": "seedts list",
    "seed:generate": "seedts generate"
  }
}
```

### 2. Create a configuration file

Create `seedts.config.mjs` in your project root:

```javascript
const config = {
  seeds: './dist/seeds/index.js',
  options: {
    parallel: false,
    transaction: true,
    verbose: true,
  },
};

export default config;
```

### 3. Run your seeds

```bash
pnpm seed
```

## Commands

### `run` - Execute Seeds

Run one or more seeds:

```bash
# Run all seeds
seedts run

# Run specific seeds
seedts run users posts

# Run with options
seedts run --parallel --verbose --dry-run

# Run seeds matching a pattern
seedts run users* --verbose
```

**Options:**
- `--parallel`, `-p` - Run seeds in parallel
- `--max-parallel <num>` - Maximum number of parallel seeds
- `--transaction`, `-t` - Wrap in database transaction
- `--no-transaction` - Don't use transactions
- `--verbose`, `-v` - Verbose logging
- `--dry-run` - Validate without executing
- `--continue-on-error` - Continue running after errors
- `--config <path>` - Path to config file

### `list` - List Available Seeds

List all seeds with their dependencies:

```bash
# List all seeds
seedts list

# List with details
seedts list --details

# List in JSON format
seedts list --json
```

**Output:**
```
Available Seeds:
  ✓ users (no dependencies)
  ✓ posts (depends on: users)
  ✓ comments (depends on: users, posts)

Total: 3 seeds
Execution order: users → posts → comments
```

**Options:**
- `--details`, `-d` - Show detailed information
- `--json` - Output as JSON
- `--tree` - Show as dependency tree

### `validate` - Validate Seeds

Validate seed definitions without executing:

```bash
# Validate all seeds
seedts validate

# Validate specific seeds
seedts validate users posts

# Strict validation
seedts validate --strict
```

**Checks:**
- Circular dependencies
- Missing dependencies
- Invalid configurations
- Adapter compatibility
- Type safety (if using TypeScript)

### `generate` - Generate Seed Files

Generate new seed files from templates:

```bash
# Generate a basic seed
seedts generate products

# Generate with entity name
seedts generate products --entity Product

# Generate from template
seedts generate users --template advanced

# Generate with JSX syntax
seedts generate users --jsx

# Specify output directory
seedts generate users --output ./src/seeds
```

**Options:**
- `--entity <name>` - Entity/model name
- `--template <name>` - Template to use (basic, advanced, jsx)
- `--jsx` - Generate JSX seed file
- `--output <path>` - Output directory
- `--force` - Overwrite existing files

**Generated file example:**
```typescript
// seeds/products.seed.ts
import { seed } from '@seedts/core';
import type { Product } from '../types';

export const productsSeed = seed<Product>('products')
  .adapter(adapter)
  .factory(async (ctx) => {
    return Array.from({ length: 50 }, (_, i) => ({
      name: `Product ${i}`,
      price: Math.random() * 100,
      stock: Math.floor(Math.random() * 100),
    }));
  })
  .build();
```

## Configuration

### Configuration File

Create `seedts.config.mjs` or `seedts.config.js`:

```javascript
export default {
  // Path to seeds (glob pattern or import path)
  seeds: './dist/seeds/**/*.seed.js',

  // Execution options
  options: {
    parallel: false,
    maxParallel: 5,
    transaction: true,
    verbose: false,
    continueOnError: false,
  },

  // Adapter configuration
  adapter: {
    type: 'postgresql',
    connection: {
      host: 'localhost',
      port: 5432,
      database: 'myapp',
      user: 'postgres',
      password: process.env.DB_PASSWORD,
    },
  },

  // Template configuration
  templates: {
    directory: './templates',
    default: 'basic',
  },

  // Hooks
  hooks: {
    beforeAll: async () => {
      console.log('Starting seed execution...');
    },
    afterAll: async (results) => {
      console.log(`Completed ${results.length} seeds`);
    },
    beforeEach: async (seed) => {
      console.log(`Running: ${seed.name}`);
    },
    afterEach: async (seed, result) => {
      console.log(`Done: ${seed.name} (${result.duration}ms)`);
    },
  },
};
```

### TypeScript Configuration

For TypeScript projects, use `seedts.config.ts`:

```typescript
import type { SeedConfig } from '@seedts/cli';

const config: SeedConfig = {
  seeds: './dist/seeds/index.js',
  options: {
    parallel: false,
    transaction: true,
  },
};

export default config;
```

### Environment-Specific Configuration

```javascript
const env = process.env.NODE_ENV || 'development';

const config = {
  seeds: './dist/seeds/index.js',
  options: {
    parallel: env === 'production',
    transaction: true,
    verbose: env === 'development',
  },
  adapter: {
    connection: {
      host: process.env.DB_HOST,
      database: process.env.DB_NAME,
    },
  },
};

export default config;
```

## Advanced Usage

### Custom Reporters

```javascript
// seedts.config.mjs
import { ConsoleReporter } from '@seedts/cli';

class CustomReporter extends ConsoleReporter {
  onSeedStart(seed) {
    console.log(`🌱 Seeding ${seed.name}...`);
  }

  onSeedComplete(seed, result) {
    console.log(`✅ ${seed.name} completed in ${result.duration}ms`);
  }
}

export default {
  reporter: new CustomReporter(),
};
```

### Programmatic Usage

Use the CLI programmatically in your code:

```typescript
import { CLI } from '@seedts/cli';

const cli = new CLI({
  seeds: './dist/seeds/index.js',
  options: {
    parallel: true,
    verbose: true,
  },
});

// Run seeds
await cli.run(['users', 'posts']);

// List seeds
const seeds = await cli.list();

// Validate seeds
const validation = await cli.validate();
```

### Custom Commands

Extend the CLI with custom commands:

```typescript
import { CLI, Command } from '@seedts/cli';

class ResetCommand extends Command {
  name = 'reset';
  description = 'Reset database and run seeds';

  async execute(args) {
    await this.dropAllTables();
    await this.runMigrations();
    await this.runSeeds();
  }
}

const cli = new CLI();
cli.addCommand(new ResetCommand());
```

## Integration with Scripts

### npm/pnpm scripts

```json
{
  "scripts": {
    "seed": "seedts run",
    "seed:dev": "seedts run --verbose",
    "seed:prod": "seedts run --parallel --transaction",
    "seed:reset": "npm run db:reset && npm run seed"
  }
}
```

### CI/CD Integration

```yaml
# .github/workflows/seed.yml
name: Seed Database

on:
  workflow_dispatch:

jobs:
  seed:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: pnpm/action-setup@v2
      - run: pnpm install
      - run: pnpm build
      - run: pnpm seed
        env:
          DB_HOST: ${{ secrets.DB_HOST }}
          DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
```

### Docker Integration

```dockerfile
# Dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package.json pnpm-lock.yaml ./
RUN pnpm install

COPY . .
RUN pnpm build

CMD ["pnpm", "seed"]
```

## Troubleshooting

### Seeds not found

Ensure your seeds path in the config matches the compiled output:

```javascript
// ❌ Wrong - points to source files
seeds: './src/seeds/index.ts'

// ✅ Correct - points to compiled files
seeds: './dist/seeds/index.js'
```

### Import errors

Make sure your TypeScript is compiled before running:

```json
{
  "scripts": {
    "preseed": "pnpm build",
    "seed": "seedts run"
  }
}
```

### Adapter not found

Install the required adapter package:

```bash
pnpm add @seedts/adapter-postgresql
```

## API Reference

For detailed API documentation, visit:
- [Full Documentation](https://seedts.dev/docs/api/cli)
- [CLI Guide](https://seedts.dev/docs/guides/cli)
- [Configuration Reference](https://seedts.dev/docs/guides/configuration)

## Related Packages

- **[@seedts/core](https://www.npmjs.com/package/@seedts/core)** - Core execution engine
- **[@seedts/types](https://www.npmjs.com/package/@seedts/types)** - Type definitions
- **[seedts](https://www.npmjs.com/package/seedts)** - Main convenience package

## Contributing

Contributions are welcome! Please see our [Contributing Guide](https://github.com/DarioBR91/seedts/blob/main/CONTRIBUTING.md).

## License

MIT © [SeedTS Contributors](../../LICENSE)