clegen
v6.1.1
Published
Generate modules with clean code for Typescript projects
Downloads
386
Maintainers
Readme
Table of Contents
- What is Clegen?
- Features
- Installation
- Quick Start
- Usage
- Project Structure
- Supported Frameworks
- Module Elements
- Examples
- Extending Clegen
- Contributing
- License
What is Clegen?
Clegen (Clean Generator) is a powerful command-line tool designed to scaffold clean architecture modules in TypeScript projects. It helps you maintain consistent code structure, enforces separation of concerns, and speeds up development by generating boilerplate code following best practices.
Why Clegen?
- ✅ Consistent Architecture: Generates modules following Clean Architecture principles
- ✅ Framework Agnostic: Supports Express, Hono, Next.js, and easily extensible
- ✅ Concept-Based Organization: Files organized by concept (routes, services, domain, etc.)
- ✅ Type-Safe: Full TypeScript support with proper imports
- ✅ Extensible: Plugin architecture allows adding new frameworks and templates
- ✅ React & React Native: Built-in support for React components and React Native styles
- ✅ Time-Saving: Generate complete modules in seconds
Features
- 🎯 Concept-Based File Organization: Files grouped by their purpose (routes, services, domain, infrastructure, etc.)
- 🔌 Multiple Backend Frameworks: Express, Hono, Next.js
- ⚛️ React & React Native Support: Components, hooks, and platform-specific styles
- 🏗️ Clean Architecture Layers: Domain, Services, Infrastructure separation
- 📦 Modular Templates: Repository pattern, service layer, entities, types
- 🎨 Style Support: CSS and React Native StyleSheet
- 🚀 CLI or Interactive: Use flags for automation or interactive prompts for flexibility
- 🧩 Plugin Architecture: Easy to extend with new frameworks and templates
Installation
NPX (Recommended)
Use Clegen directly without installation:
npx clegen@latestGlobal Installation
npm install -g clegenLocal Development
npm install clegen --save-devQuick Start
Generate a complete module in seconds:
# Interactive mode
npx clegen@latest
# With CLI flags
npx clegen@latest --name User --framework express --elements routes,service,types,repositoryUsage
Interactive Mode
Simply run clegen and follow the prompts:
npx clegen@latestThe tool will ask you:
- Module name (e.g., User, Product, Order)
- Framework (Express, Hono, Next.js)
- Elements to generate (routes, services, components, etc.)
- Module path (where to create the module)
- Implementation type (optional, e.g., MongoDB, PostgreSQL)
CLI Flags Mode
Skip prompts by providing configuration via flags:
npx clegen@latest \
--name User \
--framework express \
--elements routes,service,types,repository \
--path ./src/modules/User \
--implementation MongoDBAvailable Options
| Flag | Shorthand | Description | Example |
|------|-----------|-------------|---------|
| --name | -n | Module name (PascalCase) | User, Product |
| --framework | -f | Backend framework | express, hono, nextjs |
| --elements | -e | Comma-separated elements | routes,service,types |
| --path | -p | Module output path | ./src/modules/User |
| --implementation | -i | Implementation type | MongoDB, PostgreSQL |
| --help | -h | Show help message | - |
Project Structure
Clegen organizes files by concept, not by layer. This makes related code easier to find:
User/
├── routes/ # API endpoint handlers
│ └── UserRouter.ts
├── services/ # Business logic layer
│ └── UserService.ts
├── components/ # React components and hooks
│ ├── User.tsx
│ └── useUser.tsx
├── styles/ # CSS and React Native styles
│ ├── User.css
│ └── User.styles.ts
├── domain/ # Entities, types, repositories
│ ├── User.ts
│ ├── UserTypes.ts
│ └── UserRepository.ts
├── infrastructure/ # Schemas, implementations
│ ├── UserSchemas.ts
│ └── MongoDBUserRepository.ts
└── utils/ # Utility functions
└── UserUtils.tsConcept Groups
| Group | Purpose | Contains | |-------|---------|----------| | routes/ | HTTP handlers | API route definitions | | services/ | Business logic | Service classes with domain logic | | components/ | UI layer | React components and custom hooks | | styles/ | Presentation | CSS and React Native StyleSheet | | domain/ | Core domain | Entities, types, repository interfaces | | infrastructure/ | External concerns | DB schemas, repository implementations | | utils/ | Helpers | Utility functions |
Supported Frameworks
Backend Frameworks
| Framework | Template | Example |
|-----------|----------|---------|
| Express | REST API routes | Router() with service integration |
| Hono | Lightweight routes | Hono() app with handlers |
| Next.js | API routes | Next.js API route handlers |
Frontend
| Framework | Template | Example |
|-----------|----------|---------|
| React | Components, Hooks | Functional components with TypeScript |
| React Native | Native styles | StyleSheet.create() |
Module Elements
Clegen can generate the following elements:
| Element | Description | Group | File Example |
|---------|-------------|-------|--------------|
| routes | API endpoint handlers | routes | UserRouter.ts |
| service | Business logic layer | services | UserService.ts |
| component | React component | components | User.tsx |
| hook | React custom hook | components | useUser.tsx |
| styles | CSS styles | styles | User.css |
| styles-native | React Native styles | styles | User.styles.ts |
| types | TypeScript types/interfaces | domain | UserTypes.ts |
| entity | Domain entity | domain | User.ts |
| repository | Repository interface | domain | UserRepository.ts |
| schema | Validation schemas (Zod) | infrastructure | UserSchemas.ts |
| implementation | Repository implementation | infrastructure | MongoDBUserRepository.ts |
| utils | Utility functions | utils | UserUtils.ts |
Examples
Example 1: Express API Module
npx clegen@latest \
--name Product \
--framework express \
--elements routes,service,types,repository,implementation \
--implementation MongoDBGenerated files:
Product/
├── routes/UserRouter.ts # Express router
├── services/ProductService.ts # Business logic
├── domain/ProductTypes.ts # TypeScript types
├── domain/ProductRepository.ts # Repository interface
└── infrastructure/MongoDBProductRepository.ts # MongoDB implementationExample 2: React Component with Styles
npx clegen@latest \
--name UserProfile \
--elements component,hook,styles,typesGenerated files:
UserProfile/
├── components/UserProfile.tsx # React component
├── components/useUserProfile.tsx # Custom hook
├── styles/UserProfile.css # CSS styles
└── domain/UserProfileTypes.ts # TypeScript typesExample 3: React Native Module
npx clegen@latest \
--name Profile \
--elements component,hook,styles-native,typesGenerated files:
Profile/
├── components/Profile.tsx # React component
├── components/useProfile.tsx # Custom hook
├── styles/Profile.styles.ts # React Native StyleSheet
└── domain/ProfileTypes.ts # TypeScript typesExample 4: Full-Stack Module
npx clegen@latest \
--name Order \
--framework hono \
--elements routes,service,component,hook,styles,types,entity,repository,schema,implementation \
--implementation PostgreSQLGenerated files:
Order/
├── routes/OrderRoutes.ts # Hono routes
├── services/OrderService.ts # Business logic
├── components/Order.tsx # React component
├── components/useOrder.tsx # Custom hook
├── styles/Order.css # CSS styles
├── domain/Order.ts # Entity
├── domain/OrderTypes.ts # Types
├── domain/OrderRepository.ts # Repository interface
├── infrastructure/OrderSchemas.ts # Zod schemas
└── infrastructure/PostgreSQLOrderRepository.ts # PostgreSQL implementationExtending Clegen
Clegen is designed to be easily extensible. You can add new frameworks, templates, and elements.
Adding a New Framework
- Create a framework plugin in
src/plugins/frameworks/:
// src/plugins/frameworks/FastifyPlugin.ts
import { FrameworkPlugin } from '../../core/types/FrameworkPlugin';
import { GenerationContext, FileOutput } from '../../core/types/GenerationContext';
import { TemplateReader } from '../../core/base/TemplateReader';
export class FastifyPlugin extends TemplateReader implements FrameworkPlugin {
readonly id = 'fastify' as const;
readonly name = 'Fastify';
async generate(context: GenerationContext): Promise<FileOutput> {
const content = await this.readTemplate('routes/fastify.md', context);
return {
relativePath: `${context.entityName}Routes.ts`,
content,
};
}
}- Create the template in
src/fixtures/templates/routes/:
<!-- src/fixtures/templates/routes/fastify.md -->
import { FastifyInstance } from 'fastify';
import { {{ entity }}Service } from './{{ Entity }}Service';
export async function {{ entity }}Routes(fastify: FastifyInstance) {
fastify.get('/{{ entity }}', async (request, reply) => {
const items = await {{ entity }}Service.getAll();
return items;
});
fastify.get('/{{ entity }}/:id', async (request, reply) => {
const { id } = request.params as { id: string };
const item = await {{ entity }}Service.getById(id);
return item;
});
fastify.post('/{{ entity }}', async (request, reply) => {
const item = await {{ entity }}Service.create(request.body);
return item;
});
}- Register the plugin in
src/plugins/plugins.config.ts:
import { FastifyPlugin } from './frameworks/FastifyPlugin';
export const FRAMEWORK_PLUGINS = {
express: new ExpressPlugin(),
hono: new HonoPlugin(),
nextjs: new NextJsPlugin(),
fastify: new FastifyPlugin(), // Add your plugin
};Adding a New Template
- Create a template provider in
src/plugins/templates/:
// src/plugins/templates/GraphQLResolverTemplate.ts
import { TemplateProvider } from '../../core/types/TemplateProvider';
import { GenerationContext, FileOutput } from '../../core/types/GenerationContext';
import { TemplateReader } from '../../core/base/TemplateReader';
export class GraphQLResolverTemplate extends TemplateReader implements TemplateProvider {
readonly id = 'resolver' as const;
readonly name = 'GraphQL Resolver';
readonly category = 'api' as const;
async generate(context: GenerationContext): Promise<FileOutput> {
const content = await this.readTemplate('graphql/resolver.md', context);
return {
relativePath: `${context.entityName}Resolver.ts`,
content,
};
}
}- Create the template file:
<!-- src/fixtures/templates/graphql/resolver.md -->
import { {{ entity }}Service } from '../services/{{ Entity }}Service';
export const {{ entity }}Resolvers = {
Query: {
{{ entity }}: async (_: any, { id }: { id: string }) => {
return await {{ entity }}Service.getById(id);
},
{{ entity }}s: async () => {
return await {{ entity }}Service.getAll();
},
},
Mutation: {
create{{ Entity }}: async (_: any, { input }: { input: any }) => {
return await {{ entity }}Service.create(input);
},
},
};- Register in plugins.config.ts:
import { GraphQLResolverTemplate } from './templates/GraphQLResolverTemplate';
export const TEMPLATE_PROVIDERS = {
// ... existing templates
resolver: new GraphQLResolverTemplate(),
};Adding Custom Elements
- Add to
ModuleElementtype insrc/core/types/GenerationContext.ts:
export type ModuleElement =
| "routes"
| "service"
// ... existing elements
| "resolver" // Add your new element
| "graphql-schema";- Map to concept group in
src/core/types/ConceptMapping.ts:
export const ELEMENT_TO_GROUP: Record<ModuleElement, ConceptGroup> = {
// ... existing mappings
resolver: 'routes',
'graphql-schema': 'infrastructure',
};- Add to multiselect in
src/Generators/ModularGenerator.ts:
const { elements } = await prompt<{ elements: ModuleElement[] }>({
type: "multiselect",
name: "elements",
choices: [
// ... existing choices
{ role: "separator", message: "── GraphQL ──" },
{ name: "resolver", message: "GraphQL Resolver - Query/Mutation handlers" },
{ name: "graphql-schema", message: "GraphQL Schema - Type definitions" },
],
});Contributing
Contributions are welcome! Here's how you can help:
Development Setup
- Fork and clone the repository:
git clone https://github.com/mvrcoag/clegen.git
cd clegen- Install dependencies:
npm install- Build the project:
npm run prepare- Link for local testing:
npm link- Test your changes:
clegen --name Test --framework express --elements routes,serviceProject Structure
clegen/
├── src/
│ ├── core/ # Core types and base classes
│ │ ├── types/ # TypeScript types and interfaces
│ │ └── base/ # Base classes (TemplateReader, CliParser)
│ ├── plugins/ # Framework and template plugins
│ │ ├── frameworks/ # Framework plugins (Express, Hono, etc.)
│ │ ├── templates/ # Template providers
│ │ └── plugins.config.ts # Plugin registry
│ ├── Generators/ # Generator classes
│ │ └── ModularGenerator.ts # Main generator
│ ├── fixtures/ # Template files
│ │ └── templates/ # Markdown templates
│ └── index.ts # CLI entry point
├── dist/ # Compiled output
└── scripts/ # Build scriptsGuidelines
- TypeScript: Use strict typing, avoid
any - Templates: Use Markdown files with
{{ placeholders }} - Imports: Ensure cross-group imports use correct relative paths
- Tests: Add tests for new features (when test suite is available)
- Documentation: Update README for new features
Submitting Changes
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes
- Build and test:
npm run prepare && clegen --name Test ... - Commit:
git commit -m "feat: add my feature" - Push:
git push origin feature/my-feature - Open a Pull Request
License
This project is licensed under the MIT License.
