Code Generation (~~)

Generate valid NAIDE code from natural language instructions. No AI, no network, no dependencies — pure pattern matching + template composition with self-healing parser validation. Runs in microseconds.

CLI Usage

Use ~~ or gen followed by a quoted instruction:

naide ~~ "REST API for users with auth"
naide gen "todo app with database"
naide ~~ "Discord bot with hello command"
naide ~~ "blog app with auth and websocket"
naide ~~ "users and products and orders with auth"
naide gen "chat app"

Japanese instructions are fully supported:

naide ~~ "ユーザー管理APIを認証付きで"
naide ~~ "掲示板アプリ"
naide ~~ "ECサイト"
naide ~~ "チャットアプリ"

Write the output to a file with -o:

naide ~~ "REST API for users" -o app.naide

Multi-Target Output

Generate and compile to any of the 15 supported targets with --target:

naide ~~ "REST API for users" --target python    # Python/Flask
naide ~~ "todo app" --target go                  # Go/net-http
naide ~~ "REST API for users" --target rust       # Rust/actix-web
naide ~~ "REST API for users" --target all        # All 15 targets
naide ~~ "REST API for users" --target all -o app # app.py, app.go, app.rs, ...

Targets: node, python, bun, typescript, go, java, rust, cpp, c, csharp, kotlin, swift, dart, php, ruby.

Multi-Entity Support

Specify multiple entities separated by spaces, and, &, or ,. The engine detects parent-child and many-to-many relationships automatically:

naide ~~ "users products orders with auth"
naide ~~ "users and products and orders with auth"

This generates 3 schemas (User, Product, Order), detects that User → Order and Product → Order, and adds user_id and product_id FK fields automatically. Each entity gets full CRUD, paginated list, soft delete, batch operations, nested routes, and tests.

Composite keywords also expand to multiple entities:

naide ~~ "shop"       # User + Product + Order
naide ~~ "ECサイト"    # User + Product + Order
naide ~~ "crm"        # User + Contact + Deal + Activity
naide ~~ "sns"        # User + Post + Comment + Message + Notification

Project Mode

Generate a complete project directory with all supporting files:

naide ~~ "e-commerce app with auth" --project

This creates a directory with 17 files:

Project Update

Run --project again on an existing project directory to add entities and features incrementally:

# Step 1: Create project
naide ~~ "chat app" --project -o my-app

# Step 2: Add users with auth
naide ~~ "users with auth" --project -o my-app

# Step 3: Add products
naide ~~ "products" --project -o my-app

# Step 4: Remove an entity
naide ~~ "remove products" --project -o my-app

The engine detects the existing app.naide, combines all entities, regenerates the full code with relationships, and updates all 15 supporting files.

Entity removal is supported via remove, delete, or drop keywords. The engine filters out the target entities and regenerates the project without them.

File Write Mode

Write generated code directly to a .naide file:

naide ~~ "REST API for users with auth" --write app.naide
naide ~~ "todo app" --write todo.naide
naide ~~ "users API" --write app.naide --replace

Without --replace, the engine merges intelligently — avoids duplicate schemas and servers. With --replace, the file is overwritten completely.

Generated Features

Every server-type generation automatically includes:

Per-Entity Routes

RouteDescription
GET /api/users?page=1&limit=20&search=&sort=id&order=descPaginated list with search, sort, filter
POST /api/usersCreate (with validation)
GET /api/users/:idGet by ID
PUT /api/users/:idUpdate (with validation)
DELETE /api/users/:idHard delete
DELETE /api/users/:id/softSoft delete (sets deleted = true)
PUT /api/users/:id/restoreRestore soft-deleted
POST /api/users/batchBatch create
DELETE /api/users/batchBatch delete

Nested Routes (from relationships)

When parent-child relationships are detected, nested routes are generated:

GET /api/users/:userId/orders    # Orders by User
GET /api/users/:userId/posts     # Posts by User
GET /api/products/:productId/orders  # Orders by Product

Global Routes

RouteDescription
GET /api/healthHealth check with entity counts
POST /api/uploadFile upload endpoint
POST /api/webhooksRegister a webhook
GET /api/webhooks/healthWebhook health check

Auth Routes (when auth intent detected)

RouteDescription
POST /api/auth/registerUser registration
POST /api/auth/loginJWT login
GET /api/auth/meCurrent user profile
POST /api/auth/forgot-passwordRequest password reset token
POST /api/auth/reset-passwordReset password with token
POST /api/auth/change-passwordChange password (authenticated)
GET /api/admin/statsAdmin-only aggregate stats

Many-to-Many Routes

When two entities have a known M:N relationship (e.g., User ↔ Product), a junction table and link/unlink routes are auto-generated:

RouteDescription
GET /api/users/:id/productsProducts for a User (via Favorite junction)
GET /api/products/:id/usersUsers for a Product
POST /api/favoriteLink User ↔ Product
DELETE /api/favoriteUnlink User ↔ Product

Known M:N pairs: User↔Product (Favorite), User↔Team (TeamMember), Post↔Category (PostTag), Product↔Category (ProductCategory), User↔Group (GroupMember).

Utility Functions

Standard response helpers and input sanitization:

fn ok(any data, any meta) → {ok: true, data, meta}
fn err(str message, int code) → {ok: false, error: message, code}
fn sanitize(str input) → stripped HTML tags

Input Validation

A validateEntity(body) function is generated per entity, checking required fields, types, enum values, and min/max constraints. POST and PUT routes call validation before saving.

Rate Limiting & Logging

A rateLimit(windowMs, maxReqs) function and a requestLogger(req, res, next) middleware are generated for production hardening.

Caching

A GET /api/cache-demo route demonstrates Cache-Control headers for static content caching.

Swagger UI

A GET /docs route serves an interactive Swagger UI page powered by the generated OpenAPI spec at /api/openapi.json. Both routes are public (no auth required).

RBAC (Role-Based Access Control)

When auth is enabled, a requireRole(allowed) middleware function is generated. Delete routes require admin or moderator role. Roles: user, admin, moderator.

WebSocket Rooms + Auth

When websocket intent is detected, room-based WebSocket is generated with join, leave, and broadcast actions. Messages are scoped to rooms. When auth is also enabled, WS connections require a JWT token via ?token= query parameter — unauthenticated clients are rejected.

Frontend SPA

Project mode generates an index.html with a complete single-page application:

Integration Tests

Project mode generates a test.mjs file with HTTP integration tests using Node.js built-in test runner. Tests cover:

Run with npm test (requires server running).

Database Migration

Project mode generates a migrate.naide file with SQL DDL for all entities. Includes migrate() (CREATE TABLE with types, constraints, foreign keys) and rollback() (DROP TABLE). Run with npm run migrate.

Enum Validation

Fields named status, priority, role, or visibility automatically get enum validation with preset allowed values.

Audit Log

When auth is enabled, an AuditLog schema and auditLog() function are generated for tracking actions.

Seed Function

A fn seed() function is generated with sample data for each entity, callable via npm run seed in project mode.

Auto-Generated Tests

CRUD test suites are generated for each entity — create, find, list, remove with assertions.

Inline Directives

Use ~~ inside .naide files. The directive is expanded at compile time, before parsing:

# app.naide
~~ "REST API for users with auth"

# You can mix with hand-written code
fn customRoute(req, res):
  ret {custom: true}

Debug the expansion with --expand:

naide --expand app.naide

API Usage

Use programmatically in JavaScript/TypeScript:

import { generate, generateProject } from 'naider';

const result = generate("users and products with auth");

console.log(result.code);          // generated NAIDE source code
console.log(result.valid);         // true (parser-validated)
console.log(result.intents);       // ['server', 'schema', 'crud', 'auth', 'database']
console.log(result.entities);      // ['User', 'Product']
console.log(result.relationships); // [{parent:'User', child:'Product', fk:'user_id'}]
console.log(result.port);          // 3000
console.log(result.fixed);         // false (true if auto-repaired)
console.log(result.repairs);       // [] (list of auto-fix descriptions)
console.log(result.analysis);      // {entities, relationships, plan, ...}

// Full project generation (17 files)
const project = generateProject("e-commerce with auth");
project.files.forEach(f => console.log(f.path));
// app.naide, package.json, .env, .env.development, .env.production,
// Dockerfile, .dockerignore, docker-compose.yml, README.md,
// openapi.json, admin.html, index.html, client.mjs, test.mjs,
// migrate.naide, .github/workflows/ci.yml

// Multi-target: generate for a specific target
import { generateForTarget, generateAllTargets } from 'naider';

const py = await generateForTarget("users API", "python");
console.log(py.compiled);  // Python/Flask code
console.log(py.target);    // "python"

// Generate for ALL 15 targets at once
const all = await generateAllTargets("todo app");
for (const [target, result] of Object.entries(all.targets)) {
  console.log(target, result.ext, result.error || 'OK');
}

MCP Server

The naide_generate tool is available via the MCP server for AI agent integration:

naide-mcp

The tool accepts instruction, port, and schemaName parameters, and returns generated code with metadata.

Self-Healing Validation

Generated code is validated against the actual NAIDE parser. If a parse error occurs, the engine auto-repairs it (up to 5 retries):

Repairs are logged in result.repairs:

["L5: added missing ':' at end of block header",
 "L8: renamed reserved word 'post' → 'postApp'"]

Field Normalization

Field names are automatically normalized via a synonym dictionary:

InputNormalizedInferred Type
e-mail, mail_addressemailstr + email
pwd, passwdpasswordstr + min(8)
tel, phone_numberphonestr
desc, detaildescriptionstr
img, pic, avatarimagestr
qtyquantityint
is_done, is_activedone, activebool
created_atcreatedauto

Keyword Cheat Sheet

Intent Keywords

KeywordWhat it generates
server api rest web backendServer block with Express
schema model entitySchema definition with fields
crud create listAuto-generated REST endpoints
auth jwt loginJWT authentication middleware
database db storagePersistent storage (db "data/")
botBot with event handlers
cli command terminalCLI app with flags
page html frontendHTML page generation
test specTest block with assertions
websocket ws realtimeWebSocket endpoint
ai llm gptAI prompt endpoint
mail smtpEmail configuration
graphql gqlGraphQL endpoint

Composite Keywords

These trigger multiple intents and multi-entity generation:

KeywordEntitiesIntents
todoTodoserver + crud + database
blogPostserver + crud + database
chatMessageserver + websocket + database
shop ecommerce ECサイトUser + Product + Orderserver + crud + auth + database
fullstack(from instruction)server + crud + auth + database
board 掲示板Postserver + crud + database
crmUser + Contact + Deal + Activityserver + crud + auth + database
inventoryProduct + Category + Inventoryserver + crud + auth + database
booking 予約User + Event + Reservationserver + crud + auth + database
snsUser + Post + Comment + Message + Notificationserver + crud + auth + websocket + database

Natural Language Detection

Complex phrases are parsed into intents:

PhraseDetected
"users can comment", "users post reviews"auth + crud
"admin delete", "admin manage"auth + admin routes
"upload", "file upload"upload route
"search", "filter", "sort"paginated list
"notification", "push", "alert"websocket
"deploy", "docker", "container"Docker support
"seed", "初期データ", "サンプルデータ"seed function

Platform & DB Keywords

KeywordEffect
discord slack telegram lineBot platform selection
sqlitedb.sql "sqlite"
postgresdb.sql "postgres"

Japanese Keywords

CategoryKeywords
Intentサーバー 認証 ログイン 会員 CRUD 管理 データベース ボット テスト ページ メール リアルタイム
Entityユーザー 商品 記事 タスク 注文 コメント イベント 問い合わせ 通知 カテゴリ 掲示板 決済 予約 社員
Composite管理システム やることリスト ブログ チャットアプリ ECサイト 掲示板

Field Specification

Add with followed by field names to customize the schema:

naide ~~ "REST API for users with name email age role"

Field types are auto-inferred from names: id→auto, email→str+email, age→int, done→bool, created→auto. Without with, preset fields are used based on the entity name.

Agent-Style Analysis

The CLI shows an analysis header before code output, including detected entities, relationships, plan, and feature counts:

--- NAIDE Agent Analysis ---
Entities: User (5 fields), Product (6 fields), Order (5 fields)
Relations: User → Order (user_id), Product → Order (product_id)
Intents: server, schema, crud, auth, database
Routes: 9 per entity + 3 nested + 6 global
Plan: Define User/Product/Order schemas, configure database, create server with CRUD...

Examples

Multi-Entity E-commerce

naide ~~ "users and products and orders with auth"

Generates: 3 schemas with auto FK relations, paginated CRUD, soft delete, batch ops, nested routes, seed, tests, auth with admin stats

Full Project (15 files)

naide ~~ "e-commerce app with auth" --project

Generates: complete project with source, package.json, Docker + Compose, OpenAPI, admin dashboard, frontend SPA, API client, CI pipeline, env configs, README

CRM System

naide ~~ "crm"

Generates: User + Contact + Deal + Activity with auth, relationships, full CRUD stack

Write to File

naide ~~ "REST API for users with auth" --write app.naide

Generates and writes directly to app.naide, merging with existing code

Japanese: EC Site

naide ~~ "ECサイト"

Generates: User + Product + Order with auth, same as English "shop" composite