Sample: a generator in TypeScript
This sample is a generator in one TypeScript file. Node.js runs it as it is, with no build step and no packages. It is a generator: the Cratis CLI runs it for every build order, and does everything else a builder does, from connecting to Studio to committing and reporting. See Build with a generator for how the two fit together.
For every slice in the order, the generator writes a Markdown sheet with the slice’s acceptance criteria to slices/<feature>/<slice>.md in the project, and reports what it wrote. The comment in the code marks where real code generation goes.
The Bash and C# samples do exactly the same thing, and write the same sheets. The language is your choice: anything the shell can start works.
What you need
Section titled “What you need”- The Cratis CLI, with
cratis build. - Node.js 22.18 or later, which runs TypeScript files directly.
- A clean clone of the application’s repository.
The code
Section titled “The code”Save the file as ~/slice-sheets/generate.mts, outside the application’s repository. The .mts extension tells Node.js it is a module.
// Slice sheets: a generator for `cratis build`. For every slice in the build order it writes// a Markdown sheet with the slice's acceptance criteria into the project.import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { dirname } from 'node:path';
type Slice = { id: string; name: string; type: string };type Specification = { sliceId: string; id: string; name: string; given: string[]; when: string; then: string[] };type Order = { scope: { feature: { name: string }; slices: Slice[] }; specifications: Specification[] };
const order: Order = JSON.parse(readFileSync(process.env.STUDIO_BUILD_ORDER!, 'utf8'));const outcomeFile = process.env.STUDIO_BUILD_OUTCOME!;const writeOutcome = (outcome: object) => writeFileSync(outcomeFile, JSON.stringify(outcome, null, 2));const safe = (name: string) => /^[A-Za-z0-9_ -][A-Za-z0-9._ -]*$/.test(name);
function sheetFor(slice: Slice): string { const lines = [`# ${slice.name}`, '', `A ${slice.type} slice in ${order.scope.feature.name}.`, '', '## Acceptance criteria']; for (const specification of order.specifications.filter(s => s.sliceId === slice.id)) { lines.push( '', `### ${specification.name}`, '', `- Given ${specification.given.length > 0 ? specification.given.join(', ') : 'nothing'}`, `- When ${specification.when}`, `- Then ${specification.then.join(', ')}`); } return lines.join('\n') + '\n';}
try { const feature = order.scope.feature.name; if (!safe(feature)) throw new Error(`The feature name '${feature}' cannot be used as a folder name.`);
const files: string[] = []; for (const slice of order.scope.slices) { if (!safe(slice.name)) throw new Error(`The slice name '${slice.name}' cannot be used as a file name.`); const file = `slices/${feature}/${slice.name}.md`;
// This is where real generation goes: run your code generator or templates for the // slice here and write the files they produce. This sample writes one sheet per slice. const sheet = sheetFor(slice);
if (existsSync(file) && readFileSync(file, 'utf8') === sheet) continue; mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, sheet); files.push(file); }
if (files.length === 0) { writeOutcome({ kind: 'nothingToDo' }); } else { writeOutcome({ kind: 'built', files, specifications: order.specifications.map(s => ({ id: s.id, result: 'notRun' })), assumptions: ['Wrote a slice sheet for each slice; no code was generated.'] }); }} catch (error) { writeOutcome({ kind: 'failed', error: error instanceof Error ? error.message : String(error), retryable: false });}Run it once, offline
Section titled “Run it once, offline”cratis build once runs the generator on an order from a file, without connecting to Studio, and commits what it built just as a real build does.
-
Save the example backend order as
~/order.json. -
In the clone of the repository, run the generator on it:
Terminal window cratis build once --order ~/order.json --exec "node $HOME/slice-sheets/generate.mts" --verify "test -d slices" --outcome ~/outcome.json--verifyis where your build and tests go, for exampledotnet testornpm test. Every--verifycommand runs after the generator; one that fails turns the outcome intofailed. -
Check the result.
~/outcome.jsonsaysbuiltand listsslices/Invoicing/PayInvoice.md, andgit logshows the commit. Run the same command again: the sheet is unchanged, so the outcome isnothingToDoand nothing is committed.
Run it for real
Section titled “Run it for real”-
Register the machine with your organization, once, and have a maintainer approve it with the code it shows. See Connect a builder and approve it.
Terminal window cratis build connect --studio --organization <your organization> -
In the clone of the repository, start the build loop with the generator:
Terminal window cratis build run --exec "node $HOME/slice-sheets/generate.mts" --verify "test -d slices" -
In Studio, choose the builder for the application, and mark a slice Ready for implementation. The terminal shows the generator running, the commit, and how Studio settled the slice.
The CLI pushes each commit with your own Git credentials. Add --no-push to keep the commits local, or --once to stop after one slice.
Keep it running
Section titled “Keep it running”On macOS and Linux, install the loop as a user service, from the clone of the repository:
cratis build service install --exec "node $HOME/slice-sheets/generate.mts" --verify "test -d slices"It starts when you sign in and restarts when it stops. cratis build service status says where its output goes, and cratis build service uninstall removes it.
How it works
Section titled “How it works”Reading the order
Section titled “Reading the order”JSON.parse reads the file STUDIO_BUILD_ORDER names. The Order type declares only the members the sample uses; Build orders and outcomes lists them all, with a JSON Schema you can generate types from. The script runs in the project folder, so the paths it writes are relative to the project.
Writing the sheet
Section titled “Writing the sheet”sheetFor builds the sheet for one slice: its name and type, then each specification whose sliceId matches, as Given, When and Then. This is where your own generation goes: call a code generator, fill templates, or write the command and event files for the slice.
Nothing to do
Section titled “Nothing to do”A sheet that is already in the project with the same content is skipped. When every sheet is unchanged, the script reports nothingToDo, so the CLI makes no empty commit.
The outcome
Section titled “The outcome”writeOutcome writes built with the files the script wrote, each specification as notRun (the sample runs no tests), and one assumption. The CLI adds the order’s id, the contract version and the commit.
Failing
Section titled “Failing”Any error, such as a feature or slice name that cannot be a file name, is caught and written as a failed outcome with retryable set to false, and the script exits with 0 because it wrote an outcome. Set retryable to true for an error another attempt could get past.
Related
Section titled “Related”- Build with a generator: the generator contract, step by step.
- Deterministic with AI on top: a generator that writes the structure, and a coding agent that completes it.
- Build orders and outcomes: everything in the order the generator reads.
- Use the reference builder: every
cratis buildcommand, and build kits.