Skip to main content

TsGenerator

TsGenerator generates TypeScript client code from a live OPRA service. It fetches the API schema from the service's $schema endpoint, then writes typed model classes and HTTP controller proxies into the specified output directory.

This is the programmatic API behind the oprimp CLI command. Use it when you need to integrate code generation into a build script or a custom tooling pipeline.

import { TsGenerator } from '@opra/cli';

const generator = new TsGenerator({
serviceUrl: 'https://api.example.com',
outDir: './src/generated',
});

await generator.generate();

Constructor

new TsGenerator(options: TsGenerator.Options)

Methods

generate()

Fetches the API schema, generates TypeScript files, and writes them to outDir. Clears the output directory before writing.

generate(): Promise<void>

The method is idempotent per instance — calling it a second time on the same instance is a no-op.


Events

TsGenerator extends EventEmitter. Subscribe to these events to monitor progress.

EventPayloadDescription
startGeneration started
finishGeneration completed
logmessage, ...argsGeneral progress message
warnmessage, ...argsNon-fatal warning
errormessage, ...argsError occurred
debugmessage, ...argsVerbose debug output
generator.on('log', msg => console.log(msg));
generator.on('error', err => console.error(err));

When a logger is provided in options, log events are forwarded to it automatically.


Interfaces

TsGenerator.Options

interface Options {
serviceUrl: string;
outDir: string;
cwd?: string;
logger?: ILogger;
writer?: IFileWriter;
fileHeader?: string;
importExt?: boolean;
referenceNamespaces?: boolean;
}
PropertyTypeDefaultDescription
serviceUrlstringBase URL of the OPRA service to generate from
outDirstringOutput directory for generated files
cwdstringprocess.cwd()Working directory used to resolve outDir
loggerILoggerLogger for progress output
writerIFileWriterFileWriterFile writer implementation; override for custom output (e.g. dry-run, in-memory)
fileHeaderstring''Comment block prepended to every generated file
importExtbooleanfalseAppend .js to import paths (required for ESM output)
referenceNamespacesbooleanfalseExport referenced API documents under separate namespaces

ILogger

Implement this interface to forward generator messages to your logging system.

interface ILogger {
log(message: any, ...args: any[]): void;
error(message: any, ...args: any[]): void;
warn(message: any, ...args: any[]): void;
debug?(message: any, ...args: any[]): void;
verbose?(message: any, ...args: any[]): void;
}

console satisfies this interface and can be passed directly.


IFileWriter

Implement this interface to redirect generated output — useful for testing or writing to virtual filesystems.

interface IFileWriter {
writeFile(filename: string, contents: string): Promise<void> | void;
}

The default implementation (FileWriter) calls fs.writeFileSync.


Examples

Basic usage

import { TsGenerator } from '@opra/cli';

await new TsGenerator({
serviceUrl: 'https://api.example.com',
outDir: './src/generated',
logger: console,
fileHeader: '/* Auto-generated — do not edit */',
importExt: true,
}).generate();

Custom file writer (dry-run / in-memory)

import { TsGenerator, IFileWriter } from '@opra/cli';

const files: Record<string, string> = {};

const dryRunWriter: IFileWriter = {
writeFile(filename, contents) {
files[filename] = contents;
},
};

await new TsGenerator({
serviceUrl: 'https://api.example.com',
outDir: './generated',
writer: dryRunWriter,
}).generate();

console.log(Object.keys(files));

Integration in a build script

import { TsGenerator } from '@opra/cli';

async function codegen() {
const generator = new TsGenerator({
serviceUrl: process.env.API_URL!,
outDir: './src/api',
importExt: true,
fileHeader: `/* Generated ${new Date().toISOString()} */`,
logger: console,
});

generator.on('finish', () => console.log('Code generation complete'));
await generator.generate();
}

codegen().catch(err => {
console.error(err);
process.exit(1);
});

See also