spfn
Version:
Superfunction CLI - Add SPFN to your Next.js project
260 lines (212 loc) • 8.46 kB
Markdown
# spfn
> Superfunction CLI - The Backend Layer for Next.js
The official CLI tool for SPFN framework. Initialize projects, generate boilerplate code, and manage your database.
## Usage
> ⚠️ **Alpha Release**: SPFN is currently in alpha. Use `@alpha` tag for installation.
### Quick Start (New Project)
```bash
# Create new project with all SPFN features pre-configured
npx spfn@alpha create my-app
cd my-app
docker compose up -d
npm run spfn:dev
```
### Add to Existing Next.js Project
```bash
# Using npx (no installation required) - Recommended
npx spfn@alpha init
# Or install globally (alpha version)
npm install -g spfn@alpha
spfn init
```
## Commands
### Create New Project
```bash
spfn create <name> # Create new Next.js project with SPFN (all-in-one)
spfn create my-app # Example: Create project with TypeScript, App Router, SVGR, and SPFN
spfn create my-app --shadcn # Include shadcn/ui component library
```
### Project Initialization
```bash
spfn init # Initialize SPFN in existing Next.js project
spfn init -y # Skip prompts, use defaults
```
**What `spfn init` creates:**
- `src/lib/contracts/` - API contracts (shared between frontend and backend)
- `src/server/routes/` - Backend route handlers
- `src/server/entities/` - Database entities (Drizzle ORM)
- `docker-compose.yml` - PostgreSQL + Redis for local development
- `Dockerfile`, `.dockerignore`, `docker-compose.production.yml` - Production deployment
- `.env.local.example` - Environment variable template
- `spfn.config.js` - Deployment configuration with JSDoc type hints
- `.spfnrc.json` - Code generation configuration
**SPFN's Contract-Based Architecture:**
- **Contracts** (`src/lib/contracts/`): Define API endpoints with absolute paths (e.g., `/users/:id`)
- **Handlers** (`src/server/routes/`): Import contracts and implement business logic
- **Frontend**: Import contracts for type-safe API calls
- **Auto-generated Client**: `src/lib/api/` is auto-generated from contracts (via `spfn dev` or `spfn build`)
### Generate Function Modules
```bash
spfn generate fn <name> # Generate new SPFN function module (interactive)
spfn g fn <name> # Short alias
# With options
spfn g fn blog -e posts,comments -y # Create blog module with posts & comments entities
spfn g fn shop -d "E-commerce shop" -e products,orders,customers
```
**What `spfn generate fn` creates:**
- `packages/<name>/` - New function module in monorepo
- `src/server/entities/schema.ts` - **Exported schema** (ensures CREATE SCHEMA in migrations)
- `src/server/entities/*.ts` - Drizzle ORM entity definitions (import schema)
- `src/server/repositories/` - CRUD repository layer
- `src/server/routes/` - RESTful API route handlers
- `src/lib/contracts/` - TypeBox API contracts
- `package.json` - Pre-configured with SPFN metadata
- `tsup.config.ts` - Build configuration
- `drizzle.config.ts` - Database migration setup
**Database Schema Naming:**
- Scope and module name are automatically converted to safe PostgreSQL schema names
- Examples: `@my-company/blog` → `my_company_blog`, `@spfn/cms` → `spfn_cms`
- Special characters (`.`, `!`, `-`) are converted to underscores
- Names starting with numbers get `_` prefix (e.g., `@123company` → `_123company`)
- Ensures PostgreSQL compatibility (lowercase, numbers, underscores only)
**Options:**
- `-e, --entities <list>` - Comma-separated entity names
- `-d, --description <text>` - Module description
- `--skip-routes` - Generate entities without routes
- `--skip-cache` - Skip cache generation
- `-y, --yes` - Skip all prompts
**Example workflow:**
```bash
# 1. Generate module
spfn g fn blog -e posts,comments -y
# 2. Build the module
cd packages/blog
npm run build
# 3. Install in your app
spfn add @spfn/blog
```
### Install Ecosystem Packages
```bash
spfn add <package> # Install SPFN ecosystem package with automatic DB setup
spfn add @spfn/cms # Install CMS package
spfn add @company/plugin # Install third-party SPFN package
```
**What `spfn add` does:**
1. ✅ Installs the package via pnpm/npm
2. ✅ Discovers package's pre-built migrations
3. ✅ Applies package migrations to your database
4. ✅ Shows package-specific setup guide
**Example: Installing @spfn/cms**
```bash
$ pnpm spfn add @spfn/cms
📦 Setting up @spfn/cms...
✓ Package installed
🗄️ Setting up database for @spfn/cms...
✓ Migrations applied
✅ @spfn/cms installed successfully!
📚 Setup Guide:
1. Import CMS components: import { useLabels } from '@spfn/cms'
2. View labels in Drizzle Studio: pnpm spfn db studio
3. Learn more: https://github.com/spfnio/spfn
```
**How it works:**
- SPFN automatically discovers schemas from packages via `package.json`:
```json
{
"name": "@spfn/cms",
"spfn": {
"schemas": ["./dist/server/entities/*.js"],
"migrations": { "dir": "./migrations" },
"setupMessage": "📚 Next steps: ..."
}
}
```
- Packages include pre-built migrations in their `migrations/` directory
- Package migrations are applied first, then project migrations
- Works with both published npm packages and local development (workspace packages)
### Development & Production
```bash
# Development
spfn dev # Start both Next.js (3790) + API server (8790)
spfn dev --server-only # Start API server only (8790)
spfn dev --no-watch # Disable hot reload
# Production
spfn build # Build Next.js + compile server
spfn start # Start production server
spfn start --server-only # Start API server only (no Next.js)
```
### Database Management
```bash
spfn db generate # Generate database migrations
spfn db push # Push schema to database (no migrations)
spfn db migrate # Run pending migrations
spfn db studio # Open Drizzle Studio (database GUI)
spfn db check # Check database connection
spfn db drop # Drop all tables (⚠️ dangerous!)
```
### Setup Features
```bash
spfn setup icons # Setup SVGR for SVG icon management
```
### Utilities
```bash
spfn key # Generate encryption key for .env
```
## Configuration
### spfn.config.js
SPFN uses `spfn.config.js` for deployment configuration with full JSDoc type support for IDE autocomplete.
**Basic Configuration:**
```javascript
/**
* @type {import('spfn').SpfnConfig}
*/
export default {
packageManager: 'pnpm',
deployment: {
// Your app's subdomain on spfn.app
// Creates region-specific domains:
// - myapp.us.spfn.app (Next.js)
// - api-myapp.us.spfn.app (API)
subdomain: 'myapp',
// Optional: Deployment region (defaults to 'us')
// Available: 'us' (Virginia, default), 'kr' (Seoul), 'jp', 'sg', 'eu' (coming soon)
region: 'us',
// Optional: Add custom domains
customDomains: {
nextjs: ['www.example.com', 'example.com'],
spfn: ['api.example.com']
},
// Optional: Environment variables for both Next.js and SPFN backend
// ⚠️ WARNING: These values are committed to Git
// Do NOT put sensitive credentials here!
env: {
NEXT_PUBLIC_API_URL: 'https://api-myapp.us.spfn.app',
NODE_ENV: 'production'
}
}
}
```
**Features:**
- **JSDoc Type Hints** - IDE autocomplete via `@type {import('spfn').SpfnConfig}`
- **Multi-Region Deployment** - Deploy to Seoul (kr), Virginia (us), and more
- **Dual Domain Setup** - Automatic `{subdomain}.{region}.spfn.app` and `api-{subdomain}.{region}.spfn.app`
- **Custom Domains** - Support for multiple custom domains
- **Environment Variables** - Shared between Next.js and SPFN backend
- **ESM/CJS Support** - Works with both module systems
**Security Note:**
- `spfn.config.js` is committed to Git
- Only use for non-sensitive configuration
- For secrets (DB passwords, API keys), use CI/CD secrets management
## Documentation
For complete documentation and guides, see:
- **[SPFN Framework](../../README.md)** - Getting started
- **[@spfn/core](../core/README.md)** - API reference and core concepts
## Requirements
- Node.js 18+
- Next.js 15+ (App Router)
- PostgreSQL (optional: Redis)
## Links
- 🌐 Website: [superfunction.xyz](https://superfunction.xyz)
- 📦 npm: [spfn](https://npmjs.com/package/spfn) (CLI)
- 📦 npm: [@spfn/core](https://npmjs.com/package/@spfn/core) (Core)
- 💬 GitHub: [spfn/spfn](https://github.com/spfn/spfn)