@voilajsx/appkit
Version:
Minimal and framework agnostic Node.js toolkit designed for AI agentic backend development
507 lines (395 loc) ⢠14 kB
Markdown
# AppKit CLI Documentation
## Overview
The AppKit CLI is a powerful command-line interface for creating production-ready TypeScript backend applications with Feature-Based Component Architecture (FBCA). It provides auto-discovery routing, complete authentication systems, secure environment configuration, database integration, and follows modern development best practices.
## Installation
```bash
npm install -g @voilajsx/appkit
```
## Quick Start
```bash
# Create a new app
appkit generate app myproject
cd myproject
# Add authentication system
appkit generate feature user
# Add custom features
appkit generate feature product
appkit generate feature order
# Start development
npm run dev:api
```
## Commands Overview
| Command | Description | When to Use | Security Features |
|---------|-------------|-------------|-------------------|
| `generate app [name]` | Create complete backend app | Starting new project | Random secure keys, GitHub-safe |
| `generate feature <name>` | Add custom CRUD feature | Need basic API endpoints | Follows security patterns |
| `generate feature user` | Add authentication system | Need user management/auth | JWT, role-based access, 9-role hierarchy |
## Commands Reference
### š `appkit generate app [name]`
Creates a complete TypeScript backend application with modern architecture.
**Usage:**
```bash
# Create in current directory
appkit generate app
# Create in new directory
appkit generate app myproject
```
**What it creates:**
```
myproject/
āāā package.json # Dependencies & scripts
āāā tsconfig.json # TypeScript configuration
āāā .env # Secure environment variables
āāā prisma/
ā āāā schema.prisma # Database schema
āāā src/api/
āāā server.ts # Main server
āāā lib/
ā āāā api-router.ts # Auto-discovery router
āāā features/
āāā welcome/ # Default welcome feature
āāā sample/ # Example CRUD feature
āāā new/ # Example feature
```
**⨠Features:**
- ā
**Secure by default** - Random 44-char auth secrets, 26-char API keys
- ā
**GitHub-safe** - No hardcoded credentials
- ā
**TypeScript ready** - Full type safety with proper configuration
- ā
**Auto-discovery** - Routes automatically discovered and mounted
- ā
**Production-ready** - Environment separation, logging, error handling
- ā
**Database ready** - Prisma integration with SQLite default
**Generated .env file:**
```bash
DATABASE_URL="file:./dev.db"
VOILA_FRONTEND_KEY="voila_abc123..." # 26 characters
VOILA_AUTH_SECRET="auth_xyz789..." # 44 characters
DEFAULT_USER_PASSWORD="pwd9x7k4m2" # 10 alphanumeric
```
### š§ `appkit generate feature <name>`
Creates a custom feature with complete CRUD operations.
**Usage:**
```bash
appkit generate feature product
appkit generate feature order
appkit generate feature blog
```
**What it creates:**
```
src/api/features/product/
āāā product.route.ts # Express routes with CRUD endpoints
āāā product.service.ts # Business logic with validation
āāā product.types.ts # TypeScript interfaces
āāā product.model.ts # Database model
āāā product.http # HTTP test file
```
**Generated endpoints:**
- `GET /api/product` - Get all records
- `POST /api/product` - Create new record
- `GET /api/product/:id` - Get record by ID
- `PUT /api/product/:id` - Update record
- `DELETE /api/product/:id` - Delete record
**When to use:**
- ā
Need custom business logic
- ā
Want specific data models
- ā
Building domain-specific APIs
- ā
Rapid prototyping
### š `appkit generate feature user`
Creates a complete authentication and user management system.
**Usage:**
```bash
appkit generate feature user
```
**What it creates:**
```
src/api/features/user/
āāā user.route.ts # Authentication routes
āāā user.service.ts # Auth business logic
āāā user.types.ts # User interfaces
āāā user.model.ts # User database model
āāā user.http # Complete test suite
prisma/seeding/
āāā user.seed.js # Seed data for all roles
```
**š Authentication Features:**
- ā
**JWT Authentication** - Secure token-based auth
- ā
**9-Role Hierarchy** - user.basic ā admin.system
- ā
**Password Security** - bcrypt hashing, random generation
- ā
**Role-based Access** - Route protection by role/level
- ā
**Complete User Management** - CRUD for admin users
- ā
**Password Reset** - Forgot/reset password flow
- ā
**Account Management** - Profile updates, password changes
**Generated endpoints:**
```
# Authentication
POST /api/user/register # Create new user
POST /api/user/login # User login
POST /api/user/forgot-password # Request password reset
POST /api/user/reset-password # Reset with token
# Profile Management
GET /api/user/profile # Get user profile
PUT /api/user/profile # Update profile
POST /api/user/change-password # Change password
# Admin Only
GET /api/user/all # Get all users
GET /api/user/list # Get users (moderator+)
PUT /api/user/list/:id # Update user
DELETE /api/user/list/:id # Delete user
```
**š”ļø Role Hierarchy:**
```
User Roles (Level 1-3):
āāā user.basic # Basic user permissions
āāā user.pro # Pro user features
āāā user.max # Maximum user features
Moderator Roles (Level 4-6):
āāā moderator.review # Can review content
āāā moderator.approve # Can approve/reject
āāā moderator.manage # Can manage users
Admin Roles (Level 7-9):
āāā admin.tenant # Tenant administration
āāā admin.org # Organization administration
āāā admin.system # System administration
```
**When to use:**
- ā
Need user accounts and authentication
- ā
Building multi-user applications
- ā
Need role-based access control
- ā
Want production-ready auth system
- ā
Building SaaS or enterprise apps
## Decision Guide
### When to use `generate app`
- šÆ **Starting a new project**
- šÆ **Need complete backend foundation**
- šÆ **Want security best practices built-in**
- šÆ **Building production applications**
### When to use `generate feature <name>`
- šÆ **Adding business-specific functionality**
- šÆ **Need custom data models**
- šÆ **Building domain APIs (products, orders, etc.)**
- šÆ **Rapid prototyping**
### When to use `generate feature user`
- šÆ **Need user authentication**
- šÆ **Building multi-user applications**
- šÆ **Need role-based permissions**
- šÆ **Want enterprise-grade user management**
## Architecture
### Feature-Based Component Architecture (FBCA)
Each feature is self-contained and follows consistent patterns:
```
src/api/features/<feature>/
āāā <feature>.route.ts # HTTP endpoints & middleware
āāā <feature>.service.ts # Business logic & validation
āāā <feature>.types.ts # TypeScript interfaces
āāā <feature>.model.ts # Database schema
āāā <feature>.http # API testing
```
### Auto-Discovery System
- š **Automatic route detection** - Scans `/features` directory
- š **Zero configuration** - Routes auto-mount at `/api/{feature}`
- š **Hot-reload friendly** - Changes reflected immediately
- š **Discovery endpoint** - `GET /api` lists all features
### Security Architecture
**Environment Security:**
- š **Random key generation** - Unique per project
- š« **No hardcoded secrets** - GitHub-safe repositories
- š”ļø **Environment separation** - Dev/prod configurations
- š **Secure defaults** - Strong random passwords
**Authentication Security:**
- š« **JWT tokens** - Stateless authentication
- š **Password hashing** - bcrypt with salt rounds
- š”ļø **Role-based access** - Granular permissions
- š **Token validation** - Middleware protection
## Development Workflow
### 1. Project Setup
```bash
# Create project
appkit generate app myapp
cd myapp
# Install dependencies (auto-done)
npm install
# Start development
npm run dev:api
```
### 2. Add Authentication
```bash
# Add complete auth system
appkit generate feature user
# Seed test users
node prisma/seeding/user.seed.js
# Test login
curl -X POST http://localhost:3000/api/user/login \
-H "Content-Type: application/json" \
-d '{"email":"admin.system@myapp.com","password":"YOUR_DEFAULT_PASSWORD"}'
```
### 3. Add Custom Features
```bash
# Add business features
appkit generate feature product
appkit generate feature order
appkit generate feature customer
```
### 4. Test & Deploy
```bash
# Run tests
npm test
# Build for production
npm run build
# Start production
npm run start:prod
```
## Environment Configuration
### Auto-Generated .env
```bash
# Server Configuration
PORT=3000
NODE_ENV=development
# Database Configuration
DATABASE_URL="file:./dev.db"
# Application Configuration
APP_NAME=myapp
API_VERSION=1.0.0
# Security (Auto-generated, GitHub-safe)
VOILA_FRONTEND_KEY=voila_abc123def456... # 26 chars
VOILA_AUTH_SECRET=auth_xyz789abc123... # 44 chars
DEFAULT_USER_PASSWORD=pwd9x7k4m2 # 10 chars
# Logging
LOG_LEVEL=info
```
### Production Environment
```bash
# Override for production
NODE_ENV=production
PORT=8080
DATABASE_URL="postgresql://user:pass@host:5432/db"
LOG_LEVEL=warn
```
## Available Scripts
| Script | Description | When to Use |
|--------|-------------|-------------|
| `npm run dev:api` | Development server with hot-reload | During development |
| `npm run build` | Build TypeScript to JavaScript | Before deployment |
| `npm run start:prod` | Start production server | Production deployment |
| `npm run start` | Start without build | Quick production start |
## Testing
### HTTP Test Files
Each feature includes a `.http` file for easy testing:
```http
### Test login
POST http://localhost:3000/api/user/login
Content-Type: application/json
{
"email": "admin.system@myapp.com",
"password": "YOUR_DEFAULT_PASSWORD"
}
### Test protected endpoint
GET http://localhost:3000/api/user/profile
Authorization: Bearer YOUR_JWT_TOKEN
```
### Integration Testing
```bash
# Test endpoints with curl
curl http://localhost:3000/health
curl http://localhost:3000/api
curl http://localhost:3000/api/user/test
```
## AppKit Integration
### Database
```typescript
import { databaseClass } from '@voilajsx/appkit/database';
const db = await databaseClass.get();
const users = await db.user.findMany();
```
### Authentication
```typescript
import { authClass } from '@voilajsx/appkit/auth';
const auth = authClass.get();
const token = auth.generateLoginToken({ userId, role, level });
```
### Error Handling
```typescript
import { errorClass } from '@voilajsx/appkit/error';
const error = errorClass.get();
throw error.badRequest('Invalid input');
throw error.notFound('User not found');
```
### Logging
```typescript
import { loggerClass } from '@voilajsx/appkit/logger';
const logger = loggerClass.get('feature-name');
logger.info('Request processed', { userId });
```
## Best Practices
### Security
- ā
**Use environment variables** for all secrets
- ā
**Never commit .env files** to version control
- ā
**Use role-based access control** for sensitive endpoints
- ā
**Validate all inputs** in service layers
- ā
**Use JWT tokens** for stateless authentication
### Code Organization
- ā
**Follow FBCA patterns** - keep features self-contained
- ā
**Use TypeScript interfaces** for type safety
- ā
**Implement proper error handling** with AppKit error classes
- ā
**Add comprehensive logging** for debugging
- ā
**Write HTTP tests** for all endpoints
### Database
- ā
**Use AppKit database class** for consistency
- ā
**Include tenant_id fields** for multi-tenancy
- ā
**Transform dates to ISO strings** in responses
- ā
**Implement input validation** before database operations
## Troubleshooting
### Common Issues
**Feature not discovered:**
- ā
Check file naming: `{feature}.route.ts`
- ā
Ensure default export: `export default router`
- ā
Verify directory structure: `features/{feature}/`
**Authentication errors:**
- ā
Check `VOILA_AUTH_SECRET` in .env
- ā
Verify password in seeding
- ā
Test with correct user credentials
**Database connection issues:**
- ā
Verify `DATABASE_URL` in .env
- ā
Run `npx prisma generate`
- ā
Run `npx prisma db push`
**TypeScript compilation errors:**
- ā
Check import paths use `.js` extensions
- ā
Verify `moduleResolution: "bundler"` in tsconfig
- ā
Ensure proper AppKit module imports
## Examples
### Complete User Management Flow
```bash
# 1. Create app with auth
appkit generate app userapp
cd userapp
appkit generate feature user
# 2. Seed test users
node prisma/seeding/user.seed.js
# 3. Test authentication
curl -X POST http://localhost:3000/api/user/login \
-H "Content-Type: application/json" \
-d '{"email":"admin.system@userapp.com","password":"YOUR_DEFAULT_PASSWORD"}'
# 4. Use JWT token for protected endpoints
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
http://localhost:3000/api/user/profile
```
### E-commerce API Example
```bash
# Create e-commerce backend
appkit generate app shopapi
cd shopapi
# Add authentication
appkit generate feature user
# Add business features
appkit generate feature product
appkit generate feature order
appkit generate feature customer
appkit generate feature category
# Result: Complete e-commerce API with auth
# GET /api/user/* - User management
# GET /api/product/* - Product catalog
# GET /api/order/* - Order management
# GET /api/customer/* - Customer data
# GET /api/category/* - Product categories
```
---
**AppKit CLI - Production-ready backend applications in minutes, not hours.** š
**Generated with AppKit CLI v3.0 - Enhanced with Authentication, Security, and GitHub-safe Repositories**