UNPKG

@kubb/plugin-oas

Version:

OpenAPI Specification (OAS) plugin for Kubb, providing core functionality for parsing and processing OpenAPI/Swagger schemas for code generation.

420 lines (419 loc) • 17.1 kB
import { t as __name } from "./chunk--u3MIqq1.js"; import { i as SchemaKeywordMapper, t as Schema } from "./SchemaMapper-SneuY1wg.js"; import { HttpMethod, Oas, Operation, SchemaObject, contentType } from "@kubb/oas"; import { AsyncEventEmitter, Config, FileMetaBase, Group, KubbEvents, Output, Plugin, PluginFactoryOptions, PluginManager, ResolveNameParams } from "@kubb/core"; import { KubbFile } from "@kubb/fabric-core/types"; import { OperationNode, SchemaNode } from "@kubb/ast/types"; import { Fabric, FabricReactNode } from "@kubb/react-fabric/types"; //#region src/types.d.ts type GetOasOptions = { validate?: boolean; }; type Context$2 = { getOas(options?: GetOasOptions): Promise<Oas>; getBaseURL(): Promise<string | undefined>; }; declare global { namespace Kubb { interface PluginContext extends Context$2 {} } } type ResolvePathOptions = { pluginKey?: Plugin['key']; group?: { tag?: string; path?: string; }; type?: ResolveNameParams['type']; }; type Options = { /** * Validate your input(see kubb.config) based on '@apidevtools/swagger-parser'. * @default true */ validate?: boolean; /** * Specify the export location for the files and define the behavior of the output * @default { path: 'schemas', barrelType: 'named' } */ output?: Output<Oas>; /** * Group the JSON files based on the provided name. */ group?: Group; /** * Which server to use from the array of `servers.url[serverIndex]` * @example * - `0` returns `http://petstore.swagger.io/api` * - `1` returns `http://localhost:3000` */ serverIndex?: number; /** * Override OpenAPI server variables when resolving the base URL. * * When `serverIndex` is set and the selected server URL contains `{variable}` placeholders * (as defined in the OpenAPI `servers[].variables` object), these values will be substituted. * Any variable not provided here falls back to its `default` value from the specification. * * @example * Given an OpenAPI spec with: * ```yaml * servers: * - url: https://api.{env}.example.com * variables: * env: * default: dev * enum: [dev, staging, prod] * ``` * * ```ts * pluginOas({ * serverIndex: 0, * serverVariables: { env: 'prod' }, * }) * ``` * Results in baseURL: `https://api.prod.example.com` */ serverVariables?: Record<string, string>; /** * Define which contentType should be used. * By default, uses the first valid JSON media type. */ contentType?: contentType; /** * Defines how the discriminator value should be interpreted during processing. * - 'strict' uses the oneOf schemas as defined, without modification. * - 'inherit' replaces the oneOf schema with the schema referenced by discriminator.mapping[key]. * @default 'strict' * @see https://github.com/kubb-labs/kubb/issues/1736 */ discriminator?: 'strict' | 'inherit'; /** * Override some behavior of the Oas class instance, see '@kubb/oas' */ oasClass?: typeof Oas; /** * Define some generators next to the JSON generation */ generators?: Array<Generator<PluginOas>>; /** * Resolve name collisions when schemas from different components share the same name (case-insensitive). * * When enabled, Kubb automatically detects and resolves collisions using intelligent suffixes: * - Cross-component collisions: Adds semantic suffixes based on the component type (Schema/Response/Request) * - Same-component collisions: Adds numeric suffixes (2, 3, ...) for case-insensitive duplicates * - Nested enum collisions: Includes root schema name in enum names to prevent duplicates across schemas * * When disabled (legacy behavior), collisions may result in duplicate files or overwrite issues. * * **Cross-component collision example:** * If you have "Order" in both schemas and requestBodies: * - With `collisionDetection: true`: Generates `OrderSchema.ts`, `OrderRequest.ts` * - With `collisionDetection: false`: May generate duplicate `Order.ts` files * * **Same-component collision example:** * If you have "Variant" and "variant" in schemas: * - With `collisionDetection: true`: Generates `Variant.ts`, `Variant2.ts` * - With `collisionDetection: false`: May overwrite or create duplicates * * **Nested enum collision example:** * If you have "params.channel" enum in both "NotificationTypeA" and "NotificationTypeB": * - With `collisionDetection: true`: Generates `notificationTypeAParamsChannelEnum`, `notificationTypeBParamsChannelEnum` * - With `collisionDetection: false`: Generates duplicate `paramsChannelEnum` in both files * * @default false (will be `true` in v5) * @see https://github.com/kubb-labs/kubb/issues/1999 * @note In Kubb v5, this will be enabled by default and the deprecated `usedEnumNames` mechanism will be removed */ collisionDetection?: boolean; }; /** * `propertyName` is the ref name + resolved with the nameResolver * @example import { Pet } from './Pet' * * `originalName` is the original name used(in PascalCase), only used to remove duplicates * * `pluginKey` can be used to override the current plugin being used, handy when you want to import a type/schema out of another plugin * @example import a type(plugin-ts) for a mock file(swagger-faker) */ type Ref = { propertyName: string; originalName: string; path: KubbFile.Path; pluginKey?: Plugin['key']; }; type Refs = Record<string, Ref>; type Resolver = { /** * Original name or name resolved by `resolveName({ name: operation?.getOperationId() as string, pluginName })` */ name: string; baseName: KubbFile.BaseName; path: KubbFile.Path; }; type OperationSchema = { /** * Converted name, contains already `PathParams`, `QueryParams`, ... */ name: string; schema: SchemaObject; operation?: Operation; /** * OperationName in PascalCase, only being used in OperationGenerator */ operationName: string; description?: string; statusCode?: number; keys?: string[]; keysToOmit?: string[]; withData?: boolean; }; type OperationSchemas = { pathParams?: OperationSchema & { keysToOmit?: never; }; queryParams?: OperationSchema & { keysToOmit?: never; }; headerParams?: OperationSchema & { keysToOmit?: never; }; request?: OperationSchema; response: OperationSchema; responses: Array<OperationSchema>; statusCodes?: Array<OperationSchema>; errors?: Array<OperationSchema>; }; type ByTag = { type: 'tag'; pattern: string | RegExp; }; type ByOperationId = { type: 'operationId'; pattern: string | RegExp; }; type ByPath = { type: 'path'; pattern: string | RegExp; }; type ByMethod = { type: 'method'; pattern: HttpMethod | RegExp; }; type BySchemaName = { type: 'schemaName'; pattern: string | RegExp; }; type ByContentType = { type: 'contentType'; pattern: string | RegExp; }; type Exclude = ByTag | ByOperationId | ByPath | ByMethod | ByContentType; type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType; type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & { options: Partial<TOptions>; }; type ResolvedOptions = Options & { output: Output<Oas>; }; type PluginOas = PluginFactoryOptions<'plugin-oas', Options, ResolvedOptions, Context$2, ResolvePathOptions>; //#endregion //#region src/OperationGenerator.d.ts type OperationMethodResult<TFileMeta extends FileMetaBase> = Promise<KubbFile.File<TFileMeta> | Array<KubbFile.File<TFileMeta>> | null>; type Context$1<TOptions, TPluginOptions extends PluginFactoryOptions> = { fabric: Fabric; oas: Oas; exclude: Array<Exclude> | undefined; include: Array<Include> | undefined; override: Array<Override<TOptions>> | undefined; contentType: contentType | undefined; pluginManager: PluginManager; events?: AsyncEventEmitter<KubbEvents>; /** * Current plugin */ plugin: Plugin<TPluginOptions>; mode: KubbFile.Mode; UNSTABLE_NAMING?: true; }; declare class OperationGenerator<TPluginOptions extends PluginFactoryOptions = PluginFactoryOptions, TFileMeta extends FileMetaBase = FileMetaBase> { #private; constructor(options: TPluginOptions['resolvedOptions'], context: Context$1<TPluginOptions['resolvedOptions'], TPluginOptions>); get options(): TPluginOptions['resolvedOptions']; set options(options: TPluginOptions['resolvedOptions']); get context(): Context$1<TPluginOptions['resolvedOptions'], TPluginOptions>; getOptions(operation: Operation, method: HttpMethod): Partial<TPluginOptions['resolvedOptions']>; getSchemas(operation: Operation, { resolveName }?: { resolveName?: (name: string) => string; }): OperationSchemas; getOperations(): Promise<Array<{ path: string; method: HttpMethod; operation: Operation; }>>; build(...generators: Array<Generator<TPluginOptions, Version>>): Promise<Array<KubbFile.File<TFileMeta>>>; } //#endregion //#region src/SchemaGenerator.d.ts type GetSchemaGeneratorOptions<T extends SchemaGenerator<any, any, any>> = T extends SchemaGenerator<infer Options, any, any> ? Options : never; type SchemaMethodResult<TFileMeta extends FileMetaBase> = Promise<KubbFile.File<TFileMeta> | Array<KubbFile.File<TFileMeta>> | null>; type Context<TOptions, TPluginOptions extends PluginFactoryOptions> = { fabric: Fabric; oas: Oas; pluginManager: PluginManager; events?: AsyncEventEmitter<KubbEvents>; /** * Current plugin */ plugin: Plugin<TPluginOptions>; mode: KubbFile.Mode; include?: Array<'schemas' | 'responses' | 'requestBodies'>; override: Array<Override<TOptions>> | undefined; contentType?: contentType; output?: string; }; type SchemaGeneratorOptions = { dateType: false | 'string' | 'stringOffset' | 'stringLocal' | 'date'; integerType?: 'number' | 'bigint'; unknownType: 'any' | 'unknown' | 'void'; emptySchemaType: 'any' | 'unknown' | 'void'; enumType?: 'enum' | 'asConst' | 'asPascalConst' | 'constEnum' | 'literal' | 'inlineLiteral'; enumSuffix?: string; /** * @deprecated Will be removed in v5. Use `collisionDetection: true` instead to prevent enum name collisions. * When `collisionDetection` is enabled, the rootName-based approach eliminates the need for numeric suffixes. * @internal */ usedEnumNames?: Record<string, number>; mapper?: Record<string, string>; typed?: boolean; transformers: { /** * Customize the names based on the type that is provided by the plugin. */ name?: (name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string; /** * Receive schema and name(propertyName) and return Schema array. * Return `undefined` to fall through to default schema generation. * @beta */ schema?: (schemaProps: SchemaProps$1, defaultSchemas: Schema[]) => Array<Schema> | undefined; }; }; type SchemaGeneratorBuildOptions = Omit<OperationSchema, 'name' | 'schema'>; type SchemaProps$1 = { schema: SchemaObject | null; name: string | null; parentName: string | null; rootName?: string | null; }; declare class SchemaGenerator<TOptions extends SchemaGeneratorOptions = SchemaGeneratorOptions, TPluginOptions extends PluginFactoryOptions = PluginFactoryOptions, TFileMeta extends FileMetaBase = FileMetaBase> { #private; constructor(options: TOptions, context: Context<TOptions, TPluginOptions>); get options(): TOptions; set options(options: TOptions); get context(): Context<TOptions, TPluginOptions>; refs: Refs; /** * Creates a type node from a given schema. * Delegates to getBaseTypeFromSchema internally and * optionally adds a union with null. */ parse(props: SchemaProps$1): Schema[]; static deepSearch<T extends keyof SchemaKeywordMapper>(tree: Schema[] | undefined, keyword: T): Array<SchemaKeywordMapper[T]>; static find<T extends keyof SchemaKeywordMapper>(tree: Schema[] | undefined, keyword: T): SchemaKeywordMapper[T] | undefined; static combineObjects(tree: Schema[] | undefined): Schema[]; build(...generators: Array<Generator<TPluginOptions, Version>>): Promise<Array<KubbFile.File<TFileMeta>>>; } //#endregion //#region src/generators/createReactGenerator.d.ts type UserGenerator$1<TOptions extends PluginFactoryOptions, TVersion extends Version> = { name: string; version?: TVersion; Operations?: (props: OperationsProps<TOptions, TVersion>) => FabricReactNode; Operation?: (props: OperationProps<TOptions, TVersion>) => FabricReactNode; Schema?: (props: SchemaProps<TOptions, TVersion>) => FabricReactNode; }; type ReactGenerator<TOptions extends PluginFactoryOptions, TVersion extends Version> = { name: string; type: 'react'; version: TVersion; Operations: (props: OperationsProps<TOptions, TVersion>) => FabricReactNode; Operation: (props: OperationProps<TOptions, TVersion>) => FabricReactNode; Schema: (props: SchemaProps<TOptions, TVersion>) => FabricReactNode; }; /**** * Creates a generator that uses React component functions to generate files for OpenAPI operations and schemas. * * The returned generator exposes async methods for generating files from operations, a single operation, or a schema, using the corresponding React components if provided. If a component is not defined, the method returns an empty array. * * @returns A generator object with async methods for operations, operation, and schema file generation. */ declare function createReactGenerator<TOptions extends PluginFactoryOptions, TVersion extends Version = '1'>(generator: UserGenerator$1<TOptions, TVersion>): ReactGenerator<TOptions, TVersion>; //#endregion //#region src/generators/types.d.ts type Version = '1' | '2'; type OperationsV1Props<TOptions extends PluginFactoryOptions> = { config: Config; generator: Omit<OperationGenerator<TOptions>, 'build'>; plugin: Plugin<TOptions>; operations: Array<Operation>; }; type OperationsV2Props<TOptions extends PluginFactoryOptions> = { config: Config; plugin: Plugin<TOptions>; nodes: Array<OperationNode>; }; type OperationV1Props<TOptions extends PluginFactoryOptions> = { config: Config; generator: Omit<OperationGenerator<TOptions>, 'build'>; plugin: Plugin<TOptions>; operation: Operation; }; type OperationV2Props<TOptions extends PluginFactoryOptions> = { config: Config; plugin: Plugin<TOptions>; node: OperationNode; }; type OperationsProps<TOptions extends PluginFactoryOptions, TVersion extends Version = '1'> = TVersion extends '2' ? OperationsV2Props<TOptions> : OperationsV1Props<TOptions>; type OperationProps<TOptions extends PluginFactoryOptions, TVersion extends Version = '1'> = TVersion extends '2' ? OperationV2Props<TOptions> : OperationV1Props<TOptions>; type SchemaV1Props<TOptions extends PluginFactoryOptions> = { config: Config; generator: Omit<SchemaGenerator<SchemaGeneratorOptions, TOptions>, 'build'>; plugin: Plugin<TOptions>; schema: { name: string; tree: Array<Schema>; value: SchemaObject; }; }; type SchemaV2Props<TOptions extends PluginFactoryOptions> = { config: Config; plugin: Plugin<TOptions>; node: SchemaNode; }; type SchemaProps<TOptions extends PluginFactoryOptions, TVersion extends Version = '1'> = TVersion extends '2' ? SchemaV2Props<TOptions> : SchemaV1Props<TOptions>; type Generator<TOptions extends PluginFactoryOptions, TVersion extends Version = Version> = CoreGenerator<TOptions, TVersion> | ReactGenerator<TOptions, TVersion>; //#endregion //#region src/generators/createGenerator.d.ts type UserGenerator<TOptions extends PluginFactoryOptions, TVersion extends Version> = { name: string; version?: TVersion; operations?: (props: OperationsProps<TOptions, TVersion>) => Promise<KubbFile.File[]>; operation?: (props: OperationProps<TOptions, TVersion>) => Promise<KubbFile.File[]>; schema?: (props: SchemaProps<TOptions, TVersion>) => Promise<KubbFile.File[]>; }; type CoreGenerator<TOptions extends PluginFactoryOptions, TVersion extends Version> = { name: string; type: 'core'; version: TVersion; operations: (props: OperationsProps<TOptions, TVersion>) => Promise<KubbFile.File[]>; operation: (props: OperationProps<TOptions, TVersion>) => Promise<KubbFile.File[]>; schema: (props: SchemaProps<TOptions, TVersion>) => Promise<KubbFile.File[]>; }; declare function createGenerator<TOptions extends PluginFactoryOptions, TVersion extends Version = '1'>(generator: UserGenerator<TOptions, TVersion>): CoreGenerator<TOptions, TVersion>; //#endregion export { ResolvePathOptions as C, Refs as S, OperationSchemas as _, ReactGenerator as a, PluginOas as b, SchemaGenerator as c, SchemaMethodResult as d, OperationGenerator as f, OperationSchema as g, Include as h, Version as i, SchemaGeneratorBuildOptions as l, Exclude as m, createGenerator as n, createReactGenerator as o, OperationMethodResult as p, Generator as r, GetSchemaGeneratorOptions as s, CoreGenerator as t, SchemaGeneratorOptions as u, Options as v, Resolver as w, Ref as x, Override as y }; //# sourceMappingURL=createGenerator-W6EtzLmf.d.ts.map