# Bangstack Quick Reference

Fast reference for common Bangstack commands, patterns, and workflows.

## CLI Commands

### Basic Commands

```bash
# Create new workflow interactively
bang create

# Initialize new project with preset
bang init my-app --preset mern

# Generate code from workflow
bang generate workflow.yaml

# Generate with custom output directory
bang generate workflow.yaml --output ./my-app

# Validate workflow without generating
bang validate workflow.yaml

# List available generators
bang list-generators

# Show detailed generator info
bang list-generators --verbose

# Filter generators by category
bang list-generators --category backend
```

### Advanced Generation

```bash
# Dry run (preview without writing files)
bang generate workflow.yaml --dry-run

# Verbose output
bang generate workflow.yaml --verbose

# Resume after failure
bang generate workflow.yaml --resume

# Disable checkpoints
bang generate workflow.yaml --no-checkpoint

# Disable automatic retry
bang generate workflow.yaml --no-retry

# Set max retries
bang generate workflow.yaml --max-retries 5
```

### Performance & Benchmarking

```bash
# Run performance benchmarks
npm run benchmark

# View benchmark results
cat benchmark-results.json

# Generate with parallel execution (default enabled)
# Provides 2-3x speedup for typical workflows
bang generate workflow.yaml

# CLI startup uses lazy loading (4.9x faster)
# Generators loaded on-demand automatically
```

### Version Management

```bash
# Create version/commit
bang commit -m "Add user authentication"

# Show commit history
bang log

# Show one-line commits
bang log --oneline

# Limit number of commits
bang log -n 10

# Show specific commit
bang show abc123

# Show commit stats only
bang show abc123 --stat

# Rollback to previous version
bang rollback abc123

# List all versions
bang version list

# Show version diff
bang version diff v1.0.0 v1.1.0

# Tag a version
bang version tag v1.0.0 -m "First release"
```

## Workflow Syntax

### Minimal Workflow

```yaml
workflow:
  id: my-app
  version: 1.0.0
  name: My Application
  description: A simple application

technology:
  frontend:
    type: react
  backend:
    type: express
  database:
    type: postgresql
    orm: drizzle
```

### Full-Stack MERN

```yaml
workflow:
  id: mern-app
  version: 1.0.0
  name: MERN Application
  description: MongoDB, Express, React, Node.js

technology:
  frontend:
    type: react
    framework: vite
    directory: client
  backend:
    type: express
    directory: server
  database:
    type: mongodb
    orm: mongoose
    directory: database
```

### With Authentication

```yaml
workflow:
  id: auth-app
  version: 1.0.0
  name: App with Auth
  description: Application with JWT authentication

technology:
  frontend:
    type: react
  backend:
    type: express
  database:
    type: postgresql
    orm: drizzle

authentication:
  enabled: true
  provider: jwt
  features:
    - login
    - signup
    - logout
    - refresh-token
    - password-reset
```

### With Data Models

```yaml
workflow:
  id: blog
  version: 1.0.0
  name: Blog
  description: Blog with posts and comments

technology:
  frontend:
    type: react
  backend:
    type: express
  database:
    type: postgresql
    orm: drizzle

models:
  User:
    description: Blog user
    fields:
      - name: id
        type: uuid
        required: true
        system_field: true
      - name: email
        type: string
        length: 255
        required: true
        unique: true
      - name: username
        type: string
        length: 100
        required: true
        unique: true
      - name: created_at
        type: timestamp
        required: true
        system_field: true

  Post:
    description: Blog post
    fields:
      - name: id
        type: uuid
        required: true
        system_field: true
      - name: title
        type: string
        length: 255
        required: true
      - name: content
        type: text
        required: true
      - name: author_id
        type: uuid
        required: true
        foreign_key:
          model: User
      - name: status
        type: enum
        enum_values: [draft, published, archived]
        default: draft
      - name: created_at
        type: timestamp
        required: true
        system_field: true
      - name: updated_at
        type: timestamp
        required: true
        system_field: true
```

## Common Patterns

### Full-Stack with Everything

```yaml
workflow:
  id: enterprise-app
  version: 1.0.0
  name: Enterprise Application
  description: Production-ready full-stack app

technology:
  frontend:
    type: react
    framework: vite
    directory: frontend
    config:
      cssFramework: tailwindcss
      stateManagement: zustand
  backend:
    type: express
    directory: backend
  database:
    type: postgresql
    orm: drizzle
    directory: database
  cache:
    type: upstash-redis

authentication:
  enabled: true
  provider: jwt
  jwt:
    access_token_expiry: 15m
    refresh_token_expiry: 7d
  features:
    - login
    - signup
    - logout
    - refresh-token
    - password-reset
    - email-verification
  authorization:
    type: rbac
    roles:
      - name: admin
        permissions: ["*"]
      - name: user
        permissions: ["read"]

testing:
  frontend:
    framework: vitest
    e2e: playwright
  backend:
    framework: vitest
    coverage: true

infrastructure:
  deployment:
    platform: docker
    compose_version: "3.8"
  services:
    - name: postgres
      type: database
      image: postgres:15
    - name: redis
      type: cache
      image: redis:7

ci_cd:
  platform: github-actions
  triggers:
    - push
    - pull_request
  jobs:
    - lint
    - test
    - build
```

## Field Types Reference

### Basic Types

```yaml
fields:
  # String
  - name: email
    type: string
    length: 255

  # Text (unlimited length)
  - name: bio
    type: text

  # Integer
  - name: age
    type: integer

  # Float/Decimal
  - name: price
    type: decimal

  # Boolean
  - name: is_active
    type: boolean
    default: true

  # UUID
  - name: id
    type: uuid

  # Date
  - name: birth_date
    type: date

  # Timestamp
  - name: created_at
    type: timestamp

  # Enum
  - name: status
    type: enum
    enum_values: [active, inactive, pending]

  # JSON
  - name: metadata
    type: json
```

### Field Modifiers

```yaml
fields:
  # Required field
  - name: email
    type: string
    required: true

  # Unique field
  - name: username
    type: string
    unique: true

  # Default value
  - name: role
    type: string
    default: user

  # System field (auto-managed)
  - name: created_at
    type: timestamp
    system_field: true

  # Foreign key
  - name: author_id
    type: uuid
    foreign_key:
      model: User
      field: id  # optional, defaults to 'id'

  # With validation
  - name: age
    type: integer
    validation:
      min: 0
      max: 150
```

### Validation Rules

```yaml
fields:
  # String validation
  - name: username
    type: string
    validation:
      min_length: 3
      max_length: 50
      pattern: "^[a-zA-Z0-9_]+$"

  # Email validation
  - name: email
    type: string
    validation:
      format: email

  # URL validation
  - name: website
    type: string
    validation:
      format: url

  # Number validation
  - name: rating
    type: integer
    validation:
      min: 1
      max: 5

  # Custom validation
  - name: zipcode
    type: string
    validation:
      pattern: "^\\d{5}(-\\d{4})?$"
```

## Technology Stack Options

### Frontend

```yaml
technology:
  frontend:
    type: react          # React
    type: vue            # Vue.js
    type: next           # Next.js
    type: svelte         # Svelte
    type: angular        # Angular
```

### Backend

```yaml
technology:
  backend:
    type: express        # Express (Node.js)
    type: fastify        # Fastify (Node.js)
    type: nestjs         # NestJS (Node.js)
    type: fastapi        # FastAPI (Python)
    type: django         # Django (Python)
    type: gin            # Gin (Go)
    type: spring         # Spring Boot (Java)
```

### Database

```yaml
technology:
  database:
    type: postgresql     # PostgreSQL
    type: mysql          # MySQL
    type: sqlite         # SQLite
    type: mongodb        # MongoDB
    type: supabase       # Supabase
    type: planetscale    # PlanetScale

    orm: prisma          # Prisma ORM
    orm: drizzle         # Drizzle ORM
    orm: typeorm         # TypeORM
    orm: mongoose        # Mongoose (for MongoDB)
```

### Cache

```yaml
technology:
  cache:
    type: redis          # Redis
    type: upstash-redis  # Upstash Redis (serverless)
```

## Authentication Patterns

### JWT Authentication

```yaml
authentication:
  enabled: true
  provider: jwt
  jwt:
    secret_env: JWT_SECRET
    access_token_expiry: 15m
    refresh_token_expiry: 7d
  features:
    - login
    - signup
    - logout
    - refresh-token
```

### OAuth Social Login

```yaml
authentication:
  enabled: true
  provider: oauth
  oauth:
    providers:
      - google
      - github
      - facebook
  features:
    - social-login
    - account-linking
```

### Role-Based Access Control

```yaml
authentication:
  enabled: true
  provider: jwt
  authorization:
    type: rbac
    roles:
      - name: admin
        permissions: ["*"]
      - name: editor
        permissions: ["posts:*", "comments:*"]
      - name: user
        permissions: ["posts:read", "comments:create"]
```

## Testing Configuration

```yaml
testing:
  # Frontend tests
  frontend:
    framework: vitest     # or jest
    coverage: true
    e2e: playwright       # or cypress

  # Backend tests
  backend:
    framework: vitest     # or jest
    coverage: true
    integration: true

  # E2E tests
  e2e:
    framework: playwright # or cypress
    browsers: [chromium, firefox, webkit]
```

## Infrastructure Patterns

### Docker Compose

```yaml
infrastructure:
  deployment:
    platform: docker
    compose_version: "3.8"

  services:
    - name: postgres
      type: database
      image: postgres:15
      ports: ["5432:5432"]
      environment:
        POSTGRES_DB: myapp
        POSTGRES_PASSWORD: postgres

    - name: redis
      type: cache
      image: redis:7
      ports: ["6379:6379"]
```

### CI/CD

```yaml
ci_cd:
  platform: github-actions  # or gitlab-ci, circleci

  triggers:
    - push
    - pull_request

  jobs:
    - lint
    - test
    - build
    - deploy

  deployment:
    staging:
      branch: develop
      environment: staging
    production:
      branch: main
      environment: production
```

## Programmatic Usage

### Generate Code

```typescript
import { generateFromWorkflow } from 'bangstack';

const result = await generateFromWorkflow({
  workflowPath: './workflow.yaml',
  outputDirectory: './output',
});

console.log(`Generated ${result.files.length} files`);
```

### Validate Workflow

```typescript
import { validateWorkflow } from 'bangstack';

const validation = await validateWorkflow('./workflow.yaml');

if (!validation.valid) {
  console.error('Errors:', validation.errors);
}
```

### Parallel Execution (Performance)

```typescript
import { ParallelExecutor } from 'bangstack';

const executor = new ParallelExecutor();

const result = await executor.execute(generators, context, {
  maxConcurrency: 4,  // Run 4 generators concurrently
  timeout: 60000,     // 60 second timeout
  onProgress: (completed, total, name) => {
    console.log(`[${completed}/${total}] ${name}`);
  },
});

// 2-3x faster than sequential execution
console.log(`Success rate: ${result.metrics.getSuccessRate()}%`);
```

### Lazy Loading (Performance)

```typescript
import { createLazyRegistry, GeneratorRegistry } from 'bangstack';

const baseRegistry = new GeneratorRegistry();
const lazyRegistry = createLazyRegistry(baseRegistry);

// Generators loaded on-demand (4.9x faster startup)
const reactGen = await lazyRegistry.getFrontendGenerator('react');

// Check load stats
const stats = lazyRegistry.getLoadStats();
console.log(`Loaded: ${stats.loaded}/${stats.total}`);
```

### Custom Generator

```typescript
import { CodeGenerator, globalRegistry } from 'bangstack';

class MyGenerator extends CodeGenerator {
  constructor() {
    super({
      id: 'my-gen',
      name: 'My Generator',
      description: 'Custom generator',
    });
  }

  async generateCode(context) {
    return {
      files: [
        {
          path: 'output.ts',
          content: 'console.log("Generated!");',
        },
      ],
    };
  }
}

const gen = new MyGenerator();
globalRegistry.registerCustomGenerator(gen);
```

## Common Workflows

### Create New Project

```bash
# Interactive creation
bang create

# With preset
bang init my-blog --preset mern

# Generate code
cd my-blog
bang generate workflows/my-blog.workflow.yaml
```

### Add New Feature

```bash
# Edit workflow.yaml to add new model or feature
vim workflow.yaml

# Regenerate (only changed files updated)
bang generate workflow.yaml --output .

# Commit changes
bang commit -m "Add user profile feature"
```

### Deploy to Production

```bash
# Generate production build
bang generate workflow.yaml --output ./prod

# Build Docker images
cd prod
docker-compose build

# Deploy
docker-compose up -d
```

## Environment Variables

### Common Variables

```bash
# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb

# JWT
JWT_SECRET=your-super-secret-key-here
JWT_REFRESH_SECRET=another-secret-for-refresh-tokens

# Redis
REDIS_URL=redis://localhost:6379
UPSTASH_REDIS_REST_URL=https://your-instance.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token

# Email
SENDGRID_API_KEY=SG.xxxx
EMAIL_FROM=noreply@example.com

# OAuth
GOOGLE_CLIENT_ID=xxx.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=xxx
GITHUB_CLIENT_ID=xxx
GITHUB_CLIENT_SECRET=xxx

# Application
NODE_ENV=production
PORT=3001
FRONTEND_URL=http://localhost:3000
```

## Troubleshooting

### Validation Errors

```bash
# Check what's wrong
bang validate workflow.yaml

# Verbose output
bang validate workflow.yaml --verbose
```

### Generation Failures

```bash
# Resume from checkpoint
bang generate workflow.yaml --resume

# Dry run to see what would be generated
bang generate workflow.yaml --dry-run

# Verbose output
bang generate workflow.yaml --verbose
```

### Verify Generated Code

```bash
# Check for dependency mismatches
bang verify workflow.yaml --output ./generated

# Verbose output
bang verify workflow.yaml --output ./generated --verbose
```

## File Structure

### Generated Project Structure

```
my-app/
├── frontend/              # Frontend application
│   ├── src/
│   │   ├── components/    # React components
│   │   ├── pages/         # Page components
│   │   ├── hooks/         # Custom hooks
│   │   ├── api/           # API client
│   │   ├── types/         # TypeScript types
│   │   └── App.tsx        # Main app
│   ├── package.json
│   └── vite.config.ts
├── backend/               # Backend API
│   ├── src/
│   │   ├── routes/        # API routes
│   │   ├── middleware/    # Express middleware
│   │   ├── utils/         # Utilities
│   │   └── index.ts       # Main server
│   └── package.json
├── database/              # Database layer
│   ├── schema.ts          # Drizzle schema
│   ├── migrations/        # Migration files
│   └── seed.ts            # Seed data
├── docker-compose.yml     # Docker config
├── .github/
│   └── workflows/
│       └── ci.yml         # CI/CD pipeline
└── README.md              # Documentation
```

## Tips & Tricks

### 1. Use Interactive Mode

```bash
# Fastest way to get started
bang create
```

### 2. Start with Presets

```bash
# Use built-in presets
bang init my-app --preset mern
bang init my-app --preset next-trpc
```

### 3. Validate Often

```bash
# Validate before generating
bang validate workflow.yaml
```

### 4. Use Dry Run

```bash
# Preview changes before writing
bang generate workflow.yaml --dry-run
```

### 5. Version Your Workflows

```bash
# Commit workflow changes
bang commit -m "Add authentication"

# View history
bang log

# Rollback if needed
bang rollback abc123
```

### 6. Leverage System Fields

```yaml
fields:
  # Let Bangstack manage these
  - name: id
    type: uuid
    system_field: true
  - name: created_at
    type: timestamp
    system_field: true
  - name: updated_at
    type: timestamp
    system_field: true
```

### 7. Use Foreign Keys

```yaml
# Define relationships clearly
- name: author_id
  type: uuid
  foreign_key:
    model: User
```

### 8. Organize Models

```yaml
# Group related models together
models:
  # Auth models
  User:
    # ...
  Session:
    # ...

  # Content models
  Post:
    # ...
  Comment:
    # ...
```

## Resources

- [Full Documentation](../README.md)
- [API Reference](./API-REFERENCE.md)
- [Build a Blog Tutorial](./tutorials/BUILD-A-BLOG-IN-5-MINUTES.md)
- [Authentication Guide](./tutorials/ADD-AUTHENTICATION.md)
- [Custom Generators](./tutorials/CUSTOM-GENERATORS.md)
- [Extended Schema Guide](./EXTENDED-SCHEMA-GUIDE.md)
- [GitHub Repository](https://github.com/mogullabs/bangstack)

## Keyboard Shortcuts (Interactive Mode)

```
↑/↓         Navigate options
Space       Select/deselect
Enter       Confirm
Esc         Cancel
Tab         Autocomplete
```

## Getting Help

```bash
# General help
bang --help

# Command-specific help
bang generate --help
bang validate --help
bang list-generators --help

# Version
bang --version
```

---

**Quick Start**: `bang create` → Answer prompts → `bang generate workflow.yaml` → Done! 🚀
