scribase-cli/scripts/generate.ts

177 lines
5.9 KiB
TypeScript
Raw Permalink Normal View History

/**
* Generate `src/types.gen.ts` from `api/openapi.yaml`.
*
* A focused, dependency-light OpenAPI 3.1 → TypeScript emitter tailored to the
* Scribase management contract: it handles `$ref`, string/integer enums,
* objects with required/optional properties, arrays, scalars, and inline
* response bodies. It is intentionally not a general-purpose codegen — the
* contract is small and stable, and a readable emitter beats a giant dependency.
*
* Usage: `pnpm generate` (or `tsx scripts/generate.ts [openapi.yaml] [out.ts]`).
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parse } from 'yaml';
interface SchemaNode {
$ref?: string;
type?: string;
enum?: Array<string | number>;
properties?: Record<string, SchemaNode>;
required?: string[];
items?: SchemaNode;
format?: string;
description?: string;
oneOf?: SchemaNode[];
anyOf?: SchemaNode[];
}
interface OpenApiDoc {
components?: { schemas?: Record<string, SchemaNode> };
paths?: Record<string, Record<string, OperationNode>>;
}
interface OperationNode {
operationId?: string;
responses?: Record<string, { content?: Record<string, { schema?: SchemaNode }> }>;
}
const HTTP_METHODS = ['get', 'put', 'post', 'delete', 'patch'] as const;
function refName(ref: string): string {
const parts = ref.split('/');
const last = parts[parts.length - 1];
if (last === undefined || last.length === 0) {
throw new Error(`unresolvable $ref: ${ref}`);
}
return last;
}
function pascalCase(input: string): string {
return input.replace(/(^|[_-])([a-z])/g, (_, __, ch: string) => ch.toUpperCase());
}
/** Render a schema node as a TypeScript type expression. */
function typeExpr(schema: SchemaNode, indent: string): string {
if (schema.$ref) {
return refName(schema.$ref);
}
// `oneOf`/`anyOf` become a TS union. The contract uses this for nullable
// references (e.g. `ImportVerification | null`), so it must not collapse to
// `unknown` — a caller needs to see that the value can be null.
const variants = schema.oneOf ?? schema.anyOf;
if (variants && variants.length > 0) {
const members = variants.map((variant) => typeExpr(variant, indent));
return [...new Set(members)].join(' | ');
}
if (schema.enum && schema.enum.length > 0) {
return schema.enum
.map((value) => (typeof value === 'string' ? JSON.stringify(value) : String(value)))
.join(' | ');
}
switch (schema.type) {
case 'null':
return 'null';
case 'string':
return 'string';
case 'integer':
case 'number':
return 'number';
case 'boolean':
return 'boolean';
case 'array':
return `${typeExpr(schema.items ?? { type: 'string' }, indent)}[]`;
case 'object':
return objectExpr(schema, indent);
default:
return 'unknown';
}
}
/** Render an object schema as an inline `{ ... }` type or interface body. */
function objectExpr(schema: SchemaNode, indent: string): string {
const props = schema.properties ?? {};
const required = new Set(schema.required ?? []);
const inner = `${indent} `;
const lines = Object.entries(props).map(([name, prop]) => {
const optional = required.has(name) ? '' : '?';
const doc = prop.description ? `${inner}/** ${prop.description} */\n` : '';
return `${doc}${inner}${name}${optional}: ${typeExpr(prop, inner)};`;
});
return `{\n${lines.join('\n')}\n${indent}}`;
}
/** Emit a top-level named declaration for one component schema. */
function emitSchema(name: string, schema: SchemaNode): string {
const doc = schema.description ? `/** ${schema.description} */\n` : '';
if (schema.enum && schema.enum.length > 0 && schema.type !== 'object') {
return `${doc}export type ${name} = ${typeExpr(schema, '')};\n`;
}
if (schema.type === 'object') {
return `${doc}export interface ${name} ${objectExpr(schema, '')}\n`;
}
return `${doc}export type ${name} = ${typeExpr(schema, '')};\n`;
}
/** Collect inline (non-$ref) object response bodies, named after their op. */
function emitInlineResponses(paths: OpenApiDoc['paths']): string[] {
if (!paths) {
return [];
}
const out: string[] = [];
for (const item of Object.values(paths)) {
for (const method of HTTP_METHODS) {
const op = item[method];
if (!op?.operationId || !op.responses) {
continue;
}
for (const [status, response] of Object.entries(op.responses)) {
const schema = response.content?.['application/json']?.schema;
if (!schema || schema.$ref || schema.type !== 'object' || !schema.properties) {
continue;
}
if (status[0] !== '2') {
continue;
}
const name = `${pascalCase(op.operationId)}Response`;
out.push(
`/** Inline ${status} body of \`${op.operationId}\`. */\n` +
`export interface ${name} ${objectExpr(schema, '')}\n`,
);
}
}
}
return out;
}
function main(): void {
const here = dirname(fileURLToPath(import.meta.url));
const inputPath = process.argv[2] ?? resolve(here, '..', '..', '..', 'api', 'openapi.yaml');
const outputPath = process.argv[3] ?? resolve(here, '..', 'src', 'types.gen.ts');
const doc = parse(readFileSync(inputPath, 'utf8')) as OpenApiDoc;
const schemas = doc.components?.schemas ?? {};
const header =
'/**\n' +
' * DO NOT EDIT BY HAND.\n' +
' *\n' +
` * Generated from \`api/openapi.yaml\` by \`scripts/generate.ts\`.\n` +
' * Run `pnpm generate` to refresh after the contract changes.\n' +
' */\n';
const parts: string[] = [header];
for (const [name, schema] of Object.entries(schemas)) {
parts.push(emitSchema(name, schema));
}
parts.push(...emitInlineResponses(doc.paths));
writeFileSync(outputPath, `${parts.join('\n')}`, 'utf8');
process.stdout.write(
`Wrote ${Object.keys(schemas).length} schemas to ${outputPath}\n`,
);
}
main();