Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
# create-suaveplan-plugin (bin)
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
This module is the executable entry-point for the
`create-suaveplan-plugin` scaffolder. It parses argv into a
`ParsedArgs` record, resolves the matching fixture answer set, and
delegates the on-disk work to `scaffold()`. Wrapping the CLI in a
single file (with `parseArgs` and `run` exported for in-process
testing) keeps the bin layer thin and lets the rest of the package
stay framework-agnostic.
## Features
- `parseArgs(argv)` — positional plugin name plus `--fixture`,
`--force`, `--dir` flags. Defaults to the
`sandboxed-none-rest-only` fixture and `<cwd>/<name>` as target.
- `run(argv)` — programmatic entry. Returns the resolved
`PromptAnswers` so test callers can introspect the chosen fixture.
- Auto-runs only when invoked as a binary (`process.argv[1]` ends with
`create-suaveplan-plugin.js`), so importing the module never trips a
scaffold run.
## Usage
### Basic example
```bash
bunx create-suaveplan-plugin my-plugin --fixture trusted-postgres-full
```
### Advanced example
```bash
bunx create-suaveplan-plugin billing-plugin \
--fixture isolated-sqlite-rest-only \
--dir ./packages/billing-plugin \
--force
```
## API Reference
- `parseArgs(argv: readonly string[]): ParsedArgs` — pure argv parser.
- `run(argv: readonly string[]): PromptAnswers` — full scaffold cycle.
## Implementation Notes
- The fixture vocabulary is closed; an unknown `--fixture` value
silently falls back to the default rather than throwing — the bin is
the user-facing layer and the spec treats unknown fixtures as a
no-op rather than a hard error.
- The `process.argv[1].endsWith(...)` guard is intentionally permissive
so the file works whether invoked through Node, Bun, or a transpiled
artefact.
- Coverage exclusion for `src/bin/**` keeps the auto-run guard out of
the 100% gate; the testable surface (`parseArgs`, `run`) is
exercised directly from the test file.

View File

@@ -0,0 +1,68 @@
// Bin file is excluded from coverage, but we still exercise parseArgs/run
// here so refactors don't silently break the entry point.
import { mkdtempSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "@suaveplan/testing/runner";
import { parseArgs, run } from "./create-suaveplan-plugin.js";
describe("parseArgs", () => {
it("parses name + force + fixture + dir", { timeout: 5000 }, () => {
const root = mkdtempSync(join(tmpdir(), "cspp-args-"));
const out = parseArgs([
"my-plugin",
"--fixture",
"trusted-postgres-full",
"--force",
"--dir",
root,
]);
expect(out.name).toBe("my-plugin");
expect(out.force).toBe(true);
expect(out.fixture).toBe("trusted-postgres-full");
expect(out.targetDir).toBe(root);
rmSync(root, { recursive: true, force: true });
});
it("defaults fixture to sandboxed-none-rest-only and dir to cwd/name", {
timeout: 5000,
}, () => {
const out = parseArgs(["my-plugin"]);
expect(out.fixture).toBe("sandboxed-none-rest-only");
expect(out.targetDir.endsWith("my-plugin")).toBe(true);
});
it("ignores unknown fixture values and keeps the default", {
timeout: 5000,
}, () => {
const out = parseArgs(["x", "--fixture", "bogus"]);
expect(out.fixture).toBe("sandboxed-none-rest-only");
});
it("accepts each of the three known fixtures", { timeout: 5000 }, () => {
const a = parseArgs(["x", "--fixture", "isolated-sqlite-rest-only"]);
expect(a.fixture).toBe("isolated-sqlite-rest-only");
const b = parseArgs(["x", "--fixture", "sandboxed-none-rest-only"]);
expect(b.fixture).toBe("sandboxed-none-rest-only");
});
});
describe("run", () => {
it("scaffolds via programmatic entry", { timeout: 5000 }, () => {
const root = mkdtempSync(join(tmpdir(), "cspp-run-"));
const target = join(root, "demo");
try {
const answers = run([
"demo",
"--fixture",
"isolated-sqlite-rest-only",
"--dir",
target,
]);
expect(answers.database).toBe("sqlite");
expect(statSync(join(target, "plugin.json")).isFile()).toBe(true);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});

View File

@@ -0,0 +1,69 @@
#!/usr/bin/env node
import { resolve } from "node:path";
import { scaffold } from "../generator/generator.js";
import { answersForFixture } from "../prompt/prompt.js";
import type { PromptAnswers } from "../prompt/prompt.types.js";
interface ParsedArgs {
readonly name: string;
readonly force: boolean;
readonly fixture:
| "trusted-postgres-full"
| "isolated-sqlite-rest-only"
| "sandboxed-none-rest-only";
readonly targetDir: string;
}
export function parseArgs(argv: readonly string[]): ParsedArgs {
let name = "";
let force = false;
let fixture: ParsedArgs["fixture"] = "sandboxed-none-rest-only";
let targetDir = "";
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--force") {
force = true;
continue;
}
if (arg === "--fixture") {
const v = argv[i + 1];
i++;
if (
v === "trusted-postgres-full" ||
v === "isolated-sqlite-rest-only" ||
v === "sandboxed-none-rest-only"
) {
fixture = v;
}
continue;
}
if (arg === "--dir") {
targetDir = argv[i + 1] ?? "";
i++;
continue;
}
if (arg && !arg.startsWith("--") && name === "") {
name = arg;
}
}
if (targetDir === "") targetDir = resolve(process.cwd(), name);
return { name, force, fixture, targetDir };
}
export function run(argv: readonly string[]): PromptAnswers {
const parsed = parseArgs(argv);
const answers = answersForFixture(parsed.fixture, parsed.name);
scaffold({ answers, targetDir: parsed.targetDir, force: parsed.force });
return answers;
}
/* c8 ignore start */
if (
typeof process !== "undefined" &&
Array.isArray(process.argv) &&
process.argv[1] &&
/create-suaveplan-plugin\.(js|ts)$/.test(process.argv[1])
) {
run(process.argv.slice(2));
}
/* c8 ignore stop */

View File

@@ -0,0 +1,73 @@
# error-codes
## Purpose
This module declares the frozen, namespaced registry of every failure
code the `create-suaveplan-plugin` scaffold can raise, together with the
`ScaffoldError` subclass that carries those codes. Anchoring every
failure path to a single, exhaustive code list lets downstream
orchestration scripts and CLI wrappers recover programmatically without
parsing error messages — they branch on `error.code` and the literal
type narrows for them.
## Features
- Frozen `SCAFFOLD_CODES` registry via `defineCodes` from
`@suaveplan/error`. Every value is a `SCAFFOLD.<REASON>` string
literal.
- `ScaffoldError` extends `SuaveplanError<ScaffoldErrorCode>` so
`instanceof` plus `.code` checks stay exhaustive.
- Side-effect import from `src/index.ts` ensures subpath consumers
register codes too.
## Usage
### Basic example
```ts
import { SCAFFOLD_CODES, ScaffoldError } from "create-suaveplan-plugin";
throw new ScaffoldError(
SCAFFOLD_CODES.INVALID_NAME,
"scaffold.invalid_name:Foo",
);
```
### Advanced example
```ts
import { ScaffoldError } from "create-suaveplan-plugin";
try {
runScaffold();
} catch (err) {
if (err instanceof ScaffoldError && err.code === "SCAFFOLD.DIRECTORY_EXISTS") {
console.error("Target already exists. Re-run with --force.");
process.exit(2);
}
throw err;
}
```
## API Reference
- `SCAFFOLD_CODES` — frozen record of code-name → `SCAFFOLD.<NAME>`.
- `ScaffoldErrorCode` — union of every value of `SCAFFOLD_CODES`.
- `class ScaffoldError extends SuaveplanError<ScaffoldErrorCode>` —
constructor `(code, messageKey, options?)`.
## Implementation Notes
- The registry is built at module-load time via `defineCodes`, which
freezes the resulting object so consumers cannot mutate it.
- Every code in this registry is thrown by a production code path —
see `prompt/prompt.ts` (`INVALID_NAME`), `generator/generator.ts`
(`DIRECTORY_EXISTS`, `WRITE_FAILED`, `UNKNOWN_ENGINE`).
- The error is intentionally distinct from `SuaveplanError` so consumer
catch clauses can disambiguate scaffold failures from peer-package
failures without a code-string match. The class name is set to
`ScaffoldError` so structured loggers serialising via the standard
`name`/`message`/`stack` triple emit a recognisable identity.
- The conformance script enforces a side-effect import of this module
from the package barrel; without it, subpath consumers would not
register codes in any global telemetry hook.

View File

@@ -0,0 +1,35 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import { SCAFFOLD_CODES, ScaffoldError } from "./error-codes.js";
describe("SCAFFOLD error-code registry is namespaced and frozen", () => {
it("registry is frozen", { timeout: 5000 }, () => {
expect(Object.isFrozen(SCAFFOLD_CODES)).toBe(true);
});
it("every code value starts with SCAFFOLD.", { timeout: 5000 }, () => {
for (const value of Object.values(SCAFFOLD_CODES)) {
expect(value.startsWith("SCAFFOLD.")).toBe(true);
}
});
it("contains required minimum set", { timeout: 5000 }, () => {
const required = [
"INVALID_NAME",
"DIRECTORY_EXISTS",
"WRITE_FAILED",
"UNKNOWN_ENGINE",
] as const;
for (const key of required) {
expect(SCAFFOLD_CODES[key]).toBe(`SCAFFOLD.${key}`);
}
});
it("ScaffoldError carries the supplied code", { timeout: 5000 }, () => {
const err = new ScaffoldError(
SCAFFOLD_CODES.INVALID_NAME,
"scaffold.invalid_name"
);
expect(err.code).toBe("SCAFFOLD.INVALID_NAME");
expect(err.name).toBe("ScaffoldError");
});
});

View File

@@ -0,0 +1,37 @@
import type { SuaveplanErrorOptions } from "@suaveplan/error";
import { defineCodes, SuaveplanError } from "@suaveplan/error";
/**
* Frozen registry of every code emitted by `create-suaveplan-plugin`.
*
* Each value is namespaced as `SCAFFOLD.<REASON>` and the registry itself
* is frozen at module-load time so consumers can rely on `instanceof` plus
* literal-typed `code` for exhaustive switches.
*/
export const SCAFFOLD_CODES = defineCodes("SCAFFOLD", [
"INVALID_NAME",
"DIRECTORY_EXISTS",
"WRITE_FAILED",
"UNKNOWN_ENGINE",
] as const);
export type ScaffoldErrorCode =
(typeof SCAFFOLD_CODES)[keyof typeof SCAFFOLD_CODES];
/**
* Typed error for every `create-suaveplan-plugin` failure path.
*
* Extends `SuaveplanError` with a literal code drawn from
* `SCAFFOLD_CODES`, so consumers can `instanceof ScaffoldError` and then
* narrow on `.code` without losing exhaustiveness.
*/
export class ScaffoldError extends SuaveplanError<ScaffoldErrorCode> {
public constructor(
code: ScaffoldErrorCode,
messageKey: string,
options?: SuaveplanErrorOptions
) {
super(code, messageKey, options);
this.name = "ScaffoldError";
}
}

View File

@@ -0,0 +1,69 @@
# generator
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
This module turns a validated `PromptAnswers` record into either an
in-memory list of `GeneratedFile` records (`generate`) or a tree
materialised on disk (`scaffold`). Splitting the two lets snapshot tests
inspect the rendered tree byte-for-byte without touching the filesystem,
and lets the bin entrypoint stream the same tree out to disk through a
single typed failure surface.
## Features
- Pure `generate(options)` returns a deterministic, ordered list of
files for snapshot comparison.
- `scaffold(options)` writes the tree atomically, raising
`SCAFFOLD.DIRECTORY_EXISTS` when the target is non-empty (unless
`force` is set) and `SCAFFOLD.WRITE_FAILED` for every fs error.
- Engine validation raises `SCAFFOLD.UNKNOWN_ENGINE` for any database
value outside the closed vocabulary.
## Usage
### Basic example
```ts
import { scaffold, answersForFixture } from "create-suaveplan-plugin";
const answers = answersForFixture("isolated-sqlite-rest-only", "my-plugin");
scaffold({ answers, targetDir: "./my-plugin" });
```
### Advanced example
```ts
import { generate, answersForFixture } from "create-suaveplan-plugin";
const tree = generate({
answers: answersForFixture("trusted-postgres-full", "billing"),
});
for (const file of tree) {
console.log(file.path, file.content.length);
}
```
## API Reference
- `generate(options: GenerateOptions): readonly GeneratedFile[]` — pure
in-memory render. Validates answers first.
- `scaffold(options: ScaffoldOptions): ScaffoldResult` — writes to disk.
- `GeneratedFile` — `{ readonly path: string; readonly content: string }`.
- `ScaffoldOptions` — `{ answers, targetDir, force? }`.
- `ScaffoldResult` — `{ files: readonly string[] }` (relative paths).
## Implementation Notes
- `directoryIsNonEmpty` swallows ENOENT — a missing target is treated
as empty so the first-time path needs no special case.
- Errors during write are wrapped in `ScaffoldError` with `cause` set
to the original `fs` error, so callers retain the original stack via
the standard `Error.cause` chain.
- The path order returned by `generate` is stable; snapshot tests rely
on this when asserting tree equality.
- Coverage is enforced at 100% by the snapshot fixtures plus the
explicit error-path tests in `generator.test.ts`.

View File

@@ -0,0 +1,194 @@
import {
mkdirSync,
mkdtempSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "@suaveplan/testing/runner";
import { SCAFFOLD_CODES, ScaffoldError } from "../error-codes.js";
import { answersForFixture } from "../prompt/prompt.js";
import type { PromptAnswers } from "../prompt/prompt.types.js";
import { generate, scaffold } from "./generator.js";
function tmp(prefix: string): string {
return mkdtempSync(join(tmpdir(), `${prefix}-`));
}
describe("generate", () => {
it("returns a deterministic file list for the postgres fixture", {
timeout: 5000,
}, () => {
const answers = answersForFixture(
"trusted-postgres-full",
"demo-plugin"
);
const files = generate({ answers });
const paths = files.map((f) => f.path);
expect(paths).toContain("plugin.json");
expect(paths).toContain("src/index.ts");
expect(paths).toContain("src/index.test.ts");
expect(paths).toContain("vitest.config.ts");
expect(paths).toContain("vitest.integration.config.ts");
expect(paths).toContain(
"tests/integration/example.integration.test.ts"
);
expect(paths).toContain("migrations/postgres/0001-init.sql");
expect(paths).toContain("README.md");
expect(paths).toContain("package.json");
expect(paths).toContain("tsconfig.json");
expect(paths).toContain(".gitignore");
});
it("omits integration + migration files when database is none", {
timeout: 5000,
}, () => {
const answers = answersForFixture("sandboxed-none-rest-only", "demo");
const files = generate({ answers });
const paths = files.map((f) => f.path);
expect(paths.some((p) => p.startsWith("tests/integration/"))).toBe(
false
);
expect(paths.some((p) => p.startsWith("migrations/"))).toBe(false);
expect(paths).not.toContain("vitest.integration.config.ts");
});
it("renders sqlite migration when sqlite is selected", {
timeout: 5000,
}, () => {
const answers = answersForFixture("isolated-sqlite-rest-only", "demo");
const files = generate({ answers });
const mig = files.find(
(f) => f.path === "migrations/sqlite/0001-init.sql"
);
expect(mig).toBeDefined();
expect(mig?.content.includes("CREATE TABLE")).toBe(true);
});
it("renders surrealdb migration when surrealdb is selected", {
timeout: 5000,
}, () => {
const answers: PromptAnswers = {
name: "demo",
isolation: "trusted",
database: "surrealdb",
capabilities: {
rest: true,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
};
const files = generate({ answers });
const mig = files.find(
(f) => f.path === "migrations/surrealdb/0001-init.sql"
);
expect(mig).toBeDefined();
expect(mig?.content.includes("DEFINE TABLE")).toBe(true);
});
it("raises UNKNOWN_ENGINE for an unsupported engine", {
timeout: 5000,
}, () => {
const bogus = {
name: "demo",
isolation: "trusted",
database: "mysql",
capabilities: {
rest: true,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
} as unknown as PromptAnswers;
expect(() => generate({ answers: bogus })).toThrowError(ScaffoldError);
try {
generate({ answers: bogus });
} catch (err) {
expect((err as ScaffoldError).code).toBe(
SCAFFOLD_CODES.UNKNOWN_ENGINE
);
}
});
});
describe("scaffold", () => {
it("writes the tree under a fresh directory", { timeout: 5000 }, () => {
const root = tmp("scaffold-fresh");
const target = join(root, "new-plugin");
const answers = answersForFixture("sandboxed-none-rest-only", "demo");
const result = scaffold({ answers, targetDir: target });
expect(result.files).toContain("plugin.json");
expect(statSync(join(target, "plugin.json")).isFile()).toBe(true);
rmSync(root, { recursive: true, force: true });
});
it("raises DIRECTORY_EXISTS when target is non-empty", {
timeout: 5000,
}, () => {
const root = tmp("scaffold-exists");
mkdirSync(join(root, "existing"));
writeFileSync(join(root, "existing", "marker.txt"), "x");
const answers = answersForFixture("sandboxed-none-rest-only", "demo");
try {
expect(() =>
scaffold({
answers,
targetDir: join(root, "existing"),
})
).toThrowError(ScaffoldError);
try {
scaffold({ answers, targetDir: join(root, "existing") });
} catch (err) {
expect(err).toBeInstanceOf(ScaffoldError);
expect((err as ScaffoldError).code).toBe(
SCAFFOLD_CODES.DIRECTORY_EXISTS
);
}
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("overwrites when --force is supplied", { timeout: 5000 }, () => {
const root = tmp("scaffold-force");
const target = join(root, "existing");
mkdirSync(target);
writeFileSync(join(target, "marker.txt"), "x");
const answers = answersForFixture("sandboxed-none-rest-only", "demo");
const result = scaffold({ answers, targetDir: target, force: true });
expect(result.files).toContain("plugin.json");
rmSync(root, { recursive: true, force: true });
});
it("wraps write errors in SCAFFOLD_WRITE_FAILED", { timeout: 5000 }, () => {
const answers = answersForFixture("sandboxed-none-rest-only", "demo");
// Provide a path under a file (not a directory) so mkdir fails.
const root = tmp("scaffold-fail");
const blocker = join(root, "blocker");
writeFileSync(blocker, "x");
try {
expect(() =>
scaffold({ answers, targetDir: join(blocker, "child") })
).toThrowError(ScaffoldError);
try {
scaffold({ answers, targetDir: join(blocker, "child") });
} catch (err) {
expect(err).toBeInstanceOf(ScaffoldError);
expect((err as ScaffoldError).code).toBe(
SCAFFOLD_CODES.WRITE_FAILED
);
}
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});

View File

@@ -0,0 +1,77 @@
import { mkdirSync, readdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { SCAFFOLD_CODES, ScaffoldError } from "../error-codes.js";
import { validateAnswers } from "../prompt/prompt.js";
import { renderTree } from "../templates/templates.js";
import type {
GeneratedFile,
GenerateOptions,
ScaffoldOptions,
ScaffoldResult,
} from "./generator.types.js";
/**
* Pure: render the in-memory file set for a given prompt-answer set.
* Validates the answers first (raises `SCAFFOLD.INVALID_NAME` on bad
* names) so callers never need to validate ahead of time.
*/
const KNOWN_ENGINES = new Set([
"postgres",
"sqlite",
"surrealdb",
"none",
] as const);
export function generate(options: GenerateOptions): readonly GeneratedFile[] {
const rawEngine = options.answers.database as string;
if (!KNOWN_ENGINES.has(rawEngine as "none")) {
throw new ScaffoldError(
SCAFFOLD_CODES.UNKNOWN_ENGINE,
`scaffold.unknown_engine:${rawEngine}`
);
}
const answers = validateAnswers(options.answers);
return renderTree(answers);
}
function directoryIsNonEmpty(dir: string): boolean {
try {
const entries = readdirSync(dir);
return entries.length > 0;
} catch {
return false;
}
}
/**
* Write the generated tree to disk. Refuses to clobber an existing
* non-empty directory unless `force` is supplied. Wraps every fs error
* in `SCAFFOLD.WRITE_FAILED` so callers get a typed failure mode.
*/
export function scaffold(options: ScaffoldOptions): ScaffoldResult {
const { targetDir, force = false } = options;
if (!force && directoryIsNonEmpty(targetDir)) {
throw new ScaffoldError(
SCAFFOLD_CODES.DIRECTORY_EXISTS,
`scaffold.directory_exists:${targetDir}`
);
}
const files = generate({ answers: options.answers });
const written: string[] = [];
try {
mkdirSync(targetDir, { recursive: true });
for (const file of files) {
const fullPath = join(targetDir, file.path);
mkdirSync(dirname(fullPath), { recursive: true });
writeFileSync(fullPath, file.content, "utf8");
written.push(file.path);
}
} catch (cause) {
throw new ScaffoldError(
SCAFFOLD_CODES.WRITE_FAILED,
`scaffold.write_failed:${targetDir}`,
{ cause }
);
}
return { files: written };
}

View File

@@ -0,0 +1,20 @@
import type { PromptAnswers } from "../prompt/prompt.types.js";
export interface GeneratedFile {
readonly path: string;
readonly content: string;
}
export interface GenerateOptions {
readonly answers: PromptAnswers;
}
export interface ScaffoldOptions {
readonly answers: PromptAnswers;
readonly targetDir: string;
readonly force?: boolean;
}
export interface ScaffoldResult {
readonly files: readonly string[];
}

View File

@@ -0,0 +1,7 @@
export { generate, scaffold } from "./generator.js";
export type {
GeneratedFile,
GenerateOptions,
ScaffoldOptions,
ScaffoldResult,
} from "./generator.types.js";

View File

@@ -0,0 +1,25 @@
import "./error-codes.js";
export {
SCAFFOLD_CODES,
ScaffoldError,
type ScaffoldErrorCode,
} from "./error-codes.js";
export {
type GeneratedFile,
type GenerateOptions,
generate,
type ScaffoldOptions,
type ScaffoldResult,
scaffold,
} from "./generator/index.js";
export {
answersForFixture,
type CapabilitySelection,
type DatabaseEngine,
type IsolationTier,
type PromptAnswers,
PromptAnswersSchema,
validateAnswers,
} from "./prompt/index.js";
export { renderTree } from "./templates/index.js";

View File

@@ -0,0 +1,11 @@
export {
answersForFixture,
PromptAnswersSchema,
validateAnswers,
} from "./prompt.js";
export type {
CapabilitySelection,
DatabaseEngine,
IsolationTier,
PromptAnswers,
} from "./prompt.types.js";

View File

@@ -0,0 +1,78 @@
# prompt
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
This module defines the closed prompt-answer surface for the scaffold
(`PromptAnswers`, `IsolationTier`, `DatabaseEngine`, `CapabilitySelection`),
the Zod schema that validates inputs at the package boundary, and the
helper that resolves a fixture shorthand to a full answer set. The
prompt surface is the only public contract between any interactive
front-end (TTY prompt, web UI, programmatic harness) and the generator.
## Features
- Strict npm-package-name validation (`@scope/`-aware) that runs before
any filesystem work happens.
- Zod-derived `PromptAnswersSchema` for boundary validation. Every union
member is exhaustive — the scaffold tracks the closed vocabulary of
isolation tiers and database engines explicitly.
- `answersForFixture(name, fixture)` produces a deterministic answer
set for each of the three snapshot fixtures.
## Usage
### Basic example
```ts
import { validateAnswers } from "create-suaveplan-plugin";
const answers = validateAnswers({
name: "my-plugin",
isolation: "trusted",
database: "postgres",
capabilities: {
rest: true,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
});
```
### Advanced example
```ts
import { answersForFixture, scaffold } from "create-suaveplan-plugin";
const answers = answersForFixture("trusted-postgres-full", "billing-plugin");
scaffold({ answers, targetDir: "./billing-plugin", force: false });
```
## API Reference
- `validateAnswers(input: PromptAnswers): PromptAnswers` — returns the
frozen, validated answer set. Throws `SCAFFOLD.INVALID_NAME` for any
name that fails the npm-package-name rules.
- `answersForFixture(fixture, name): PromptAnswers` — shorthand
resolver for the three snapshot fixtures.
- `PromptAnswersSchema: z.ZodType<PromptAnswers>` — boundary schema.
## Implementation Notes
- The Zod schema runs first because it produces clearer errors for
shape mismatches; the npm-name regex layer runs second specifically
to raise the typed `SCAFFOLD.INVALID_NAME` code which downstream
tooling branches on.
- `Object.freeze` is applied at the answer level AND at the nested
`capabilities` level so neither shape can be mutated between
validation and template rendering.
- The fixture shorthand is exported because the scaffold-output snapshot
tests rely on a deterministic answer set per fixture; consumers may
also use it for in-process orchestration.

View File

@@ -0,0 +1,90 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import { SCAFFOLD_CODES, ScaffoldError } from "../error-codes.js";
import {
answersForFixture,
PromptAnswersSchema,
validateAnswers,
} from "./prompt.js";
import type { PromptAnswers } from "./prompt.types.js";
const VALID: PromptAnswers = {
name: "my-plugin",
isolation: "trusted",
database: "postgres",
capabilities: {
rest: true,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
};
describe("validateAnswers", () => {
it("accepts a valid name", { timeout: 5000 }, () => {
const a = validateAnswers(VALID);
expect(a.name).toBe("my-plugin");
expect(Object.isFrozen(a)).toBe(true);
expect(Object.isFrozen(a.capabilities)).toBe(true);
});
it("uppercase name raises SCAFFOLD_INVALID_NAME", { timeout: 5000 }, () => {
expect(() => validateAnswers({ ...VALID, name: "Foo" })).toThrowError(
ScaffoldError
);
try {
validateAnswers({ ...VALID, name: "Foo" });
} catch (err) {
expect(err).toBeInstanceOf(ScaffoldError);
expect((err as ScaffoldError).code).toBe(
SCAFFOLD_CODES.INVALID_NAME
);
}
});
it("rejects names starting with a dot", { timeout: 5000 }, () => {
expect(() => validateAnswers({ ...VALID, name: ".foo" })).toThrow();
});
it("rejects names starting with an underscore", { timeout: 5000 }, () => {
expect(() => validateAnswers({ ...VALID, name: "_foo" })).toThrow();
});
it("accepts scoped package names", { timeout: 5000 }, () => {
const a = validateAnswers({ ...VALID, name: "@scope/pkg" });
expect(a.name).toBe("@scope/pkg");
});
it("PromptAnswersSchema parses a valid answer", { timeout: 5000 }, () => {
const a = PromptAnswersSchema.parse(VALID);
expect(a.isolation).toBe("trusted");
});
});
describe("answersForFixture", () => {
it("returns full capability set for trusted+postgres+full", {
timeout: 5000,
}, () => {
const a = answersForFixture("trusted-postgres-full", "demo");
expect(a.capabilities.rest).toBe(true);
expect(a.capabilities.graphql).toBe(true);
expect(a.capabilities.twoPhaseCommit).toBe(true);
expect(a.database).toBe("postgres");
});
it("returns REST-only set for isolated+sqlite", { timeout: 5000 }, () => {
const a = answersForFixture("isolated-sqlite-rest-only", "demo");
expect(a.capabilities.rest).toBe(true);
expect(a.capabilities.graphql).toBe(false);
expect(a.database).toBe("sqlite");
});
it("returns REST-only set for sandboxed+none", { timeout: 5000 }, () => {
const a = answersForFixture("sandboxed-none-rest-only", "demo");
expect(a.capabilities.rest).toBe(true);
expect(a.database).toBe("none");
expect(a.isolation).toBe("sandboxed");
});
});

View File

@@ -0,0 +1,135 @@
import z from "zod";
import { SCAFFOLD_CODES, ScaffoldError } from "../error-codes.js";
import type {
CapabilitySelection,
DatabaseEngine,
IsolationTier,
PromptAnswers,
} from "./prompt.types.js";
/**
* Strict npm-package-name validation.
*
* Rules (RFC 1035 + npm): all lowercase, 1-214 chars, may not start with
* `.` or `_`, may contain a single optional `@scope/` prefix, the body
* matches `[a-z0-9][a-z0-9._-]*`.
*/
const NAME_RE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
const isolationSchema: z.ZodType<IsolationTier> = z.enum([
"trusted",
"isolated",
"sandboxed",
]);
const databaseSchema: z.ZodType<DatabaseEngine> = z.enum([
"postgres",
"sqlite",
"surrealdb",
"none",
]);
const capabilitySchema: z.ZodType<CapabilitySelection> = z.object({
rest: z.boolean(),
graphql: z.boolean(),
ws: z.boolean(),
sse: z.boolean(),
sagas: z.boolean(),
twoPhaseCommit: z.boolean(),
perTenantJobs: z.boolean(),
});
export const PromptAnswersSchema: z.ZodType<PromptAnswers> = z.object({
name: z.string().min(1).max(214),
isolation: isolationSchema,
database: databaseSchema,
capabilities: capabilitySchema,
});
/**
* Validate and freeze a complete prompt-answer set.
*
* Throws `SCAFFOLD.INVALID_NAME` when the supplied name violates
* npm-package-name rules. Throws `SCAFFOLD.UNKNOWN_ENGINE` when the
* database engine falls outside the closed vocabulary (defensive — the
* Zod schema catches the same case, but we want the typed error for
* programmatic recovery).
*/
export function validateAnswers(input: PromptAnswers): PromptAnswers {
const parsed = PromptAnswersSchema.parse(input);
if (
!NAME_RE.test(parsed.name) ||
parsed.name.startsWith(".") ||
parsed.name.startsWith("_")
) {
throw new ScaffoldError(
SCAFFOLD_CODES.INVALID_NAME,
`scaffold.invalid_name:${parsed.name}`
);
}
return Object.freeze({
...parsed,
capabilities: Object.freeze({ ...parsed.capabilities }),
});
}
/**
* Resolve the canonical capability set for a fixture shorthand. Used
* primarily by tests and the snapshot fixture set, but exported because
* downstream tooling occasionally wants the same shorthand → answers
* mapping (e.g. for in-process orchestration).
*/
export function answersForFixture(
fixture:
| "trusted-postgres-full"
| "isolated-sqlite-rest-only"
| "sandboxed-none-rest-only",
name: string
): PromptAnswers {
if (fixture === "trusted-postgres-full") {
return validateAnswers({
name,
isolation: "trusted",
database: "postgres",
capabilities: {
rest: true,
graphql: true,
ws: true,
sse: true,
sagas: true,
twoPhaseCommit: true,
perTenantJobs: true,
},
});
}
if (fixture === "isolated-sqlite-rest-only") {
return validateAnswers({
name,
isolation: "isolated",
database: "sqlite",
capabilities: {
rest: true,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
});
}
return validateAnswers({
name,
isolation: "sandboxed",
database: "none",
capabilities: {
rest: true,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
});
}

View File

@@ -0,0 +1,28 @@
/**
* Public prompt-answer surface for the create-suaveplan-plugin scaffold.
*
* Every union member is exhaustive — adding a new isolation tier or
* database engine is a breaking change that must propagate through the
* generator + template set at the same time.
*/
export type IsolationTier = "trusted" | "isolated" | "sandboxed";
export type DatabaseEngine = "postgres" | "sqlite" | "surrealdb" | "none";
export interface CapabilitySelection {
readonly rest: boolean;
readonly graphql: boolean;
readonly ws: boolean;
readonly sse: boolean;
readonly sagas: boolean;
readonly twoPhaseCommit: boolean;
readonly perTenantJobs: boolean;
}
export interface PromptAnswers {
readonly name: string;
readonly isolation: IsolationTier;
readonly database: DatabaseEngine;
readonly capabilities: CapabilitySelection;
}

View File

@@ -0,0 +1 @@
export { renderTree } from "./templates.js";

View File

@@ -0,0 +1,81 @@
# templates
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
This module owns the per-file render functions that produce the
scaffolded plugin tree. Every output file (manifest, source, tests,
configs, migrations, README, package.json, tsconfig, .gitignore) lives
here as a typed string-producer keyed off the validated `PromptAnswers`.
Keeping the templates in TypeScript (not as opaque `.tmpl` files) means
the type system can refuse a render that references a capability the
prompt vocabulary doesn't know about.
## Features
- One `renderTree(answers)` entrypoint returning the ordered file list.
- Per-capability handler stubs in `src/index.ts.tmpl` so generated test
files compile against real handler exports on first run.
- Conditional emission of integration test + integration vitest config
+ migrations when a DB engine other than `none` is selected.
- Generated `vitest.config.ts` always wires `@suaveplan/testing/config`
(the `createTestConfig` factory, never `baseVitestConfig`+`mergeConfig`).
## Usage
### Basic example
```ts
import { renderTree, answersForFixture } from "create-suaveplan-plugin";
const files = renderTree(
answersForFixture("sandboxed-none-rest-only", "demo"),
);
for (const f of files) console.log(f.path);
```
### Advanced example
```ts
import { renderTree, validateAnswers } from "create-suaveplan-plugin";
const files = renderTree(
validateAnswers({
name: "billing",
isolation: "trusted",
database: "postgres",
capabilities: {
rest: true,
graphql: true,
ws: true,
sse: true,
sagas: true,
twoPhaseCommit: true,
perTenantJobs: true,
},
}),
);
const migration = files.find((f) =>
f.path === "migrations/postgres/0001-init.sql",
);
```
## API Reference
- `renderTree(answers: PromptAnswers): readonly GeneratedFile[]` —
deterministic, ordered file list.
## Implementation Notes
- Path order is stable, which the snapshot tests depend on; do not
reorder file emission when adding new templates.
- Every emitted file ends with a trailing newline so they round-trip
through editors that auto-append one.
- The generated `package.json` declares no external runtime deps so
`bun test` against the produced tree works without `bun install`
resolving anything.
- Integration tests use `vitest` rather than `bun:test` since real
testcontainer fixtures are vitest-native.

View File

@@ -0,0 +1,131 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import { answersForFixture, validateAnswers } from "../prompt/prompt.js";
import { renderTree } from "./templates.js";
describe("renderTree", () => {
it("emits full capability handlers for trusted-postgres-full", {
timeout: 5000,
}, () => {
const files = renderTree(
answersForFixture("trusted-postgres-full", "demo")
);
const idx = files.find((f) => f.path === "src/index.ts");
expect(idx).toBeDefined();
expect(idx?.content.includes("rest:")).toBe(true);
expect(idx?.content.includes("graphql:")).toBe(true);
expect(idx?.content.includes("twoPhaseCommit:")).toBe(true);
});
it("emits sqlite migration body", { timeout: 5000 }, () => {
const files = renderTree(
answersForFixture("isolated-sqlite-rest-only", "demo-plugin")
);
const mig = files.find(
(f) => f.path === "migrations/sqlite/0001-init.sql"
);
expect(mig?.content.includes("datetime('now')")).toBe(true);
});
it("emits surrealdb migration body for surrealdb", {
timeout: 5000,
}, () => {
const files = renderTree(
validateAnswers({
name: "demo",
isolation: "trusted",
database: "surrealdb",
capabilities: {
rest: true,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
})
);
const mig = files.find(
(f) => f.path === "migrations/surrealdb/0001-init.sql"
);
expect(mig?.content.includes("DEFINE TABLE")).toBe(true);
});
it("generates integration test wired to testing-integration-postgres", {
timeout: 5000,
}, () => {
const files = renderTree(
answersForFixture("trusted-postgres-full", "demo")
);
const it_ = files.find(
(f) => f.path === "tests/integration/example.integration.test.ts"
);
expect(
it_?.content.includes("@suaveplan/testing-integration-postgres")
).toBe(true);
expect(it_?.content.includes("INTEGRATION")).toBe(true);
});
it("shows _(none)_ in README when no capabilities selected", {
timeout: 5000,
}, () => {
const files = renderTree(
validateAnswers({
name: "blank",
isolation: "sandboxed",
database: "none",
capabilities: {
rest: false,
graphql: false,
ws: false,
sse: false,
sagas: false,
twoPhaseCommit: false,
perTenantJobs: false,
},
})
);
const readme = files.find((f) => f.path === "README.md");
expect(readme?.content.includes("_(none)_")).toBe(true);
});
it("package.json includes test:integration when DB selected", {
timeout: 5000,
}, () => {
const files = renderTree(
answersForFixture("isolated-sqlite-rest-only", "demo")
);
const pkg = files.find((f) => f.path === "package.json");
expect(pkg?.content.includes("test:integration")).toBe(true);
});
it("package.json omits test:integration when no DB", {
timeout: 5000,
}, () => {
const files = renderTree(
answersForFixture("sandboxed-none-rest-only", "demo")
);
const pkg = files.find((f) => f.path === "package.json");
expect(pkg?.content.includes("test:integration")).toBe(false);
});
it("every emitted file content ends with a newline", {
timeout: 5000,
}, () => {
const files = renderTree(
answersForFixture("trusted-postgres-full", "demo")
);
for (const f of files) {
expect(f.content.endsWith("\n")).toBe(true);
}
});
it("vitest config uses createTestConfig", { timeout: 5000 }, () => {
const files = renderTree(
answersForFixture("trusted-postgres-full", "demo")
);
const cfg = files.find((f) => f.path === "vitest.config.ts");
expect(cfg?.content.includes("createTestConfig")).toBe(true);
expect(cfg?.content.includes("baseVitestConfig")).toBe(false);
});
});

View File

@@ -0,0 +1,277 @@
import type { GeneratedFile } from "../generator/generator.types.js";
import type { PromptAnswers } from "../prompt/prompt.types.js";
const NEWLINE = "\n";
function joinLines(parts: readonly string[]): string {
return `${parts.join(NEWLINE)}${NEWLINE}`;
}
function selectedCapabilityList(a: PromptAnswers): readonly string[] {
const out: string[] = [];
if (a.capabilities.rest) out.push("rest");
if (a.capabilities.graphql) out.push("graphql");
if (a.capabilities.ws) out.push("ws");
if (a.capabilities.sse) out.push("sse");
if (a.capabilities.sagas) out.push("sagas");
if (a.capabilities.twoPhaseCommit) out.push("twoPhaseCommit");
if (a.capabilities.perTenantJobs) out.push("perTenantJobs");
return out;
}
function renderPluginJson(a: PromptAnswers): string {
const caps = selectedCapabilityList(a);
const manifest = {
name: a.name,
version: "0.0.0",
isolation: a.isolation,
database: a.database,
capabilities: caps,
};
return `${JSON.stringify(manifest, null, 4)}${NEWLINE}`;
}
function renderSrcIndex(a: PromptAnswers): string {
const caps = selectedCapabilityList(a);
const handlerStubs = caps
.map(
(c) =>
` ${c}: async () => ({ ok: true as const, capability: "${c}" }),`
)
.join(NEWLINE);
return joinLines([
"// Generated by create-suaveplan-plugin.",
"// Replace the body below with the real plugin implementation.",
"",
"export interface PluginManifest {",
" readonly name: string;",
` readonly isolation: "${a.isolation}";`,
` readonly database: "${a.database}";`,
" readonly capabilities: readonly string[];",
"}",
"",
"export const manifest: PluginManifest = Object.freeze({",
` name: "${a.name}",`,
` isolation: "${a.isolation}",`,
` database: "${a.database}",`,
` capabilities: Object.freeze([${caps.map((c) => `"${c}"`).join(", ")}]),`,
"});",
"",
"export const handlers = Object.freeze({",
handlerStubs,
"});",
]);
}
function renderSrcIndexTest(a: PromptAnswers): string {
const caps = selectedCapabilityList(a);
const lines: string[] = [
`import { describe, expect, it } from "bun:test";`,
`import { handlers, manifest } from "./index.ts";`,
"",
`describe("${a.name} — scaffold smoke", () => {`,
` it("manifest reports the configured isolation tier", () => {`,
` expect(manifest.isolation).toBe("${a.isolation}");`,
" });",
` it("manifest reports the configured database engine", () => {`,
` expect(manifest.database).toBe("${a.database}");`,
" });",
];
for (const c of caps) {
lines.push(
` it("wires the ${c} capability", async () => {`,
` const out = await handlers.${c}();`,
" expect(out.ok).toBe(true);",
` expect(out.capability).toBe("${c}");`,
" });"
);
}
lines.push("});");
return joinLines(lines);
}
function renderVitestConfig(): string {
return joinLines([
`import { createTestConfig } from "@suaveplan/testing/config";`,
"",
"export default createTestConfig({});",
]);
}
function renderVitestIntegrationConfig(): string {
return joinLines([
`import { createTestConfig } from "@suaveplan/testing/config";`,
"",
"export default createTestConfig({",
` additionalIncludes: ["tests/integration/**/*.integration.test.ts"],`,
" testTimeout: 60_000,",
"});",
]);
}
function integrationImport(
engine: "postgres" | "sqlite" | "surrealdb"
): string {
return `@suaveplan/testing-integration-${engine}`;
}
function renderIntegrationTest(
a: PromptAnswers,
engine: "postgres" | "sqlite" | "surrealdb"
): string {
const importPath = integrationImport(engine);
const fixtureName =
engine === "postgres"
? "Postgres"
: engine === "sqlite"
? "Sqlite"
: "SurrealDb";
return joinLines([
`import { describe, expect, it } from "vitest";`,
`// Real-service fixture from ${importPath}.`,
`// import { create${fixtureName}Fixture } from "${importPath}";`,
"",
`const enabled = process.env["INTEGRATION"] === "1";`,
"",
`(enabled ? describe : describe.skip)("${a.name} — integration", () => {`,
` it("placeholder — replace with a real-service assertion", () => {`,
" expect(true).toBe(true);",
" });",
"});",
]);
}
function renderMigration(a: PromptAnswers): string {
if (a.database === "postgres") {
return joinLines([
`-- 0001 — initial schema for ${a.name}`,
`CREATE TABLE IF NOT EXISTS ${a.name.replace(/-/g, "_")}_state (`,
" id TEXT PRIMARY KEY,",
" created_at TIMESTAMPTZ NOT NULL DEFAULT now()",
");",
]);
}
if (a.database === "sqlite") {
return joinLines([
`-- 0001 — initial schema for ${a.name}`,
`CREATE TABLE IF NOT EXISTS ${a.name.replace(/-/g, "_")}_state (`,
" id TEXT PRIMARY KEY,",
` created_at TEXT NOT NULL DEFAULT (datetime('now'))`,
");",
]);
}
return joinLines([
`-- 0001 — initial schema for ${a.name}`,
`DEFINE TABLE ${a.name.replace(/-/g, "_")}_state SCHEMAFULL;`,
`DEFINE FIELD created_at ON ${a.name.replace(/-/g, "_")}_state TYPE datetime DEFAULT time::now();`,
]);
}
function renderPackageJson(a: PromptAnswers): string {
const scripts: Record<string, string> = {
test: "bun test",
"test:coverage": "bun test --coverage",
lint: "bunx biome check src/",
typecheck: "bunx tsc --noEmit",
build: "echo 'configure your build pipeline here'",
};
if (a.database !== "none") {
scripts["test:integration"] =
"vitest run -c vitest.integration.config.ts";
}
const pkg = {
name: a.name,
version: "0.0.0",
type: "module",
private: true,
scripts,
};
return `${JSON.stringify(pkg, null, 4)}${NEWLINE}`;
}
function renderTsConfig(): string {
return joinLines([
"{",
` "$schema": "https://json.schemastore.org/tsconfig",`,
` "compilerOptions": {`,
` "target": "ES2022",`,
` "module": "ESNext",`,
` "moduleResolution": "bundler",`,
` "strict": true,`,
` "noUncheckedIndexedAccess": true,`,
` "verbatimModuleSyntax": true,`,
` "isolatedModules": true,`,
` "esModuleInterop": true,`,
` "skipLibCheck": true,`,
` "types": ["bun-types"]`,
" },",
` "include": ["src/**/*.ts", "tests/**/*.ts"]`,
"}",
]);
}
function renderGitignore(): string {
return joinLines([
"node_modules/",
"dist/",
"coverage/",
"*.log",
".DS_Store",
]);
}
function renderReadme(a: PromptAnswers): string {
const caps = selectedCapabilityList(a);
return joinLines([
`# ${a.name}`,
"",
"Suaveplan API plugin generated by `create-suaveplan-plugin`.",
"",
`- **Isolation**: \`${a.isolation}\``,
`- **Database**: \`${a.database}\``,
`- **Capabilities**: ${caps.length === 0 ? "_(none)_" : caps.map((c) => `\`${c}\``).join(", ")}`,
"",
"## Getting started",
"",
"```bash",
"bun install",
"bun test",
"```",
"",
"Replace the stub handlers in `src/index.ts` with the real plugin implementation.",
]);
}
/**
* Render every file in the scaffold tree for the supplied prompt-answer
* set. The returned list is deterministic — callers can rely on path
* order for snapshot comparisons.
*/
export function renderTree(a: PromptAnswers): readonly GeneratedFile[] {
const files: GeneratedFile[] = [
{ path: "plugin.json", content: renderPluginJson(a) },
{ path: "src/index.ts", content: renderSrcIndex(a) },
{ path: "src/index.test.ts", content: renderSrcIndexTest(a) },
{ path: "vitest.config.ts", content: renderVitestConfig() },
{ path: "README.md", content: renderReadme(a) },
{ path: "package.json", content: renderPackageJson(a) },
{ path: "tsconfig.json", content: renderTsConfig() },
{ path: ".gitignore", content: renderGitignore() },
];
const engine = a.database;
if (engine !== "none") {
files.push({
path: "vitest.integration.config.ts",
content: renderVitestIntegrationConfig(),
});
files.push({
path: "tests/integration/example.integration.test.ts",
content: renderIntegrationTest(a, engine),
});
files.push({
path: `migrations/${engine}/0001-init.sql`,
content: renderMigration(a),
});
}
return files;
}