JSPM

  • Created
  • Published
  • Downloads 22
  • Score
    100M100P100Q60562F
  • License MIT

Advanced TypeScript type guard generator with sophisticated recursion detection, enhanced enum handling, and comprehensive utility support using guardz 1.10.3 library

Package Exports

  • guardz-generator
  • guardz-generator/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (guardz-generator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Guardz Generator

GitHub Sponsors

A professional TypeScript type guard generator that automatically creates runtime validation functions from your TypeScript interfaces and types using the guardz library.

Overview

Guardz Generator transforms your TypeScript type definitions into robust runtime type guards, enabling comprehensive runtime validation for your applications. It supports complex TypeScript features including generics, recursive types, enums, and cross-file dependencies.

Key Features

  • 🔧 Full TypeScript Support: Interfaces, type aliases, enums, generics, unions, intersections
  • 🔄 Recursive Type Handling: Automatic detection and support for direct/indirect recursion
  • 📁 Smart Import Resolution: Maintains your project's import structure and path aliases
  • ⚡ Performance Optimized: Intelligent caching and batch processing
  • 🎯 Guardz Integration: Complete compatibility with guardz 1.10.3 runtime library
  • 🔍 Post-Processing: Optional formatting, linting, and type checking
  • 🛠️ Flexible API: CLI and programmatic interfaces

Installation

npm install guardz-generator

Quick Start

1. Basic Setup

Create a configuration file guardz.generator.config.ts in your project root:

export default {
  includes: ['src/**/*.ts'],
  excludes: [
    'node_modules/**/*',
    '**/*.test.ts',
    '**/*.guardz.ts',
    'dist/**/*'
  ],
  postProcess: true
};

2. Generate Type Guards

# Generate for all files in config
npx guardz-generator

# Generate for specific files
npx guardz-generator generate "src/models/**/*.ts"

# Generate for specific type
npx guardz-generator generate "src/**/*.ts" -t User

3. Use Generated Guards

import { isUser } from './models/User.guardz';

// Runtime validation
const validateUser = (data: unknown) => {
  if (isUser(data)) {
    // data is now typed as User
    console.log(`Valid user: ${data.name}`);
  } else {
    console.error('Invalid user data');
  }
};

Configuration

Configuration File Options

export default {
  // File patterns to include
  includes: ['src/**/*.ts', 'lib/**/*.ts'],
  
  // File patterns to exclude
  excludes: [
    'node_modules/**/*',
    '**/*.test.ts',
    '**/*.spec.ts',
    '**/*.guardz.ts',
    'dist/**/*'
  ],
};

CLI Options

npx guardz-generator generate [options] [files...]

Options:
  -c, --config <path>       Configuration file path
  -n, --name <name>         Custom guard function name
  -t, --type <type>         Generate guard for specific type
  --no-post-process         Skip formatting and linting
  --includes <patterns...>  File patterns to include
  --excludes <patterns...>  File patterns to exclude
  -h, --help               Display help

Programmatic Usage

import { GenerateTypeGuardsUseCase } from 'guardz-generator';

const useCase = new GenerateTypeGuardsUseCase();

// Generate all type guards
const files = await useCase.execute(['src/**/*.ts']);

// Generate specific type guard
const guardCode = await useCase.executeForSpecificType(
  ['src/**/*.ts'], 
  'User'
);

Direct Generator API

import { TypeGuardGenerator } from 'guardz-generator';

const generator = new TypeGuardGenerator(['src/**/*.ts']);

// Generate all type guards
const files = generator.generateAllTypeGuards();
await generator.writeTypeGuardsToSameDirectory(files);

// Generate specific type guard
const guardCode = generator.generateTypeGuard('User');

Supported TypeScript Features

Core Types

  • Interfaces & Type Aliases: Complete support for all interface and type definitions
  • Primitive Types: string, number, boolean, bigint, symbol
  • Nullable & Optional: string | null, name?: string
  • Arrays & Tuples: string[], [number, string, boolean]

Advanced Types

  • Generics: ApiResponse<T>, PaginatedResponse<T>
  • Unions & Intersections: 'active' | 'inactive', HasId & HasTimestamps
  • Recursive Types: Self-referencing interfaces and types
  • Enums: String and numeric enums with isEnum() support

Complex Features

  • Interface Extensions: interface B extends A with proper inheritance
  • Index Signatures: { [key: string]: unknown }
  • Cross-file References: Types imported from other files
  • NPM Package Types: External package types with smart fallbacks

Integration with Guardz Library

Guardz Generator is fully compatible with guardz 1.10.3 and generates guards using all available utilities:

Core Guards

import { 
  isString, isNumber, isBoolean, isDate,
  isAny, isUnknown, isDefined, isNil,
  isType, isObject, isArrayWithEachItem
} from 'guardz';

Advanced Guards

import {
  isExtensionOf, isIntersectionOf, isPartialOf,
  isOneOf, isUndefinedOr, isNullOr,
  isPositiveNumber, isNonEmptyString,
  isFile, isBlob, isFormData
} from 'guardz';

Type Aliases

import type { TypeGuardFn, TypeGuardFnConfig } from 'guardz';

Project Structure

src/
├── models/
│   ├── User.ts              # Your TypeScript interfaces
│   ├── User.guardz.ts       # Generated type guards
│   ├── Product.ts
│   └── Product.guardz.ts
├── types/
│   ├── ApiResponse.ts
│   └── ApiResponse.guardz.ts
└── utils/
    ├── validation.ts        # Use generated guards
    └── validation.guardz.ts

Best Practices

1. Configuration Management

// guardz.generator.config.ts
export default {
  includes: ['src/**/*.ts'],
  excludes: [
    '**/*.test.ts',
    '**/*.guardz.ts',
    'node_modules/**/*'
  ],
  postProcess: true
};

2. Import Organization

// Generated guards maintain your import structure
import type { User } from './User';
import { isString, isNumber, isType } from 'guardz';
import { isAddress } from './Address.guardz';

3. Runtime Validation

import { isUser } from './User.guardz';

export const validateUserInput = (data: unknown): User | null => {
  return isUser(data) ? data : null;
};

4. Error Handling

import { isApiResponse } from './ApiResponse.guardz';

export const handleApiResponse = (response: unknown) => {
  if (isApiResponse(response)) {
    // Type-safe access to response.data, response.status
    return response.data;
  }
  throw new Error('Invalid API response format');
};

Performance Considerations

  • Caching: Import strategies are cached for improved performance
  • Batch Processing: Use shared context for multiple file generation
  • Selective Generation: Generate only needed types with -t flag
  • Post-Processing: Disable with --no-post-process for faster generation

Troubleshooting

Common Issues

  1. Missing TypeGuardFnConfig Import

    • Ensure typeGuardCode parameter is passed to buildImportStatements
    • Check that recursive types are properly detected
  2. Import Path Issues

    • Verify path aliases in tsconfig.json
    • Check relative path calculations
  3. Post-Processing Errors

    • Disable with --no-post-process flag
    • Check Prettier/ESLint configuration

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Support

GitHub Sponsors

Support the development of Guardz Generator:

GitHub Sponsors

Community Support

  • 📖 Documentation: IMPORT_BUILDER.md for advanced usage
  • 🐛 Issues: Report bugs on GitHub Issues
  • 💬 Discussions: Join community discussions
  • Star: Show your support by starring the repository

License

MIT License - see LICENSE for details.