import type { ForgeConfig, ForgeSymbol, OpenAPIDocument, OpenAPIInfoObject, OpenAPIOperationObject, OpenAPIParameterObject, OpenAPIPathItemObject, OpenAPISchemaObject, } from "@forge-ts/core"; import { Visibility } from "@forge-ts/core"; import { signatureToSchema } from "./schema-mapper.js"; import type { SDKProperty, SDKType } from "./sdk-extractor.js"; export type { OpenAPIDocument }; /** * Generates a production-quality OpenAPI 3.2 document from the extracted SDK * types. * * The document is populated with: * - An `info` block sourced from the config or reasonable defaults. * - A `components.schemas` section with one schema per exported type. * - `tags` derived from unique source file paths (grouping by file). * - Visibility filtering: `@internal` symbols are never emitted. * - HTTP paths are extracted from `@route` tags and appropriately mapped. * * @remarks * Produces an OpenAPI 3.2.0 document. Symbols marked `@internal` or `@private` * are filtered out before schema generation. * * HTTP paths are extracted from `@route` tags in the format `METHOD /path`. * Path template variables like `{id}` become required path parameters * (`in: "path"`). Any `@param` entries whose names are NOT found in the * route path template are classified as query parameters (`in: "query"`). * * @param config - The resolved {@link ForgeConfig}. * @param sdkTypes - SDK types to include as component schemas. * @param symbols - Raw symbols used to extract HTTP route paths from `@route` tags. * @returns An {@link OpenAPIDocument} object. * @example * ```typescript * import { generateOpenAPISpec } from "@forge-ts/api"; * import { extractSDKTypes } from "@forge-ts/api"; * const spec = generateOpenAPISpec(config, extractSDKTypes(symbols), symbols); * console.log(spec.openapi); // "3.2.0" * ``` * @public */ export function generateOpenAPISpec( config: ForgeConfig, sdkTypes: SDKType[], symbols: ForgeSymbol[] = [], ): OpenAPIDocument { // Visibility filtering: never emit @internal or @private symbols. const visibleTypes = sdkTypes.filter( (t) => t.visibility !== Visibility.Internal && t.visibility !== Visibility.Private, ); const schemas: Record = {}; for (const t of visibleTypes) { schemas[t.name] = buildSchema(t); } // Derive tags from unique source files (basename without extension). const tagNames = deriveTagNames(visibleTypes); const tags = tagNames.map((name) => ({ name })); const paths = extractPaths(symbols); return { openapi: "3.2.0", info: buildInfo(config), ...(tags.length > 0 ? { tags } : {}), paths, components: { schemas }, }; } // --------------------------------------------------------------------------- // Info block // --------------------------------------------------------------------------- /** * Builds the OpenAPI `info` block from the config. * * @param config - The resolved {@link ForgeConfig}. * @returns An info object with title, version, and description. * @internal */ function buildInfo(config: ForgeConfig): OpenAPIInfoObject { return { title: config.project?.packageName ?? "API Reference", version: config.project?.version ?? "0.0.0", description: config.project?.description ?? "Generated by forge-ts", }; } // --------------------------------------------------------------------------- // Schema builders // --------------------------------------------------------------------------- /** * Converts an {@link SDKType} to an OpenAPI schema object. * * - `interface` / `class` → object schema with `properties` and `required` * - `enum` → schema with `enum` array and `type: "string"` * - `type` alias → schema derived from signature parsing * * @param sdkType - The type descriptor to convert. * @returns An OpenAPI schema object. * @internal */ function buildSchema(sdkType: SDKType): OpenAPISchemaObject { const base: OpenAPISchemaObject = {}; if (sdkType.description) { base.description = sdkType.description; } if (sdkType.deprecated) { base.deprecated = true; } switch (sdkType.kind) { case "interface": case "class": return { ...base, ...buildObjectSchema(sdkType) }; case "enum": return { ...base, ...buildEnumSchema(sdkType) }; case "type": return { ...base, ...buildTypeAliasSchema(sdkType) }; default: return { ...base, type: "object" }; } } /** * Builds an object schema for an interface or class type. * * @param sdkType - An interface or class {@link SDKType}. * @returns An OpenAPI object schema. * @internal */ function buildObjectSchema(sdkType: SDKType): OpenAPISchemaObject { if (sdkType.properties.length === 0) { return { type: "object" }; } const properties: Record = {}; const required: string[] = []; for (const prop of sdkType.properties) { properties[prop.name] = buildPropertySchema(prop); if (prop.required) { required.push(prop.name); } } const schema: OpenAPISchemaObject = { type: "object", properties }; if (required.length > 0) { schema.required = required; } return schema; } /** * Builds the schema for a single property. * * @param prop - The {@link SDKProperty} to convert. * @returns A partial OpenAPI schema for the property. * @internal */ function buildPropertySchema(prop: SDKProperty): OpenAPISchemaObject { const schema: OpenAPISchemaObject = { ...signatureToSchema(prop.type) }; if (prop.description) { schema.description = prop.description; } if (prop.deprecated) { schema.deprecated = true; } return schema; } /** * Builds an enum schema for an enum type. * * If the enum has properties (members), their names are used as the enum * values. The type defaults to `"string"` unless a member type suggests * otherwise. * * @param sdkType - An enum {@link SDKType}. * @returns An OpenAPI schema with `enum` values. * @internal */ function buildEnumSchema(sdkType: SDKType): OpenAPISchemaObject { if (sdkType.properties.length === 0) { return { type: "string", enum: [] }; } const values = sdkType.properties.map((p) => { // Use the type value if it looks like a string literal; otherwise use name. const t = p.type.trim(); if (t.startsWith('"') || t.startsWith("'")) { return t.replace(/^['"]|['"]$/g, ""); } return p.name; }); // Detect numeric enums: if all values are parseable numbers use "number". const allNumeric = values.every((v) => !Number.isNaN(Number(v))); return { type: allNumeric ? "number" : "string", enum: allNumeric ? values.map(Number) : values, }; } /** * Builds a schema for a type alias. * * Attempts to parse the signature string directly; falls back to * `{ type: "object" }` for complex generics or intersections. * * @param sdkType - A type alias {@link SDKType}. * @returns An OpenAPI schema. * @internal */ function buildTypeAliasSchema(sdkType: SDKType): OpenAPISchemaObject { if (!sdkType.signature) { return { type: "object" }; } // The signature for a type alias is often `type Name = ActualType`. // Strip the leading declaration if present. const equalsIndex = sdkType.signature.indexOf("="); const rawType = equalsIndex !== -1 ? sdkType.signature.slice(equalsIndex + 1).trim() : sdkType.signature; return signatureToSchema(rawType); } // --------------------------------------------------------------------------- // Path extraction // --------------------------------------------------------------------------- /** * Builds OpenAPI path items from symbols that carry `@route` TSDoc tags. * * Each `@route` tag must be in the format `METHOD /path` (e.g. `GET /users/{id}`). * Path template variables like `{id}` are emitted as required path parameters. * Any `@param` entries not matched to a path variable become query parameters. * * @param symbols - All {@link ForgeSymbol} instances from the walker. * @returns A map of path template strings to their OpenAPI path item objects. * @internal */ function extractPaths(symbols: ForgeSymbol[]): Record { const paths: Record = {}; for (const symbol of symbols) { const routeTags: string[] = symbol.documentation?.tags?.route ?? []; for (const routeTag of routeTags) { const match = routeTag.match(/^(GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD)\s+(\S+)/i); if (!match) continue; const method = match[1].toLowerCase() as | "get" | "post" | "put" | "delete" | "patch" | "options" | "head"; const path = match[2]; if (!paths[path]) { paths[path] = {}; } const fileBasename = symbol.filePath.split("/").pop()?.replace(/\.ts$/, "") ?? "default"; const operation: OpenAPIOperationObject = { operationId: symbol.name, summary: symbol.documentation?.summary, description: symbol.documentation?.summary, tags: [fileBasename], }; // Extract path template variables like {id} const pathParams = [...path.matchAll(/\{(\w+)\}/g)].map((m) => m[1]); const parameters: OpenAPIParameterObject[] = []; for (const paramName of pathParams) { const paramDoc = symbol.documentation?.params?.find((p) => p.name === paramName); parameters.push({ name: paramName, in: "path", required: true, description: paramDoc?.description ?? `The ${paramName} parameter`, schema: { type: "string" }, }); } // Non-path @param entries become query parameters const nonPathParams = (symbol.documentation?.params ?? []).filter( (p) => !pathParams.includes(p.name), ); for (const param of nonPathParams) { parameters.push({ name: param.name, in: "query", description: param.description, schema: { type: "string" }, }); } if (parameters.length > 0) { operation.parameters = parameters; } // @returns becomes the 200 response description if (symbol.documentation?.returns) { operation.responses = { "200": { description: symbol.documentation.returns.description, }, }; } paths[path][method] = operation; } } return paths; } // --------------------------------------------------------------------------- // Tag derivation // --------------------------------------------------------------------------- /** * Derives OpenAPI tag names from the unique source file basenames of the * provided types (without directory path or extension). * * @param types - The visible SDK types. * @returns A sorted, deduplicated array of tag name strings. * @internal */ function deriveTagNames(types: SDKType[]): string[] { const seen = new Set(); for (const t of types) { const basename = t.sourceFile.split("/").pop() ?? t.sourceFile; const withoutExt = basename.replace(/\.[^.]+$/, ""); seen.add(withoutExt); } return Array.from(seen).sort(); }