NitroStack Logo
/cli
/generate

Generate Command

Overview

The generate command creates boilerplate code for common NitroStack components, saving time and ensuring consistency.

Usage

Bash
nitrostack-cli generate <type> [name] [options]

Types

TypeDescriptionRequires Name
typesGenerate TypeScript types from toolsNo
moduleGenerate a new module (with tools, resources, prompts)Yes
toolsGenerate tool definition classYes
resourcesGenerate resource definition classYes
promptsGenerate prompt definition classYes
guardGenerate an authentication guardYes
middlewareGenerate middlewareYes
interceptorGenerate an interceptorYes
pipeGenerate an argument validation/transform pipeYes
filterGenerate an exception filterYes
serviceGenerate an injectable serviceYes
healthGenerate a health check classYes

Options

OptionDescription
--module <name>Specify module (for tools, resources, prompts)
--output <path>Custom output path (for types generation)
--forceOverwrite existing files
--skip-relatedSkip generating related files (tools, resources, prompts) for modules

Examples

Generate Types

Auto-generate TypeScript types from your tool definitions:

Bash
nitrostack-cli generate types

Output: src/types/generated-tools.ts

Typescript
export type GetProductInput = {
  product_id: string;
};

export type GetProductOutput = {
  id: string;
  name: string;
  price: number;
};

export interface ToolInputs {
  'get_product': GetProductInput;
}

export interface ToolOutputs {
  'get_product': GetProductOutput;
}

Custom output path:

Bash
nitrostack-cli generate types --output src/types/custom.ts

Generate Module

Create a new feature module:

Bash
nitrostack-cli generate module payments

Creates:

  • src/modules/payments/payments.module.ts
  • src/modules/payments/payments.tools.ts
  • src/modules/payments/payments.resources.ts
  • src/modules/payments/payments.prompts.ts

Generated Code:

Typescript
// payments.module.ts
import { Module } from '@nitrostack/core';
import { PaymentsTools } from './payments.tools.js';
import { PaymentsResources } from './payments.resources.js';
import { PaymentsPrompts } from './payments.prompts.js';

@Module({
  name: 'payments',
  description: 'Payments module',
  controllers: [PaymentsTools, PaymentsResources, PaymentsPrompts]
})
export class PaymentsModule {}

Generate Tools

Add a tools controller class to an existing module:

Bash
nitrostack-cli generate tools payments --module payments

Creates: src/modules/payments/payments.tools.ts

Typescript
import { ToolDecorator as Tool, z, ExecutionContext, Injectable } from '@nitrostack/core';

/**
 * payments Tools
 * 
 * TODO: Add description
 */
@Injectable()
export class paymentsTools {
  @Tool({
    name: 'payments_example',
    description: 'TODO: Add description',
    inputSchema: z.object({
      id: z.string().describe('ID parameter'),
    }),
  })
  async exampleTool(input: { id: string }, context: ExecutionContext) {
    // TODO: Implement tool logic
    return { id: input.id, result: 'success' };
  }
}

Generate Resources

Add a resources controller class to an existing module:

Bash
nitrostack-cli generate resources payments --module payments

Creates: src/modules/payments/payments.resources.ts

Typescript
import { ResourceDecorator as Resource, ExecutionContext } from '@nitrostack/core';

/**
 * payments Resources
 * 
 * TODO: Add description
 */
export class paymentsResources {
  @Resource({
    uri: 'payments://example',
    name: 'Example Resource',
    description: 'TODO: Add description',
    mimeType: 'application/json',
  })
  async exampleResource(context: ExecutionContext) {
    // TODO: Implement resource logic
    return {
      type: 'text' as const,
      text: JSON.stringify({ example: 'data' }, null, 2),
    };
  }
}

Generate Prompts

Add a prompts controller class to an existing module:

Bash
nitrostack-cli generate prompts payments --module payments

Creates: src/modules/payments/payments.prompts.ts

Typescript
import { PromptDecorator as Prompt, ExecutionContext } from '@nitrostack/core';

/**
 * payments Prompts
 * 
 * TODO: Add description
 */
export class paymentsPrompts {
  @Prompt({
    name: 'payments-help',
    description: 'TODO: Add description',
  })
  async helpPrompt(args: Record<string, unknown>, context: ExecutionContext) {
    return [
      {
        role: 'user' as const,
        content: {
          type: 'text' as const,
          text: 'TODO: Add prompt content',
        },
      },
    ];
  }
}

Generate Guard

Create an authentication guard:

Bash
nitrostack-cli generate guard admin

Creates: src/guards/admin.guard.ts

Typescript
import { Guard, ExecutionContext } from '@nitrostack/core';

export class AdminGuard implements Guard {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // TODO: Implement admin check
    const user = context.auth?.user;
    return user?.role === 'admin';
  }
}

Generate Middleware

Bash
nitrostack-cli generate middleware logging

Creates: src/middleware/logging.middleware.ts

Typescript
import { Middleware, MiddlewareInterface, ExecutionContext } from '@nitrostack/core';

@Middleware()
export class LoggingMiddleware implements MiddlewareInterface {
  async use(context: ExecutionContext, next: () => Promise<any>) {
    const start = Date.now();
    console.log(`[${context.toolName}] Started`);
    
    const result = await next();
    
    const duration = Date.now() - start;
    console.log(`[${context.toolName}] Completed in ${duration}ms`);
    
    return result;
  }
}

Generate Interceptor

Bash
nitrostack-cli generate interceptor transform

Creates: src/interceptors/transform.interceptor.ts

Typescript
import { Interceptor, InterceptorInterface, ExecutionContext } from '@nitrostack/core';

@Interceptor()
export class TransformInterceptor implements InterceptorInterface {
  async intercept(context: ExecutionContext, next: () => Promise<any>) {
    const result = await next();
    
    return {
      success: true,
      data: result,
      timestamp: new Date().toISOString()
    };
  }
}

Generate Pipe

Bash
nitrostack-cli generate pipe validation

Creates: src/pipes/validation.pipe.ts

Typescript
import { Pipe, PipeInterface, ArgumentMetadata } from '@nitrostack/core';

@Pipe()
export class ValidationPipe implements PipeInterface {
  transform(value: any, metadata: ArgumentMetadata) {
    // TODO: Implement validation
    return value;
  }
}

Generate Filter

Bash
nitrostack-cli generate filter http-exception

Creates: src/filters/http-exception.filter.ts

Typescript
import { ExceptionFilter, ExceptionFilterInterface, ExecutionContext } from '@nitrostack/core';

@ExceptionFilter()
export class HttpExceptionFilter implements ExceptionFilterInterface {
  catch(exception: any, context: ExecutionContext) {
    return {
      statusCode: exception.status || 500,
      message: exception.message || 'Internal server error',
      timestamp: new Date().toISOString(),
      tool: context.toolName
    };
  }
}

Generate Service

Bash
nitrostack-cli generate service email

Creates: src/services/email.service.ts

Typescript
import { Injectable } from '@nitrostack/core';

@Injectable()
export class EmailService {
  async send(to: string, subject: string, body: string) {
    // TODO: Implement email sending
    console.log(`Sending email to ${to}: ${subject}`);
  }
}

Workflow Examples

Adding a New Feature

Bash
# 1. Generate module
nitrostack-cli generate module notifications

# 2. Generate tools
nitrostack-cli generate tools notifications --module notifications

# 3. Generate service
nitrostack-cli generate service notification

# 4. Generate types
nitrostack-cli generate types

# 5. Register module in app.module.ts
# Import and add to imports array

# 6. Start dev mode
nitrostack-cli dev

Adding Authentication

Bash
# 1. Generate guard
nitrostack-cli generate guard jwt

# 2. Implement guard logic
# Edit src/guards/jwt.guard.ts

# 3. Use on tools
# @UseGuards(JWTGuard)

# 4. Test in Studio
nitrostack-cli dev

Refactoring to Services

Bash
# 1. Generate service
nitrostack-cli generate service user

# 2. Move business logic from tools to service
# 3. Inject service in tools via constructor
# 4. Register service in module providers

Best Practices

1. Generate Before Manual Creation

Always use generators for consistency:

Bash
# Good
nitrostack-cli generate module users

# Avoid
# Manually creating files

2. Regenerate Types Frequently

After changing tools:

Bash
nitrostack-cli generate types

This ensures type safety between backend and widgets.

3. Use Module Flag

Keep code organized:

Bash
# Good - organized
nitrostack-cli generate tools users --module users

# Avoid - scattered
nitrostack-cli generate tools users

4. Review Generated Code

Generators create boilerplate - customize it:

Typescript
// Generated
@Tool({
  name: 'my_tool',
  description: 'TODO: Add description',  // ← Update this
  inputSchema: z.object({
    // TODO: Add fields  // ← Add fields
  })
})

5. Commit Generated Files

Generated files are part of your codebase:

Bash
git add src/types/generated-tools.ts
git commit -m "chore: update generated types"

Troubleshooting

File Already Exists

Error: File already exists

Solution:

Bash
# Use --force to overwrite
nitrostack-cli generate tools users --module users --force

# Or rename/delete existing file
rm src/modules/users/users.tools.ts

Module Not Found

Error: Module 'payments' not found

Solution:

Bash
# Create module first
nitrostack-cli generate module payments

# Then add tools
nitrostack-cli generate tools payments --module payments

Types Generation Failed

Error: No tool files found

Solution:

Bash
# Ensure tools exist
ls src/modules/*/tools.ts

# Check file naming
# Should be: *.tools.ts

Permission Denied

Error: EACCES: permission denied

Solution:

Bash
# Fix permissions
chmod +w src/

# Or run with sudo (not recommended)
sudo nitrostack-cli generate types

Advanced Usage

Custom Templates

Coming soon: Custom generator templates

Batch Generation

Bash
# Generate multiple at once
nitrostack-cli generate module payments && \
nitrostack-cli generate tools payments --module payments && \
nitrostack-cli generate types

Integration with IDE

Many IDEs support running npm scripts:

JSON
{
  "scripts": {
    "gen:types": "nitrostack-cli generate types",
    "gen:module": "nitrostack-cli generate module"
  }
}

Next Steps


Tip: Create aliases for frequent commands:

Bash
# In .bashrc or .zshrc
alias smg='nitrostack-cli generate'
alias smgt='nitrostack-cli generate types'
alias smgm='nitrostack-cli generate module'