UNPKG

ng-openapi

Version:

Generate Angular services and TypeScript types from OpenAPI/Swagger specifications

282 lines (265 loc) 10 kB
import { Project, ScriptTarget, ModuleKind, MethodDeclaration, FunctionDeclaration } from 'ts-morph'; import { HttpInterceptor } from '@angular/common/http'; import { Info, ExternalDocs, Path, ParameterType, XML, BodyParameter, QueryParameter, Security, Tag } from 'swagger-schema-official'; interface MethodGenerationContext { pathParams: Array<{ name: string; in: string; }>; queryParams: Array<{ name: string; in: string; }>; hasBody: boolean; isMultipart: boolean; formDataFields: string[]; responseType: "json" | "blob" | "arraybuffer" | "text"; } interface TypeSchema { type?: string; format?: string; $ref?: string; items?: any; nullable?: boolean; enum?: Array<string | number>; [key: string]: any; } interface GetMethodGenerationContext { pathParams: Array<{ name: string; in: string; }>; queryParams: Array<{ name: string; in: string; }>; responseType: "json" | "blob" | "arraybuffer" | "text"; } interface Parameter { name: string; in: "query" | "path" | "header" | "cookie"; required?: boolean; schema?: any; type?: string; format?: string; description?: string; } interface PathInfo { path: string; method: string; operationId?: string; summary?: string; description?: string; tags?: string[]; parameters?: Parameter[]; requestBody?: RequestBody; responses?: Record<string, SwaggerResponse>; } interface RequestBody { required?: boolean; content?: Record<string, { schema?: SwaggerDefinition; }>; } interface SwaggerResponse { description?: string; content?: Record<string, { schema?: any; }>; } interface SwaggerDefinition { type?: ParameterType | undefined; format?: string | undefined; title?: string | undefined; description?: string | undefined; default?: any; multipleOf?: number | undefined; maximum?: number | undefined; exclusiveMaximum?: boolean | undefined; minimum?: number | undefined; exclusiveMinimum?: boolean | undefined; maxLength?: number | undefined; minLength?: number | undefined; pattern?: string | undefined; maxItems?: number | undefined; minItems?: number | undefined; uniqueItems?: boolean | undefined; maxProperties?: number | undefined; minProperties?: number | undefined; enum?: any[] | undefined; items?: SwaggerDefinition | SwaggerDefinition[] | undefined; $ref?: string | undefined; allOf?: SwaggerDefinition[] | undefined; additionalProperties?: SwaggerDefinition | boolean | undefined; properties?: { [propertyName: string]: SwaggerDefinition; } | undefined; discriminator?: string | undefined; readOnly?: boolean | undefined; nullable?: boolean | undefined; xml?: XML | undefined; externalDocs?: ExternalDocs | undefined; example?: any; required?: string[] | undefined; oneOf?: SwaggerDefinition[]; anyOf?: SwaggerDefinition[]; } interface SwaggerSpec { openapi: string; swagger: string; info: Info; externalDocs?: ExternalDocs | undefined; host?: string | undefined; basePath?: string | undefined; schemes?: string[] | undefined; consumes?: string[] | undefined; produces?: string[] | undefined; paths: { [pathName: string]: Path; }; definitions?: { [definitionsName: string]: SwaggerDefinition; } | undefined; parameters?: { [parameterName: string]: BodyParameter | QueryParameter; } | undefined; responses?: { [responseName: string]: SwaggerResponse; } | undefined; security?: Array<{ [securityDefinitionName: string]: string[]; }> | undefined; securityDefinitions?: { [securityDefinitionName: string]: Security; } | undefined; tags?: Tag[] | undefined; components?: { schemas?: Record<string, SwaggerDefinition>; }; } type EnumValueObject = { Name: string; Value: number; }; declare class SwaggerParser { private readonly spec; private constructor(); static create(swaggerPathOrUrl: string, config: GeneratorConfig): Promise<SwaggerParser>; private static loadContent; private static fetchUrlContent; private static parseSpecContent; private static detectFormat; getDefinitions(): Record<string, SwaggerDefinition>; getDefinition(name: string): SwaggerDefinition | undefined; resolveReference(ref: string): SwaggerDefinition | undefined; getAllDefinitionNames(): string[]; getSpec(): SwaggerSpec; getPaths(): Record<string, any>; isValidSpec(): boolean; getSpecVersion(): { type: "swagger" | "openapi"; version: string; } | null; } /** * Interface for generator instances */ interface IPluginGenerator { /** * Generate code files */ generate(outputRoot: string): void; } /** * Interface for generator constructor with static methods */ interface IPluginGeneratorConstructor { /** * Create a generator instance */ create(swaggerPathOrUrl: string, project: Project, config: GeneratorConfig): Promise<IPluginGenerator>; /** * Constructor signature */ new (parser: SwaggerParser, project: Project, config: GeneratorConfig): IPluginGenerator; } /** * Combined type that includes both static and instance methods */ type IPluginGeneratorClass = IPluginGeneratorConstructor & { prototype: IPluginGenerator; }; interface GeneratorConfig { input: string; output: string; clientName?: string; validateInput?: (spec: SwaggerSpec) => boolean; options: { dateType: "string" | "Date"; enumStyle: "enum" | "union"; generateServices?: boolean; generateEnumBasedOnDescription?: boolean; customHeaders?: Record<string, string>; responseTypeMapping?: { [contentType: string]: "json" | "blob" | "arraybuffer" | "text"; }; customizeMethodName?: (operationId: string) => string; }; compilerOptions?: { declaration?: boolean; target?: ScriptTarget; module?: ModuleKind; strict?: boolean; }; plugins?: (new (...args: any) => IPluginGenerator)[]; } interface NgOpenapiClientConfig { clientName: string; basePath: string; enableDateTransform?: boolean; interceptors?: (new (...args: HttpInterceptor[]) => HttpInterceptor)[]; } declare function camelCase(str: string): string; declare function kebabCase(str: string): string; declare function pascalCase(str: string): string; /** * Convert OpenAPI/Swagger types to TypeScript types * @param schemaOrType - Either a schema object or a type string * @param config - generator configuration * @param formatOrNullable - Either format string (if first param is string) or nullable boolean * @param isNullable - Nullable boolean (only used if first param is string) * @param context - Whether this is for type generation or service generation */ declare function getTypeScriptType(schemaOrType: TypeSchema | string | undefined, config: GeneratorConfig, formatOrNullable?: string | boolean, isNullable?: boolean, context?: "type" | "service"): string; declare function nullableType(type: string, isNullable?: boolean): string; declare function escapeString(str: string): string; type placeHolder = {}; declare function collectUsedTypes(operations: PathInfo[]): Set<string>; declare function getClientContextTokenName(clientName?: string): string; declare function getBasePathTokenName(clientName?: string): string; declare function hasDuplicateFunctionNames<T extends MethodDeclaration | FunctionDeclaration>(arr: T[]): boolean; declare function extractPaths(swaggerPaths?: { [p: string]: Path; }, methods?: string[]): PathInfo[]; declare function getResponseTypeFromResponse(response: SwaggerResponse, responseTypeMapping?: { [p: string]: "json" | "blob" | "arraybuffer" | "text"; }): "json" | "blob" | "arraybuffer" | "text"; declare function isPrimitiveType(schema: any): boolean; declare function inferResponseTypeFromContentType(contentType: string): "json" | "blob" | "arraybuffer" | "text"; declare function getResponseType(response: SwaggerResponse, config: GeneratorConfig): string; declare const TYPE_GENERATOR_HEADER_COMMENT: string; declare const SERVICE_INDEX_GENERATOR_HEADER_COMMENT: string; declare const SERVICE_GENERATOR_HEADER_COMMENT: (controllerName: string) => string; declare const MAIN_INDEX_GENERATOR_HEADER_COMMENT: string; declare const PROVIDER_GENERATOR_HEADER_COMMENT: string; declare const BASE_INTERCEPTOR_HEADER_COMMENT: (clientName: string) => string; declare const HTTP_RESOURCE_GENERATOR_HEADER_COMMENT: (resourceName: string) => string; /** * Validates input (file or URL) */ declare function validateInput(inputPath: string): void; /** * Generates Angular services and types from a configuration object */ declare function generateFromConfig(config: GeneratorConfig): Promise<void>; export { BASE_INTERCEPTOR_HEADER_COMMENT, type EnumValueObject, type GeneratorConfig, type GetMethodGenerationContext, HTTP_RESOURCE_GENERATOR_HEADER_COMMENT, type IPluginGenerator, type IPluginGeneratorClass, type IPluginGeneratorConstructor, MAIN_INDEX_GENERATOR_HEADER_COMMENT, type MethodGenerationContext, type NgOpenapiClientConfig, PROVIDER_GENERATOR_HEADER_COMMENT, type Parameter, type PathInfo, type RequestBody, SERVICE_GENERATOR_HEADER_COMMENT, SERVICE_INDEX_GENERATOR_HEADER_COMMENT, type SwaggerDefinition, SwaggerParser, type SwaggerResponse, type SwaggerSpec, TYPE_GENERATOR_HEADER_COMMENT, type TypeSchema, camelCase, collectUsedTypes, escapeString, extractPaths, generateFromConfig, getBasePathTokenName, getClientContextTokenName, getResponseType, getResponseTypeFromResponse, getTypeScriptType, hasDuplicateFunctionNames, inferResponseTypeFromContentType, isPrimitiveType, kebabCase, nullableType, pascalCase, type placeHolder, validateInput };