Skip to content

fluent-gen-tsType-safe Fluent Builders for TypeScript

Transform your TypeScript interfaces into elegant, chainable builders with zero runtime dependencies

Quick Example ​

Transform this interface:

typescript
interface User {
  id: string;
  name: string;
  email?: string;
  role: 'admin' | 'user';
  isActive: boolean;
}

Into this fluent builder:

typescript
const user = user()
  .withId('123')
  .withName('Alice')
  .withEmail('alice@example.com')
  .withRole('admin')
  .withIsActive(true)
  .build();

Installation ​

bash
npm install -D fluent-gen-ts

Quick Start ​

Interactive Setup ​

bash
npx fluent-gen-ts init

The interactive CLI will guide you through:

  • Scanning your TypeScript files
  • Selecting interfaces to generate builders for
  • Configuring output directory and naming conventions
  • Setting up a configuration file

Generate a Single Builder ​

bash
npx fluent-gen-ts generate ./src/types.ts User --output ./src/builders/

Batch Generation ​

bash
npx fluent-gen-ts batch

Why fluent-gen-ts? ​

The Problem ​

Creating test data and complex object structures in TypeScript often leads to:

  • Verbose object literals with repetitive property assignments
  • Difficulty in creating variations of objects for testing
  • No IDE support while building objects incrementally
  • Manual maintenance of builder patterns

The Solution ​

fluent-gen-ts automatically generates fluent builders that:

  • Provide a chainable API for building objects step by step
  • Offer full IntelliSense support at each step
  • Generate valid objects with smart defaults
  • Support complex scenarios like nested objects and arrays
  • Require zero runtime dependencies

Core Features ​

🎯 Complete Type Safety ​

Every generated builder maintains full type safety throughout the chain:

typescript
const product = product()
  .withId('P001') // âś“ string
  .withPrice(99.99) // âś“ number
  .withInStock(true) // âś“ boolean
  .withCategories(['electronics', 'computers']) // âś“ string[]
  .build();

🔄 Nested Builders with Deferred Builds ​

Build complex nested structures with ease:

typescript
const order = order()
  .withId('ORD-001')
  .withCustomer(
    customer().withName('John Doe').withAddress(
      address().withStreet('123 Main St').withCity('New York'),
      // No .build() needed - automatically handled!
    ),
  )
  .withItems([
    item().withName('Laptop').withPrice(999),
    item().withName('Mouse').withPrice(29),
  ])
  .build();

🧩 Extensible Plugin System ​

Create custom plugins to extend functionality:

typescript
import { createPlugin, primitive } from 'fluent-gen-ts';

const validationPlugin = createPlugin('validation-plugin', '1.0.0')
  .setDescription('Adds email validation and custom methods')

  // Configure required imports
  .requireImports(imports => imports.addExternal('validator', ['isEmail']))

  // Transform property methods with type-safe matching
  .transformPropertyMethods(builder =>
    builder
      .when(
        ctx => ctx.property.name === 'email' && ctx.type.isPrimitive('string'),
      )
      .setParameter('string')
      .setValidator(
        `
      if (value && !isEmail(value)) {
        throw new Error('Invalid email format');
      }
    `,
      )
      .done(),
  )

  // Add custom builder methods
  .addMethod(method =>
    method
      .name('withRandomId')
      .parameter('prefix', 'string', { defaultValue: '"user"' })
      .returns('this')
      .implementation(
        `
      const id = \`\${prefix}-\${Date.now()}-\${Math.random().toString(36).substr(2, 9)}\`;
      return this.withId(id);
    `,
      )
      .jsDoc('/**\\n * Generates and sets a random ID\\n */'),
  )

  .build();

⚙️ Flexible Generation Modes ​

Single Builder Generation ​

Generates self-contained builders with inlined utilities - perfect for standalone use.

Batch Generation ​

Creates a shared common.ts file with utilities that all builders import - ideal for generating multiple builders.

Custom Common File ​

Use setup-common to create your own customizable common utilities file.

Learn More ​

Released under the MIT License.