From 076dce2861a9ec767a9fe52de3bf5f998c4cdd67 Mon Sep 17 00:00:00 2001 From: ru44 <18311071+ru44@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:09:32 +0300 Subject: [PATCH 01/29] refactor(cli): route argv to scaffold, make and skills commands --- CLAUDE.md => .claude/CLAUDE.md | 0 .../skills => skills}/cliuno-matrix/SKILL.md | 0 .../cliuno-matrix/evals/evals.json | 0 .../cliuno-matrix/references/backends.md | 0 .../cliuno-matrix/references/contract.md | 0 .../cliuno-scaffold/SKILL.md | 0 .../cliuno-scaffold/references/stacks.md | 0 src/app.ts | 138 +++++------------- src/cli/argv.test.ts | 38 +++++ src/cli/argv.ts | 81 ++++++++++ src/commands/scaffold.ts | 110 ++++++++++++++ 11 files changed, 264 insertions(+), 103 deletions(-) rename CLAUDE.md => .claude/CLAUDE.md (100%) rename {.claude/skills => skills}/cliuno-matrix/SKILL.md (100%) rename {.claude/skills => skills}/cliuno-matrix/evals/evals.json (100%) rename {.claude/skills => skills}/cliuno-matrix/references/backends.md (100%) rename {.claude/skills => skills}/cliuno-matrix/references/contract.md (100%) rename {.claude/skills => skills}/cliuno-scaffold/SKILL.md (100%) rename {.claude/skills => skills}/cliuno-scaffold/references/stacks.md (100%) create mode 100644 src/cli/argv.test.ts create mode 100644 src/cli/argv.ts create mode 100644 src/commands/scaffold.ts diff --git a/CLAUDE.md b/.claude/CLAUDE.md similarity index 100% rename from CLAUDE.md rename to .claude/CLAUDE.md diff --git a/.claude/skills/cliuno-matrix/SKILL.md b/skills/cliuno-matrix/SKILL.md similarity index 100% rename from .claude/skills/cliuno-matrix/SKILL.md rename to skills/cliuno-matrix/SKILL.md diff --git a/.claude/skills/cliuno-matrix/evals/evals.json b/skills/cliuno-matrix/evals/evals.json similarity index 100% rename from .claude/skills/cliuno-matrix/evals/evals.json rename to skills/cliuno-matrix/evals/evals.json diff --git a/.claude/skills/cliuno-matrix/references/backends.md b/skills/cliuno-matrix/references/backends.md similarity index 100% rename from .claude/skills/cliuno-matrix/references/backends.md rename to skills/cliuno-matrix/references/backends.md diff --git a/.claude/skills/cliuno-matrix/references/contract.md b/skills/cliuno-matrix/references/contract.md similarity index 100% rename from .claude/skills/cliuno-matrix/references/contract.md rename to skills/cliuno-matrix/references/contract.md diff --git a/.claude/skills/cliuno-scaffold/SKILL.md b/skills/cliuno-scaffold/SKILL.md similarity index 100% rename from .claude/skills/cliuno-scaffold/SKILL.md rename to skills/cliuno-scaffold/SKILL.md diff --git a/.claude/skills/cliuno-scaffold/references/stacks.md b/skills/cliuno-scaffold/references/stacks.md similarity index 100% rename from .claude/skills/cliuno-scaffold/references/stacks.md rename to skills/cliuno-scaffold/references/stacks.md diff --git a/src/app.ts b/src/app.ts index ea78a0f..b7a8f77 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,118 +1,50 @@ #!/usr/bin/env node "use strict"; -import chalk from "chalk"; -import shell from "shelljs"; -import { select } from "@inquirer/prompts"; -import * as messages from "./utils/messages"; -import * as handler from "./utils/GitHandler"; +import { parseArgv } from "./cli/argv"; import { runDoctor } from "./utils/doctor"; -import { questions } from "./utils/questions"; +import { banner, runScaffold } from "./commands/scaffold"; +import { runMake, MAKE_USAGE } from "./commands/make"; +import { runSkills, SKILLS_USAGE } from "./commands/skills"; import { version } from "../package.json"; -console.log(chalk.blue("CLIuno 🕹")); -console.log( - chalk.green( - "Welcome to CLIuno, the Ultimate tool for making full web apps in less than min 🚀", - ), -); -console.log("Current version:", chalk.yellow(version)); +const HELP = ` +Usage: cliuno [command] [options] -const noJsPackageManager = new Set([ - "Django", - "FastAPI", - "Rails", - "Spring Boot", - "ASP.NET", - "Without Backend", -]); -const args = new Set(process.argv.slice(2)); - -if (args.has("--help") || args.has("-h")) { - console.log(` -Usage: cliuno [options] +Commands: + (none) interactive scaffolder: pick a backend / frontend / mobile template + make list the generators available in the current project + make: generate a resource, controller, model, … in the current project + skills status|install check / install the CLIuno Claude skills (.claude/skills/) Options: --help, -h Show this help message --version, -v Show the current version --doctor Run system diagnostics -`); - process.exit(0); -} else if (args.has("--version") || args.has("-v")) { - process.exit(0); -} else if (args.has("--doctor")) { - runDoctor(); -} else { - try { - const designPattern = await select(questions.DesignPattern); - - if (designPattern === "Doctor 🩺") { - runDoctor(); - } else if (designPattern === "MVC") { - await handleMVC(); - } else { - await handleRestApi(); - } - } catch { - console.log(chalk.yellow("\n👋 Bye!")); - process.exit(0); - } -} - -async function askPackageManager(): Promise { - return select(questions.PackageManager); -} - -async function handleMVC() { - console.log(chalk.yellow("🚧 Only TallStack is available for MVC with Postgres 🚧")); - const mvcChoice = await select(questions.MVC); - - if (mvcChoice === "TallStack") { - handler.mkdirAndClone(mvcChoice); - shell.exec("composer install"); - const packageManager = await askPackageManager(); - shell.exec(handler.getInstallCmd(packageManager)); - messages.goodBye(); - handler.cleaner(); - } else { - console.log(chalk.red("🚧 This feature is not available yet 🚧")); - } -} +${MAKE_USAGE}${SKILLS_USAGE}`; -async function handleRestApi() { - console.log(chalk.yellow("🚧 Only SQLite is supported for now 🚧")); - const backendChoice = await select(questions.RestApiBackend); +const parsed = parseArgv(process.argv.slice(2)); - let packageManager = "npm"; - if (!noJsPackageManager.has(backendChoice)) { - packageManager = await askPackageManager(); - } - - console.log(chalk.green("📁 Created a folder for the backend project")); - handler.backendInstaller(backendChoice, packageManager); - - const frontendType = await select(questions.RestApiFrontend); - - if (frontendType === "Website") { - if (noJsPackageManager.has(backendChoice)) { - packageManager = await askPackageManager(); - } - await handleWebsite(packageManager); - } else if (frontendType === "Mobile") { - await handleMobile(); - } else { - messages.withoutDepend(); - } -} - -async function handleWebsite(packageManager: string) { - const frontend = await select(questions.RestApiWebsite); - console.log(chalk.green("📁 Created a folder for the frontend project")); - handler.frontEndInstaller(frontend, packageManager); -} - -async function handleMobile() { - const mobile = await select(questions.RestApiMobile); - console.log(chalk.green("📁 Created a folder for the mobile app project")); - handler.mobileInstaller(mobile); +switch (parsed.command) { + case "help": + console.log(HELP); + process.exit(0); + break; + case "version": + console.log(version); + process.exit(0); + break; + case "doctor": + banner(version); + runDoctor(); + break; + case "make": + process.exit(await runMake(parsed)); + break; + case "skills": + process.exit(await runSkills(parsed)); + break; + default: + banner(version); + process.exit(await runScaffold()); } diff --git a/src/cli/argv.test.ts b/src/cli/argv.test.ts new file mode 100644 index 0000000..c5321a4 --- /dev/null +++ b/src/cli/argv.test.ts @@ -0,0 +1,38 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { parseArgv } from "./argv"; + +test("make: with name and flags", () => { + const parsed = parseArgv(["make:resource", "Post", "--fields", "a:string", "--dry-run"]); + assert.equal(parsed.command, "make"); + assert.equal(parsed.kind, "resource"); + assert.equal(parsed.name, "Post"); + assert.equal(parsed.flags.fields, "a:string"); + assert.equal(parsed.flags["dry-run"], true); +}); + +test("bare make lists generators", () => { + const parsed = parseArgv(["make"]); + assert.equal(parsed.command, "make"); + assert.equal(parsed.kind, undefined); +}); + +test("skills sub-command and global flag", () => { + const parsed = parseArgv(["skills", "install", "--global", "--force"]); + assert.equal(parsed.command, "skills"); + assert.equal(parsed.sub, "install"); + assert.equal(parsed.flags.global, true); + assert.equal(parsed.flags.force, true); +}); + +test("legacy flags still route", () => { + assert.equal(parseArgv(["--doctor"]).command, "doctor"); + assert.equal(parseArgv(["-v"]).command, "version"); + assert.equal(parseArgv(["--help"]).command, "help"); + assert.equal(parseArgv([]).command, "scaffold"); +}); + +test("--flag=value form", () => { + const parsed = parseArgv(["make:model", "Tag", "--fields=name:string"]); + assert.equal(parsed.flags.fields, "name:string"); +}); diff --git a/src/cli/argv.ts b/src/cli/argv.ts new file mode 100644 index 0000000..20cd9bf --- /dev/null +++ b/src/cli/argv.ts @@ -0,0 +1,81 @@ +export interface ParsedArgv { + command: "scaffold" | "make" | "skills" | "doctor" | "help" | "version"; + kind?: string; + name?: string; + sub?: string; + flags: Record; + positional: string[]; +} + +const BOOLEAN_FLAGS = new Set([ + "force", + "dry-run", + "global", + "help", + "h", + "version", + "v", + "doctor", +]); + +function flagName(raw: string): string { + return raw.replace(/^--?/, ""); +} + +export function parseArgv(argv: string[]): ParsedArgv { + const flags: Record = {}; + const positional: string[] = []; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] as string; + if (!arg.startsWith("-")) { + positional.push(arg); + continue; + } + const eq = arg.indexOf("="); + if (eq !== -1) { + flags[flagName(arg.slice(0, eq))] = arg.slice(eq + 1); + continue; + } + const name = flagName(arg); + const next = argv[i + 1]; + if (BOOLEAN_FLAGS.has(name) || next === undefined || next.startsWith("-")) { + flags[name] = true; + } else { + flags[name] = next; + i++; + } + } + + const first = positional[0]; + if (flags.help || flags.h) return { command: "help", flags, positional }; + if (flags.version || flags.v) return { command: "version", flags, positional }; + if (flags.doctor) return { command: "doctor", flags, positional }; + + if (first === "make" || first?.startsWith("make:")) { + const kind = first === "make" ? undefined : first.slice("make:".length); + return { + command: "make", + kind, + name: positional[1], + flags, + positional: positional.slice(2), + }; + } + if (first === "skills") { + return { command: "skills", sub: positional[1], flags, positional: positional.slice(2) }; + } + return { command: "scaffold", flags, positional }; +} + +export function flagString( + flags: Record, + name: string, +): string | undefined { + const value = flags[name]; + return typeof value === "string" ? value : undefined; +} + +export function flagBool(flags: Record, name: string): boolean { + return flags[name] === true || flags[name] === "true"; +} diff --git a/src/commands/scaffold.ts b/src/commands/scaffold.ts new file mode 100644 index 0000000..f24fe54 --- /dev/null +++ b/src/commands/scaffold.ts @@ -0,0 +1,110 @@ +import chalk from "chalk"; +import shell from "shelljs"; +import { select } from "@inquirer/prompts"; +import * as messages from "../utils/messages"; +import * as handler from "../utils/GitHandler"; +import { runDoctor } from "../utils/doctor"; +import { questions } from "../utils/questions"; +import { shouldHintSkills } from "./skills"; + +const noJsPackageManager = new Set([ + "Django", + "FastAPI", + "Rails", + "Spring Boot", + "ASP.NET", + "Drogon", + "Without Backend", +]); + +export function banner(version: string) { + console.log(chalk.blue("CLIuno 🕹")); + console.log( + chalk.green( + "Welcome to CLIuno, the Ultimate tool for making full web apps in less than min 🚀", + ), + ); + console.log("Current version:", chalk.yellow(version)); + if (shouldHintSkills(process.cwd())) { + console.log( + chalk.gray("💡 AI agent here? Install the CLIuno skills: ") + + chalk.cyan("cliuno skills install"), + ); + } +} + +export async function runScaffold(): Promise { + try { + const designPattern = await select(questions.DesignPattern); + + if (designPattern === "Doctor 🩺") { + runDoctor(); + } else if (designPattern === "MVC") { + await handleMVC(); + } else { + await handleRestApi(); + } + return 0; + } catch { + console.log(chalk.yellow("\n👋 Bye!")); + return 0; + } +} + +async function askPackageManager(): Promise { + return select(questions.PackageManager); +} + +async function handleMVC() { + console.log(chalk.yellow("🚧 Only TallStack is available for MVC with Postgres 🚧")); + const mvcChoice = await select(questions.MVC); + + if (mvcChoice === "TallStack") { + handler.mkdirAndClone(mvcChoice); + shell.exec("composer install"); + const packageManager = await askPackageManager(); + shell.exec(handler.getInstallCmd(packageManager)); + messages.goodBye(); + handler.cleaner(); + } else { + console.log(chalk.red("🚧 This feature is not available yet 🚧")); + } +} + +async function handleRestApi() { + console.log(chalk.yellow("🚧 Only SQLite is supported for now 🚧")); + const backendChoice = await select(questions.RestApiBackend); + + let packageManager = "npm"; + if (!noJsPackageManager.has(backendChoice)) { + packageManager = await askPackageManager(); + } + + console.log(chalk.green("📁 Created a folder for the backend project")); + handler.backendInstaller(backendChoice, packageManager); + + const frontendType = await select(questions.RestApiFrontend); + + if (frontendType === "Website") { + if (noJsPackageManager.has(backendChoice)) { + packageManager = await askPackageManager(); + } + await handleWebsite(packageManager); + } else if (frontendType === "Mobile") { + await handleMobile(); + } else { + messages.withoutDepend(); + } +} + +async function handleWebsite(packageManager: string) { + const frontend = await select(questions.RestApiWebsite); + console.log(chalk.green("📁 Created a folder for the frontend project")); + handler.frontEndInstaller(frontend, packageManager); +} + +async function handleMobile() { + const mobile = await select(questions.RestApiMobile); + console.log(chalk.green("📁 Created a folder for the mobile app project")); + handler.mobileInstaller(mobile); +} From db07b9ed0d48a84fd63f9e12a337fc6d7b5f48e1 Mon Sep 17 00:00:00 2001 From: ru44 <18311071+ru44@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:09:33 +0300 Subject: [PATCH 02/29] feat(make): generator engine, stack detection, express and react generators --- src/commands/make.ts | 143 +++++++ src/generators/detect.test.ts | 73 ++++ src/generators/detect.ts | 225 +++++++++++ src/generators/engine.test.ts | 158 ++++++++ src/generators/engine.ts | 187 +++++++++ src/generators/fields.test.ts | 52 +++ src/generators/fields.ts | 106 ++++++ src/generators/names.test.ts | 48 +++ src/generators/names.ts | 110 ++++++ src/generators/stacks/adonis.ts | 9 + src/generators/stacks/angular.ts | 9 + src/generators/stacks/aspnet.ts | 9 + src/generators/stacks/django.ts | 9 + src/generators/stacks/drogon.ts | 9 + src/generators/stacks/express.ts | 414 ++++++++++++++++++++ src/generators/stacks/fastapi.ts | 9 + src/generators/stacks/fastify.ts | 9 + src/generators/stacks/flutter.ts | 9 + src/generators/stacks/index.ts | 47 +++ src/generators/stacks/laravel.ts | 9 + src/generators/stacks/nest.ts | 9 + src/generators/stacks/next.ts | 9 + src/generators/stacks/nuxt.ts | 9 + src/generators/stacks/rails.ts | 9 + src/generators/stacks/react.ts | 550 +++++++++++++++++++++++++++ src/generators/stacks/reactnative.ts | 9 + src/generators/stacks/shared.ts | 16 + src/generators/stacks/solid.ts | 9 + src/generators/stacks/spring.ts | 9 + src/generators/stacks/stacks.test.ts | 77 ++++ src/generators/stacks/svelte.ts | 9 + src/generators/stacks/tallstack.ts | 9 + src/generators/stacks/vue.ts | 9 + src/generators/types.ts | 76 ++++ 34 files changed, 2453 insertions(+) create mode 100644 src/commands/make.ts create mode 100644 src/generators/detect.test.ts create mode 100644 src/generators/detect.ts create mode 100644 src/generators/engine.test.ts create mode 100644 src/generators/engine.ts create mode 100644 src/generators/fields.test.ts create mode 100644 src/generators/fields.ts create mode 100644 src/generators/names.test.ts create mode 100644 src/generators/names.ts create mode 100644 src/generators/stacks/adonis.ts create mode 100644 src/generators/stacks/angular.ts create mode 100644 src/generators/stacks/aspnet.ts create mode 100644 src/generators/stacks/django.ts create mode 100644 src/generators/stacks/drogon.ts create mode 100644 src/generators/stacks/express.ts create mode 100644 src/generators/stacks/fastapi.ts create mode 100644 src/generators/stacks/fastify.ts create mode 100644 src/generators/stacks/flutter.ts create mode 100644 src/generators/stacks/index.ts create mode 100644 src/generators/stacks/laravel.ts create mode 100644 src/generators/stacks/nest.ts create mode 100644 src/generators/stacks/next.ts create mode 100644 src/generators/stacks/nuxt.ts create mode 100644 src/generators/stacks/rails.ts create mode 100644 src/generators/stacks/react.ts create mode 100644 src/generators/stacks/reactnative.ts create mode 100644 src/generators/stacks/shared.ts create mode 100644 src/generators/stacks/solid.ts create mode 100644 src/generators/stacks/spring.ts create mode 100644 src/generators/stacks/stacks.test.ts create mode 100644 src/generators/stacks/svelte.ts create mode 100644 src/generators/stacks/tallstack.ts create mode 100644 src/generators/stacks/vue.ts create mode 100644 src/generators/types.ts diff --git a/src/commands/make.ts b/src/commands/make.ts new file mode 100644 index 0000000..f4b752c --- /dev/null +++ b/src/commands/make.ts @@ -0,0 +1,143 @@ +import chalk from "chalk"; +import { detectStack, PROBES } from "../generators/detect"; +import { generators } from "../generators/stacks"; +import { buildNames } from "../generators/names"; +import { parseFields, FIELD_TYPES } from "../generators/fields"; +import { apply, plan, UnsupportedKindError } from "../generators/engine"; +import { KINDS, type Ctx, type Kind } from "../generators/types"; +import { flagBool, flagString, type ParsedArgv } from "../cli/argv"; + +export const MAKE_USAGE = ` +Usage: cliuno make list generators for the detected stack + cliuno make: [options] + +Kinds: ${KINDS.join(", ")} +Options: + --fields a:string,b:int? fields for the resource (types: ${FIELD_TYPES.join(", ")}; "?" = nullable) + default: title:string,description:text? + --dry-run print what would be written, write nothing + --force overwrite files that already exist + +Examples: + cliuno make:resource Product --fields name:string,price:number,inStock:boolean + cliuno make:controller Invoice --dry-run +`; + +function printPlan(label: string, kind: Kind, p: ReturnType) { + console.log(chalk.blue(`cliuno make:${kind}`) + chalk.gray(` (${label})`)); + for (const call of p.native) + console.log(chalk.yellow(` $ ${call.bin} ${call.args.join(" ")}`)); + for (const file of p.files) { + console.log(chalk.green(` + ${file.path}`)); + console.log(file.content.replace(/^/gm, " ")); + } + for (const patch of p.patches) { + console.log(chalk.cyan(` ~ ${patch.path}: ${patch.describe}`)); + console.log(patch.insert.replace(/^/gm, " ")); + } +} + +export async function runMake(parsed: ParsedArgv, cwd = process.cwd()): Promise { + const detection = detectStack(cwd); + if (!detection) { + console.error( + chalk.red( + "Could not detect a CLIuno stack here. Run this inside a scaffolded project.", + ), + ); + console.error(chalk.gray("Probes, in order:")); + for (const probe of PROBES) + console.error(chalk.gray(` ${probe.stack.padEnd(12)} ${probe.describe}`)); + return 1; + } + const gen = generators[detection.stack]; + const kinds = Object.keys(gen.commands) as Kind[]; + + if (!parsed.kind) { + console.log(chalk.blue(`${gen.label}`) + chalk.gray(` (${detection.root})`)); + if (kinds.length === 0) { + console.log(chalk.yellow(" no generators for this stack yet")); + return 0; + } + for (const kind of kinds) { + const cmd = gen.commands[kind]!; + const native = cmd.native + ? chalk.gray(` [native: ${cmd.native(demoCtx(detection.root))[0]?.bin}]`) + : ""; + console.log(` make:${kind.padEnd(11)} ${cmd.describe}${native}`); + } + console.log(MAKE_USAGE); + return 0; + } + + if (!(KINDS as readonly string[]).includes(parsed.kind)) { + console.error( + chalk.red(`Unknown generator "make:${parsed.kind}".`) + ` Kinds: ${KINDS.join(", ")}`, + ); + return 1; + } + if (!parsed.name) { + console.error( + chalk.red(`make:${parsed.kind} needs a name, e.g. cliuno make:${parsed.kind} Product`), + ); + return 1; + } + + let ctx: Ctx; + try { + ctx = { + cwd: detection.root, + names: buildNames(parsed.name), + fields: parseFields(flagString(parsed.flags, "fields")), + force: flagBool(parsed.flags, "force"), + dryRun: flagBool(parsed.flags, "dry-run"), + }; + } catch (error) { + console.error(chalk.red((error as Error).message)); + return 1; + } + + let p; + try { + p = plan(gen, parsed.kind as Kind, ctx); + } catch (error) { + if (error instanceof UnsupportedKindError) { + console.error(chalk.red(error.message)); + return 1; + } + console.error(chalk.red((error as Error).message)); + return 1; + } + + if (ctx.dryRun) printPlan(gen.label, parsed.kind as Kind, p); + + const result = await apply(p, ctx, undefined, gen); + if (result.nativeExit !== undefined) { + if (result.nativeExit !== 0) + console.error(chalk.red(`native command failed (exit ${result.nativeExit})`)); + for (const note of result.notes) console.log(chalk.gray(` ${note}`)); + return result.nativeExit; + } + + if (!ctx.dryRun) { + for (const file of result.written) console.log(chalk.green(` + ${file}`)); + for (const file of result.patched) console.log(chalk.cyan(` ~ ${file}`)); + } + for (const file of result.skipped) + console.log(chalk.yellow(` = ${file} exists (use --force to overwrite)`)); + if (result.formatted) console.log(chalk.gray(" ✓ formatted")); + for (const note of result.notes) console.log(chalk.gray(` ! ${note}`)); + if (result.written.length === 0 && result.patched.length === 0 && result.skipped.length > 0) + return 1; + return 0; +} + +function demoCtx(cwd: string): Ctx { + return { + cwd, + names: buildNames("example"), + fields: parseFields(undefined), + force: false, + dryRun: true, + }; +} diff --git a/src/generators/detect.test.ts b/src/generators/detect.test.ts new file mode 100644 index 0000000..a8b288d --- /dev/null +++ b/src/generators/detect.test.ts @@ -0,0 +1,73 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { detectStack } from "./detect"; + +function fixture(files: Record): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cliuno-detect-")); + for (const [file, content] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); + fs.writeFileSync(path.join(dir, file), content); + } + return dir; +} + +const pkg = (deps: Record) => JSON.stringify({ dependencies: deps }); + +const cases: Array<[string, Record]> = [ + [ + "tallstack", + { + "composer.json": JSON.stringify({ + require: { "laravel/framework": "^13", "livewire/livewire": "^3" }, + }), + }, + ], + ["laravel", { "composer.json": JSON.stringify({ require: { "laravel/framework": "^13" } }) }], + ["django", { "pyproject.toml": 'dependencies = ["django>=6.0", "djangorestframework"]' }], + ["fastapi", { "pyproject.toml": 'dependencies = ["fastapi[standard]>=0.1"]' }], + ["rails", { Gemfile: 'source "https://rubygems.org"\ngem "rails", "~> 8.1"' }], + [ + "spring", + { + "pom.xml": + "spring-boot-starter-parent", + }, + ], + ["aspnet", { "Api/Api.csproj": '' }], + ["drogon", { "CMakeLists.txt": "find_package(Drogon CONFIG REQUIRED)" }], + ["flutter", { "pubspec.yaml": "dependencies:\n flutter:\n sdk: flutter\n" }], + ["nest", { "package.json": pkg({ "@nestjs/core": "1", express: "1" }) }], + ["adonis", { "package.json": pkg({ "@adonisjs/core": "1" }) }], + ["fastify", { "package.json": pkg({ fastify: "1" }) }], + ["express", { "package.json": pkg({ express: "1" }) }], + ["next", { "package.json": pkg({ next: "1", react: "1" }) }], + ["nuxt", { "package.json": pkg({ nuxt: "1", vue: "1", "vue-router": "1" }) }], + ["reactnative", { "package.json": pkg({ expo: "1", react: "1" }) }], + ["react", { "package.json": pkg({ react: "1", "react-router-dom": "1" }) }], + ["vue", { "package.json": pkg({ vue: "1", "vue-router": "1" }) }], + ["svelte", { "package.json": pkg({ "@sveltejs/kit": "1" }) }], + ["solid", { "package.json": pkg({ "solid-js": "1" }) }], + ["angular", { "package.json": pkg({ "@angular/core": "1" }) }], +]; + +for (const [stack, files] of cases) { + test(`detects ${stack}`, () => { + const dir = fixture(files); + assert.equal(detectStack(dir)?.stack, stack); + }); +} + +test("walks up from a sub directory and returns the root", () => { + const dir = fixture({ "package.json": pkg({ express: "1" }), "src/controllers/.keep": "" }); + const found = detectStack(path.join(dir, "src/controllers")); + assert.equal(found?.stack, "express"); + assert.equal(found?.root, dir); +}); + +test("returns null when nothing matches", () => { + assert.equal(detectStack(fixture({ "README.md": "" })), null); + assert.equal(detectStack(fixture({ "package.json": pkg({ lodash: "1" }) })), null); +}); diff --git a/src/generators/detect.ts b/src/generators/detect.ts new file mode 100644 index 0000000..dff4209 --- /dev/null +++ b/src/generators/detect.ts @@ -0,0 +1,225 @@ +import fs from "node:fs"; +import path from "node:path"; + +export type StackId = + | "express" + | "fastify" + | "nest" + | "adonis" + | "django" + | "fastapi" + | "laravel" + | "tallstack" + | "rails" + | "spring" + | "aspnet" + | "drogon" + | "react" + | "next" + | "vue" + | "nuxt" + | "svelte" + | "solid" + | "angular" + | "flutter" + | "reactnative"; + +export interface Detection { + stack: StackId; + root: string; +} + +interface Probe { + stack: StackId; + describe: string; + test: (dir: string) => boolean; +} + +function read(dir: string, file: string): string | null { + try { + return fs.readFileSync(path.join(dir, file), "utf8"); + } catch { + return null; + } +} + +function pkgDeps(dir: string): Record | null { + const raw = read(dir, "package.json"); + if (!raw) return null; + try { + const pkg = JSON.parse(raw) as { + dependencies?: Record; + devDependencies?: Record; + }; + return { ...pkg.dependencies, ...pkg.devDependencies }; + } catch { + return null; + } +} + +function composerRequires(dir: string, name: string): boolean { + const raw = read(dir, "composer.json"); + if (!raw) return false; + try { + const c = JSON.parse(raw) as { require?: Record }; + return Boolean(c.require?.[name]); + } catch { + return false; + } +} + +function pyprojectHas(dir: string, name: string): boolean { + const raw = read(dir, "pyproject.toml"); + return raw !== null && new RegExp(`["']${name}(\\[|[>=<~!]|["'])`, "i").test(raw); +} + +function csprojIsWeb(dir: string): boolean { + const candidates: string[] = []; + try { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (entry.isFile() && entry.name.endsWith(".csproj")) + candidates.push(path.join(dir, entry.name)); + if (entry.isDirectory() && !entry.name.startsWith(".")) { + try { + for (const sub of fs.readdirSync(path.join(dir, entry.name))) { + if (sub.endsWith(".csproj")) + candidates.push(path.join(dir, entry.name, sub)); + } + } catch { + /* unreadable sub dir */ + } + } + } + } catch { + return false; + } + return candidates.some((file) => + fs.readFileSync(file, "utf8").includes("Microsoft.NET.Sdk.Web"), + ); +} + +const dep = (dir: string, name: string) => Boolean(pkgDeps(dir)?.[name]); + +export const PROBES: readonly Probe[] = [ + { + stack: "tallstack", + describe: "composer.json requires livewire/livewire", + test: (d) => composerRequires(d, "livewire/livewire"), + }, + { + stack: "laravel", + describe: "composer.json requires laravel/framework", + test: (d) => composerRequires(d, "laravel/framework"), + }, + { + stack: "django", + describe: "pyproject.toml lists django", + test: (d) => pyprojectHas(d, "django"), + }, + { + stack: "fastapi", + describe: "pyproject.toml lists fastapi", + test: (d) => pyprojectHas(d, "fastapi"), + }, + { + stack: "rails", + describe: 'Gemfile has gem "rails"', + test: (d) => /gem\s+["']rails["']/.test(read(d, "Gemfile") ?? ""), + }, + { + stack: "spring", + describe: "pom.xml contains spring-boot", + test: (d) => (read(d, "pom.xml") ?? "").includes("spring-boot"), + }, + { stack: "aspnet", describe: "*.csproj uses Microsoft.NET.Sdk.Web", test: csprojIsWeb }, + { + stack: "drogon", + describe: "CMakeLists.txt links Drogon", + test: (d) => (read(d, "CMakeLists.txt") ?? "").includes("Drogon"), + }, + { + stack: "flutter", + describe: "pubspec.yaml depends on flutter", + test: (d) => /^\s+flutter:\s*$/m.test(read(d, "pubspec.yaml") ?? ""), + }, + { + stack: "nest", + describe: "package.json depends on @nestjs/core", + test: (d) => dep(d, "@nestjs/core"), + }, + { + stack: "adonis", + describe: "package.json depends on @adonisjs/core", + test: (d) => dep(d, "@adonisjs/core"), + }, + { + stack: "fastify", + describe: "package.json depends on fastify", + test: (d) => dep(d, "fastify"), + }, + { + stack: "express", + describe: "package.json depends on express", + test: (d) => dep(d, "express"), + }, + { stack: "next", describe: "package.json depends on next", test: (d) => dep(d, "next") }, + { stack: "nuxt", describe: "package.json depends on nuxt", test: (d) => dep(d, "nuxt") }, + { stack: "reactnative", describe: "package.json depends on expo", test: (d) => dep(d, "expo") }, + { + stack: "react", + describe: "package.json depends on react + react-router-dom", + test: (d) => dep(d, "react") && dep(d, "react-router-dom"), + }, + { + stack: "vue", + describe: "package.json depends on vue + vue-router", + test: (d) => dep(d, "vue") && dep(d, "vue-router"), + }, + { + stack: "svelte", + describe: "package.json depends on @sveltejs/kit", + test: (d) => dep(d, "@sveltejs/kit"), + }, + { + stack: "solid", + describe: "package.json depends on solid-js", + test: (d) => dep(d, "solid-js"), + }, + { + stack: "angular", + describe: "package.json depends on @angular/core", + test: (d) => dep(d, "@angular/core"), + }, +]; + +const MANIFESTS = [ + "package.json", + "composer.json", + "pyproject.toml", + "Gemfile", + "pom.xml", + "CMakeLists.txt", + "pubspec.yaml", +]; + +function hasManifest(dir: string): boolean { + if (MANIFESTS.some((m) => fs.existsSync(path.join(dir, m)))) return true; + return csprojIsWeb(dir); +} + +/** Walk up from cwd (≤ 6 levels) to the first directory with a manifest, then run the probes in order. */ +export function detectStack(cwd: string): Detection | null { + let dir = path.resolve(cwd); + for (let depth = 0; depth <= 6; depth++) { + if (hasManifest(dir)) { + for (const probe of PROBES) { + if (probe.test(dir)) return { stack: probe.stack, root: dir }; + } + return null; + } + const parent = path.dirname(dir); + if (parent === dir) break; + dir = parent; + } + return null; +} diff --git a/src/generators/engine.test.ts b/src/generators/engine.test.ts new file mode 100644 index 0000000..b784433 --- /dev/null +++ b/src/generators/engine.test.ts @@ -0,0 +1,158 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { apply, applyPatch, plan, type Io } from "./engine"; +import type { Ctx, Generator, Patch } from "./types"; +import { buildNames } from "./names"; +import { parseFields } from "./fields"; + +const ctx = (over: Partial = {}): Ctx => ({ + cwd: "/app", + names: buildNames("post"), + fields: parseFields(undefined), + force: false, + dryRun: false, + ...over, +}); + +function memIo( + files: Record, + bins: string[] = [], +): Io & { files: Record; ran: string[] } { + const ran: string[] = []; + return { + files, + ran, + exists: (f) => f in files, + read: (f) => files[f] as string, + write: (f, c) => { + files[f] = c; + }, + which: (bin) => bins.includes(bin), + run: (call) => { + ran.push(`${call.bin} ${call.args.join(" ")}`); + return 0; + }, + }; +} + +const gen: Generator = { + id: "express", + label: "Express", + kind: "backend", + commands: { + model: { + describe: "entity", + native: () => [{ bin: "php", args: ["artisan", "make:model"] }], + files: (c) => [{ path: `src/${c.names.kebab}.ts`, content: "stub" }], + }, + migration: { + describe: "only native", + native: () => [{ bin: "php", args: ["artisan", "make:migration"] }], + }, + resource: { + describe: "all", + files: (c) => [{ path: `src/${c.names.kebab}.ts`, content: "stub" }], + patches: () => [ + { + path: "src/index.ts", + anchor: "// end", + insert: "use(post)\n", + where: "before", + skipIf: "use(post)", + describe: "register", + }, + ], + }, + }, +}; + +const patch: Patch = { + path: "x", + anchor: "// anchor", + insert: "NEW\n", + where: "after", + skipIf: "NEW", + describe: "add", +}; + +test("applyPatch after/before/skip/missing", () => { + assert.equal(applyPatch("a\n// anchor\nb", patch).text, "a\n// anchorNEW\n\nb"); + assert.equal( + applyPatch("a\n// anchor\nb", { ...patch, where: "before" }).text, + "a\nNEW\n// anchor\nb", + ); + assert.equal(applyPatch("NEW\n// anchor", patch).status, "skipped"); + assert.equal(applyPatch("nothing", patch).status, "anchor-missing"); + assert.equal( + applyPatch("x\nimport a\nimport b\ny", { ...patch, anchor: /^import .*$/m }).text, + "x\nimport a\nimport bNEW\n\ny", + ); +}); + +test("plan prefers native when the binary exists, falls back to stubs otherwise", () => { + const withPhp = plan(gen, "model", ctx(), memIo({}, ["php"])); + assert.equal(withPhp.native.length, 1); + assert.equal(withPhp.files.length, 0); + const noPhp = plan(gen, "model", ctx(), memIo({})); + assert.equal(noPhp.native.length, 0); + assert.equal(noPhp.files.length, 1); + assert.match(noPhp.notes[0] as string, /not found/); + assert.throws(() => plan(gen, "migration", ctx(), memIo({})), /not found on PATH/); + assert.throws(() => plan(gen, "page", ctx(), memIo({})), /no "make:page"/); +}); + +test("apply refuses to overwrite without --force, writes with it, dry-run touches nothing", async () => { + const io = memIo({ "/app/src/post.ts": "old", "/app/src/index.ts": "// end" }); + const p = plan(gen, "resource", ctx(), io); + let r = await apply(p, ctx(), io); + assert.deepEqual(r.skipped, ["src/post.ts"]); + assert.equal(io.files["/app/src/post.ts"], "old"); + assert.equal(io.files["/app/src/index.ts"], "use(post)\n// end"); + + r = await apply(p, ctx({ force: true }), io); + assert.deepEqual(r.written, ["src/post.ts"]); + assert.equal(io.files["/app/src/post.ts"], "stub"); + assert.equal(io.files["/app/src/index.ts"], "use(post)\n// end", "patch is idempotent"); + assert.deepEqual(r.patched, []); + + const dry = memIo({ "/app/src/index.ts": "// end" }); + r = await apply(p, ctx({ dryRun: true }), dry); + assert.deepEqual(r.written, ["src/post.ts"]); + assert.equal(dry.files["/app/src/post.ts"], undefined); + assert.equal(dry.files["/app/src/index.ts"], "// end"); +}); + +test("missing patch target or anchor becomes a note", async () => { + const io = memIo({}); + const r = await apply(plan(gen, "resource", ctx(), io), ctx(), io); + assert.match(r.notes[0] as string, /src\/index.ts not found/); + const io2 = memIo({ "/app/src/index.ts": "no anchor here" }); + const r2 = await apply(plan(gen, "resource", ctx(), io2), ctx(), io2); + assert.match(r2.notes[0] as string, /Could not find where to register/); +}); + +test("native calls run in order and dry-run only reports them", async () => { + const io = memIo({}, ["php"]); + const r = await apply(plan(gen, "model", ctx(), io), ctx(), io); + assert.deepEqual(io.ran, ["php artisan make:model"]); + assert.equal(r.nativeExit, 0); + const dry = memIo({}, ["php"]); + const r2 = await apply(plan(gen, "model", ctx(), dry), ctx({ dryRun: true }), dry); + assert.deepEqual(dry.ran, []); + assert.match(r2.notes[0] as string, /would run: php artisan make:model/); +}); + +test("formatter runs on written + patched files when its binary exists", async () => { + const io = memIo({ "/app/src/index.ts": "// end" }, ["node_modules/.bin/oxfmt"]); + const formatted: Generator = { + ...gen, + format: (files) => ({ bin: "node_modules/.bin/oxfmt", args: files, quiet: true }), + }; + const r = await apply(plan(formatted, "resource", ctx(), io), ctx(), io, formatted); + assert.equal(r.formatted, true); + assert.deepEqual(io.ran, ["node_modules/.bin/oxfmt src/post.ts src/index.ts"]); + const none = memIo({ "/app/src/index.ts": "// end" }); + const r2 = await apply(plan(formatted, "resource", ctx(), none), ctx(), none, formatted); + assert.equal(r2.formatted, undefined); + assert.deepEqual(none.ran, []); +}); diff --git a/src/generators/engine.ts b/src/generators/engine.ts new file mode 100644 index 0000000..367cbb2 --- /dev/null +++ b/src/generators/engine.ts @@ -0,0 +1,187 @@ +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import type { Command, Ctx, Generator, Kind, NativeCall, Patch, Plan } from "./types"; + +export interface Io { + exists: (file: string) => boolean; + read: (file: string) => string; + write: (file: string, content: string) => void; + which: (bin: string, cwd: string) => boolean; + run: (call: NativeCall, cwd: string) => number; +} + +export const realIo: Io = { + exists: (file) => fs.existsSync(file), + read: (file) => fs.readFileSync(file, "utf8"), + write: (file, content) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + }, + which: (bin, cwd) => { + if (bin.includes("/") || bin.includes("\\")) return fs.existsSync(path.resolve(cwd, bin)); + const result = spawnSync(process.platform === "win32" ? "where" : "which", [bin], { + stdio: "ignore", + }); + return result.status === 0; + }, + run: (call, cwd) => { + const result = spawnSync(call.bin, call.args, { + cwd, + stdio: call.quiet ? "ignore" : "inherit", + shell: process.platform === "win32", + }); + return result.status ?? 1; + }, +}; + +export class UnsupportedKindError extends Error { + constructor( + public readonly gen: Generator, + public readonly kind: Kind, + ) { + super( + `${gen.label} has no "make:${kind}" generator. Available: ${Object.keys(gen.commands).join(", ")}.`, + ); + } +} + +function command(gen: Generator, kind: Kind): Command { + const cmd = gen.commands[kind]; + if (!cmd) throw new UnsupportedKindError(gen, kind); + return cmd; +} + +/** Decide between native delegation and stub rendering, then collect everything the command would do. */ +export function plan(gen: Generator, kind: Kind, ctx: Ctx, io: Io = realIo): Plan { + const cmd = command(gen, kind); + const nativeCalls = cmd.native?.(ctx) ?? []; + const canDelegate = + nativeCalls.length > 0 && nativeCalls.every((c) => io.which(c.bin, ctx.cwd)); + const result: Plan = { native: [], files: [], patches: [], notes: cmd.notes?.(ctx) ?? [] }; + + if (canDelegate) { + result.native = nativeCalls; + return result; + } + if (!cmd.files && !cmd.patches) { + const needed = [...new Set(nativeCalls.map((c) => c.bin))].join(", "); + throw new Error( + `"make:${kind}" for ${gen.label} delegates to "${needed}", which was not found on PATH.`, + ); + } + if (nativeCalls.length > 0) { + result.notes.unshift( + `Native CLI (${nativeCalls[0]!.bin}) not found — rendered CLIuno stubs instead.`, + ); + } + result.files = cmd.files?.(ctx) ?? []; + result.patches = cmd.patches?.(ctx) ?? []; + return result; +} + +export function applyPatch( + source: string, + patch: Patch, +): { text: string; status: "applied" | "skipped" | "anchor-missing" } { + if (patch.skipIf && source.includes(patch.skipIf)) return { text: source, status: "skipped" }; + const anchor = patch.anchor; + let index = -1; + let length = 0; + if (typeof anchor === "string") { + index = patch.where === "after" ? source.lastIndexOf(anchor) : source.indexOf(anchor); + length = anchor.length; + } else { + const flags = anchor.flags.includes("g") ? anchor.flags : `${anchor.flags}g`; + const re = new RegExp(anchor.source, flags); + let match: RegExpExecArray | null; + let last: RegExpExecArray | null = null; + while ((match = re.exec(source)) !== null) { + last = match; + if (patch.where === "before") break; + if (match[0].length === 0) re.lastIndex++; + } + if (last) { + index = last.index; + length = last[0].length; + } + } + if (index === -1) return { text: source, status: "anchor-missing" }; + const at = patch.where === "after" ? index + length : index; + return { text: source.slice(0, at) + patch.insert + source.slice(at), status: "applied" }; +} + +export interface ApplyResult { + written: string[]; + skipped: string[]; + patched: string[]; + notes: string[]; + nativeExit?: number; + formatted?: boolean; +} + +export async function apply( + p: Plan, + ctx: Ctx, + io: Io = realIo, + gen?: Generator, +): Promise { + const result: ApplyResult = { written: [], skipped: [], patched: [], notes: [...p.notes] }; + + if (p.native.length > 0) { + if (ctx.dryRun) { + result.notes.push(...p.native.map((c) => `would run: ${c.bin} ${c.args.join(" ")}`)); + return result; + } + for (const call of p.native) { + const code = io.run(call, ctx.cwd); + if (code !== 0) { + result.nativeExit = code; + return result; + } + } + result.nativeExit = 0; + return result; + } + + for (const file of p.files) { + const abs = path.join(ctx.cwd, file.path); + if (io.exists(abs) && !ctx.force) { + result.skipped.push(file.path); + continue; + } + if (!ctx.dryRun) io.write(abs, file.content); + result.written.push(file.path); + } + + for (const patch of p.patches) { + const abs = path.join(ctx.cwd, patch.path); + if (!io.exists(abs)) { + result.notes.push( + `${patch.path} not found — ${patch.describe} by hand: ${patch.insert.trim()}`, + ); + continue; + } + const { text, status } = applyPatch(io.read(abs), patch); + if (status === "applied") { + if (!ctx.dryRun) io.write(abs, text); + result.patched.push(patch.path); + } else if (status === "anchor-missing") { + result.notes.push( + `Could not find where to ${patch.describe} in ${patch.path} — add by hand: ${patch.insert.trim()}`, + ); + } + } + + const touched = [...result.written, ...result.patched]; + if (gen?.format && touched.length > 0 && !ctx.dryRun) { + const call = gen.format(touched); + if (io.which(call.bin, ctx.cwd)) { + const code = io.run({ ...call, args: call.args }, ctx.cwd); + if (code !== 0) + result.notes.push(`formatter ${call.bin} exited ${code} — run it by hand.`); + else result.formatted = true; + } + } + return result; +} diff --git a/src/generators/fields.test.ts b/src/generators/fields.test.ts new file mode 100644 index 0000000..1c43e09 --- /dev/null +++ b/src/generators/fields.test.ts @@ -0,0 +1,52 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { labelField, mapType, parseFields } from "./fields"; + +test("defaults when omitted", () => { + const f = parseFields(undefined); + assert.deepEqual( + f.map((x) => [x.name, x.type, x.nullable]), + [ + ["title", "string", false], + ["description", "text", true], + ], + ); + assert.deepEqual(parseFields(" "), f); +}); + +test("tolerates spaces and trailing comma, maps aliases, marks nullable", () => { + const f = parseFields(" name:string , price:float?, qty : integer, "); + assert.deepEqual( + f.map((x) => [x.name, x.type, x.nullable]), + [ + ["name", "string", false], + ["price", "number", true], + ["qty", "int", false], + ], + ); +}); + +test("unknown type lists the valid ones", () => { + assert.throws( + () => parseFields("price:money"), + /string, text, int, number, boolean, date, json/, + ); +}); + +test("duplicates and malformed entries fail", () => { + assert.throws(() => parseFields("a:string,a:text"), /Duplicate/); + assert.throws(() => parseFields("justname"), /expected name:type/); + assert.throws(() => parseFields("1x:string"), /Invalid field name/); +}); + +test("case variants of a field", () => { + const [f] = parseFields("dueDate:date"); + assert.equal(f!.snake, "due_date"); + assert.equal(f!.camel, "dueDate"); + assert.equal(f!.pascal, "DueDate"); + assert.equal( + mapType(f!, { string: 1, text: 2, int: 3, number: 4, boolean: 5, date: 6, json: 7 }), + 6, + ); + assert.equal(labelField(parseFields("done:boolean,name:string")).name, "name"); +}); diff --git a/src/generators/fields.ts b/src/generators/fields.ts new file mode 100644 index 0000000..14e80fd --- /dev/null +++ b/src/generators/fields.ts @@ -0,0 +1,106 @@ +export const FIELD_TYPES = ["string", "text", "int", "number", "boolean", "date", "json"] as const; +export type FieldType = (typeof FIELD_TYPES)[number]; + +export interface Field { + name: string; + camel: string; + snake: string; + pascal: string; + type: FieldType; + nullable: boolean; +} + +const ALIASES: Record = { + str: "string", + varchar: "string", + longtext: "text", + integer: "int", + bigint: "int", + float: "number", + double: "number", + decimal: "number", + bool: "boolean", + datetime: "date", + timestamp: "date", + object: "json", + array: "json", +}; + +export const DEFAULT_FIELDS_SPEC = "title:string,description:text?"; + +function toParts(name: string): string[] { + return name + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .map((w) => w.toLowerCase()); +} + +export function makeField(rawName: string, rawType: string, nullable: boolean): Field { + const name = rawName.trim(); + if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name)) { + throw new Error( + `Invalid field name "${rawName}": use letters, digits or "_" and start with a letter.`, + ); + } + const typeKey = rawType.trim().toLowerCase(); + const type = (FIELD_TYPES as readonly string[]).includes(typeKey) + ? (typeKey as FieldType) + : ALIASES[typeKey]; + if (!type) { + throw new Error( + `Unknown field type "${rawType}" for "${name}". Valid types: ${FIELD_TYPES.join(", ")}.`, + ); + } + const parts = toParts(name); + const pascal = parts.map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(""); + return { + name, + camel: pascal.charAt(0).toLowerCase() + pascal.slice(1), + snake: parts.join("_"), + pascal, + type, + nullable, + }; +} + +/** Parse `name:type?,other:type` — empty/undefined falls back to the default title/description pair. */ +export function parseFields(spec?: string): Field[] { + const source = spec && spec.trim() ? spec : DEFAULT_FIELDS_SPEC; + const fields: Field[] = []; + const seen = new Set(); + for (const chunk of source.split(",")) { + const item = chunk.trim(); + if (!item) continue; + const [rawName, rawType] = item.split(":"); + if (!rawName || !rawType) { + throw new Error( + `Invalid field "${item}": expected name:type (e.g. title:string). Valid types: ${FIELD_TYPES.join(", ")}.`, + ); + } + const nullable = rawType.trim().endsWith("?"); + const field = makeField( + rawName, + nullable ? rawType.trim().slice(0, -1) : rawType, + nullable, + ); + if (seen.has(field.snake)) throw new Error(`Duplicate field "${field.name}".`); + seen.add(field.snake); + fields.push(field); + } + if (fields.length === 0) throw new Error("At least one field is required."); + return fields; +} + +export function mapType(field: Field, map: Record): T { + return map[field.type]; +} + +/** First string-ish field — used by stubs as the display/"title" column. */ +export function labelField(fields: Field[]): Field { + return ( + fields.find((f) => f.type === "string") ?? + fields.find((f) => f.type === "text") ?? + (fields[0] as Field) + ); +} diff --git a/src/generators/names.test.ts b/src/generators/names.test.ts new file mode 100644 index 0000000..d74fae3 --- /dev/null +++ b/src/generators/names.test.ts @@ -0,0 +1,48 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { buildNames, pluralize, singularize } from "./names"; + +test("every spelling normalises to the same set", () => { + for (const raw of [ + "post", + "Posts", + "blog-post", + "BlogPost", + "blog_posts", + "Blog Posts", + "blogPosts", + ]) { + const n = buildNames(raw); + const expectPascal = raw.toLowerCase().includes("blog") ? "BlogPost" : "Post"; + assert.equal(n.pascal, expectPascal, raw); + assert.equal(n.plural.pascal, `${expectPascal}s`, raw); + } + const n = buildNames("blog-post"); + assert.deepEqual( + [n.pascal, n.camel, n.kebab, n.snake, n.title], + ["BlogPost", "blogPost", "blog-post", "blog_post", "Blog Post"], + ); + assert.deepEqual( + [n.plural.pascal, n.plural.camel, n.plural.kebab, n.plural.snake], + ["BlogPosts", "blogPosts", "blog-posts", "blog_posts"], + ); +}); + +test("plural rules", () => { + assert.equal(pluralize("category"), "categories"); + assert.equal(pluralize("box"), "boxes"); + assert.equal(pluralize("person"), "people"); + assert.equal(pluralize("status"), "statuses"); + assert.equal(pluralize("day"), "days"); + assert.equal(pluralize("leaf"), "leaves"); + assert.equal(singularize("categories"), "category"); + assert.equal(singularize("statuses"), "status"); + assert.equal(singularize("people"), "person"); + assert.equal(singularize("todos"), "todo"); + assert.equal(singularize("address"), "address"); +}); + +test("invalid names are rejected", () => { + assert.throws(() => buildNames("1abc"), /Invalid name/); + assert.throws(() => buildNames("a/b"), /Invalid name/); +}); diff --git a/src/generators/names.ts b/src/generators/names.ts new file mode 100644 index 0000000..5d742f4 --- /dev/null +++ b/src/generators/names.ts @@ -0,0 +1,110 @@ +export interface CaseSet { + pascal: string; + camel: string; + kebab: string; + snake: string; + title: string; +} + +export interface Names extends CaseSet { + raw: string; + plural: CaseSet; +} + +const IRREGULAR: Record = { + person: "people", + child: "children", + man: "men", + woman: "women", + mouse: "mice", + foot: "feet", + tooth: "teeth", + goose: "geese", +}; + +const UNCOUNTABLE = new Set([ + "news", + "series", + "species", + "sheep", + "fish", + "deer", + "equipment", + "information", + "media", + "data", +]); + +export function pluralize(word: string): string { + const lower = word.toLowerCase(); + if (UNCOUNTABLE.has(lower)) return word; + if (IRREGULAR[lower]) return matchCase(word, IRREGULAR[lower] as string); + if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`; + if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`; + if (/(?:fe|[^f]f)$/i.test(word)) return word.replace(/fe?$/i, "ves"); + return `${word}s`; +} + +export function singularize(word: string): string { + const lower = word.toLowerCase(); + if (UNCOUNTABLE.has(lower)) return word; + for (const [singular, plural] of Object.entries(IRREGULAR)) { + if (lower === plural) return matchCase(word, singular); + } + if (/ies$/i.test(word) && word.length > 4) return `${word.slice(0, -3)}y`; + if (/(ss|us|is)$/i.test(word)) return word; + if (/(ches|shes|xes|zes|sses|uses)$/i.test(word)) return word.slice(0, -2); + if (/ves$/i.test(word) && word.length > 4) return `${word.slice(0, -3)}f`; + if (/s$/i.test(word) && word.length > 2) return word.slice(0, -1); + return word; +} + +function matchCase(source: string, target: string): string { + if (source[0] && source[0] === source[0].toUpperCase()) { + return target[0]!.toUpperCase() + target.slice(1); + } + return target; +} + +function words(raw: string): string[] { + return raw + .trim() + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .map((w) => w.toLowerCase()); +} + +function caseSet(parts: string[]): CaseSet { + const cap = (w: string) => w.charAt(0).toUpperCase() + w.slice(1); + const pascal = parts.map(cap).join(""); + return { + pascal, + camel: pascal.charAt(0).toLowerCase() + pascal.slice(1), + kebab: parts.join("-"), + snake: parts.join("_"), + title: parts.map(cap).join(" "), + }; +} + +export function isValidName(raw: string): boolean { + return /^[A-Za-z][A-Za-z0-9_ -]*$/.test(raw.trim()); +} + +/** Normalise any spelling/plurality of a resource name to one consistent set of cases. */ +export function buildNames(raw: string): Names { + if (!isValidName(raw)) { + throw new Error( + `Invalid name "${raw}": use letters, digits, "-" or "_" and start with a letter.`, + ); + } + const parts = words(raw); + const last = parts[parts.length - 1] as string; + const singularParts = [...parts.slice(0, -1), singularize(last)]; + const pluralParts = [ + ...singularParts.slice(0, -1), + pluralize(singularParts[singularParts.length - 1] as string), + ]; + return { raw, ...caseSet(singularParts), plural: caseSet(pluralParts) }; +} diff --git a/src/generators/stacks/adonis.ts b/src/generators/stacks/adonis.ts new file mode 100644 index 0000000..9ca05d5 --- /dev/null +++ b/src/generators/stacks/adonis.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const adonis: Generator = { + id: "adonis", + label: "AdonisJS", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/angular.ts b/src/generators/stacks/angular.ts new file mode 100644 index 0000000..79261af --- /dev/null +++ b/src/generators/stacks/angular.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const angular: Generator = { + id: "angular", + label: "Angular", + kind: "frontend", + commands: {}, +}; diff --git a/src/generators/stacks/aspnet.ts b/src/generators/stacks/aspnet.ts new file mode 100644 index 0000000..0109cbb --- /dev/null +++ b/src/generators/stacks/aspnet.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const aspnet: Generator = { + id: "aspnet", + label: "ASP.NET", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/django.ts b/src/generators/stacks/django.ts new file mode 100644 index 0000000..1c6ac83 --- /dev/null +++ b/src/generators/stacks/django.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const django: Generator = { + id: "django", + label: "Django", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/drogon.ts b/src/generators/stacks/drogon.ts new file mode 100644 index 0000000..aa87e5a --- /dev/null +++ b/src/generators/stacks/drogon.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const drogon: Generator = { + id: "drogon", + label: "Drogon", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/express.ts b/src/generators/stacks/express.ts new file mode 100644 index 0000000..32aa331 --- /dev/null +++ b/src/generators/stacks/express.ts @@ -0,0 +1,414 @@ +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { labelField } from "../fields"; +import { oxfmt } from "./shared"; + +const COLUMN: Record = { + string: "text", + text: "text", + int: "integer", + number: "real", + boolean: "boolean", + date: "datetime", + json: "simple-json", +}; + +const TS: Record = { + string: "string", + text: "string", + int: "number", + number: "number", + boolean: "boolean", + date: "Date", + json: "Record", +}; + +function column(f: Field): string { + const opts: string[] = []; + if (f.nullable) opts.push("nullable: true"); + if (f.type === "boolean" && !f.nullable) opts.push("default: false"); + const options = opts.length ? `, { ${opts.join(", ")} }` : ""; + return ` @Column('${COLUMN[f.type]}'${options})\n ${f.camel}: ${TS[f.type]}\n`; +} + +function entity(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + return { + path: `src/entities/${names.kebab}.entity.ts`, + content: `import { + Entity, + Column, + PrimaryGeneratedColumn, + ManyToOne, + JoinColumn, + CreateDateColumn, + UpdateDateColumn, +} from 'typeorm' + +import { User } from './user.entity' + +@Entity('${names.plural.pascal}') +export class ${names.pascal} { + @PrimaryGeneratedColumn('uuid') + id: string + +${fields.map(column).join("\n")} + @CreateDateColumn() + createdAt: Date + + @UpdateDateColumn() + updatedAt: Date + + @ManyToOne(() => User, { nullable: false }) + @JoinColumn({ name: 'user_id' }) + user: User +} +`, + }; +} + +function controller(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const required = fields.filter((f) => !f.nullable); + const label = labelField(fields); + const destructure = fields.map((f) => f.camel).join(", "); + const requiredGuard = required + .map( + ( + f, + ) => ` if (${f.camel} === undefined || ${f.camel} === null${f.type === "string" || f.type === "text" ? ` || ${f.camel} === ''` : ""}) { + res.status(400).json({ status: 'error', message: '${f.pascal} is required' }) + return + }`, + ) + .join("\n"); + const assign = fields.map((f) => ` ${f.camel},`).join("\n"); + const updates = fields + .map( + (f) => + ` if (${f.camel} !== undefined) ${names.camel}.${f.camel} = ${f.camel}`, + ) + .join("\n"); + const one = names.camel; + const many = names.plural.camel; + const P = names.pascal; + const title = names.title; + const titles = names.plural.title; + + return { + path: `src/controllers/${names.kebab}.controller.ts`, + content: `import { Request, Response } from 'express' + +import { myDataSource } from '@/database/app-data-source' +import { ${P} } from '@/entities/${names.kebab}.entity' +import { User } from '@/entities/user.entity' +import logThisError from '@/helpers/error-logger' + +export const ${P}Controller = { + getAll: async (req: Request, res: Response): Promise => { + try { + const ${many} = await myDataSource.getRepository(${P}).find({ + relations: ['user'], + order: { createdAt: 'DESC' }, + }) + res.status(200).json({ + status: 'success', + message: '${titles} fetched successfully', + data: { ${many} }, + }) + } catch (error) { + logThisError(error) + res.status(500).json({ status: 'error', message: 'Internal server error' }) + } + }, + + getById: async (req: Request, res: Response): Promise => { + try { + const ${one} = await myDataSource.getRepository(${P}).findOne({ + where: { id: req.params.id as string }, + relations: ['user'], + }) + if (!${one}) { + res.status(404).json({ status: 'error', message: '${title} not found' }) + return + } + res.status(200).json({ + status: 'success', + message: '${title} fetched successfully', + data: { ${one} }, + }) + } catch (error) { + logThisError(error) + res.status(500).json({ status: 'error', message: 'Internal server error' }) + } + }, + + getCurrentUser${names.plural.pascal}: async (req: Request, res: Response): Promise => { + try { + const userId = (req as any).user.id + const ${many} = await myDataSource.getRepository(${P}).find({ + where: { user: { id: userId } }, + relations: ['user'], + order: { createdAt: 'DESC' }, + }) + res.status(200).json({ + status: 'success', + message: '${titles} fetched successfully', + data: { ${many} }, + }) + } catch (error) { + logThisError(error) + res.status(500).json({ status: 'error', message: 'Internal server error' }) + } + }, + + create: async (req: Request, res: Response): Promise => { + try { + const { ${destructure} } = req.body + const userId = (req as any).user.id + +${requiredGuard} + + const user = await myDataSource.getRepository(User).findOneBy({ id: userId }) + if (!user) { + res.status(404).json({ status: 'error', message: 'User not found' }) + return + } + + const ${one} = myDataSource.getRepository(${P}).create({ +${assign} + user, + }) + const result = await myDataSource.getRepository(${P}).save(${one}) + + res.status(201).json({ + status: 'success', + message: '${title} created successfully', + data: { ${one}: result }, + }) + } catch (error) { + logThisError(error) + res.status(500).json({ status: 'error', message: 'Internal server error' }) + } + }, + + update: async (req: Request, res: Response): Promise => { + try { + const userId = (req as any).user.id + const ${one} = await myDataSource.getRepository(${P}).findOne({ + where: { id: req.params.id as string }, + relations: ['user'], + }) + + if (!${one}) { + res.status(404).json({ status: 'error', message: '${title} not found' }) + return + } + + if (${one}.user.id !== userId) { + res.status(403).json({ + status: 'error', + message: 'You can only update your own ${names.plural.kebab.replace(/-/g, " ")}', + }) + return + } + + const { ${destructure} } = req.body +${updates} + + await myDataSource.getRepository(${P}).save(${one}) + res.status(200).json({ + status: 'success', + message: '${title} updated successfully', + data: { ${one} }, + }) + } catch (error) { + logThisError(error) + res.status(500).json({ status: 'error', message: 'Internal server error' }) + } + }, + + delete: async (req: Request, res: Response): Promise => { + try { + const userId = (req as any).user.id + const ${one} = await myDataSource.getRepository(${P}).findOne({ + where: { id: req.params.id as string }, + relations: ['user'], + }) + + if (!${one}) { + res.status(404).json({ status: 'error', message: '${title} not found' }) + return + } + + if (${one}.user.id !== userId) { + res.status(403).json({ + status: 'error', + message: 'You can only delete your own ${names.plural.kebab.replace(/-/g, " ")}', + }) + return + } + + await myDataSource.getRepository(${P}).remove(${one}) + res.status(200).json({ status: 'success', message: '${title} deleted successfully' }) + } catch (error) { + logThisError(error) + res.status(500).json({ status: 'error', message: 'Internal server error' }) + } + }, +} +// ${label.camel} is the display field used by the frontends' list pages. +`, + }; +} + +function router(ctx: Ctx): FileSpec { + const { names } = ctx; + return { + path: `src/routers/v1/${names.kebab}.router.ts`, + content: `import { Router } from 'express' + +import { ${names.pascal}Controller } from '@/controllers/${names.kebab}.controller' +import { ensureAuthenticated } from '@/middlewares/auth.middleware' + +const router: Router = Router() + +router.use(ensureAuthenticated) + +// CRUD operations +router.get('/current-user', ${names.pascal}Controller.getCurrentUser${names.plural.pascal}) +router.get('/', ${names.pascal}Controller.getAll) +router.get('/:id', ${names.pascal}Controller.getById) +router.post('/', ${names.pascal}Controller.create) +router.patch('/:id', ${names.pascal}Controller.update) +router.delete('/:id', ${names.pascal}Controller.delete) + +export default router +`, + }; +} + +function validator(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const JOI: Record = { + string: "Joi.string()", + text: "Joi.string().allow('')", + int: "Joi.number().integer()", + number: "Joi.number()", + boolean: "Joi.boolean()", + date: "Joi.date()", + json: "Joi.object()", + }; + const rules = fields + .map((f) => ` ${f.camel}: ${JOI[f.type]}${f.nullable ? ".allow(null)" : ".required()"},`) + .join("\n"); + return { + path: `src/validators/${names.kebab}.validator.ts`, + content: `import { Request } from 'express' +import Joi from 'joi' + +const schema = Joi.object({ +${rules} +}) + +export async function Validate${names.pascal}(req: Request) { + try { + await schema.validateAsync(req.body) + } catch (error: any) { + const statusCode = error.isJoi ? 400 : 500 + throw { + statusCode, + message: error.details ? error.details[0].message : 'Internal server error', + } + } +} +`, + }; +} + +function spec(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const sample = fields + .map((f) => { + const value: Record = { + string: `'Sample ${f.name}'`, + text: `'Sample ${f.name}'`, + int: "1", + number: "1.5", + boolean: "false", + date: "new Date().toISOString()", + json: "{}", + }; + return ` ${f.camel}: ${value[f.type]},`; + }) + .join("\n"); + return { + path: `src/__tests__/${names.kebab}.spec.ts`, + content: `import { ${names.pascal} } from '@/entities/${names.kebab}.entity' + +describe('${names.pascal} entity', () => { + test('has the generated fields', () => { + const ${names.camel} = Object.assign(new ${names.pascal}(), { +${sample} + }) +${fields.map((f) => ` expect(${names.camel}.${f.camel}).toBeDefined()`).join("\n")} + }) +}) +`, + }; +} + +function registerRoute(ctx: Ctx): Patch[] { + const { names } = ctx; + return [ + { + path: "src/routers/index.ts", + anchor: /^import \w+ from '\.\/v1\/[\w.-]+'$/m, + where: "after", + insert: `\nimport ${names.camel}Router from './v1/${names.kebab}.router'`, + skipIf: `./v1/${names.kebab}.router`, + describe: `import the ${names.kebab} router`, + }, + { + path: "src/routers/index.ts", + anchor: "// Export the main router", + where: "before", + insert: `// ${names.plural.title} Router\nrouter.use('/${names.plural.kebab}', ${names.camel}Router)\n\n`, + skipIf: `router.use('/${names.plural.kebab}'`, + describe: `mount /${names.plural.kebab}`, + }, + ]; +} + +export const express: Generator = { + id: "express", + format: oxfmt, + label: "Express", + kind: "backend", + commands: { + resource: { + describe: + "entity + controller + router (mounted under /api/v1/) + validator + jest spec", + files: (ctx) => [entity(ctx), controller(ctx), router(ctx), validator(ctx), spec(ctx)], + patches: registerRoute, + notes: (ctx) => [ + `TypeORM synchronize is on — restart the dev server and the ${names(ctx).plural.pascal} table appears.`, + `Wire Validate${names(ctx).pascal} into the router if you want request validation (see auth.router.ts).`, + ], + }, + model: { describe: "TypeORM entity in src/entities/", files: (ctx) => [entity(ctx)] }, + controller: { + describe: "controller in src/controllers/ using the {status, message, data} envelope", + files: (ctx) => [controller(ctx)], + }, + validator: { + describe: "Joi validator in src/validators/", + files: (ctx) => [validator(ctx)], + }, + test: { describe: "jest spec in src/__tests__/", files: (ctx) => [spec(ctx)] }, + }, +}; + +function names(ctx: Ctx) { + return ctx.names; +} diff --git a/src/generators/stacks/fastapi.ts b/src/generators/stacks/fastapi.ts new file mode 100644 index 0000000..499d8e8 --- /dev/null +++ b/src/generators/stacks/fastapi.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const fastapi: Generator = { + id: "fastapi", + label: "FastAPI", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/fastify.ts b/src/generators/stacks/fastify.ts new file mode 100644 index 0000000..636e86d --- /dev/null +++ b/src/generators/stacks/fastify.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const fastify: Generator = { + id: "fastify", + label: "Fastify", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/flutter.ts b/src/generators/stacks/flutter.ts new file mode 100644 index 0000000..085ce2d --- /dev/null +++ b/src/generators/stacks/flutter.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const flutter: Generator = { + id: "flutter", + label: "Flutter", + kind: "mobile", + commands: {}, +}; diff --git a/src/generators/stacks/index.ts b/src/generators/stacks/index.ts new file mode 100644 index 0000000..c251d21 --- /dev/null +++ b/src/generators/stacks/index.ts @@ -0,0 +1,47 @@ +import type { Generator } from "../types"; +import type { StackId } from "../detect"; +import { express } from "./express"; +import { fastify } from "./fastify"; +import { nest } from "./nest"; +import { adonis } from "./adonis"; +import { django } from "./django"; +import { fastapi } from "./fastapi"; +import { laravel } from "./laravel"; +import { tallstack } from "./tallstack"; +import { rails } from "./rails"; +import { spring } from "./spring"; +import { aspnet } from "./aspnet"; +import { drogon } from "./drogon"; +import { react } from "./react"; +import { next } from "./next"; +import { vue } from "./vue"; +import { nuxt } from "./nuxt"; +import { svelte } from "./svelte"; +import { solid } from "./solid"; +import { angular } from "./angular"; +import { flutter } from "./flutter"; +import { reactnative } from "./reactnative"; + +export const generators: Record = { + express, + fastify, + nest, + adonis, + django, + fastapi, + laravel, + tallstack, + rails, + spring, + aspnet, + drogon, + react, + next, + vue, + nuxt, + svelte, + solid, + angular, + flutter, + reactnative, +}; diff --git a/src/generators/stacks/laravel.ts b/src/generators/stacks/laravel.ts new file mode 100644 index 0000000..6ff0126 --- /dev/null +++ b/src/generators/stacks/laravel.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const laravel: Generator = { + id: "laravel", + label: "Laravel", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/nest.ts b/src/generators/stacks/nest.ts new file mode 100644 index 0000000..0b32c64 --- /dev/null +++ b/src/generators/stacks/nest.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const nest: Generator = { + id: "nest", + label: "NestJS", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/next.ts b/src/generators/stacks/next.ts new file mode 100644 index 0000000..eb52d0c --- /dev/null +++ b/src/generators/stacks/next.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const next: Generator = { + id: "next", + label: "Next.js", + kind: "frontend", + commands: {}, +}; diff --git a/src/generators/stacks/nuxt.ts b/src/generators/stacks/nuxt.ts new file mode 100644 index 0000000..34ec2f2 --- /dev/null +++ b/src/generators/stacks/nuxt.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const nuxt: Generator = { + id: "nuxt", + label: "Nuxt", + kind: "frontend", + commands: {}, +}; diff --git a/src/generators/stacks/rails.ts b/src/generators/stacks/rails.ts new file mode 100644 index 0000000..7153da6 --- /dev/null +++ b/src/generators/stacks/rails.ts @@ -0,0 +1,9 @@ +import type { Generator } from "../types"; + +// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). +export const rails: Generator = { + id: "rails", + label: "Rails", + kind: "backend", + commands: {}, +}; diff --git a/src/generators/stacks/react.ts b/src/generators/stacks/react.ts new file mode 100644 index 0000000..c725eae --- /dev/null +++ b/src/generators/stacks/react.ts @@ -0,0 +1,550 @@ +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { labelField } from "../fields"; +import { oxfmt } from "./shared"; + +const TS: Record = { + string: "string", + text: "string", + int: "number", + number: "number", + boolean: "boolean", + date: "string", + json: "Record", +}; + +function tsType(f: Field): string { + return `${TS[f.type]}${f.nullable ? " | null" : ""}`; +} + +function iface(ctx: Ctx): string { + const { names, fields } = ctx; + return `interface ${names.pascal} { + id: string +${fields.map((f) => ` ${f.camel}: ${tsType(f)}`).join("\n")} + createdAt: string + user: { id: string; username: string; first_name: string; last_name: string } +}`; +} + +function inputType(fields: Field[], partial: boolean): string { + return `{ ${fields.map((f) => `${f.camel}${partial || f.nullable ? "?" : ""}: ${TS[f.type]}${f.nullable ? " | null" : ""}`).join("; ")} }`; +} + +function api(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const path = names.plural.kebab; + return { + path: `src/apis/${names.kebab}-api.ts`, + content: `import http from './http' + +const ${names.camel}Api = { + getAll${names.plural.pascal}: () => http.get('/${path}'), + get${P}ById: (id: string) => http.get(\`/${path}/\${id}\`), + create${P}: (data: ${inputType(fields, false)}) => http.post('/${path}', data), + update${P}: (id: string, data: ${inputType(fields, true)}) => + http.patch(\`/${path}/\${id}\`, data), + delete${P}: (id: string) => http.delete(\`/${path}/\${id}\`), +} + +export default ${names.camel}Api +`, + }; +} + +function formState(fields: Field[]): string { + return fields + .map((f) => { + const init: Record = { + string: "''", + text: "''", + int: "0", + number: "0", + boolean: "false", + date: "''", + json: "{}", + }; + return ` const [${f.camel}, set${f.pascal}] = useState<${TS[f.type]}>(${init[f.type]})`; + }) + .join("\n"); +} + +function formInput(f: Field): string { + const id = `${f.snake}-input`; + if (f.type === "boolean") { + return `
+ set${f.pascal}(v === true)} + /> + +
`; + } + if (f.type === "text") { + return `
+ + +
`; + } + const numeric = f.type === "int" || f.type === "number"; + const type = numeric ? "number" : f.type === "date" ? "datetime-local" : "text"; + return `
+ + +
`; +} + +/** Angular interpolation for one field; `??` only on nullable fields (strictTemplates warns otherwise). */ +function display(f: Field, varName: string): string { + const v = `${varName}.${f.camel}`; + if (f.type === "boolean") return `{{ ${v} ? 'Yes' : 'No' }}`; + if (f.type === "json") return `{{ ${v} | json }}`; + if (f.type === "date") + return f.nullable ? `{{ ${v} ? timeAgo(${v}) : '—' }}` : `{{ timeAgo(${v}) }}`; + return f.nullable ? `{{ ${v} ?? '—' }}` : `{{ ${v} }}`; +} + +const PARSE_JSON = `function parseJson(text: string): Record { + try { + return JSON.parse(text) + } catch { + return {} + } +} +`; + +function listComponent(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const PP = names.plural.pascal; + const kp = names.plural.kebab; + const label = labelField(fields); + const others = fields.filter((f) => f !== label); + const usesJson = fields.some((f) => f.type === "json"); + const usesCheckbox = fields.some((f) => f.type === "boolean"); + const usesTextarea = fields.some((f) => f.type === "text" || f.type === "json"); + const usesInput = fields.some((f) => !["boolean", "text", "json"].includes(f.type)); + const imports = [ + usesJson ? "JsonPipe" : "", + "FormsModule", + "RouterLink", + "NgIcon", + "HlmButton", + "HlmCard", + "HlmCardContent", + usesCheckbox ? "HlmCheckbox" : "", + usesInput ? "HlmInput" : "", + "HlmLabel", + usesTextarea ? "HlmTextarea" : "", + "HlmSpinner", + "HlmDialog", + "HlmDialogContent", + "HlmDialogHeader", + "HlmDialogTitle", + "HlmDialogFooter", + "BrnDialogTrigger", + "BrnDialogContent", + "BrnDialogClose", + ].filter(Boolean); + return { + path: `src/app/views/app/${kp}.component.ts`, + content: `${usesJson ? "import { JsonPipe } from '@angular/common'\n" : ""}import { Component, OnInit } from '@angular/core' +import { FormsModule } from '@angular/forms' +import { RouterLink } from '@angular/router' +import { NgIcon, provideIcons } from '@ng-icons/core' +import { lucidePlus, lucidePackage, lucideUser, lucideTrash2 } from '@ng-icons/lucide' +import { ${P}, ${P}ApiService } from '../../services/${names.kebab}-api.service' +import { AuthStore } from '../../services/auth.store' +import { timeAgo } from '../../utils/helpers' +import { HlmButton } from '@spartan-ng/helm/button' +import { HlmCard, HlmCardContent } from '@spartan-ng/helm/card' +${usesCheckbox ? "import { HlmCheckbox } from '@spartan-ng/helm/checkbox'\n" : ""}${usesInput ? "import { HlmInput } from '@spartan-ng/helm/input'\n" : ""}import { HlmLabel } from '@spartan-ng/helm/label' +${usesTextarea ? "import { HlmTextarea } from '@spartan-ng/helm/textarea'\n" : ""}import { HlmSpinner } from '@spartan-ng/helm/spinner' +import { + HlmDialog, + HlmDialogContent, + HlmDialogHeader, + HlmDialogTitle, + HlmDialogFooter, +} from '@spartan-ng/helm/dialog' +import { BrnDialogTrigger, BrnDialogContent, BrnDialogClose } from '@spartan-ng/brain/dialog' + +${usesJson ? `${PARSE_JSON}\n` : ""}@Component({ + selector: 'app-${kp}', + standalone: true, + imports: [ +${imports.map((i) => ` ${i},`).join("\n")} + ], + viewProviders: [provideIcons({ lucidePlus, lucidePackage, lucideUser, lucideTrash2 })], + template: \` +
+ +
+
+

${names.plural.title}

+

Manage your ${names.plural.title.toLowerCase()}

+
+ + + + + +

Create New ${names.title}

+
+
+${fields.map((f) => formInput(f, names.kebab)).join("\n")} + + + + +
+
+
+
+ + + @if (loading) { +
+ +
+ } + + + @if (!loading && ${names.plural.camel}.length === 0) { +
+ +

No ${names.plural.title.toLowerCase()} yet

+

Create your first ${names.title.toLowerCase()} to get started!

+
+ } + + + @if (!loading && ${names.plural.camel}.length > 0) { +
+ @for (item of ${names.plural.camel}; track item.id) { +
+
+
+ +

+ ${display(label, "item")} +

+
+${others + .map( + (f) => `

+ ${f.pascal}: ${display(f, "item")} +

`, + ) + .join("\n")} +
+ + + {{ item.user.username }} + + {{ timeAgo(item.createdAt) }} +
+
+ + @if (item.user.id === authStore.user()?.id) { + + } +
+
+ } +
+ } +
+ \`, +}) +export class ${PP}Component implements OnInit { + ${names.plural.camel}: ${P}[] = [] + loading = true + creating = false +${formProps(fields)} + timeAgo = timeAgo + + constructor( + private readonly ${names.camel}Api: ${P}ApiService, + public authStore: AuthStore, + ) {} + + ngOnInit() { + this.fetch${PP}() + } + + fetch${PP}() { + this.loading = true + this.${names.camel}Api.getAll${PP}().subscribe({ + next: (res) => { + this.${names.plural.camel} = res.data.${names.plural.camel} + this.loading = false + }, + error: () => { + this.loading = false + }, + }) + } + + create${P}(dialog: { close: () => void }) { + this.creating = true + this.${names.camel}Api.create${P}({ ${payload(fields)} }).subscribe({ + next: () => { +${formReset(fields)} + this.creating = false + dialog.close() + this.fetch${PP}() + }, + error: () => { + this.creating = false + }, + }) + } + + delete${P}(id: string) { + this.${names.camel}Api.delete${P}(id).subscribe({ + next: () => { + this.${names.plural.camel} = this.${names.plural.camel}.filter((item) => item.id !== id) + }, + }) + } +} +`, + }; +} + +function detailComponent(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const kp = names.plural.kebab; + const label = labelField(fields); + const others = fields.filter((f) => f !== label); + const usesJson = fields.some((f) => f.type === "json"); + const v = names.camel; + return { + path: `src/app/views/app/${names.kebab}-detail.component.ts`, + content: `${usesJson ? "import { JsonPipe } from '@angular/common'\n" : ""}import { Component, OnInit } from '@angular/core' +import { ActivatedRoute, Router, RouterLink } from '@angular/router' +import { NgIcon, provideIcons } from '@ng-icons/core' +import { lucideArrowLeft, lucideTrash2, lucideUser } from '@ng-icons/lucide' +import { ${P}, ${P}ApiService } from '../../services/${names.kebab}-api.service' +import { AuthStore } from '../../services/auth.store' +import { timeAgo } from '../../utils/helpers' +import { HlmButton } from '@spartan-ng/helm/button' +import { HlmCard, HlmCardContent } from '@spartan-ng/helm/card' +import { HlmSpinner } from '@spartan-ng/helm/spinner' +import { HlmSeparator } from '@spartan-ng/helm/separator' + +@Component({ + selector: 'app-${names.kebab}-detail', + standalone: true, + imports: [${usesJson ? "JsonPipe, " : ""}RouterLink, NgIcon, HlmButton, HlmCard, HlmCardContent, HlmSpinner, HlmSeparator], + viewProviders: [provideIcons({ lucideArrowLeft, lucideTrash2, lucideUser })], + template: \` +
+ + + + Back to ${names.plural.title} + + + @if (loading) { +
+ +
+ } + + @if (!loading && ${v}) { +
+
+
+

${display(label, v)}

+ @if (${v}.user.id === authStore.user()?.id) { + + } +
+${others + .map( + (f) => `

+ ${f.pascal}: ${display(f, v)} +

`, + ) + .join("\n")} + + + + + +
+
+ } +
+ \`, +}) +export class ${P}DetailComponent implements OnInit { + ${v}: ${P} | null = null + loading = true + timeAgo = timeAgo + + constructor( + private readonly route: ActivatedRoute, + private readonly router: Router, + private readonly ${v}Api: ${P}ApiService, + public authStore: AuthStore, + ) {} + + ngOnInit() { + const id = this.route.snapshot.paramMap.get('id') ?? '' + this.${v}Api.get${P}ById(id).subscribe({ + next: (res) => { + this.${v} = res.data.${v} + this.loading = false + }, + error: () => { + this.loading = false + }, + }) + } + + remove() { + const ${v} = this.${v} + if (!${v}) return + this.${v}Api.delete${P}(${v}.id).subscribe({ + next: () => { + this.router.navigate(['/${kp}']) + }, + }) + } +} +`, + }; +} + +function store(ctx: Ctx): FileSpec { + const { names } = ctx; + const P = names.pascal; + return { + path: `src/app/services/${names.kebab}.store.ts`, + content: `import { Injectable, signal } from '@angular/core' +import { ${P}, ${P}ApiService } from './${names.kebab}-api.service' + +@Injectable({ providedIn: 'root' }) +export class ${P}Store { + items = signal<${P}[]>([]) + loading = signal(false) + + constructor(private readonly ${names.camel}Api: ${P}ApiService) {} + + fetchAll() { + this.loading.set(true) + this.${names.camel}Api.getAll${names.plural.pascal}().subscribe({ + next: (res) => { + this.items.set(res.data.${names.plural.camel}) + this.loading.set(false) + }, + error: () => { + this.loading.set(false) + }, + }) + } + + remove(id: string) { + this.${names.camel}Api.delete${P}(id).subscribe({ + next: () => { + this.items.update((items) => items.filter((item) => item.id !== id)) + }, + }) + } +} +`, + }; +} + +function routePatches(ctx: Ctx): Patch[] { + const { names } = ctx; + const P = names.pascal; + const PP = names.plural.pascal; + const kp = names.plural.kebab; + return [ + { + path: "src/app/app.routes.ts", + // right after the `todos/:id` route object inside the authGuard children + anchor: /m\.TodoDetailComponent\),\n\s*\},/, + where: "after", + insert: `\n {\n path: '${kp}',\n loadComponent: () => import('./views/app/${kp}.component').then((m) => m.${PP}Component),\n },\n {\n path: '${kp}/:id',\n loadComponent: () =>\n import('./views/app/${names.kebab}-detail.component').then((m) => m.${P}DetailComponent),\n },`, + skipIf: `path: '${kp}'`, + describe: `add /${kp} routes next to the todo routes (same authGuard group)`, + }, + ]; +} -// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). export const angular: Generator = { id: "angular", + format: oxfmt, label: "Angular", kind: "frontend", - commands: {}, + commands: { + resource: { + describe: + "api service + list component + detail component, routed in src/app/app.routes.ts", + files: (ctx) => [service(ctx), listComponent(ctx), detailComponent(ctx)], + patches: routePatches, + notes: (ctx) => [ + `Add a nav link to /${ctx.names.plural.kebab} in src/app/layouts/default-layout.component.ts if you want it in the menu.`, + `Move the ${ctx.names.pascal} interface into src/app/types/models.ts if you prefer the shared models file.`, + ], + }, + api: { + describe: "HttpService-based API service in src/app/services/ (providedIn: root)", + files: (ctx) => [service(ctx)], + }, + service: { + describe: "alias of make:api — API service in src/app/services/", + files: (ctx) => [service(ctx)], + }, + page: { + describe: "list + detail standalone components in src/app/views/app/ (+ routes)", + files: (ctx) => [listComponent(ctx), detailComponent(ctx)], + patches: routePatches, + }, + store: { + describe: "signals store service in src/app/services/ (same shape as auth.store.ts)", + files: (ctx) => [store(ctx)], + }, + component: { + describe: "spartan-ng helm UI component via ng g @spartan-ng/cli:ui", + native: (ctx) => [ + { bin: "node_modules/.bin/ng", args: ["g", "@spartan-ng/cli:ui", ctx.names.kebab] }, + ], + }, + }, }; diff --git a/src/generators/stacks/django.ts b/src/generators/stacks/django.ts index 1c6ac83..661c11b 100644 --- a/src/generators/stacks/django.ts +++ b/src/generators/stacks/django.ts @@ -1,9 +1,487 @@ -import type { Generator } from "../types"; +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { labelField } from "../fields"; + +// Stubs mirror the template's todo resource: src/views/todo_views.py, src/serializers/ +// todo_serializers.py, src/urls/todo_urls.py, src/tests/test_todos.py and the Todo model in +// src/models.py — DRF function views, `{status, message, data}` envelope, single quotes. +// No post-write formatter on purpose: the template is hand-formatted (single quotes, hanging +// indents) and `ruff format` would rewrite the patched src/models.py wholesale. + +const MODEL_FIELD: Record = { + string: "CharField", + text: "TextField", + int: "IntegerField", + number: "FloatField", + boolean: "BooleanField", + date: "DateTimeField", + json: "JSONField", +}; + +/** Field types whose JSON round-trip equals the Python literal (dates don't). */ +const COMPARABLE = new Set(["string", "text", "int", "number", "boolean", "json"]); + +function modelField(f: Field): string { + const opts: string[] = []; + if (f.type === "string") opts.push("max_length=255"); + if (f.nullable) opts.push("blank=True", "null=True"); + else if (f.type === "boolean") opts.push("default=False"); + return ` ${f.snake} = models.${MODEL_FIELD[f.type]}(${opts.join(", ")})`; +} + +/** Sample literals for tests: ORM create value, JSON create payload value, JSON update value. */ +function sample(f: Field): { orm: string; api: string; updated: string } { + switch (f.type) { + case "string": + case "text": + return { + orm: `'Test ${f.snake}'`, + api: `'New ${f.snake}'`, + updated: `'Updated ${f.snake}'`, + }; + case "int": + return { orm: "1", api: "2", updated: "3" }; + case "number": + return { orm: "1.5", api: "2.5", updated: "3.5" }; + case "boolean": + return { orm: "False", api: "True", updated: "True" }; + case "date": + return { + orm: "timezone.now()", + api: "'2026-01-01T00:00:00Z'", + updated: "'2026-02-01T00:00:00Z'", + }; + case "json": + return { + orm: "{'key': 'value'}", + api: "{'key': 'new'}", + updated: "{'key': 'updated'}", + }; + } +} + +function required(fields: Field[]): Field[] { + return fields.filter((f) => !f.nullable && f.type !== "boolean"); +} + +/** `[a, b]` on one line when it fits in 99 columns, else one item per line. */ +function pyList(items: string[], indent: number, prefixLength: number): string { + const inline = `[${items.join(", ")}]`; + if (indent + prefixLength + inline.length <= 99) return inline; + const pad = " ".repeat(indent); + return `[\n${items.map((item) => `${pad} ${item},`).join("\n")}\n${pad}]`; +} + +function pyDict(pairs: string[], indent: number): string { + const inline = `{${pairs.join(", ")}}`; + if (indent + inline.length + 1 <= 99) return inline; + const pad = " ".repeat(indent); + return `{\n${pairs.map((pair) => `${pad} ${pair},`).join("\n")}\n${pad}}`; +} + +function modelClass(ctx: Ctx): string { + const { names, fields } = ctx; + const label = labelField(fields); + const str = + (label.type === "string" || label.type === "text") && !label.nullable + ? `self.${label.snake}` + : `str(self.${label.snake})`; + return `class ${names.pascal}(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) +${fields.map(modelField).join("\n")} + user = models.ForeignKey( + User, on_delete=models.CASCADE, related_name='${names.plural.snake}') + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + db_table = '${names.plural.snake}' + ordering = ['-created_at'] + + def __str__(self): + return ${str} +`; +} + +/** Append the model class at the end of src/models.py (after the last non-blank character). */ +function modelPatch(ctx: Ctx): Patch { + return { + path: "src/models.py", + anchor: /\S\s*$/, + where: "after", + insert: `\n\n${modelClass(ctx)}`, + skipIf: `class ${ctx.names.pascal}(models.Model):`, + describe: `append the ${ctx.names.pascal} model`, + }; +} + +function serializer(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const all = ["id", ...fields.map((f) => f.snake), "user", "created_at", "updated_at"].map( + (f) => `'${f}'`, + ); + return { + path: `src/serializers/${names.snake}_serializers.py`, + content: `from rest_framework import serializers + +from src.models import ${names.pascal} + + +class ${names.pascal}Serializer(serializers.ModelSerializer): + class Meta: + model = ${names.pascal} + fields = ${pyList(all, 8, "fields = ".length)} + read_only_fields = ['id', 'user', 'created_at', 'updated_at'] +`, + }; +} + +function views(ctx: Ctx): FileSpec { + const { names } = ctx; + const P = names.pascal; + const one = names.snake; + const many = names.plural.snake; + const key = names.camel; + const keys = names.plural.camel; + const title = names.title; + const titles = names.plural.title; + const own = names.plural.kebab.replace(/-/g, " "); + const notFound = ` return Response( + {'status': 'error', 'message': '${title} not found'}, + status=status.HTTP_404_NOT_FOUND, + )`; + const invalid = ` return Response( + {'status': 'error', 'message': serializer.errors}, + status=status.HTTP_400_BAD_REQUEST, + )`; + + return { + path: `src/views/${one}_views.py`, + content: `from rest_framework import status +from rest_framework.decorators import api_view, permission_classes +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response + +from src.models import ${P} +from src.serializers.${one}_serializers import ${P}Serializer + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +def get_current_user_${many}(request): + ${many} = ${P}.objects.filter(user=request.user) + return Response({ + 'status': 'success', + 'message': '${titles} fetched successfully', + 'data': {'${keys}': ${P}Serializer(${many}, many=True).data}, + }) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +def get_all_${many}(request): + ${many} = ${P}.objects.select_related('user').all() + return Response({ + 'status': 'success', + 'message': '${titles} fetched successfully', + 'data': {'${keys}': ${P}Serializer(${many}, many=True).data}, + }) + + +@api_view(['GET']) +@permission_classes([IsAuthenticated]) +def get_${one}_by_id(request, pk): + try: + ${one} = ${P}.objects.select_related('user').get(id=pk) + except ${P}.DoesNotExist: +${notFound} + return Response({ + 'status': 'success', + 'message': '${title} fetched successfully', + 'data': {'${key}': ${P}Serializer(${one}).data}, + }) + + +@api_view(['POST']) +@permission_classes([IsAuthenticated]) +def create_${one}(request): + serializer = ${P}Serializer(data=request.data) + if not serializer.is_valid(): +${invalid} + + ${one} = serializer.save(user=request.user) + return Response({ + 'status': 'success', + 'message': '${title} created successfully', + 'data': {'${key}': ${P}Serializer(${one}).data}, + }, status=status.HTTP_201_CREATED) + + +@api_view(['PATCH']) +@permission_classes([IsAuthenticated]) +def update_${one}(request, pk): + try: + ${one} = ${P}.objects.select_related('user').get(id=pk) + except ${P}.DoesNotExist: +${notFound} + + if ${one}.user.id != request.user.id: + return Response( + {'status': 'error', 'message': 'You can only update your own ${own}'}, + status=status.HTTP_403_FORBIDDEN, + ) + + serializer = ${P}Serializer(${one}, data=request.data, partial=True) + if not serializer.is_valid(): +${invalid} + serializer.save() + + return Response({ + 'status': 'success', + 'message': '${title} updated successfully', + 'data': {'${key}': ${P}Serializer(${one}).data}, + }) + + +@api_view(['DELETE']) +@permission_classes([IsAuthenticated]) +def delete_${one}(request, pk): + try: + ${one} = ${P}.objects.select_related('user').get(id=pk) + except ${P}.DoesNotExist: +${notFound} + + if ${one}.user.id != request.user.id: + return Response( + {'status': 'error', 'message': 'You can only delete your own ${own}'}, + status=status.HTTP_403_FORBIDDEN, + ) + + ${one}.delete() + return Response({'status': 'success', 'message': '${title} deleted successfully'}) +`, + }; +} + +function urls(ctx: Ctx): FileSpec { + const { names } = ctx; + const one = names.snake; + const many = names.plural.snake; + const imported = [ + `create_${one}`, + `delete_${one}`, + `get_all_${many}`, + `get_current_user_${many}`, + `get_${one}_by_id`, + `update_${one}`, + ].sort(); + return { + path: `src/urls/${one}_urls.py`, + content: `from django.urls import path + +from src.urls.dispatch import method_dispatch +from src.views.${one}_views import ( +${imported.map((name) => ` ${name},`).join("\n")} +) + +urlpatterns = [ + path('/current-user', get_current_user_${many}, name='${names.kebab}-current-user'), + path('', method_dispatch(GET=get_all_${many}, POST=create_${one}), name='${names.kebab}-collection'), + path('/', + method_dispatch(GET=get_${one}_by_id, PATCH=update_${one}, DELETE=delete_${one}), + name='${names.kebab}-detail'), +] +`, + }; +} + +function urlPatch(ctx: Ctx): Patch { + const { names } = ctx; + return { + path: "src/urls/__init__.py", + anchor: /^ {4}path\('[^']*', include\('src\.urls\.\w+'\)\),$/m, + where: "after", + insert: `\n path('${names.plural.kebab}', include('src.urls.${names.snake}_urls')),`, + skipIf: `src.urls.${names.snake}_urls`, + describe: `mount /${names.plural.kebab}`, + }; +} + +function test(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const one = names.snake; + const many = names.plural.snake; + const key = names.camel; + const keys = names.plural.camel; + const label = labelField(fields); + const base = `/api/v1/${names.plural.kebab}`; + const hasDate = fields.some((f) => f.type === "date"); + const ormKwargs = (owner: string) => + [...fields.map((f) => `${f.snake}=${sample(f).orm}`), `user=${owner}`] + .map((kw) => ` ${kw},`) + .join("\n"); + const createPayload = pyDict( + fields.map((f) => `'${f.snake}': ${sample(f).api}`), + 12, + ); + const updatePayload = `{'${label.snake}': ${sample(label).updated}}`; + const assertLabel = (expr: string, value: string) => + COMPARABLE.has(label.type) + ? `self.assertEqual(${expr}['${label.snake}'], ${value})` + : `self.assertIn('${label.snake}', ${expr})`; + const assertUpdated = COMPARABLE.has(label.type) + ? `\n self.assertEqual(self.${one}.${label.snake}, ${sample(label).updated})` + : ""; + const missingRequired = + required(fields).length > 0 + ? ` + def test_create_${one}_missing_required(self): + resp = self.client.post( + '${base}', + {}, + content_type='application/json', + **self.auth_header(), + ) + self.assertEqual(resp.status_code, 400) +` + : ""; + + return { + path: `src/tests/test_${many}.py`, + content: `import uuid +${hasDate ? "\nfrom django.utils import timezone\n" : ""} +from src.models import ${P} +from src.tests.base import BaseTestCase + + +class ${P}CRUDTest(BaseTestCase): + def setUp(self): + super().setUp() + self.${one} = ${P}.objects.create( +${ormKwargs("self.user")} + ) + + def test_get_all_${many}(self): + resp = self.client.get('${base}', **self.auth_header()) + self.assertEqual(resp.status_code, 200) + self.assertEqual(len(resp.json()['data']['${keys}']), 1) + + def test_get_${one}_by_id(self): + resp = self.client.get( + f'${base}/{self.${one}.id}', **self.auth_header() + ) + self.assertEqual(resp.status_code, 200) + ${assertLabel(`resp.json()['data']['${key}']`, sample(label).orm)} + + def test_get_${one}_not_found(self): + resp = self.client.get( + f'${base}/{uuid.uuid4()}', **self.auth_header() + ) + self.assertEqual(resp.status_code, 404) + + def test_create_${one}(self): + resp = self.client.post( + '${base}', + ${createPayload}, + content_type='application/json', + **self.auth_header(), + ) + self.assertEqual(resp.status_code, 201) + ${assertLabel(`resp.json()['data']['${key}']`, sample(label).api)} +${missingRequired} + def test_update_own_${one}(self): + resp = self.client.patch( + f'${base}/{self.${one}.id}', + ${updatePayload}, + content_type='application/json', + **self.auth_header(), + ) + self.assertEqual(resp.status_code, 200) + self.${one}.refresh_from_db()${assertUpdated} + + def test_cannot_update_others_${one}(self): + other_${one} = ${P}.objects.create( +${ormKwargs("self.admin_user")} + ) + resp = self.client.patch( + f'${base}/{other_${one}.id}', + ${updatePayload}, + content_type='application/json', + **self.auth_header(), + ) + self.assertEqual(resp.status_code, 403) + + def test_delete_own_${one}(self): + resp = self.client.delete( + f'${base}/{self.${one}.id}', **self.auth_header() + ) + self.assertEqual(resp.status_code, 200) + self.assertFalse(${P}.objects.filter(id=self.${one}.id).exists()) + + def test_get_current_user_${many}(self): + resp = self.client.get( + '${base}/current-user', **self.auth_header()) + self.assertEqual(resp.status_code, 200) + self.assertEqual(len(resp.json()['data']['${keys}']), 1) + + def test_no_auth(self): + resp = self.client.get('${base}') + self.assertEqual(resp.status_code, 401) +`, + }; +} + +function migrateNote(ctx: Ctx): string { + return `Create and apply the migration: uv run python manage.py makemigrations src && uv run python manage.py migrate (the ${ctx.names.plural.snake} table does not exist until then).`; +} -// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). export const django: Generator = { id: "django", label: "Django", kind: "backend", - commands: {}, + commands: { + resource: { + describe: + "model appended to src/models.py + serializer + DRF views + urls (mounted under /api/v1/) + TestCase", + files: (ctx) => [serializer(ctx), views(ctx), urls(ctx), test(ctx)], + patches: (ctx) => [modelPatch(ctx), urlPatch(ctx)], + notes: (ctx) => [ + migrateNote(ctx), + `Run the suite: uv run python manage.py test src.tests.test_${ctx.names.plural.snake}`, + ], + }, + model: { + describe: "model class appended to src/models.py", + patches: (ctx) => [modelPatch(ctx)], + notes: (ctx) => [migrateNote(ctx)], + }, + migration: { + describe: "manage.py makemigrations src --name (after editing src/models.py)", + native: (ctx) => [ + { + bin: "uv", + args: [ + "run", + "python", + "manage.py", + "makemigrations", + "src", + "--name", + ctx.names.snake, + ], + }, + ], + notes: () => ["Apply it with: uv run python manage.py migrate"], + }, + controller: { + describe: "DRF function views in src/views/ using the {status, message, data} envelope", + files: (ctx) => [views(ctx)], + }, + validator: { + describe: "ModelSerializer in src/serializers/", + files: (ctx) => [serializer(ctx)], + }, + test: { describe: "TestCase in src/tests/ (BaseTestCase)", files: (ctx) => [test(ctx)] }, + }, }; diff --git a/src/generators/stacks/drogon.ts b/src/generators/stacks/drogon.ts index aa87e5a..e20c6ef 100644 --- a/src/generators/stacks/drogon.ts +++ b/src/generators/stacks/drogon.ts @@ -1,9 +1,394 @@ -import type { Generator } from "../types"; +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; + +// Stubs mirror CLIuno-Drogon-template: one self-contained HttpController per resource in +// controllers/

Controller.cc (METHOD_LIST + ADD_METHOD_TO, raw SQL through +// app().getDbClient()->execSqlSync with sqlite "?" placeholders, cliuno::ok/fail/envelope for +// the {status, message, data} envelope, currentUserId(req) as the auth guard). CMake globs +// controllers/*.cc, so the only registration is the CREATE TABLE statement in main.cc. + +const SQLITE: Record = { + string: "TEXT", + text: "TEXT", + int: "INTEGER", + number: "REAL", + boolean: "INTEGER", + date: "TEXT", + json: "TEXT", +}; + +const SIG = "const HttpRequestPtr &, std::function &&"; + +/** `field(b, "title")`, or the camelCase key with a snake_case fallback for multi-word names. */ +function read(f: Field): string { + return f.camel === f.snake ? `field(b, "${f.camel}")` : `field(b, "${f.camel}", "${f.snake}")`; +} + +/** jsoncpp predicate that the request value has the right shape. */ +function check(f: Field): string { + const v = read(f); + switch (f.type) { + case "string": + case "text": + case "date": + return `${v}.isString()`; + case "int": + return `${v}.isIntegral()`; + case "number": + return `${v}.isNumeric()`; + case "boolean": + return `${v}.isBool()`; + case "json": + return `!${v}.isNull()`; + } +} + +/** Expression that converts the request value into a bindable sqlite argument. */ +function bind(f: Field): string { + const v = read(f); + switch (f.type) { + case "string": + case "text": + case "date": + return `${v}.asString()`; + case "int": + return `${v}.asInt64()`; + case "number": + return `${v}.asDouble()`; + case "boolean": + return `${v}.asBool() ? 1 : 0`; + case "json": + return `jsonText(${v})`; + } +} + +/** Expression that reads the column back from an orm::Row into a Json::Value. */ +function column(f: Field): string { + const c = `r["${f.snake}"]`; + let value: string; + switch (f.type) { + case "string": + case "text": + case "date": + value = `Json::Value(${c}.as())`; + break; + case "int": + value = `Json::Value(${c}.as())`; + break; + case "number": + value = `Json::Value(${c}.as())`; + break; + case "boolean": + value = `Json::Value(${c}.as() != 0)`; + break; + case "json": + value = `parseJson(${c}.as())`; + break; + } + if (f.nullable || f.type === "json") return `${c}.isNull() ? Json::Value() : ${value}`; + return value; +} + +function schemaColumn(f: Field): string { + const parts = [f.snake, SQLITE[f.type]]; + if (!f.nullable) parts.push("NOT NULL"); + if (f.type === "boolean" && !f.nullable) parts.push("DEFAULT 0"); + return parts.join(" "); +} + +function requiredGuard(f: Field, title: string): string { + const v = read(f); + const test = + f.type === "string" || f.type === "text" + ? `!${v}.isString() || ${v}.asString().empty()` + : `!${check(f)}`; + const line = ` if (${test})`; + const action = `return cb(fail(k400BadRequest, "warning", "${title} is required"));`; + return line.length + action.length + 1 > 100 + ? `${line}\n ${action}` + : `${line} ${action}`; +} + +/** `UPDATE SET =? …` guarded by the request value's shape (one statement per field). */ +function setStatement(f: Field, table: string, indent: string, uid: string): string { + return `${indent}if (${check(f)}) +${indent} db->execSqlSync("UPDATE ${table} SET ${f.snake}=? WHERE id=? AND user_id=?", +${indent} ${bind(f)}, id, ${uid});`; +} + +function clearStatement(f: Field, table: string, indent: string, uid: string): string { + return `${indent}else if (${read(f)}.isNull()) +${indent} db->execSqlSync("UPDATE ${table} SET ${f.snake}=NULL WHERE id=? AND user_id=?", id, ${uid});`; +} + +function controller(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const C = `${P}Controller`; + const one = names.camel; + const many = names.plural.camel; + const title = names.title; + const titles = names.plural.title; + const table = names.plural.snake; + const route = `/api/v1/${names.plural.kebab}`; + const required = fields.filter((f) => !f.nullable); + const optional = fields.filter((f) => f.nullable); + const hasJson = fields.some((f) => f.type === "json"); + const hasSnake = fields.some((f) => f.camel !== f.snake); + + const includes = ["#include ", "#include "]; + if (hasJson) includes.unshift("#include "); + + const insertColumns = ["user_id", ...required.map((f) => f.snake)]; + const insertArgs = [ + "*id", + ...required.map((f) => + f.type === "boolean" ? `${check(f)} && ${read(f)}.asBool() ? 1 : 0` : bind(f), + ), + ]; + + const guards = required + .filter((f) => f.type !== "boolean") + .map((f) => `${requiredGuard(f, f.pascal)}\n`) + .join(""); + + const helpers: string[] = []; + helpers.push(`// Request keys arrive camelCase (or snake_case); a missing key reads as null. +const Json::Value &field(const Json::Value &b, const char *camel${hasSnake ? ", const char *snake = nullptr" : ""}) +{ +${ + hasSnake + ? ` if (b.isMember(camel) || !snake) return b[camel]; + return b[snake];` + : ` return b[camel];` +} +}`); + if (hasJson) + helpers.push(`// JSON columns are stored as text and parsed again on the way out. +std::string jsonText(const Json::Value &value) +{ + Json::StreamWriterBuilder writer; + writer["indentation"] = ""; + return Json::writeString(writer, value); +} +Json::Value parseJson(const std::string &text) +{ + Json::CharReaderBuilder builder; + std::unique_ptr reader(builder.newCharReader()); + Json::Value out; + std::string errs; + if (text.empty() || !reader->parse(text.data(), text.data() + text.size(), &out, &errs)) + return Json::Value(); + return out; +}`); + if (optional.length > 0) + helpers.push(`// Nullable columns: set when the key is present, clear when it is explicitly null. +void applyOptional(const orm::DbClientPtr &db, const Json::Value &b, int64_t id, int64_t uid) +{ +${optional.map((f) => `${setStatement(f, table, " ", "uid")}\n${clearStatement(f, table, " ", "uid")}`).join("\n")} +}`); + + const pad = " ".repeat(`void ${C}::update(`.length); + const padShow = " ".repeat(`void ${C}::show(`.length); + const padList = " ".repeat(`void ${C}::list(`.length); + const padCreate = " ".repeat(`void ${C}::create(`.length); + const padCurrent = " ".repeat(`void ${C}::currentUser(`.length); + const padRemove = " ".repeat(`void ${C}::remove(`.length); + + return { + path: `controllers/${C}.cc`, + content: `#include "../utils/Helpers.h" + +#include + +${includes.join("\n")} + +using namespace drogon; +using namespace cliuno; + +// ${route} — all scoped to the authenticated owner. +class ${C} : public HttpController<${C}> +{ + public: + METHOD_LIST_BEGIN + ADD_METHOD_TO(${C}::currentUser, "${route}/current-user", Get); + ADD_METHOD_TO(${C}::list, "${route}", Get); + ADD_METHOD_TO(${C}::create, "${route}", Post); + ADD_METHOD_TO(${C}::show, "${route}/{id}", Get); + ADD_METHOD_TO(${C}::update, "${route}/{id}", Patch); + ADD_METHOD_TO(${C}::remove, "${route}/{id}", Delete); + METHOD_LIST_END + + void list(${SIG}); + void currentUser(${SIG}); + void create(${SIG}); + void show(${SIG}, std::string); + void update(${SIG}, std::string); + void remove(${SIG}, std::string); +}; + +namespace +{ +Json::Value ${one}Json(const orm::Row &r) +{ + Json::Value v(Json::objectValue); + v["id"] = r["id"].as(); + v["user_id"] = r["user_id"].as(); +${fields.map((f) => ` v["${f.snake}"] = ${column(f)};`).join("\n")} + v["created_at"] = r["created_at"].isNull() ? "" : r["created_at"].as(); + return v; +} +${helpers.join("\n")} +} // namespace + +void ${C}::list(const HttpRequestPtr &req, +${padList}std::function &&cb) +{ + auto id = currentUserId(req); + if (!id) return cb(fail(k401Unauthorized, "error", "Unauthorized")); + auto rows = app().getDbClient()->execSqlSync( + "SELECT * FROM ${table} WHERE user_id=? ORDER BY id DESC", *id); + Json::Value arr(Json::arrayValue); + for (auto &r : rows) arr.append(${one}Json(r)); + Json::Value data(Json::objectValue); + data["${many}"] = arr; + cb(ok("${titles} fetched", data)); +} + +void ${C}::currentUser(const HttpRequestPtr &req, +${padCurrent}std::function &&cb) +{ + list(req, std::move(cb)); +} + +void ${C}::create(const HttpRequestPtr &req, +${padCreate}std::function &&cb) +{ + auto id = currentUserId(req); + if (!id) return cb(fail(k401Unauthorized, "error", "Unauthorized")); + const Json::Value b = bodyJson(req); +${guards} auto db = app().getDbClient(); + auto ins = db->execSqlSync( + "INSERT INTO ${table}(${insertColumns.join(",")}) VALUES(${insertColumns.map(() => "?").join(",")})", + ${insertArgs.join(",\n ")}); +${optional.length > 0 ? ` applyOptional(db, b, static_cast(ins.insertId()), *id);\n` : ""} auto rows = db->execSqlSync("SELECT * FROM ${table} WHERE id=?", ins.insertId()); + Json::Value data(Json::objectValue); + data["${one}"] = ${one}Json(rows[0]); + cb(envelope(k201Created, "success", "${title} created", data)); +} + +void ${C}::show(const HttpRequestPtr &req, +${padShow}std::function &&cb, std::string id) +{ + auto uid = currentUserId(req); + if (!uid) return cb(fail(k401Unauthorized, "error", "Unauthorized")); + try + { + auto rows = app().getDbClient()->execSqlSync( + "SELECT * FROM ${table} WHERE id=? AND user_id=?", std::stoll(id), *uid); + if (rows.empty()) return cb(fail(k404NotFound, "warning", "${title} not found")); + Json::Value data(Json::objectValue); + data["${one}"] = ${one}Json(rows[0]); + cb(ok("", data)); + } + catch (...) + { + cb(fail(k404NotFound, "warning", "${title} not found")); + } +} + +void ${C}::update(const HttpRequestPtr &req, +${pad}std::function &&cb, std::string rowId) +{ + auto uid = currentUserId(req); + if (!uid) return cb(fail(k401Unauthorized, "error", "Unauthorized")); + try + { + const Json::Value b = bodyJson(req); + auto db = app().getDbClient(); + const int64_t id = std::stoll(rowId); + auto rows = db->execSqlSync("SELECT * FROM ${table} WHERE id=? AND user_id=?", id, *uid); + if (rows.empty()) return cb(fail(k404NotFound, "warning", "${title} not found")); +${required.map((f) => setStatement(f, table, " ", "*uid")).join("\n")} +${optional.length > 0 ? ` applyOptional(db, b, id, *uid);\n` : ""} auto updated = db->execSqlSync("SELECT * FROM ${table} WHERE id=? AND user_id=?", id, *uid); + Json::Value data(Json::objectValue); + data["${one}"] = ${one}Json(updated[0]); + cb(ok("${title} updated", data)); + } + catch (...) + { + cb(fail(k404NotFound, "warning", "${title} not found")); + } +} + +void ${C}::remove(const HttpRequestPtr &req, +${padRemove}std::function &&cb, std::string id) +{ + auto uid = currentUserId(req); + if (!uid) return cb(fail(k401Unauthorized, "error", "Unauthorized")); + try + { + auto db = app().getDbClient(); + auto rows = db->execSqlSync("SELECT * FROM ${table} WHERE id=? AND user_id=?", + std::stoll(id), *uid); + if (rows.empty()) return cb(fail(k404NotFound, "warning", "${title} not found")); + Json::Value data(Json::objectValue); + data["${one}"] = ${one}Json(rows[0]); + db->execSqlSync("DELETE FROM ${table} WHERE id=? AND user_id=?", std::stoll(id), *uid); + cb(ok("${title} deleted", data)); + } + catch (...) + { + cb(fail(k404NotFound, "warning", "${title} not found")); + } +} +`, + }; +} + +function schema(ctx: Ctx): Patch[] { + const { names, fields } = ctx; + const table = names.plural.snake; + const columns = [ + "id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL,", + ...fields.map((f) => `${schemaColumn(f)},`), + "created_at TEXT NOT NULL DEFAULT (datetime('now')))", + ]; + return [ + { + path: "main.cc", + anchor: "for (const auto &sql : schema) db->execSqlSync(sql);", + where: "after", + insert: ` + db->execSqlSync( + "CREATE TABLE IF NOT EXISTS ${table} (" +${columns.map((c) => ` "${c}"`).join("\n")});`, + skipIf: `CREATE TABLE IF NOT EXISTS ${table} (`, + describe: `create the ${table} table at boot`, + }, + ]; +} -// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). export const drogon: Generator = { id: "drogon", label: "Drogon", kind: "backend", - commands: {}, + commands: { + resource: { + describe: + "HttpController in controllers/ under /api/v1/ + CREATE TABLE in main.cc (CMake globs controllers/*.cc)", + files: (ctx) => [controller(ctx)], + patches: schema, + notes: (ctx) => [ + `Rebuild (cmake --build build) — CMake globs controllers/*.cc; the ${ctx.names.plural.snake} table is created at boot by main.cc.`, + `Routes live at /api/v1/${ctx.names.plural.kebab} (+ /current-user); rows are scoped to the Bearer user.`, + "Responses use snake_case keys; requests accept camelCase or snake_case keys.", + ], + }, + controller: { + describe: + "HttpController using currentUserId + the ok/fail envelope (needs the table in main.cc)", + files: (ctx) => [controller(ctx)], + }, + }, }; diff --git a/src/generators/stacks/fastapi.ts b/src/generators/stacks/fastapi.ts index 499d8e8..58c3709 100644 --- a/src/generators/stacks/fastapi.ts +++ b/src/generators/stacks/fastapi.ts @@ -1,9 +1,398 @@ -import type { Generator } from "../types"; +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { labelField } from "../fields"; +import { ruffFormat } from "./shared"; + +// Stubs mirror the template's todo resource: src/routers/todos.py (`_success`, `_todo_dict`, +// `CurrentUser` / `DbSession`, owner-or-admin checks), the Todo model in src/models/models.py, +// the Todo* schemas in src/schemas/schemas.py and tests/test_todos.py. Double quotes, 100 cols, +// isort-sorted imports (ruff "I" is enforced by the template). + +const SA_TYPE: Record = { + string: "String(255)", + text: "Text", + int: "Integer", + number: "Float", + boolean: "Boolean", + date: "DateTime", + json: "JSON", +}; + +const SA_IMPORT: Record = { + string: "String", + text: "Text", + int: "Integer", + number: "Float", + boolean: "Boolean", + date: "DateTime", + json: "JSON", +}; + +const PY: Record = { + string: "str", + text: "str", + int: "int", + number: "float", + boolean: "bool", + date: "datetime", + json: "dict", +}; + +/** Routers the template registers in src/app.py, in isort order — used to slot the new import. */ +const KNOWN_ROUTERS = [ + "auth", + "comments", + "follows", + "posts", + "roles", + "todos", + "uploads", + "users", +]; + +function column(f: Field): string { + const py = f.nullable ? `${PY[f.type]} | None` : PY[f.type]; + const opts = f.nullable + ? "nullable=True" + : f.type === "boolean" + ? "default=False" + : "nullable=False"; + return ` ${f.snake}: Mapped[${py}] = mapped_column(${SA_TYPE[f.type]}, ${opts})`; +} + +/** `from sqlalchemy import …` members in isort's order-by-type order: CONSTANTS, Classes, functions. */ +function sqlalchemyImports(fields: Field[]): string { + const names = new Set(["DateTime", "ForeignKey", "String"]); + for (const f of fields) names.add(SA_IMPORT[f.type]); + const constants = [...names].filter((n) => n === n.toUpperCase()).sort(); + const classes = [...names].filter((n) => n !== n.toUpperCase()).sort(); + return [...constants, ...classes, "func"].join(", "); +} + +/** Sample JSON literals for tests (double-quoted Python). */ +function sample(f: Field): { create: string; updated: string } { + switch (f.type) { + case "string": + case "text": + return { create: `"Test ${f.snake}"`, updated: `"Updated ${f.snake}"` }; + case "int": + return { create: "1", updated: "2" }; + case "number": + return { create: "1.5", updated: "2.5" }; + case "boolean": + return { create: "False", updated: "True" }; + case "date": + return { create: '"2026-01-01T00:00:00"', updated: '"2026-02-01T00:00:00"' }; + case "json": + return { create: '{"key": "value"}', updated: '{"key": "updated"}' }; + } +} + +function required(fields: Field[]): Field[] { + return fields.filter((f) => !f.nullable && f.type !== "boolean"); +} + +function model(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + return { + path: `src/models/${names.snake}.py`, + content: `import uuid +from datetime import datetime + +from sqlalchemy import ${sqlalchemyImports(fields)} +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from src.database import Base +from src.models.models import User + + +class ${names.pascal}(Base): + __tablename__ = "${names.plural.snake}" + + id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid.uuid4())) +${fields.map(column).join("\n")} + user_id: Mapped[str] = mapped_column(String(36), ForeignKey("users.id"), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now()) + updated_at: Mapped[datetime] = mapped_column( + DateTime, server_default=func.now(), onupdate=func.now() + ) + + user: Mapped[User] = relationship("User") +`, + }; +} + +function schema(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const createField = (f: Field) => + f.nullable + ? ` ${f.snake}: ${PY[f.type]} | None = None` + : f.type === "boolean" + ? ` ${f.snake}: bool = False` + : ` ${f.snake}: ${PY[f.type]}`; + const updateField = (f: Field) => ` ${f.snake}: ${PY[f.type]} | None = None`; + const outField = (f: Field) => + f.nullable + ? ` ${f.snake}: ${PY[f.type]} | None = None` + : ` ${f.snake}: ${PY[f.type]}`; + return { + path: `src/schemas/${names.snake}.py`, + content: `from datetime import datetime + +from pydantic import BaseModel + + +class ${P}Create(BaseModel): +${fields.map(createField).join("\n")} + + +class ${P}Update(BaseModel): +${fields.map(updateField).join("\n")} + + +class ${P}Out(BaseModel): + id: str +${fields.map(outField).join("\n")} + user_id: str + created_at: datetime + updated_at: datetime + + model_config = {"from_attributes": True} +`, + }; +} + +function router(ctx: Ctx): FileSpec { + const { names } = ctx; + const P = names.pascal; + const one = names.snake; + const many = names.plural.snake; + const key = names.camel; + const keys = names.plural.camel; + const title = names.title; + const titles = names.plural.title; + const idParam = `${one}_id`; + const lookup = ` ${one} = db.query(${P}).filter(${P}.id == ${idParam}).first() + if not ${one}: + raise HTTPException(status_code=404, detail="${title} not found")`; + const ownerOrAdmin = ` if ${one}.user_id != current_user.id and current_user.role.name != "admin": + raise HTTPException(status_code=403, detail="Not authorized")`; + + return { + path: `src/routers/${many}.py`, + content: `from fastapi import APIRouter, HTTPException, status + +from src.dependencies.auth import CurrentUser, DbSession +from src.models.${one} import ${P} +from src.schemas.${one} import ${P}Create, ${P}Out, ${P}Update + +router = APIRouter(prefix="/${names.plural.kebab}", tags=["${titles}"]) + + +def _success(message: str, data=None): + return {"status": "success", "message": message, "data": data} + + +def _${one}_dict(${one}: ${P}) -> dict: + return ${P}Out.model_validate(${one}).model_dump(mode="json") + + +@router.get("") +def list_${many}(current_user: CurrentUser, db: DbSession): + ${many} = db.query(${P}).all() + return _success("${titles} retrieved", {"${keys}": [_${one}_dict(item) for item in ${many}]}) + + +@router.get("/current-user") +def current_user_${many}(current_user: CurrentUser, db: DbSession): + ${many} = db.query(${P}).filter(${P}.user_id == current_user.id).all() + return _success("User ${many} retrieved", {"${keys}": [_${one}_dict(item) for item in ${many}]}) + + +@router.post("", status_code=status.HTTP_201_CREATED) +def create_${one}(body: ${P}Create, current_user: CurrentUser, db: DbSession): + ${one} = ${P}(**body.model_dump(), user_id=current_user.id) + db.add(${one}) + db.commit() + db.refresh(${one}) + return _success("${title} created successfully", {"${key}": _${one}_dict(${one})}) + + +@router.get("/{${idParam}}") +def get_${one}(${idParam}: str, current_user: CurrentUser, db: DbSession): +${lookup} + return _success("${title} retrieved", {"${key}": _${one}_dict(${one})}) + + +@router.patch("/{${idParam}}") +def update_${one}(${idParam}: str, body: ${P}Update, current_user: CurrentUser, db: DbSession): +${lookup} +${ownerOrAdmin} + for field, value in body.model_dump(exclude_unset=True).items(): + setattr(${one}, field, value) + db.commit() + db.refresh(${one}) + return _success("${title} updated successfully", {"${key}": _${one}_dict(${one})}) + + +@router.delete("/{${idParam}}") +def delete_${one}(${idParam}: str, current_user: CurrentUser, db: DbSession): +${lookup} +${ownerOrAdmin} + db.delete(${one}) + db.commit() + return _success("${title} deleted successfully") +`, + }; +} + +function test(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const one = names.snake; + const many = names.plural.snake; + const key = names.camel; + const keys = names.plural.camel; + const label = labelField(fields); + const base = `/api/v1/${names.plural.kebab}`; + const idParam = `${one}_id`; + const payload = `{${fields.map((f) => `"${f.snake}": ${sample(f).create}`).join(", ")}}`; + const missingRequired = + required(fields).length > 0 + ? ` + def test_create_${one}_missing_required(self, client, user_token): + res = client.post("${base}", json={}, headers=auth_header(user_token)) + assert res.status_code == 422 +` + : ""; + + return { + path: `tests/test_${many}.py`, + content: `from tests.conftest import auth_header + +PAYLOAD = ${payload} + + +def _create(client, token): + return client.post("${base}", json=PAYLOAD, headers=auth_header(token)) + + +class Test${names.plural.pascal}: + def test_create_${one}(self, client, user_token): + res = _create(client, user_token) + assert res.status_code == 201 + assert res.json()["data"]["${key}"]["${label.snake}"] == ${sample(label).create} +${missingRequired} + def test_list_${many}(self, client, user_token): + _create(client, user_token) + _create(client, user_token) + res = client.get("${base}", headers=auth_header(user_token)) + assert res.status_code == 200 + assert len(res.json()["data"]["${keys}"]) == 2 + + def test_current_user_${many}(self, client, user_token, second_user_token): + _create(client, user_token) + _create(client, second_user_token) + res = client.get("${base}/current-user", headers=auth_header(user_token)) + assert res.status_code == 200 + assert len(res.json()["data"]["${keys}"]) == 1 + + def test_get_${one}(self, client, user_token): + ${idParam} = _create(client, user_token).json()["data"]["${key}"]["id"] + res = client.get(f"${base}/{${idParam}}", headers=auth_header(user_token)) + assert res.status_code == 200 + assert res.json()["data"]["${key}"]["id"] == ${idParam} + + def test_get_${one}_not_found(self, client, user_token): + res = client.get("${base}/nonexistent", headers=auth_header(user_token)) + assert res.status_code == 404 + + def test_update_${one}(self, client, user_token): + ${idParam} = _create(client, user_token).json()["data"]["${key}"]["id"] + res = client.patch( + f"${base}/{${idParam}}", + json={"${label.snake}": ${sample(label).updated}}, + headers=auth_header(user_token), + ) + assert res.status_code == 200 + assert res.json()["data"]["${key}"]["${label.snake}"] == ${sample(label).updated} + + def test_update_${one}_forbidden(self, client, user_token, second_user_token): + ${idParam} = _create(client, user_token).json()["data"]["${key}"]["id"] + res = client.patch( + f"${base}/{${idParam}}", + json={"${label.snake}": ${sample(label).updated}}, + headers=auth_header(second_user_token), + ) + assert res.status_code == 403 + + def test_delete_${one}(self, client, user_token): + ${idParam} = _create(client, user_token).json()["data"]["${key}"]["id"] + res = client.delete(f"${base}/{${idParam}}", headers=auth_header(user_token)) + assert res.status_code == 200 + assert client.get(f"${base}/{${idParam}}", headers=auth_header(user_token)).status_code == 404 + + def test_delete_${one}_forbidden(self, client, user_token, second_user_token): + ${idParam} = _create(client, user_token).json()["data"]["${key}"]["id"] + res = client.delete(f"${base}/{${idParam}}", headers=auth_header(second_user_token)) + assert res.status_code == 403 +`, + }; +} + +function register(ctx: Ctx): Patch[] { + const mod = ctx.names.plural.snake; + const before = KNOWN_ROUTERS.filter((name) => name < mod); + return [ + { + path: "src/app.py", + // Slot the module into the existing `from src.routers import …` line in isort order. + anchor: `from src.routers import ${before.join(", ")}`, + where: "after", + insert: before.length > 0 ? `, ${mod}` : `${mod}, `, + skipIf: `${mod}.router`, + describe: `import the ${mod} router`, + }, + { + path: "src/app.py", + anchor: /^app\.include_router\(.*\)$/m, + where: "after", + insert: `\napp.include_router(${mod}.router, prefix="/api/v1")`, + skipIf: `${mod}.router`, + describe: `include the ${mod} router`, + }, + ]; +} -// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). export const fastapi: Generator = { id: "fastapi", label: "FastAPI", kind: "backend", - commands: {}, + format: ruffFormat, + commands: { + resource: { + describe: + "SQLAlchemy model + pydantic schemas + router (included under /api/v1/) + pytest", + files: (ctx) => [model(ctx), schema(ctx), router(ctx), test(ctx)], + patches: register, + notes: (ctx) => [ + `Tables come from Base.metadata.create_all at startup — restart the dev server and the ${ctx.names.plural.snake} table appears.`, + "If ruff reports I001 in src/app.py after several generated routers, run: uv run ruff check --fix src/app.py", + ], + }, + model: { describe: "SQLAlchemy model in src/models/", files: (ctx) => [model(ctx)] }, + controller: { + describe: "APIRouter in src/routers/ using the {status, message, data} envelope", + files: (ctx) => [router(ctx)], + }, + dto: { + describe: "pydantic Create/Update/Out schemas in src/schemas/", + files: (ctx) => [schema(ctx)], + }, + validator: { + describe: "pydantic Create/Update/Out schemas in src/schemas/ (alias of make:dto)", + files: (ctx) => [schema(ctx)], + }, + test: { describe: "pytest module in tests/", files: (ctx) => [test(ctx)] }, + }, }; diff --git a/src/generators/stacks/fastify.ts b/src/generators/stacks/fastify.ts index 636e86d..d532e88 100644 --- a/src/generators/stacks/fastify.ts +++ b/src/generators/stacks/fastify.ts @@ -1,9 +1,425 @@ -import type { Generator } from "../types"; +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { oxfmt } from "./shared"; + +// The Fastify template keeps every TypeORM entity in src/entities.ts and lists them in +// src/db.ts, so "model" is a pair of patches rather than a new file. Routes are one plugin +// per resource in src/routes/.routes.ts, registered in src/app.ts. + +const COLUMN: Record = { + string: "text", + text: "text", + int: "integer", + number: "real", + boolean: "boolean", + date: "datetime", + json: "simple-json", +}; + +const TS: Record = { + string: "string", + text: "string", + int: "number", + number: "number", + boolean: "boolean", + date: "Date", + json: "Record", +}; + +/** Wire type of a field in a request body (dates travel as ISO strings). */ +const BODY: Record = { ...TS, date: "string" }; + +/** "due_date" → "Due date" for messages. */ +function human(f: Field): string { + const words = f.snake.replace(/_/g, " "); + return words.charAt(0).toUpperCase() + words.slice(1); +} + +function column(f: Field): string { + const type = f.nullable ? `${TS[f.type]} | null` : TS[f.type]; + if (f.type === "boolean") { + const opts = f.nullable ? "nullable: true" : "default: false"; + return ` @Column({ type: 'boolean', ${opts} })\n ${f.snake}: ${type}\n`; + } + const opts = f.nullable ? ", { nullable: true }" : ""; + return ` @Column('${COLUMN[f.type]}'${opts})\n ${f.snake}: ${type}\n`; +} + +function entityClass(ctx: Ctx): string { + const { names, fields } = ctx; + return `@Entity('${names.plural.pascal}') +export class ${names.pascal} { + @PrimaryGeneratedColumn('uuid') + id: string + +${fields.map(column).join("\n")} + @CreateDateColumn() + createdAt: Date + + @UpdateDateColumn() + updatedAt: Date + + @ManyToOne(() => User, { nullable: false }) + @JoinColumn({ name: 'user_id' }) + user: User +}`; +} + +function requiredGuard(f: Field): string { + const check = + f.type === "string" || f.type === "text" + ? `!${f.snake}` + : `${f.snake} === undefined || ${f.snake} === null`; + return ` if (${check}) { + return reply.status(400).send({ status: 'error', message: '${human(f)} is required' }) + }`; +} + +function createValue(f: Field): string { + if (f.type === "date") { + return f.nullable ? `${f.snake} ? new Date(${f.snake}) : null` : `new Date(${f.snake})`; + } + if (f.type === "boolean" && !f.nullable) return `${f.snake} ?? false`; + return f.nullable ? `${f.snake} ?? null` : f.snake; +} + +function updateLine(f: Field, one: string): string { + const value = + f.type === "date" + ? f.nullable + ? `${f.snake} ? new Date(${f.snake}) : null` + : `new Date(${f.snake})` + : f.snake; + return ` if (${f.snake} !== undefined) ${one}.${f.snake} = ${value}`; +} + +function routes(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const one = names.camel; + const many = names.plural.camel; + const title = names.title; + const plain = names.plural.kebab.replace(/-/g, " "); + const destructure = fields.map((f) => f.snake).join(", "); + const bodyType = fields + .map((f) => ` ${f.snake}?: ${BODY[f.type]}${f.nullable ? " | null" : ""}`) + .join("\n"); + const guards = fields + .filter((f) => !f.nullable && f.type !== "boolean") + .map(requiredGuard) + .join("\n"); + const assign = fields.map((f) => ` ${f.snake}: ${createValue(f)},`).join("\n"); + const updates = fields.map((f) => updateLine(f, one)).join("\n"); + + return { + path: `src/routes/${names.plural.kebab}.routes.ts`, + content: `import type { FastifyInstance } from 'fastify' + +import { authenticate } from '../auth' +import { db } from '../db' +import { ${P}, User } from '../entities' + +type ${P}Body = { +${bodyType} +} + +export default async function ${one}Routes(app: FastifyInstance) { + const ${many} = () => db.getRepository(${P}) + app.addHook('preHandler', authenticate) + + app.get('/', async (_request, reply) => { + const all = await ${many}().find({ relations: ['user'], order: { createdAt: 'DESC' } }) + return reply.send({ status: 'success', data: { ${many}: all } }) + }) + + app.get('/current-user', async (request, reply) => { + const mine = await ${many}().find({ + where: { user: { id: request.user.id } }, + relations: ['user'], + order: { createdAt: 'DESC' }, + }) + return reply.send({ status: 'success', data: { ${many}: mine } }) + }) + + app.post('/', async (request, reply) => { + const { ${destructure} } = (request.body ?? {}) as ${P}Body +${guards ? `${guards}\n` : ""} const user = await db.getRepository(User).findOneBy({ id: request.user.id }) + if (!user) { + return reply.status(404).send({ status: 'error', message: 'User not found' }) + } + + const ${one} = ${many}().create({ +${assign} + user, + }) + const saved = await ${many}().save(${one}) + return reply.status(201).send({ + status: 'success', + message: '${title} created successfully', + data: { ${one}: saved }, + }) + }) + + app.get('/:id', async (request, reply) => { + const { id } = request.params as { id: string } + const ${one} = await ${many}().findOne({ where: { id }, relations: ['user'] }) + if (!${one}) { + return reply.status(404).send({ status: 'error', message: '${title} not found' }) + } + return reply.send({ status: 'success', data: { ${one} } }) + }) + + app.patch('/:id', async (request, reply) => { + const { id } = request.params as { id: string } + const ${one} = await ${many}().findOne({ where: { id }, relations: ['user'] }) + if (!${one}) { + return reply.status(404).send({ status: 'error', message: '${title} not found' }) + } + if (${one}.user.id !== request.user.id) { + return reply + .status(403) + .send({ status: 'error', message: 'You can only update your own ${plain}' }) + } + const { ${destructure} } = (request.body ?? {}) as ${P}Body +${updates} + await ${many}().save(${one}) + return reply.send({ status: 'success', message: '${title} updated', data: { ${one} } }) + }) + + app.delete('/:id', async (request, reply) => { + const { id } = request.params as { id: string } + const ${one} = await ${many}().findOne({ where: { id }, relations: ['user'] }) + if (!${one}) { + return reply.status(404).send({ status: 'error', message: '${title} not found' }) + } + if (${one}.user.id !== request.user.id) { + return reply + .status(403) + .send({ status: 'error', message: 'You can only delete your own ${plain}' }) + } + await ${many}().remove(${one}) + return reply.send({ status: 'success', message: '${title} deleted successfully' }) + }) +} +`, + }; +} + +function sample(f: Field, variant: 0 | 1): string { + const label = f.snake.replace(/_/g, " "); + const values: Record = { + string: [`'Sample ${label}'`, `'Updated ${label}'`], + text: [`'Sample ${label}'`, `'Updated ${label}'`], + int: ["1", "2"], + number: ["1.5", "2.5"], + boolean: ["false", "true"], + date: ["'2026-01-01T00:00:00.000Z'", "'2026-02-01T00:00:00.000Z'"], + json: ["{ key: 'value' }", "{ key: 'updated' }"], + }; + return values[f.type][variant]; +} + +function test(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const one = names.camel; + const many = names.plural.camel; + const prefix = `/api/v1/${names.plural.kebab}`; + const payload = fields.map((f) => ` ${f.snake}: ${sample(f, 0)},`).join("\n"); + // Compare a scalar field after the update (dates and json round-trip differently). + const scalar = fields.find((f) => f.type !== "date" && f.type !== "json"); + const updatePayload = scalar ? `{ ${scalar.snake}: ${sample(scalar, 1)} }` : "{}"; + const updateAssert = scalar + ? `\n assert.equal(updated.json().data.${one}.${scalar.snake}, ${sample(scalar, 1)})` + : ""; + const createAssert = scalar + ? `\n assert.equal(${one}.${scalar.snake}, sample.${scalar.snake})` + : ""; + + return { + path: `src/__tests__/${names.kebab}.test.ts`, + content: `// Run with: DB_FILE=:memory: node --import tsx --test src/__tests__/${names.kebab}.test.ts +// (without DB_FILE it uses the dev db.sqlite and cleans up after itself) +import assert from 'node:assert/strict' +import { after, before, test } from 'node:test' +import Fastify from 'fastify' + +import { signToken } from '../auth' +import { db } from '../db' +import { ${P}, User } from '../entities' +import ${one}Routes from '../routes/${names.plural.kebab}.routes' + +const app = Fastify() +const stamp = Date.now() +let token = '' +let userId = '' + +before(async () => { + if (!db.isInitialized) await db.initialize() + const users = db.getRepository(User) + const user = await users.save( + users.create({ + username: \`${names.kebab}-tester-\${stamp}\`, + first_name: '${P}', + last_name: 'Tester', + email: \`${names.kebab}-tester-\${stamp}@example.com\`, + password: 'not-a-real-hash', + }), + ) + userId = user.id + token = signToken(user) + await app.register(${one}Routes, { prefix: '${prefix}' }) + await app.ready() +}) + +after(async () => { + await app.close() + await db + .getRepository(${P}) + .createQueryBuilder() + .delete() + .where('user_id = :userId', { userId }) + .execute() + await db.getRepository(User).delete({ id: userId }) + await db.destroy() +}) + +test('${many}: create, list, read, update, delete', async () => { + const headers = { authorization: \`Bearer \${token}\` } + const sample = { +${payload} + } + + const created = await app.inject({ method: 'POST', url: '${prefix}', headers, payload: sample }) + assert.equal(created.statusCode, 201) + const { ${one} } = created.json().data + assert.ok(${one}.id)${createAssert} + + const listed = await app.inject({ method: 'GET', url: '${prefix}/current-user', headers }) + assert.equal(listed.statusCode, 200) + assert.ok(listed.json().data.${many}.some((item: { id: string }) => item.id === ${one}.id)) + + const fetched = await app.inject({ method: 'GET', url: \`${prefix}/\${${one}.id}\`, headers }) + assert.equal(fetched.statusCode, 200) + assert.equal(fetched.json().data.${one}.id, ${one}.id) + + const updated = await app.inject({ + method: 'PATCH', + url: \`${prefix}/\${${one}.id}\`, + headers, + payload: ${updatePayload}, + }) + assert.equal(updated.statusCode, 200)${updateAssert} + + const removed = await app.inject({ method: 'DELETE', url: \`${prefix}/\${${one}.id}\`, headers }) + assert.equal(removed.statusCode, 200) + + const gone = await app.inject({ method: 'GET', url: \`${prefix}/\${${one}.id}\`, headers }) + assert.equal(gone.statusCode, 404) +}) + +test('${many}: rejects requests without a Bearer token', async () => { + const response = await app.inject({ method: 'GET', url: '${prefix}' }) + assert.equal(response.statusCode, 401) +}) +`, + }; +} + +function registerEntity(ctx: Ctx): Patch[] { + const { names } = ctx; + const P = names.pascal; + return [ + { + path: "src/entities.ts", + // last top-level closing brace → append the class at the end of the file + anchor: /^}$/m, + where: "after", + insert: `\n\n${entityClass(ctx)}`, + skipIf: `export class ${P} {`, + describe: `add the ${P} entity`, + }, + { + path: "src/db.ts", + anchor: /^import \{[^}]*\} from '\.\/entities'$/m, + where: "after", + insert: `\nimport { ${P} } from './entities'`, + skipIf: `{ ${P} }`, + describe: `import ${P} into the data source`, + }, + { + path: "src/db.ts", + anchor: "entities: [", + where: "after", + insert: `${P}, `, + skipIf: `${P},`, + describe: `register ${P} in the DataSource entities`, + }, + ]; +} + +function registerRoutes(ctx: Ctx): Patch[] { + const { names } = ctx; + const plugin = `${names.camel}Routes`; + const file = `./routes/${names.plural.kebab}.routes`; + return [ + { + path: "src/app.ts", + anchor: /^import \w+ from '\.\/routes\/[\w.-]+'$/m, + where: "after", + insert: `\nimport ${plugin} from '${file}'`, + skipIf: `${file}'`, + describe: `import the ${names.plural.kebab} routes`, + }, + { + path: "src/app.ts", + anchor: /^ *await app\.register\(\w+, \{ prefix: `\$\{prefix\}\/[\w-]+` \}\)$/m, + where: "after", + insert: `\n await app.register(${plugin}, { prefix: \`\${prefix}/${names.plural.kebab}\` })`, + skipIf: `\${prefix}/${names.plural.kebab}\``, + describe: `register /${names.plural.kebab}`, + }, + ]; +} -// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). export const fastify: Generator = { id: "fastify", label: "Fastify", kind: "backend", - commands: {}, + format: oxfmt, + commands: { + resource: { + describe: + "entity (appended to src/entities.ts) + route plugin (mounted under /api/v1/) + node:test spec", + files: (ctx) => [routes(ctx), test(ctx)], + patches: (ctx) => [...registerEntity(ctx), ...registerRoutes(ctx)], + notes: (ctx) => [ + `TypeORM synchronize is on — restart the dev server and the ${ctx.names.plural.pascal} table appears.`, + `Run the test with: DB_FILE=:memory: node --import tsx --test src/__tests__/${ctx.names.kebab}.test.ts`, + ], + }, + model: { + describe: "TypeORM entity appended to src/entities.ts and registered in src/db.ts", + patches: registerEntity, + notes: (ctx) => [ + `Import { ${ctx.names.pascal} } from '../entities' wherever you need the repository.`, + ], + }, + controller: { + describe: + "route plugin in src/routes/ using the {status, message, data} envelope (registered in src/app.ts)", + files: (ctx) => [routes(ctx)], + patches: registerRoutes, + notes: (ctx) => [ + `The plugin expects a ${ctx.names.pascal} entity — run make:model ${ctx.names.pascal} if it does not exist yet.`, + ], + }, + test: { + describe: "node:test spec in src/__tests__/ that drives the routes through app.inject", + files: (ctx) => [test(ctx)], + notes: (ctx) => [ + `Run with: DB_FILE=:memory: node --import tsx --test src/__tests__/${ctx.names.kebab}.test.ts`, + ], + }, + }, }; diff --git a/src/generators/stacks/flutter.ts b/src/generators/stacks/flutter.ts index 085ce2d..52699a6 100644 --- a/src/generators/stacks/flutter.ts +++ b/src/generators/stacks/flutter.ts @@ -1,9 +1,577 @@ -import type { Generator } from "../types"; +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { labelField } from "../fields"; + +/** Fields DSL → Dart (documented on the API client; screens keep the template's `Map` items). */ +const DART: Record = { + string: "String", + text: "String", + int: "int", + number: "double", + boolean: "bool", + date: "String", + json: "Map", +}; + +function dartType(f: Field): string { + return `${DART[f.type]}${f.nullable ? "?" : ""}`; +} + +function title(f: Field): string { + return f.pascal.replace(/([a-z0-9])([A-Z])/g, "$1 $2"); +} + +function label(f: Field): string { + if (f.type === "json") return `${title(f)} (JSON)`; + return f.nullable && f.type !== "boolean" ? `${title(f)} (optional)` : title(f); +} + +function indent(lines: string[], n: number): string[] { + const pad = " ".repeat(n); + return lines.map((l) => (l ? pad + l : l)); +} + +function needsConvert(fields: Field[]): boolean { + return fields.some((f) => f.type === "json"); +} + +/** Dart expression that turns the form state into the JSON value sent to the API. */ +function dartValue(f: Field, prefix: string): string { + const text = `${prefix}${f.camel}Ctrl.text.trim()`; + switch (f.type) { + case "boolean": + return `${prefix}${f.camel}`; + case "int": + return f.nullable ? `int.tryParse(${text})` : `int.tryParse(${text}) ?? 0`; + case "number": + return f.nullable ? `double.tryParse(${text})` : `double.tryParse(${text}) ?? 0`; + case "json": + return f.nullable + ? `${text}.isEmpty ? null : jsonDecode(${text})` + : `${text}.isEmpty ? {} : jsonDecode(${text})`; + default: + return f.nullable ? `${text}.isEmpty ? null : ${text}` : text; + } +} + +/** Interpolation used when showing a field from an item map. */ +function dartDisplay(f: Field): string { + const v = `item['${f.camel}']`; + if (f.type === "boolean") return `\${${v} == true || ${v} == 1 ? 'Yes' : 'No'}`; + return `\${${v} ?? ''}`; +} + +/** One form field; `prefix` is "" for dialog locals and "_" for State fields. */ +function input(f: Field, prefix: string, setter: string, autofocus: boolean): string[] { + if (f.type === "boolean") { + return [ + "SwitchListTile(", + ` title: const Text('${label(f)}'),`, + ` value: ${prefix}${f.camel},`, + ` onChanged: (v) => ${setter}(() => ${prefix}${f.camel} = v),`, + "),", + ]; + } + const lines = ["TextField(", ` controller: ${prefix}${f.camel}Ctrl,`]; + if (autofocus) lines.push(" autofocus: true,"); + if (f.type === "text" || f.type === "json") lines.push(" maxLines: 3,"); + if (f.type === "int") lines.push(" keyboardType: TextInputType.number,"); + if (f.type === "number") { + lines.push( + " keyboardType: const TextInputType.numberWithOptions(", + " decimal: true,", + " ),", + ); + } + lines.push(` decoration: const InputDecoration(labelText: '${label(f)}'),`, "),"); + return lines; +} + +function api(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const route = names.plural.kebab; + const payload = fields.map((f) => `${f.camel}: ${dartType(f)}`).join(", "); + return { + path: `lib/apis/${names.snake}_api.dart`, + content: `import 'package:dio/dio.dart'; + +import 'http.dart'; + +/// \`/${route}\` — payload: {${payload}}. +class ${P}Api { + Future> get${names.plural.pascal}() => http.get('/${route}'); + + Future> get${P}ById(String id) => + http.get('/${route}/\${id}'); + + Future> create${P}(Map data) => + http.post('/${route}', data: data); + + Future> update${P}(String id, Map data) => + http.patch('/${route}/\${id}', data: data); + + Future> delete${P}(String id) => + http.delete('/${route}/\${id}'); +} + +final ${names.camel}Api = ${P}Api(); +`, + }; +} + +function createDialog(ctx: Ctx): string[] { + const { names, fields } = ctx; + const hasBool = fields.some((f) => f.type === "boolean"); + const inputs = fields.flatMap((f, i) => input(f, "", "setDialogState", i === 0)); + const alert = [ + "AlertDialog(", + ` title: const Text('New ${names.title.toLowerCase()}'),`, + " content: Column(", + " mainAxisSize: MainAxisSize.min,", + " children: [", + ...indent(inputs, 6), + " ],", + " ),", + " actions: [", + " TextButton(", + " onPressed: () => Navigator.pop(ctx, false),", + " child: const Text('Cancel'),", + " ),", + " FilledButton(", + " onPressed: () => Navigator.pop(ctx, true),", + " child: const Text('Add'),", + " ),", + " ],", + "),", + ]; + const builder = hasBool + ? [ + "builder: (ctx) => StatefulBuilder(", + ` builder: (ctx, setDialogState) => ${alert[0]}`, + ...indent(alert.slice(1), 2), + "),", + ] + : [`builder: (ctx) => ${alert[0]}`, ...alert.slice(1)]; + return [ + "final ok = await showDialog(", + " context: context,", + ...indent(builder, 2), + ");", + ]; +} + +function listScreen(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const Pp = names.plural.pascal; + const items = `_${names.plural.camel}`; + const lbl = labelField(fields); + const others = fields.filter((f) => f !== lbl); + const locals = fields.map((f) => + f.type === "boolean" + ? ` var ${f.camel} = false;` + : ` final ${f.camel}Ctrl = TextEditingController();`, + ); + const guard = + lbl.type === "string" || lbl.type === "text" + ? ` if (ok != true || ${lbl.camel}Ctrl.text.trim().isEmpty) return;` + : " if (ok != true) return;"; + const payload = fields.map((f) => ` '${f.camel}': ${dartValue(f, "")},`); + const subtitle = others.map((f) => `Text('${title(f)}: ${dartDisplay(f)}'),`); + return { + path: `lib/screens/${names.plural.snake}_screen.dart`, + content: `${needsConvert(fields) ? "import 'dart:convert';\n\n" : ""}import 'package:flutter/material.dart'; + +import '../apis/http.dart'; +import '../apis/${names.snake}_api.dart'; +import '../widgets/app_drawer.dart'; +import '${names.snake}_detail_screen.dart'; + +class ${Pp}Screen extends StatefulWidget { + const ${Pp}Screen({super.key}); + + @override + State<${Pp}Screen> createState() => _${Pp}ScreenState(); +} + +class _${Pp}ScreenState extends State<${Pp}Screen> { + List> ${items} = []; + bool _loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + final res = await ${names.camel}Api.get${Pp}(); + final list = (res.data['data'] as Map)['${names.plural.camel}'] as List? ?? []; + if (!mounted) return; + setState(() { + ${items} = list.map((e) => (e as Map).cast()).toList(); + _loading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() => _loading = false); + _snack(apiMessage(e)); + } + } + + void _snack(String msg) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg))); + } + + Future _add${P}() async { +${locals.join("\n")} +${indent(createDialog(ctx), 4).join("\n")} +${guard} + try { + await ${names.camel}Api.create${P}({ +${payload.join("\n")} + }); + await _load(); + } catch (e) { + if (mounted) _snack(apiMessage(e)); + } + } + + Future _delete(Map item) async { + try { + await ${names.camel}Api.delete${P}('\${item['id']}'); + await _load(); + } catch (e) { + if (mounted) _snack(apiMessage(e)); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('${names.plural.title}')), + drawer: const AppDrawer(), + floatingActionButton: FloatingActionButton( + onPressed: _add${P}, + child: const Icon(Icons.add), + ), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : RefreshIndicator( + onRefresh: _load, + child: ${items}.isEmpty + ? ListView( + children: const [ + Padding( + padding: EdgeInsets.all(32), + child: Center( + child: Text('No ${names.plural.title.toLowerCase()} yet — add one!'), + ), + ), + ], + ) + : ListView.builder( + itemCount: ${items}.length, + itemBuilder: (context, i) { + final item = ${items}[i]; + final author = + ((item['user'] as Map?)?['username'] ?? '') + as String; + return ListTile( + title: Text('${dartDisplay(lbl)}'), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ +${indent(subtitle, 30).join("\n")}${subtitle.length > 0 ? "\n" : ""} if (author.isNotEmpty) + Text( + '@$author', + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + trailing: IconButton( + icon: const Icon(Icons.delete_outline), + onPressed: () => _delete(item), + ), + onTap: () async { + await Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + ${P}DetailScreen(id: '\${item['id']}'), + ), + ); + await _load(); + }, + ); + }, + ), + ), + ); + } +} +`, + }; +} + +function detailScreen(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const textFields = fields.filter((f) => f.type !== "boolean"); + const boolFields = fields.filter((f) => f.type === "boolean"); + const state = [ + ...textFields.map((f) => ` final _${f.camel}Ctrl = TextEditingController();`), + " bool _loading = true;", + ...boolFields.map((f) => ` bool _${f.camel} = false;`), + ]; + const dispose = textFields.map((f) => ` _${f.camel}Ctrl.dispose();`); + const load = fields.map((f) => { + const v = `item['${f.camel}']`; + if (f.type === "boolean") return ` _${f.camel} = ${v} == true || ${v} == 1;`; + if (f.type === "json") { + return ` _${f.camel}Ctrl.text = ${v} == null ? '' : jsonEncode(${v});`; + } + return ` _${f.camel}Ctrl.text = '\${${v} ?? ''}';`; + }); + const payload = fields.map((f) => ` '${f.camel}': ${dartValue(f, "_")},`); + const inputs = fields.flatMap((f, i) => [ + ...(i > 0 ? ["const SizedBox(height: 12),"] : []), + ...input(f, "_", "setState", false), + ]); + return { + path: `lib/screens/${names.snake}_detail_screen.dart`, + content: `${needsConvert(fields) ? "import 'dart:convert';\n\n" : ""}import 'package:flutter/material.dart'; + +import '../apis/http.dart'; +import '../apis/${names.snake}_api.dart'; + +class ${P}DetailScreen extends StatefulWidget { + const ${P}DetailScreen({super.key, required this.id}); + + final String id; + + @override + State<${P}DetailScreen> createState() => _${P}DetailScreenState(); +} + +class _${P}DetailScreenState extends State<${P}DetailScreen> { +${state.join("\n")} + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { +${dispose.join("\n")}${dispose.length > 0 ? "\n" : ""} super.dispose(); + } + + Future _load() async { + try { + final res = await ${names.camel}Api.get${P}ById(widget.id); + final item = ((res.data['data'] as Map)['${names.camel}'] as Map) + .cast(); + if (!mounted) return; + setState(() { +${load.join("\n")} + _loading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() => _loading = false); + _snack(apiMessage(e)); + } + } + + void _snack(String msg) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg))); + } + + Future _save() async { + try { + await ${names.camel}Api.update${P}(widget.id, { +${payload.join("\n")} + }); + if (!mounted) return; + _snack('${names.title} saved'); + } catch (e) { + if (mounted) _snack(apiMessage(e)); + } + } + + Future _delete() async { + try { + await ${names.camel}Api.delete${P}(widget.id); + if (!mounted) return; + Navigator.pop(context); + } catch (e) { + if (mounted) _snack(apiMessage(e)); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('${names.title}'), + actions: [ + IconButton( + icon: const Icon(Icons.delete_outline), + onPressed: _delete, + ), + ], + ), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + padding: const EdgeInsets.all(16), + children: [ +${indent(inputs, 16).join("\n")} + const SizedBox(height: 8), + FilledButton(onPressed: _save, child: const Text('Save')), + ], + ), + ); + } +} +`, + }; +} + +function store(ctx: Ctx): FileSpec { + const { names } = ctx; + const P = names.pascal; + return { + path: `lib/stores/${names.snake}_store.dart`, + content: `import 'package:flutter/foundation.dart'; + +import '../apis/http.dart'; +import '../apis/${names.snake}_api.dart'; + +/// App-wide ${names.title} list (same singleton ChangeNotifier shape as AuthStore). +class ${P}Store extends ChangeNotifier { + ${P}Store._(); + + static final ${P}Store instance = ${P}Store._(); + + List> items = []; + bool loading = false; + String? error; + + Future fetchAll() async { + loading = true; + error = null; + notifyListeners(); + try { + final res = await ${names.camel}Api.get${names.plural.pascal}(); + final list = (res.data['data'] as Map)['${names.plural.camel}'] as List? ?? []; + items = list.map((e) => (e as Map).cast()).toList(); + } catch (e) { + error = apiMessage(e); + } finally { + loading = false; + notifyListeners(); + } + } + + Future remove(String id) async { + await ${names.camel}Api.delete${P}(id); + items = items.where((item) => '\${item['id']}' != id).toList(); + notifyListeners(); + } +} +`, + }; +} + +function component(ctx: Ctx): FileSpec { + const { names } = ctx; + return { + path: `lib/widgets/${names.snake}.dart`, + content: `import 'package:flutter/material.dart'; + +/// ${names.title} — reusable widget stub, edit freely. +class ${names.pascal} extends StatelessWidget { + const ${names.pascal}({super.key}); + + @override + Widget build(BuildContext context) { + return const Card( + child: Padding( + padding: EdgeInsets.all(16), + child: Text('${names.title}'), + ), + ); + } +} +`, + }; +} + +function routePatches(ctx: Ctx): Patch[] { + const { names } = ctx; + const screen = `${names.plural.pascal}Screen`; + const file = `screens/${names.plural.snake}_screen.dart`; + return [ + { + path: "lib/main.dart", + anchor: /^import 'screens\/\w+\.dart';$/m, + where: "after", + insert: `\nimport '${file}';`, + skipIf: file, + describe: `import ${screen}`, + }, + { + path: "lib/main.dart", + anchor: /^\s*'\/[\w-]+': \(_\) => const \w+\(\),$/m, + where: "after", + insert: `\n '/${names.plural.kebab}': (_) => const ${screen}(),`, + skipIf: `'/${names.plural.kebab}':`, + describe: `register the /${names.plural.kebab} route`, + }, + ]; +} + +function drawerNote(ctx: Ctx): string { + const { names } = ctx; + return `Add a drawer entry in lib/widgets/app_drawer.dart: _item(context, Icons.widgets_outlined, '${names.plural.title}', '/${names.plural.kebab}')`; +} -// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). export const flutter: Generator = { id: "flutter", label: "Flutter", kind: "mobile", - commands: {}, + format: (files) => ({ bin: "dart", args: ["format", ...files], quiet: true }), + commands: { + resource: { + describe: + "Dio API client + list screen (create dialog, delete) + detail screen, route added to lib/main.dart", + files: (ctx) => [api(ctx), listScreen(ctx), detailScreen(ctx)], + patches: routePatches, + notes: (ctx) => [drawerNote(ctx)], + }, + api: { + describe: "Dio API client class in lib/apis/ (import it directly — no registry)", + files: (ctx) => [api(ctx)], + }, + page: { + describe: "list + detail screens in lib/screens/ (+ route in lib/main.dart)", + files: (ctx) => [listScreen(ctx), detailScreen(ctx)], + patches: routePatches, + notes: (ctx) => [drawerNote(ctx)], + }, + store: { + describe: "singleton ChangeNotifier store in lib/stores/", + files: (ctx) => [store(ctx)], + }, + component: { + describe: "StatelessWidget stub in lib/widgets/", + files: (ctx) => [component(ctx)], + }, + }, }; diff --git a/src/generators/stacks/laravel.ts b/src/generators/stacks/laravel.ts index 6ff0126..3f5003d 100644 --- a/src/generators/stacks/laravel.ts +++ b/src/generators/stacks/laravel.ts @@ -1,9 +1,561 @@ -import type { Generator } from "../types"; +import fs from "node:fs"; +import path from "node:path"; +import type { Ctx, FileSpec, Generator, NativeCall, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { labelField } from "../fields"; +import { pint } from "./shared"; + +/* + * Stubs mirror CLIuno-Laravel-template's todo resource: Eloquent model with $fillable/casts(), + * anonymous-class migration, inline $request->validate() in the controller, explicit routes in + * routes/api.php inside the auth:sanctum group, {data: {|}} responses with + * snake_case attributes, and a hasMany relation on User (the todo controller uses + * $request->user()->todos()). Pint (laravel preset) formats everything written. + */ + +const COLUMN: Record = { + string: "string", + text: "text", + int: "integer", + number: "float", + boolean: "boolean", + date: "dateTime", + json: "json", +}; + +const CAST: Record = { + string: null, + text: null, + int: "integer", + number: "float", + boolean: "boolean", + date: "datetime", + json: "array", +}; + +const RULES: Record = { + string: ["string", "max:255"], + text: ["string"], + int: ["integer"], + number: ["numeric"], + boolean: ["boolean"], + date: ["date"], + json: ["array"], +}; + +/** PHP literal for a sample value (tests). */ +const SAMPLE: Record string> = { + string: (f) => `'Sample ${f.snake.replace(/_/g, " ")}'`, + text: (f) => `'Sample ${f.snake.replace(/_/g, " ")} text'`, + int: () => "1", + number: () => "1.5", + boolean: () => "false", + date: () => "'2026-01-01 00:00:00'", + json: () => "['key' => 'value']", +}; + +const UPDATED: Record string> = { + string: (f) => `'Updated ${f.snake.replace(/_/g, " ")}'`, + text: (f) => `'Updated ${f.snake.replace(/_/g, " ")} text'`, + int: () => "2", + number: () => "2.5", + boolean: () => "true", + date: () => "'2026-02-02 00:00:00'", + json: () => "['key' => 'updated']", +}; + +const phpList = (items: string[]) => items.map((i) => `'${i}'`).join(", "); + +/** Sort `use` statements the way Pint's ordered_imports (alpha) does. */ +export function phpUses(classes: string[]): string { + const key = (c: string) => c.replace(/\\/g, " ").toLowerCase(); + return [...new Set(classes)] + .sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)) + .map((c) => `use ${c};`) + .join("\n"); +} + +function storeRules(f: Field): string { + const rules = f.type === "boolean" ? ["sometimes"] : f.nullable ? ["nullable"] : ["required"]; + return ` '${f.snake}' => [${phpList([...rules, ...RULES[f.type]])}],`; +} + +function updateRules(f: Field): string { + const rules = f.nullable ? ["sometimes", "nullable"] : ["sometimes"]; + return ` '${f.snake}' => [${phpList([...rules, ...RULES[f.type]])}],`; +} + +function column(f: Field): string { + let line = ` $table->${COLUMN[f.type]}('${f.snake}')`; + if (f.type === "boolean") line += "->default(false)"; + else if (f.nullable) line += "->nullable()"; + return `${line};`; +} + +function utcStamp(): string { + const d = new Date(); + const p = (n: number) => String(n).padStart(2, "0"); + return `${d.getUTCFullYear()}_${p(d.getUTCMonth() + 1)}_${p(d.getUTCDate())}_${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`; +} + +/** Reuse an existing create__table migration so a second run is a no-op. */ +export function migrationPath(ctx: Ctx): string { + const suffix = `create_${ctx.names.plural.snake}_table.php`; + try { + const existing = fs + .readdirSync(path.join(ctx.cwd, "database", "migrations")) + .find((f) => f.endsWith(`_${suffix}`)); + if (existing) return `database/migrations/${existing}`; + } catch { + // no migrations dir (dry-run outside a checkout) — fall through to a fresh name + } + return `database/migrations/${utcStamp()}_${suffix}`; +} + +export function model(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const casts = fields.filter((f) => CAST[f.type]); + const castsBlock = casts.length + ? ` + protected function casts(): array + { + return [ +${casts.map((f) => ` '${f.snake}' => '${CAST[f.type]}',`).join("\n")} + ]; + } +` + : ""; + return { + path: `app/Models/${names.pascal}.php`, + content: ` ` '${f.snake}',`).join("\n")} + 'user_id', + ]; +${castsBlock} + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} +`, + }; +} + +export function migration(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + return { + path: migrationPath(ctx), + content: `id(); +${fields.map(column).join("\n")} + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('${names.plural.snake}'); + } +}; +`, + }; +} + +export function controller(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const one = names.camel; + const many = names.plural.camel; + const title = names.title; + return { + path: `app/Http/Controllers/${P}Controller.php`, + content: `latest()->get(); + + return response()->json(['data' => ['${many}' => $${many}]]); + } + + public function show(int $id): JsonResponse + { + $${one} = ${P}::with('user')->findOrFail($id); + + return response()->json(['data' => ['${one}' => $${one}]]); + } + + public function store(Request $request): JsonResponse + { + $validated = $request->validate([ +${fields.map(storeRules).join("\n")} + ]); + + $${one} = $request->user()->${many}()->create($validated); + + return response()->json(['data' => ['${one}' => $${one}->load('user')]], 201); + } + + public function update(Request $request, int $id): JsonResponse + { + $${one} = ${P}::findOrFail($id); + + if ($${one}->user_id !== $request->user()->id) { + return response()->json(['message' => 'Unauthorized'], 403); + } + + $validated = $request->validate([ +${fields.map(updateRules).join("\n")} + ]); + + $${one}->update($validated); + + return response()->json(['data' => ['${one}' => $${one}->fresh()->load('user')]]); + } + + public function destroy(Request $request, int $id): JsonResponse + { + $${one} = ${P}::findOrFail($id); + + if ($${one}->user_id !== $request->user()->id) { + return response()->json(['message' => 'Unauthorized'], 403); + } + + $${one}->delete(); + + return response()->json(['message' => '${title} deleted successfully']); + } + + public function currentUser(Request $request): JsonResponse + { + $${many} = $request->user()->${many}()->with('user')->latest()->get(); + + return response()->json(['data' => ['${many}' => $${many}]]); + } +} +`, + }; +} + +/** Form request (only used as the stub fallback for make:request — the controllers validate inline like the template). */ +export function formRequest(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + return { + path: `app/Http/Requests/Store${names.pascal}Request.php`, + content: `> + */ + public function rules(): array + { + return [ +${fields.map(storeRules).join("\n")} + ]; + } +} +`, + }; +} + +/** PHP array literal with one sample value per field, indented for a test body. */ +export function samplePayload(fields: Field[], indent: string): string { + return fields.map((f) => `${indent}'${f.snake}' => ${SAMPLE[f.type](f)},`).join("\n"); +} + +export function labelInfo(fields: Field[]) { + const label = labelField(fields); + const jsonAssertable = ["string", "text", "int", "number", "boolean"].includes(label.type); + const dbAssertable = ["string", "text", "int"].includes(label.type); + return { + label, + sample: SAMPLE[label.type](label), + updated: UPDATED[label.type](label), + jsonAssertable, + dbAssertable, + }; +} + +/** Pest feature test (CLIuno-Laravel-template uses Pest with RefreshDatabase bound to tests/Feature). */ +export function pestTest(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const one = names.camel; + const many = names.plural.camel; + const url = `/api/v1/${names.plural.kebab}`; + const table = names.plural.snake; + const { label, sample, updated, jsonAssertable, dbAssertable } = labelInfo(fields); + const human = names.title.toLowerCase(); + const humans = names.plural.title.toLowerCase(); + const createdAssert = jsonAssertable + ? ` + ->assertJsonPath('data.${one}.${label.snake}', ${sample})` + : ""; + const createdDb = dbAssertable + ? ` + $this->assertDatabaseHas('${table}', ['${label.snake}' => ${sample}, 'user_id' => $this->user->id]);` + : ` + $this->assertDatabaseCount('${table}', 1);`; + const updatedAssert = jsonAssertable + ? ` + ->assertJsonPath('data.${one}.${label.snake}', ${updated})` + : ""; + + return { + path: `tests/Feature/${P}Test.php`, + content: `user = User::factory()->create(); + $this->payload = [ +${samplePayload(fields, " ")} + ]; +}); + +test('${humans} require authentication', function () { + $this->getJson('${url}')->assertUnauthorized(); +}); + +test('${humans} can be listed', function () { + ${P}::create([...$this->payload, 'user_id' => $this->user->id]); + + Sanctum::actingAs($this->user); + + $this->getJson('${url}') + ->assertOk() + ->assertJsonCount(1, 'data.${many}'); +}); + +test('current user ${humans} can be listed', function () { + ${P}::create([...$this->payload, 'user_id' => $this->user->id]); + ${P}::create([...$this->payload, 'user_id' => User::factory()->create()->id]); + + Sanctum::actingAs($this->user); + + $this->getJson('${url}/current-user') + ->assertOk() + ->assertJsonCount(1, 'data.${many}'); +}); + +test('a ${human} can be created', function () { + Sanctum::actingAs($this->user); + + $this->postJson('${url}', $this->payload) + ->assertCreated()${createdAssert}; +${createdDb} +}); + +test('a ${human} can be shown', function () { + $${one} = ${P}::create([...$this->payload, 'user_id' => $this->user->id]); + + Sanctum::actingAs($this->user); + + $this->getJson('${url}/'.$${one}->id) + ->assertOk() + ->assertJsonPath('data.${one}.id', $${one}->id); +}); + +test('an own ${human} can be updated', function () { + $${one} = ${P}::create([...$this->payload, 'user_id' => $this->user->id]); + + Sanctum::actingAs($this->user); + + $this->patchJson('${url}/'.$${one}->id, ['${label.snake}' => ${updated}]) + ->assertOk()${updatedAssert}; +}); + +test('a ${human} of another user cannot be updated', function () { + $${one} = ${P}::create([...$this->payload, 'user_id' => User::factory()->create()->id]); + + Sanctum::actingAs($this->user); + + $this->patchJson('${url}/'.$${one}->id, ['${label.snake}' => ${updated}]) + ->assertForbidden(); +}); + +test('an own ${human} can be deleted', function () { + $${one} = ${P}::create([...$this->payload, 'user_id' => $this->user->id]); + + Sanctum::actingAs($this->user); + + $this->deleteJson('${url}/'.$${one}->id) + ->assertOk(); + + $this->assertDatabaseMissing('${table}', ['id' => $${one}->id]); +}); +`, + }; +} + +/** Insert `use App\Http\Controllers\

Controller;` where Pint's alpha import order wants it. */ +function useControllerPatch(ctx: Ctx): Patch { + const { names } = ctx; + const line = `use App\\Http\\Controllers\\${names.pascal}Controller;`; + const mine = `${names.pascal}Controller`.toLowerCase(); + let anchor: string | RegExp = /^use App\\Http\\Controllers\\[\w\\]+;$/m; + let where: "before" | "after" = "after"; + try { + const source = fs.readFileSync(path.join(ctx.cwd, "routes", "api.php"), "utf8"); + const re = /^use App\\Http\\Controllers\\([\w\\]+);$/gm; + let m: RegExpExecArray | null; + while ((m = re.exec(source)) !== null) { + const key = (m[1] as string).replace(/\\/g, " ").toLowerCase(); + if (key > mine) { + anchor = m[0]; + where = "before"; + break; + } + } + } catch { + // routes/api.php unreadable — append after the last controller import instead + } + return { + path: "routes/api.php", + anchor, + where, + insert: where === "before" ? `${line}\n` : `\n${line}`, + skipIf: line, + describe: `import ${names.pascal}Controller`, + }; +} + +export function apiRoutePatches(ctx: Ctx): Patch[] { + const { names } = ctx; + const P = names.pascal; + const kp = names.plural.kebab; + return [ + useControllerPatch(ctx), + { + path: "routes/api.php", + anchor: "Route::middleware(['auth:sanctum'])->group(function () {", + where: "after", + insert: ` + // ${names.plural.title} + Route::get('/${kp}/current-user', [${P}Controller::class, 'currentUser']); + Route::get('/${kp}', [${P}Controller::class, 'index']); + Route::get('/${kp}/{id}', [${P}Controller::class, 'show']); + Route::post('/${kp}', [${P}Controller::class, 'store']); + Route::patch('/${kp}/{id}', [${P}Controller::class, 'update']); + Route::delete('/${kp}/{id}', [${P}Controller::class, 'destroy']); +`, + skipIf: `Route::get('/${kp}', [${P}Controller::class, 'index']);`, + describe: `register /${kp} routes in the auth:sanctum group`, + }, + ]; +} + +/** hasMany relation on User, after the last single-line hasMany (todos/posts/comments). */ +export function userRelationPatch(ctx: Ctx): Patch { + const { names } = ctx; + const many = names.plural.camel; + return { + path: "app/Models/User.php", + anchor: / public function \w+\(\): HasMany\n \{\n return \$this->hasMany\(\w+::class\);\n \}\n/, + where: "after", + insert: ` + public function ${many}(): HasMany + { + return $this->hasMany(${names.pascal}::class); + } +`, + skipIf: `public function ${many}(): HasMany`, + describe: `add the ${many}() relation to User`, + }; +} + +export function artisan(...args: string[]): NativeCall[] { + return [{ bin: "php", args: ["artisan", ...args] }]; +} + +export function resourceNotes(ctx: Ctx): string[] { + const { names } = ctx; + return [ + `php artisan migrate — creates the ${names.plural.snake} table.`, + `Edit the validation rules in ${names.pascal}Controller (store/update) and add business logic there; the frontends destructure data.${names.plural.camel} / data.${names.camel}.`, + ]; +} -// Placeholder — implemented in a follow-up task (see docs/superpowers/plans/2026-10-10-make-generators-and-plugin.md, Task 9). export const laravel: Generator = { id: "laravel", label: "Laravel", kind: "backend", - commands: {}, + format: pint, + commands: { + resource: { + describe: + "model + migration + controller (inline validation) + routes in routes/api.php + Pest feature test", + files: (ctx) => [model(ctx), migration(ctx), controller(ctx), pestTest(ctx)], + patches: (ctx) => [...apiRoutePatches(ctx), userRelationPatch(ctx)], + notes: resourceNotes, + }, + model: { + describe: "Eloquent model in app/Models/", + native: (ctx) => artisan("make:model", ctx.names.pascal), + files: (ctx) => [model(ctx)], + }, + controller: { + describe: "API controller in app/Http/Controllers/", + native: (ctx) => artisan("make:controller", `${ctx.names.pascal}Controller`, "--api"), + files: (ctx) => [controller(ctx)], + }, + migration: { + describe: "create__table migration in database/migrations/", + native: (ctx) => artisan("make:migration", `create_${ctx.names.plural.snake}_table`), + files: (ctx) => [migration(ctx)], + }, + request: { + describe: "form request in app/Http/Requests/", + native: (ctx) => artisan("make:request", `Store${ctx.names.pascal}Request`), + files: (ctx) => [formRequest(ctx)], + }, + test: { + describe: "Pest feature test in tests/Feature/", + native: (ctx) => artisan("make:test", `${ctx.names.pascal}Test`, "--pest"), + files: (ctx) => [pestTest(ctx)], + }, + }, }; diff --git a/src/generators/stacks/next.ts b/src/generators/stacks/next.ts index eb52d0c..23e4908 100644 --- a/src/generators/stacks/next.ts +++ b/src/generators/stacks/next.ts @@ -1,9 +1,525 @@ -import type { Generator } from "../types"; +import type { Ctx, FileSpec, Generator, Patch } from "../types"; +import type { Field, FieldType } from "../fields"; +import { labelField } from "../fields"; +import { oxfmt } from "./shared"; + +// Stubs mirror ../CLIuno-Next-template (src/apis/todo-api.ts, src/app/todos/page.tsx, +// src/app/todos/[id]/page.tsx): App Router client pages ('use client'), explicit React +// imports (no auto-imports), next/link + next/navigation, Base UI shadcn components, +// zustand auth store. File routing → only src/apis/index.ts needs a patch. + +const TS: Record = { + string: "string", + text: "string", + int: "number", + number: "number", + boolean: "boolean", + date: "string", + json: "Record", +}; + +const INIT: Record = { + string: "''", + text: "''", + int: "0", + number: "0", + boolean: "false", + date: "''", + json: "{}", +}; + +function tsType(f: Field): string { + return `${TS[f.type]}${f.nullable ? " | null" : ""}`; +} + +function iface(ctx: Ctx): string { + const { names, fields } = ctx; + return `interface ${names.pascal} { + id: string | number +${fields.map((f) => ` ${f.camel}: ${tsType(f)}`).join("\n")} + createdAt?: string + user?: { id: string | number; username: string } +}`; +} + +function inputType(fields: Field[], partial: boolean): string { + return `{ ${fields.map((f) => `${f.camel}${partial || f.nullable ? "?" : ""}: ${TS[f.type]}${f.nullable ? " | null" : ""}`).join("; ")} }`; +} + +function api(ctx: Ctx): FileSpec { + const { names, fields } = ctx; + const P = names.pascal; + const path = names.plural.kebab; + return { + path: `src/apis/${names.kebab}-api.ts`, + content: `import http from './http' + +const ${names.camel}Api = { + getAll${names.plural.pascal}: () => http.get('/${path}'), + get${P}ById: (id: string) => http.get(\`/${path}/\${id}\`), + create${P}: (data: ${inputType(fields, false)}) => http.post('/${path}', data), + update${P}: (id: string, data: ${inputType(fields, true)}) => + http.patch(\`/${path}/\${id}\`, data), + delete${P}: (id: string) => http.delete(\`/${path}/\${id}\`), +} + +export default ${names.camel}Api +`, + }; +} + +function formState(fields: Field[]): string { + return fields + .map( + (f) => + ` const [${f.camel}, set${f.pascal}] = useState<${TS[f.type]}>(${INIT[f.type]})`, + ) + .join("\n"); +} + +/** Empty strings become null for nullable string-ish fields so the backend gets a real null. */ +function payload(fields: Field[]): string { + return fields + .map((f) => { + const stringish = f.type === "string" || f.type === "text" || f.type === "date"; + return f.nullable && stringish ? `${f.camel}: ${f.camel} || null` : f.camel; + }) + .join(", "); +} + +function formInput(f: Field): string { + const id = `${f.snake}-input`; + const optional = f.nullable ? " (optional)" : ""; + if (f.type === "boolean") { + return `

+ set${f.pascal}(v === true)} + /> + +
`; + } + if (f.type === "text") { + return `
+ +