# How to drive code generation from a script instead of the CLI

> Run sdkgen's model build inside a Node release script, turn its warnings into data, and fail the job unless the files it recorded match a list you review.

Source: https://voxgig.com/howto/drive-code-generation-from-a-script

- Audience: platform-team
- Level: advanced
- Languages: typescript
- Verified: 2026-11-22
- Published: 2026-11-21
- Updated: 2026-11-22

## Short answer

Call the generator as a library where it has one, and check what it produced either way. For sdkgen, run the `Model` class from `@voxgig/model` inside `.sdk` with a `pino` logger of your own, fail on `ok: false` or any warning, then fold `.sdk/log/generated.jsonl` into a file list and compare it with a committed one. Swagger Codegen's CLI exited 0 when generation threw, so check its output the same way.

---
## You will need

Node 22 or later, a project scaffolded by `@voxgig/create-sdkgen`, and a JDK for the Swagger
Codegen part. The scaffold's packages declare Node 24 in `engines`, and npm installed them on
Node 22 after printing `EBADENGINE`. `api.json` is a Bookshelf API with five operations and one
internal one, `POST /internal/reindex`, marked `x-internal`, which the script drops before
generating. `record.sh` ran every case on this page and committed its output under `runs/`, with
the time stamps in each generation record replaced so that a second recording matches the first.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Fern CLI from a script](https://buildwithfern.com/learn/cli-api-reference/cli-reference/sdk-commands) | Fern already generates and publishes your SDKs, and the script runs `fern generate` | Remote runs need a login or `FERN_TOKEN`; `--local` needs Docker or Podman and the Enterprise plan | Generation must stay offline on a free plan |
| [OpenAPI Generator Maven and Gradle plugins](https://openapi-generator.tech/docs/plugins/) | A JVM build, where generation is one more goal or task | A JVM build tool to adopt for a TypeScript SDK, with options in its build file | The release job is a Node or shell script |
| [sdkgen programmatic API](https://github.com/voxgig/model) | An sdkgen project, where the job wants warnings and errors as objects | One of four steps has no API, and the build depends on the working directory | Generation runs once by hand, where `npm run generate` is enough |
| [shelling out to the CLI](https://nodejs.org/api/child_process.html) | Any generator, and a script that should survive generator upgrades | An exit code that can say 0 on a broken run, so the files need checking | You need warnings, not a text log to grep |
| [Swagger Codegen CLI and Java API](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/workflow-integration/) | A JVM program can call `DefaultGenerator`, which returns the files it wrote | The CLI exits 0 when generation throws, so a script must count files | You script it from Node and cannot add a JVM step |

Voxgig maintains sdkgen. The table holds five options and favors none.

Shelling out is the cheapest to write and the most likely to keep working across upgrades, at the
price of trusting an exit code. The sdkgen API reports errors and warnings as data but leaves one
step as a child process. Fern documents a CLI and no library, and Swagger Codegen gives the file
list only to a JVM caller.

## Run the model build in your own process

`npm run generate` in the scaffolded project runs four commands: `node build/docgen.js`,
`tsc --build src`, then `voxgig-model` on `model/sdk.aontu` and on `test/test.aontu`. The
[`@voxgig/model` README](https://github.com/voxgig/model) shows the third as code, `new Model({ path,
base }).run()`, which resolves to `{ ok, errs }`. sdkgen's own
[API reference](https://github.com/voxgig/sdkgen/blob/main/docs/reference/api.md) documents the
layer beneath: `SdkGen.makeBuild`, the step that build calls, and `generate`, which resolves
`{ ok, name }` with no file list. `drive.mjs` runs all four from one Node process.

```js title="drive.mjs"
// 4. Generate: the same Model build that voxgig-model runs, in this process.
// A pino logger of our own turns every warning into data instead of a line.
const warnings = []
const pino = requireSdk('pino')({ level: 'info' }, { write: (line) => {
  const entry = JSON.parse(line)
  if (entry.level >= 40) warnings.push(entry.note ?? entry.msg ?? entry.point)
} })
const { Model } = requireSdk('@voxgig/model')
// The build reads templates by paths relative to the working directory, as
// `npm run generate` inside .sdk/ has it. KEEP_CWD=1 skips this, to show why.
if (process.env.KEEP_CWD !== '1') process.chdir(sdk)
for (const root of ['model/sdk.aontu', 'test/test.aontu']) {
  const path = join(sdk, root)
  const br = await new Model({ path, base: join(path, '..'), require: sdk, debug: 'info', pino }).run()
  // Each error is an object; its first line, without the stack location, is enough here.
  const first = (e) => String(e.message).split('\n')[0].replace(/ \[at .*$/, '')
  if (!br.ok) fail(`generate ${root}: ${br.errs.map(first).join('; ')}`)
}
```

The `pino` option replaces the pretty printer, so apidef's "PARTIAL BUILD" arrives as an entry
at warning level. The compile step stays a child process, because the TypeScript the scaffold
installs brings no compiler API:[^1]

```bash
cat runs/typescript-exports.txt
```

```text output
typescript 7.0.2: exports version, versionMajorMinor
```

## Fail on the record, not on the exit code

`sdkgen` appends to `.sdk/log/generated.jsonl` on each run that adds or removes a file. The first
entry lists every file it wrote; later ones list each file added, and `null` for each one removed,
but no file whose contents changed. A run that changes only the contents of files appends nothing,
as `runs/record-growth.txt` shows.
[`project-layout.md`](https://github.com/voxgig/sdkgen/blob/main/docs/reference/project-layout.md)
describes the record. `check-files.mjs` folds it into the current set and compares that with
`expected-files.txt`, the 105 files of a reviewed clean run.

```js title="check-files.mjs"
export function foldRecord(text) {
  const owned = new Map()
  const lines = text.split('\n').filter((l) => l.trim() !== '')
  if (lines.length === 0) throw new Error('the record is empty: generation wrote nothing')
  lines.forEach((line, i) => {
    let entry
    try {
      entry = JSON.parse(line)
    } catch {
      throw new Error(`record line ${i + 1} is not JSON, so the record was cut off`)
    }
    if (entry === null || typeof entry.files !== 'object' || entry.files === null || Array.isArray(entry.files)) {
      throw new Error(`record line ${i + 1} has no files map`)
    }
    if (i === 0 && entry.op !== 'record') throw new Error('the record does not start with a full listing')
    for (const [path, owner] of Object.entries(entry.files)) {
      if (owner !== null && typeof owner !== 'string') throw new Error(`record line ${i + 1}: ${path} has no owner`)
      if (owner === null) owned.delete(path)
      else owned.set(path, owner)
    }
  })
  return owned
}
```

The clean run, as `record.sh` captured it:

```bash
cat runs/drive-clean/out.txt
```

```text output
fetch    3 paths
patch    dropped 1 internal operation(s)
compile  .sdk/src
generate ok, 0 warning(s)
check: ok, 105 files recorded
publish  ready
```

## Compare the script with a shell-out

`shell.mjs` does the same job the short way: copy the spec in, run `npm run generate`, read its
exit code, and fail on any `WARN` or `ERROR` line it printed. `record.sh` ran both scripts on a
spec cut off after `"paths": ` and on one whose parameter `$ref` points at nothing. Each ran in a
project that had already generated cleanly, and `shell.mjs` ran on the clean spec too.

```bash
node verify-runs.mjs
```

```text output
  run                     exit  files  how it ended
  drive-clean             0     ok     publish  ready
  drive-dangling          1     ok     FAIL generation warned; read the warnings before you publi
  drive-keep-cwd          1     ok     FAIL generate model/sdk.aontu: CopyFiles: (bookshelf: ts/s
  drive-truncated         1     ok     FAIL fetch: the spec is not JSON (Unexpected end of JSON i
  newest-shell-dangling   1     ok     npm run generate: exit 0
  newest-shell-truncated  1     2 off  npm run generate: exit 0
  shell-clean             0     ok     npm run generate: exit 0
  shell-dangling          1     ok     npm run generate: exit 0
  shell-truncated         1     2 off  npm run generate: exit 0
```

`npm run generate` exited 0 on both broken specs, in 4.44.3 and in sdkgen 4.45.0 with apidef
8.33.1. On the truncated spec, the generated client lost its only entity:

```bash
cat runs/shell-truncated/sdk.txt
```

```text output
Book( in ts/src/BookshelfSDK.ts: 0 lines, against 2 after the clean run
ts/src/entity/BookEntity.ts on disk: yes
```

The file check caught it only from two removed test files, since `BookEntity.ts` stayed in the
record and on disk. It did not catch the dangling `$ref`, whose only trace is two warnings and a
"PARTIAL BUILD" line, so both scripts also fail on any warning.

## Script Fern and Swagger Codegen the same way

Swagger Codegen 3.0.85 runs from a script as `java -jar swagger-codegen-cli-3.0.85.jar generate`.
`record.sh` also compiled `java/Gen.java`, which calls `new DefaultGenerator().opts(input).generate()`
from the same jar and receives the files written as a `List<File>`.

```bash
cat runs/swagger-codegen.txt
```

```text output
good.json: CLI exit 0, 9 files; Java API exit 0, files 9
  CLI stderr: no exception
dangling.json: CLI exit 0, 0 files; Java API exit 1, failed: RuntimeException: Could not process operation:
  CLI stderr: Exception in thread "Thread-0" java.lang.RuntimeException: Could not process operation:
truncated.json: CLI exit 0, 0 files; Java API exit 1, failed: RuntimeException: missing OpenAPI input!
  CLI stderr: Exception in thread "Thread-0" java.lang.RuntimeException: missing OpenAPI input!
no-such-command: CLI exit 0, swagger-codegen: error: invalid choice: 'no-such-command' (choose from
```

The CLI printed the exception, raised on a thread named `Thread-0`, wrote no files, and exited 0.
It exited 0 on an unknown command as well. From Node, count the output files as `check-files.mjs`
counts sdkgen's. Its [workflow integration page](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/workflow-integration/)
documents Maven, Gradle and GitHub integration for builds that already run a JVM.

Fern's [documentation index](https://buildwithfern.com/learn/llms.txt) lists CLI reference pages
and no library, so a script runs `fern generate --target typescript --force` as a child process.
The [SDK commands](https://buildwithfern.com/learn/cli-api-reference/cli-reference/sdk-commands)
page reads `--target` from `sdk-config.yml`, the current format, and gives `--force` for skipping
prompts in CI. Remote generation needs a login, which in CI is a `FERN_TOKEN` from
[`fern token`](https://buildwithfern.com/learn/cli-api-reference/cli-reference/general-commands#fern-token).
`--local` runs the generator in Docker or Podman, and the
[self-hosted SDKs page](https://buildwithfern.com/learn/sdks/current/deep-dives/self-hosted) marks
it Enterprise. The patch step can move into Fern: its
[overlays page](https://buildwithfern.com/learn/api-definitions/openapi/overlays) names an
overlays file beside the spec in `generators.yml`, which the SDK commands page calls legacy.

## Check it worked

The suite tests the fold and the check against the committed records, holds each recorded run to
what this page says of it, and runs `check-files.mjs` on a project missing one recorded file.
It also runs `drive.mjs` with relative paths on a stand-in project, and reads the record's growth
over five generates in each release.

```bash
node --test files.test.mjs
```

```text output
# tests 12
# suites 0
# pass 12
# fail 0
```

A cut-off record line, an empty record, a first entry that is not a full listing and a file with
no owner each throw. A record that cannot be read belongs to a run that did not finish.

## When it goes wrong

The build fails with `CopyFiles` and `ENOENT` on `tm/ts/src/feature/test`. It resolves template
paths against the working directory, so a script started at the repository root reports the
`drive-keep-cwd` error in the table of runs. Change into `.sdk` first.

A dry run rewrites the SDK. `inmemory.mjs` passed `Model` a file system that counts writes, then
`dryrun: true`, then ran the scaffold's `npm run dry-generate`:

```bash
cat runs/inmemory/out.txt
```

```text output
Model({ fs, dryrun: false }): ok true, writes through fs: 0
  ts/src/BookshelfSDK.ts, deleted first: written again
  ts/src/Config.ts, edited first: edit overwritten
Model({ fs, dryrun: true }): ok true, writes through fs: 0
  ts/src/BookshelfSDK.ts, deleted first: written again
  ts/src/Config.ts, edited first: edit overwritten
npm run dry-generate: exit 0
  ts/src/BookshelfSDK.ts, deleted first: written again
  ts/src/Config.ts, edited first: edit overwritten
```

The [`@voxgig/model` README](https://github.com/voxgig/model) lists what the tool does, and one
item reads "Previews safely with `--dryrun` (writes redirected to an in-memory filesystem), and can
build against any `fs` implementation". `SdkGen` takes `fs` and `dryrun` options of its own, but in 4.44.3 and 4.45.0
`makeBuild` constructs it with only the model's logger and debug level added, so neither option
reaches the sdkgen step. Generate into a copy of the project when you want a preview.

## When not to do this

Do not write the library version for a job that runs one generator once. `shell.mjs` is 28 lines,
and with the file check and its scan for `WARN` lines it failed both broken specs.

Do not adopt sdkgen's `Model` path expecting in-memory generation or a file list in the return
value. It resolves to `{ ok, errs }`, and the files come from the record on disk.

Do not fail on every warning when your spec carries a known, harmless one. List the warnings you
accept, or the job stops on each release.

Pick Fern when its hosted pipeline already publishes your SDKs, since the script then reduces to
`fern generate` and a check of the output. Pick Swagger Codegen when the job is a JVM program,
where `DefaultGenerator` hands back the file list and throws on failure.

## Related how-tos

- [Block a release when generated SDK files have drifted](/howto/block-a-release-when-generated-sdk-files-drift)

- [Generate your first SDK with sdkgen](/howto/first-sdk-with-sdkgen)

- [Preview a regeneration as a diff before writing files](/howto/preview-a-regeneration-as-a-diff)

- [Fail a build when a generator customization becomes a fork](/howto/audit-generator-customisations-for-drift)

- [Verify a generated SDK is reproducible from its spec](/howto/verify-a-generated-sdk-is-reproducible)

## Last verified

Verified 2026-11-22 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen`
4.44.3, `@voxgig/apidef` 8.32.4, `@voxgig/model` 12.0.2, TypeScript 7.0.2 and Swagger Codegen
3.0.85 on OpenJDK 21. Every output block is what the command preceding it printed, and the `runs/`
files are what `record.sh` captured; the gate reads them and does not regenerate. sdkgen 4.45.0
with apidef 8.33.1 ran the shell-out and dry-run cases once, recorded under `runs/newest-*`, and
the five generates in `runs/record-growth.txt`. Fern was not run, because it generates only with a
Fern login, a guest session or a container runtime; its commands and plans come from its CLI
reference, self-hosting and overlays pages.

[^1]: The TypeScript team announced the native compiler on
[March 11, 2025](https://devblogs.microsoft.com/typescript/typescript-native-port/), with the
JavaScript code base to continue as the 6.x line for projects that depend on certain API features.
The 7.0.2 package the scaffold installed answers `require('typescript')` with an object holding
those two version strings, which is the whole of the API it brought.