@kubb/swagger
Advanced tools
Comparing version
@@ -1,135 +0,27 @@ | ||
import { PluginFactoryOptions, KubbFile, KubbPlugin, ResolveNameParams, PluginContext, ResolvePathParams } from '@kubb/core'; | ||
import Oas from 'oas'; | ||
import { OpenAPIV3 } from 'openapi-types'; | ||
import Operation from 'oas/operation'; | ||
import { KubbFile, ResolveNameParams, KubbPlugin } from '@kubb/core'; | ||
import { Operation } from 'oas/operation'; | ||
import { O as OperationSchemas } from './types-BaLUOV9R.js'; | ||
import 'oas/types'; | ||
type Mode = 'schemas' | 'responses' | 'requestBodies'; | ||
type GetSchemasProps = { | ||
oas: Oas; | ||
contentType?: ContentType; | ||
includes?: Mode[]; | ||
}; | ||
declare function useOas(): Oas; | ||
type ContentType = 'application/json' | (string & {}); | ||
type ResolvePathOptions = { | ||
declare function useOperation(): Operation; | ||
type UseOperationNameProps = { | ||
type: NonNullable<ResolveNameParams['type']>; | ||
pluginKey?: KubbPlugin['key']; | ||
tag?: string; | ||
type?: ResolveNameParams['type']; | ||
}; | ||
type API = { | ||
getOas: () => Promise<Oas>; | ||
getSchemas: (options?: Pick<GetSchemasProps, 'includes'>) => Promise<Record<string, OpenAPIV3.SchemaObject>>; | ||
getBaseURL: () => Promise<string | undefined>; | ||
contentType?: ContentType; | ||
}; | ||
type Options = { | ||
/** | ||
* Validate your input(see kubb.config) based on @apidevtools/swagger-parser | ||
* @default true | ||
*/ | ||
validate?: boolean; | ||
/** | ||
* Relative path to save the JSON models. | ||
* False will not generate the schema JSON's. | ||
* @default 'schemas' | ||
*/ | ||
output?: string | false; | ||
/** | ||
* Which server to use from the array of `servers.url[serverIndex]` | ||
* @example `0` will return `http://petstore.swagger.io/api` and `1` will return `http://localhost:3000` | ||
* servers: | ||
- url: http://petstore.swagger.io/api | ||
- url: http://localhost:3000 | ||
* @default 0 | ||
*/ | ||
serverIndex?: number; | ||
/** | ||
* Override ContentType that will be used for requests and responses. | ||
*/ | ||
contentType?: ContentType; | ||
}; | ||
type PluginOptions = PluginFactoryOptions<'swagger', 'schema', Options, false, API>; | ||
type Resolver = { | ||
/** | ||
* Original name or name resolved by `resolveName({ name: operation?.getOperationId() as string, pluginName })` | ||
*/ | ||
declare function useOperationName({ type, ...rest }: UseOperationNameProps): string; | ||
type FileMeta = KubbFile.FileMetaBase & { | ||
pluginKey: KubbPlugin['key']; | ||
name: string; | ||
baseName: KubbFile.BaseName; | ||
path: KubbFile.Path; | ||
tag?: string; | ||
}; | ||
type OperationSchema = { | ||
/** | ||
* Converted name, contains already `PathParams`, `QueryParams`, ... | ||
*/ | ||
name: string; | ||
/** | ||
* OperationName in PascalCase, only being used in OperationGenerator | ||
*/ | ||
operationName?: string; | ||
description?: string; | ||
schema: OpenAPIV3.SchemaObject & { | ||
$ref?: OpenAPIV3.ReferenceObject['$ref']; | ||
}; | ||
statusCode?: number; | ||
keys?: string[]; | ||
keysToOmit?: string[]; | ||
}; | ||
type OperationSchemas = { | ||
pathParams?: OperationSchema & { | ||
keysToOmit?: never; | ||
}; | ||
queryParams?: OperationSchema & { | ||
keysToOmit?: never; | ||
}; | ||
headerParams?: OperationSchema & { | ||
keysToOmit?: never; | ||
}; | ||
request?: OperationSchema; | ||
response: OperationSchema; | ||
errors?: Array<OperationSchema>; | ||
}; | ||
declare module '@kubb/core' { | ||
interface _Register { | ||
['@kubb/swagger']: PluginOptions; | ||
} | ||
} | ||
type PropsWithOperation = { | ||
operation: Operation; | ||
/** | ||
* @default `operation.getOperationId()` | ||
*/ | ||
name?: string; | ||
}; | ||
type PropsWithoutOperation = { | ||
operation?: never; | ||
/** | ||
* @default `operation.getOperationId()` | ||
*/ | ||
name: string; | ||
}; | ||
type ResolveProps = (PropsWithOperation | PropsWithoutOperation) & { | ||
type UseOperationFileProps = { | ||
pluginKey?: KubbPlugin['key']; | ||
/** | ||
* @default `operation.getTags()[0]?.name` | ||
*/ | ||
tag?: string; | ||
resolvePath: PluginContext<ResolvePathOptions>['resolvePath']; | ||
resolveName: PluginContext['resolveName']; | ||
type?: ResolveNameParams['type']; | ||
}; | ||
declare function useOperationFile(props?: UseOperationFileProps): KubbFile.File<FileMeta>; | ||
declare function useOperation(): Operation; | ||
type UseResolveProps = Omit<ResolveProps, 'operation' | 'resolvePath' | 'resolveName'> & { | ||
resolvePath?: PluginContext['resolvePath']; | ||
resolveName?: PluginContext['resolveName']; | ||
}; | ||
declare function useResolvePath(props: ResolvePathParams): KubbFile.OptionalPath; | ||
declare function useResolveName(props: Partial<ResolveNameParams>): string; | ||
declare function useResolve(props?: UseResolveProps): Resolver; | ||
declare function useSchemas(): OperationSchemas; | ||
export { UseResolveProps, useOperation, useResolve, useResolveName, useResolvePath, useSchemas }; | ||
export { useOas, useOperation, useOperationFile, useOperationName, useSchemas }; |
import { createRequire } from 'module'; | ||
import { useApp, usePluginManager } from '@kubb/react'; | ||
import './chunk-PUSDFDIP.js'; | ||
import { useApp, usePlugin, usePluginManager, useFile } from '@kubb/react'; | ||
createRequire(import.meta.url); | ||
function useOas() { | ||
const { meta } = useApp(); | ||
return meta.oas; | ||
} | ||
function useOperation() { | ||
@@ -9,47 +14,25 @@ const { meta } = useApp(); | ||
} | ||
// src/resolve.ts | ||
function resolve({ operation, name, tag, type, pluginKey, resolveName, resolvePath }) { | ||
if (!name && !operation?.getOperationId()) { | ||
throw new Error("name or operation should be set"); | ||
} | ||
const resolvedName = name ? name : resolveName({ name: operation?.getOperationId(), type, pluginKey }); | ||
if (!resolvedName) { | ||
throw new Error(`Name ${name || operation?.getOperationId()} should be defined`); | ||
} | ||
const baseName = `${resolvedName}.ts`; | ||
const path = resolvePath({ | ||
baseName, | ||
pluginKey, | ||
options: { pluginKey, type, tag: tag || operation?.getTags()[0]?.name } | ||
}); | ||
if (!path) { | ||
throw new Error(`Filepath should be defined for resolvedName "${resolvedName}" and pluginKey [${JSON.stringify(pluginKey)}]`); | ||
} | ||
return { | ||
name: resolvedName, | ||
baseName, | ||
path | ||
}; | ||
} | ||
// src/hooks/useResolve.ts | ||
function useResolvePath(props) { | ||
function useOperationName({ type, ...rest }) { | ||
const plugin = usePlugin(); | ||
const pluginManager = usePluginManager(); | ||
return pluginManager.resolvePath(props); | ||
} | ||
function useResolveName(props) { | ||
const pluginManager = usePluginManager(); | ||
const operation = useOperation(); | ||
return pluginManager.resolveName({ ...props, name: props.name || operation?.getOperationId() }); | ||
const pluginKey = rest.pluginKey || plugin.key; | ||
return pluginManager.resolveName({ name: operation.getOperationId(), pluginKey, type }); | ||
} | ||
function useResolve(props = {}) { | ||
function useOperationFile(props = {}) { | ||
const plugin = usePlugin(); | ||
const operation = useOperation(); | ||
const pluginManager = usePluginManager(); | ||
return resolve({ | ||
operation, | ||
...props, | ||
resolvePath: props.resolvePath || pluginManager.resolvePath, | ||
resolveName: props.resolveName || pluginManager.resolveName | ||
}); | ||
const pluginKey = props.pluginKey || plugin.key; | ||
const tag = operation?.getTags().at(0)?.name; | ||
const name = useOperationName({ type: "file", pluginKey }); | ||
const file = useFile({ name, pluginKey, options: { type: "file", pluginKey, tag } }); | ||
return { | ||
...file, | ||
meta: { | ||
...file.meta, | ||
name, | ||
pluginKey, | ||
tag | ||
} | ||
}; | ||
} | ||
@@ -61,4 +44,4 @@ function useSchemas() { | ||
export { useOperation, useResolve, useResolveName, useResolvePath, useSchemas }; | ||
export { useOas, useOperation, useOperationFile, useOperationName, useSchemas }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=hooks.js.map |
import * as _kubb_core from '@kubb/core'; | ||
import { KubbPlugin, ResolveNameParams, PluginFactoryOptions, KubbFile, AppMeta as AppMeta$1, PluginManager, Generator, KubbConfig, PluginContext } from '@kubb/core'; | ||
import { PluginManager, KubbConfig, KubbFile, PluginFactoryOptions, Generator, KubbPlugin } from '@kubb/core'; | ||
import { P as PluginOptions, a as Options$1, b as OperationSchema, O as OperationSchemas, c as Paths, E as Exclude, I as Include, d as Override, C as ContentType } from './types-BaLUOV9R.js'; | ||
export { A as API, h as AppMeta, F as FileResolver, i as ImportMeta, e as Ref, f as Refs, R as ResolvePathOptions, g as Resolver } from './types-BaLUOV9R.js'; | ||
import Oas from 'oas'; | ||
export { default as Oas } from 'oas'; | ||
import Operation from 'oas/operation'; | ||
export { default as Operation } from 'oas/operation'; | ||
import { HttpMethods, OASDocument } from 'oas/rmoas.types'; | ||
export { HttpMethods as HttpMethod } from 'oas/rmoas.types'; | ||
import { OpenAPIV3 } from 'openapi-types'; | ||
export { OpenAPIV3 } from 'openapi-types'; | ||
import { OASDocument, HttpMethods } from 'oas/types'; | ||
import { Operation } from 'oas/operation'; | ||
type Mode = 'schemas' | 'responses' | 'requestBodies'; | ||
type GetSchemasProps = { | ||
oas: Oas; | ||
contentType?: ContentType; | ||
includes?: Mode[]; | ||
}; | ||
type ContentType = 'application/json' | (string & {}); | ||
type ResolvePathOptions = { | ||
pluginKey?: KubbPlugin['key']; | ||
tag?: string; | ||
type?: ResolveNameParams['type']; | ||
}; | ||
type API = { | ||
getOas: () => Promise<Oas>; | ||
getSchemas: (options?: Pick<GetSchemasProps, 'includes'>) => Promise<Record<string, OpenAPIV3.SchemaObject>>; | ||
getBaseURL: () => Promise<string | undefined>; | ||
contentType?: ContentType; | ||
}; | ||
type Options$2 = { | ||
/** | ||
* Validate your input(see kubb.config) based on @apidevtools/swagger-parser | ||
* @default true | ||
*/ | ||
validate?: boolean; | ||
/** | ||
* Relative path to save the JSON models. | ||
* False will not generate the schema JSON's. | ||
* @default 'schemas' | ||
*/ | ||
output?: string | false; | ||
/** | ||
* Which server to use from the array of `servers.url[serverIndex]` | ||
* @example `0` will return `http://petstore.swagger.io/api` and `1` will return `http://localhost:3000` | ||
* servers: | ||
- url: http://petstore.swagger.io/api | ||
- url: http://localhost:3000 | ||
* @default 0 | ||
*/ | ||
serverIndex?: number; | ||
/** | ||
* Override ContentType that will be used for requests and responses. | ||
*/ | ||
contentType?: ContentType; | ||
}; | ||
type PluginOptions = PluginFactoryOptions<'swagger', 'schema', Options$2, false, API>; | ||
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; | ||
/** | ||
* OperationName in PascalCase, only being used in OperationGenerator | ||
*/ | ||
operationName?: string; | ||
description?: string; | ||
schema: OpenAPIV3.SchemaObject & { | ||
$ref?: OpenAPIV3.ReferenceObject['$ref']; | ||
}; | ||
statusCode?: number; | ||
keys?: string[]; | ||
keysToOmit?: string[]; | ||
}; | ||
type OperationSchemas = { | ||
pathParams?: OperationSchema & { | ||
keysToOmit?: never; | ||
}; | ||
queryParams?: OperationSchema & { | ||
keysToOmit?: never; | ||
}; | ||
headerParams?: OperationSchema & { | ||
keysToOmit?: never; | ||
}; | ||
request?: OperationSchema; | ||
response: 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: HttpMethods | RegExp; | ||
}; | ||
type SkipBy = ByTag | ByOperationId | ByPath | ByMethod; | ||
type OverrideBy<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod) & { | ||
options: Partial<TOptions>; | ||
}; | ||
type AppMeta = AppMeta$1 & { | ||
schemas: OperationSchemas; | ||
operation: Operation; | ||
}; | ||
declare module '@kubb/core' { | ||
interface _Register { | ||
['@kubb/swagger']: PluginOptions; | ||
} | ||
} | ||
declare const pluginName = "swagger"; | ||
declare const pluginKey: PluginOptions['key']; | ||
declare const definePlugin: (options: Options$2) => _kubb_core.KubbUserPlugin<PluginOptions>; | ||
declare const definePlugin: (options: Options$1) => _kubb_core.KubbUserPluginWithLifeCycle<PluginOptions>; | ||
type FileResolver = (name: string, ref: Ref) => string | null | undefined; | ||
type Context$1 = { | ||
oas: Oas; | ||
pluginManager: PluginManager; | ||
plugin: KubbPlugin; | ||
operation: Operation; | ||
schemas: OperationSchemas; | ||
}; | ||
/** | ||
* Abstract class that contains the building blocks for creating an type/zod builder | ||
* Abstract class that contains the building blocks for creating a type/zod builder | ||
*/ | ||
@@ -151,37 +28,4 @@ declare abstract class OasBuilder<TOptions = unknown, TContext = Context$1> { | ||
add(item: OperationSchema | Array<OperationSchema | undefined> | undefined): this; | ||
abstract print(...rest: unknown[]): string; | ||
} | ||
/** | ||
* `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(swagger-ts) for a mock file(swagger-faker) | ||
*/ | ||
type Ref = { | ||
propertyName: string; | ||
originalName: string; | ||
pluginKey?: KubbPlugin['key']; | ||
}; | ||
type Refs = Record<string, Ref>; | ||
type Import = { | ||
refs: Refs; | ||
name: string; | ||
}; | ||
type ImportMeta = { | ||
ref: Ref; | ||
path: string; | ||
}; | ||
type Options$1 = { | ||
fileResolver?: FileResolver; | ||
}; | ||
declare class ImportsGenerator extends Generator<Options$1> { | ||
items: ImportMeta[]; | ||
add(item: ImportMeta | ImportMeta[] | undefined): ImportsGenerator; | ||
build(imports: Import[]): ImportMeta[]; | ||
} | ||
type Options = { | ||
@@ -198,8 +42,9 @@ validate?: boolean; | ||
type GetOperationGeneratorOptions<T extends OperationGenerator> = T extends OperationGenerator<infer X> ? X : never; | ||
type GetOperationGeneratorOptions<T extends OperationGenerator<any, any, any>> = T extends OperationGenerator<infer Options, any, any> ? Options : never; | ||
type OperationMethodResult<TFileMeta extends KubbFile.FileMetaBase> = Promise<KubbFile.File<TFileMeta> | Array<KubbFile.File<TFileMeta>> | null>; | ||
type Context<TOptions> = { | ||
type Context<TOptions, TPluginOptions extends PluginFactoryOptions> = { | ||
oas: Oas; | ||
skipBy: Array<SkipBy> | undefined; | ||
overrideBy?: Array<OverrideBy<TOptions>> | undefined; | ||
exclude: Array<Exclude> | undefined; | ||
include: Array<Include> | undefined; | ||
override: Array<Override<TOptions>> | undefined; | ||
contentType: ContentType | undefined; | ||
@@ -210,13 +55,9 @@ pluginManager: PluginManager; | ||
*/ | ||
plugin: KubbPlugin; | ||
plugin: KubbPlugin<TPluginOptions>; | ||
mode?: KubbFile.Mode; | ||
}; | ||
declare abstract class OperationGenerator<TOptions = unknown, TFileMeta extends KubbFile.FileMetaBase = KubbFile.FileMetaBase> extends Generator<TOptions, Context<TOptions>> { | ||
declare abstract class OperationGenerator<TOptions = unknown, TPluginOptions extends PluginFactoryOptions = PluginFactoryOptions, TFileMeta extends KubbFile.FileMetaBase = KubbFile.FileMetaBase> extends Generator<TOptions, Context<TOptions, TPluginOptions>> { | ||
#private; | ||
/** | ||
* Validate an operation to see if used with camelCase we don't overwrite other files | ||
* DRAFT version | ||
*/ | ||
validate(operation: Operation): void; | ||
isSkipped(operation: Operation, method: HttpMethods): boolean; | ||
isExcluded(operation: Operation, method: HttpMethods): boolean; | ||
isIncluded(operation: Operation, method: HttpMethods): boolean; | ||
getSchemas(operation: Operation): OperationSchemas; | ||
@@ -247,31 +88,5 @@ build(): Promise<Array<KubbFile.File<TFileMeta>>>; | ||
*/ | ||
abstract all(paths: Record<string, Record<HttpMethods, Operation>>): OperationMethodResult<TFileMeta>; | ||
abstract all(paths: Paths): OperationMethodResult<TFileMeta>; | ||
} | ||
type PropsWithOperation = { | ||
operation: Operation; | ||
/** | ||
* @default `operation.getOperationId()` | ||
*/ | ||
name?: string; | ||
}; | ||
type PropsWithoutOperation = { | ||
operation?: never; | ||
/** | ||
* @default `operation.getOperationId()` | ||
*/ | ||
name: string; | ||
}; | ||
type ResolveProps = (PropsWithOperation | PropsWithoutOperation) & { | ||
pluginKey?: KubbPlugin['key']; | ||
/** | ||
* @default `operation.getTags()[0]?.name` | ||
*/ | ||
tag?: string; | ||
resolvePath: PluginContext<ResolvePathOptions>['resolvePath']; | ||
resolveName: PluginContext['resolveName']; | ||
type?: ResolveNameParams['type']; | ||
}; | ||
declare function resolve({ operation, name, tag, type, pluginKey, resolveName, resolvePath }: ResolveProps): Resolver; | ||
export { API, AppMeta, ContentType, FileResolver, GetOperationGeneratorOptions, ImportMeta, ImportsGenerator, OasBuilder, OasManager, OperationGenerator, OperationMethodResult, OperationSchema, OperationSchemas, Options$2 as Options, OverrideBy, PluginOptions, Ref, Refs, ResolvePathOptions, ResolveProps, Resolver, SkipBy, definePlugin as default, definePlugin, pluginKey, pluginName, resolve }; | ||
export { ContentType, Exclude, type GetOperationGeneratorOptions, Include, OasBuilder, OasManager, OperationGenerator, type OperationMethodResult, OperationSchema, OperationSchemas, Options$1 as Options, Override, Paths, PluginOptions, definePlugin as default, definePlugin, pluginKey, pluginName }; |
import { createRequire } from 'module'; | ||
import { getSchemas, isReference, isOpenApiV3Document, convertSwagger2ToOpenApi } from './chunk-AWEHKPOS.js'; | ||
import { __privateAdd, __privateSet, __privateGet, __privateMethod } from './chunk-PUSDFDIP.js'; | ||
import path, { resolve } from 'path'; | ||
import { createPlugin, Generator, Warning, FileManager } from '@kubb/core'; | ||
import { createPlugin, Generator } from '@kubb/core'; | ||
import { URLPath } from '@kubb/core/utils'; | ||
@@ -9,84 +11,6 @@ import SwaggerParser from '@apidevtools/swagger-parser'; | ||
import OASNormalize from 'oas-normalize'; | ||
import swagger2openapi from 'swagger2openapi'; | ||
import { pascalCase, pascalCaseTransformMerge } from 'change-case'; | ||
import transformers from '@kubb/core/transformers'; | ||
import { findSchemaDefinition } from 'oas/utils'; | ||
createRequire(import.meta.url); | ||
var __accessCheck = (obj, member, msg) => { | ||
if (!member.has(obj)) | ||
throw TypeError("Cannot " + msg); | ||
}; | ||
var __privateGet = (obj, member, getter) => { | ||
__accessCheck(obj, member, "read from private field"); | ||
return getter ? getter.call(obj) : member.get(obj); | ||
}; | ||
var __privateAdd = (obj, member, value) => { | ||
if (member.has(obj)) | ||
throw TypeError("Cannot add the same private member more than once"); | ||
member instanceof WeakSet ? member.add(obj) : member.set(obj, value); | ||
}; | ||
var __privateSet = (obj, member, value, setter) => { | ||
__accessCheck(obj, member, "write to private field"); | ||
setter ? setter.call(obj, value) : member.set(obj, value); | ||
return value; | ||
}; | ||
var __privateMethod = (obj, member, method) => { | ||
__accessCheck(obj, member, "access private method"); | ||
return method; | ||
}; | ||
// src/utils/getSchemas.ts | ||
function getSchemas({ | ||
oas, | ||
contentType, | ||
includes = ["schemas", "requestBodies", "responses"] | ||
}) { | ||
const components = oas.getDefinition().components; | ||
let schemas = {}; | ||
if (includes.includes("schemas")) { | ||
schemas = { | ||
...schemas, | ||
...components?.schemas || {} | ||
}; | ||
} | ||
const requestBodies = components?.requestBodies || {}; | ||
if (includes.includes("responses")) { | ||
const responses = components?.responses || {}; | ||
Object.entries(responses).forEach(([name, response]) => { | ||
if (response.content && !schemas[name]) { | ||
const firstContentType = Object.keys(response.content)[0] || "application/json"; | ||
schemas[name] = response.content?.[contentType || firstContentType]?.schema; | ||
} | ||
}); | ||
} | ||
if (includes.includes("requestBodies")) { | ||
Object.entries(requestBodies).forEach(([name, request]) => { | ||
if (request.content && !schemas[name]) { | ||
const firstContentType = Object.keys(request.content)[0] || "application/json"; | ||
schemas[name] = request.content?.[contentType || firstContentType]?.schema; | ||
} | ||
}); | ||
} | ||
return schemas; | ||
} | ||
function convertSwagger2ToOpenApi(document) { | ||
const options = { anchors: true }; | ||
return new Promise((resolve3, reject) => { | ||
swagger2openapi.convertObj(document, options, (err, value) => { | ||
if (err) { | ||
reject(err); | ||
} else { | ||
resolve3(value.openapi); | ||
} | ||
}); | ||
}); | ||
} | ||
// src/utils/isOpenApiV3Document.ts | ||
function isOpenApiV3Document(doc) { | ||
return "openapi" in doc; | ||
} | ||
// src/OasManager.ts | ||
var _options, _oas; | ||
@@ -143,5 +67,5 @@ var _OasManager = class _OasManager { | ||
var pluginName = "swagger"; | ||
var pluginKey = ["schema", pluginName]; | ||
var pluginKey = [pluginName]; | ||
var definePlugin = createPlugin((options) => { | ||
const { output = "schemas", validate = true, serverIndex = 0, contentType } = options; | ||
const { output = { path: "schemas" }, validate = true, serverIndex = 0, contentType } = options; | ||
const getOas = async (config, logger) => { | ||
@@ -160,3 +84,2 @@ try { | ||
options, | ||
kind: "schema", | ||
api() { | ||
@@ -185,3 +108,3 @@ const { config, logger } = this; | ||
const root = path.resolve(this.config.root, this.config.output.path); | ||
return path.resolve(root, output, baseName); | ||
return path.resolve(root, output.path, baseName); | ||
}, | ||
@@ -192,3 +115,3 @@ async writeFile(source, writePath) { | ||
} | ||
return this.fileManager.write(source, writePath); | ||
return this.fileManager.write(source, writePath, { sanity: false }); | ||
}, | ||
@@ -224,47 +147,2 @@ async buildStart() { | ||
}); | ||
var ImportsGenerator = class extends Generator { | ||
constructor() { | ||
super(...arguments); | ||
this.items = []; | ||
} | ||
add(item) { | ||
if (!item) { | ||
return this; | ||
} | ||
if (Array.isArray(item)) { | ||
item.forEach((it) => this.items.push(it)); | ||
return this; | ||
} | ||
this.items.push(item); | ||
return this; | ||
} | ||
build(imports) { | ||
const refs = imports.reduce((acc, currentValue) => { | ||
return { | ||
...acc, | ||
...currentValue.refs | ||
}; | ||
}, {}); | ||
if (Object.keys(refs).length === 0) { | ||
return this.items; | ||
} | ||
const importMeta = [...new Set(Object.keys(refs))].map(($ref) => { | ||
const ref = refs[$ref]; | ||
const { propertyName, originalName } = ref; | ||
const exists = imports.some((item) => item.name.toLowerCase() === originalName.toLowerCase()); | ||
if (exists) { | ||
return void 0; | ||
} | ||
const path2 = this.options.fileResolver?.(propertyName, ref) || `./${propertyName}`; | ||
if (path2 === "./" || path2 === ".") { | ||
return void 0; | ||
} | ||
return { | ||
ref: refs[$ref], | ||
path: path2.replace("./../", "../") | ||
}; | ||
}).filter(Boolean); | ||
return [...importMeta, ...this.items]; | ||
} | ||
}; | ||
@@ -309,9 +187,2 @@ // src/OasBuilder.ts | ||
_context = new WeakMap(); | ||
// src/utils/isReference.ts | ||
function isReference(obj) { | ||
return obj && "$ref" in obj; | ||
} | ||
// src/OperationGenerator.ts | ||
var _getOptions, getOptions_fn, _getParametersSchema, getParametersSchema_fn, _getResponseSchema, getResponseSchema_fn, _getRequestSchema, getRequestSchema_fn, _methods, methods_get; | ||
@@ -327,34 +198,39 @@ var OperationGenerator = class extends Generator { | ||
} | ||
/** | ||
* Validate an operation to see if used with camelCase we don't overwrite other files | ||
* DRAFT version | ||
*/ | ||
validate(operation) { | ||
const { oas } = this.context; | ||
const schemas = oas.getDefinition().components?.schemas || {}; | ||
const foundSchemaKey = Object.keys(schemas).find( | ||
(key) => key.toLowerCase() === pascalCase(operation.getOperationId(), { delimiter: "", transform: pascalCaseTransformMerge }).toLowerCase() | ||
); | ||
if (foundSchemaKey) { | ||
throw new Warning(`OperationId '${operation.getOperationId()}' has the same name used as in schemas '${foundSchemaKey}' when using CamelCase`); | ||
} | ||
isExcluded(operation, method) { | ||
const { exclude = [] } = this.context; | ||
let matched = false; | ||
exclude.forEach(({ pattern, type }) => { | ||
if (type === "tag" && !matched) { | ||
matched = !!operation.getTags()[0]?.name.match(pattern); | ||
} | ||
if (type === "operationId" && !matched) { | ||
matched = !!operation.getOperationId().match(pattern); | ||
} | ||
if (type === "path" && !matched) { | ||
matched = !!operation.path.match(pattern); | ||
} | ||
if (type === "method" && !matched) { | ||
matched = !!method.match(pattern); | ||
} | ||
}); | ||
return matched; | ||
} | ||
isSkipped(operation, method) { | ||
const { skipBy = [] } = this.context; | ||
let skip = false; | ||
skipBy.forEach(({ pattern, type }) => { | ||
if (type === "tag" && !skip) { | ||
skip = !!operation.getTags()[0]?.name.match(pattern); | ||
isIncluded(operation, method) { | ||
const { include = [] } = this.context; | ||
let matched = false; | ||
include.forEach(({ pattern, type }) => { | ||
if (type === "tag" && !matched) { | ||
matched = !!operation.getTags()[0]?.name.match(pattern); | ||
} | ||
if (type === "operationId" && !skip) { | ||
skip = !!operation.getOperationId().match(pattern); | ||
if (type === "operationId" && !matched) { | ||
matched = !!operation.getOperationId().match(pattern); | ||
} | ||
if (type === "path" && !skip) { | ||
skip = !!operation.path.match(pattern); | ||
if (type === "path" && !matched) { | ||
matched = !!operation.path.match(pattern); | ||
} | ||
if (type === "method" && !skip) { | ||
skip = !!method.match(pattern); | ||
if (type === "method" && !matched) { | ||
matched = !!method.match(pattern); | ||
} | ||
}); | ||
return skip; | ||
return matched; | ||
} | ||
@@ -369,4 +245,5 @@ getSchemas(operation) { | ||
pathParams: pathParamsSchema ? { | ||
name: pascalCase(`${operation.getOperationId()} PathParams`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
operationName: pascalCase(`${operation.getOperationId()}`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
name: transformers.pascalCase(`${operation.getOperationId()} PathParams`), | ||
operation, | ||
operationName: transformers.pascalCase(`${operation.getOperationId()}`), | ||
schema: pathParamsSchema, | ||
@@ -376,4 +253,5 @@ keys: pathParamsSchema.properties ? Object.keys(pathParamsSchema.properties) : void 0 | ||
queryParams: queryParamsSchema ? { | ||
name: pascalCase(`${operation.getOperationId()} QueryParams`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
operationName: pascalCase(`${operation.getOperationId()}`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
name: transformers.pascalCase(`${operation.getOperationId()} QueryParams`), | ||
operation, | ||
operationName: transformers.pascalCase(`${operation.getOperationId()}`), | ||
schema: queryParamsSchema, | ||
@@ -383,4 +261,5 @@ keys: queryParamsSchema.properties ? Object.keys(queryParamsSchema.properties) : [] | ||
headerParams: headerParamsSchema ? { | ||
name: pascalCase(`${operation.getOperationId()} HeaderParams`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
operationName: pascalCase(`${operation.getOperationId()}`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
name: transformers.pascalCase(`${operation.getOperationId()} HeaderParams`), | ||
operation, | ||
operationName: transformers.pascalCase(`${operation.getOperationId()}`), | ||
schema: headerParamsSchema, | ||
@@ -390,8 +269,6 @@ keys: headerParamsSchema.properties ? Object.keys(headerParamsSchema.properties) : void 0 | ||
request: requestSchema ? { | ||
name: pascalCase(`${operation.getOperationId()} ${operation.method === "get" ? "queryRequest" : "mutationRequest"}`, { | ||
delimiter: "", | ||
transform: pascalCaseTransformMerge | ||
}), | ||
name: transformers.pascalCase(`${operation.getOperationId()} ${operation.method === "get" ? "queryRequest" : "mutationRequest"}`), | ||
description: operation.schema.requestBody?.description, | ||
operationName: pascalCase(`${operation.getOperationId()}`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
operation, | ||
operationName: transformers.pascalCase(`${operation.getOperationId()}`), | ||
schema: requestSchema, | ||
@@ -405,8 +282,6 @@ keys: requestSchema.properties ? Object.keys(requestSchema.properties) : void 0, | ||
response: { | ||
name: pascalCase(`${operation.getOperationId()} ${operation.method === "get" ? "queryResponse" : "mutationResponse"}`, { | ||
delimiter: "", | ||
transform: pascalCaseTransformMerge | ||
}), | ||
name: transformers.pascalCase(`${operation.getOperationId()} ${operation.method === "get" ? "queryResponse" : "mutationResponse"}`), | ||
description: operation.getResponseAsJSONSchema("200")?.at(0)?.description, | ||
operationName: pascalCase(`${operation.getOperationId()}`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
operation, | ||
operationName: transformers.pascalCase(`${operation.getOperationId()}`), | ||
schema: responseSchema, | ||
@@ -427,6 +302,7 @@ statusCode: 200, | ||
return { | ||
name: pascalCase(`${operation.getOperationId()} ${name}`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
name: transformers.pascalCase(`${operation.getOperationId()} ${name}`), | ||
description: operation.getResponseAsJSONSchema(statusCode)?.at(0)?.description || operation.getResponseByStatusCode(statusCode)?.description, | ||
schema, | ||
operationName: pascalCase(`${operation.getOperationId()}`, { delimiter: "", transform: pascalCaseTransformMerge }), | ||
operation, | ||
operationName: transformers.pascalCase(`${operation.getOperationId()}`), | ||
statusCode: name === "error" ? void 0 : Number(statusCode), | ||
@@ -447,4 +323,5 @@ keys: schema?.properties ? Object.keys(schema.properties) : void 0 | ||
if (operation && __privateGet(this, _methods, methods_get)[method]) { | ||
const isSkipped = this.isSkipped(operation, method); | ||
if (!isSkipped) { | ||
const isExcluded = this.isExcluded(operation, method); | ||
const isIncluded = this.context.include ? this.isIncluded(operation, method) : true; | ||
if (isIncluded && !isExcluded) { | ||
if (!acc[path2]) { | ||
@@ -455,3 +332,6 @@ acc[path2] = {}; | ||
...acc[path2], | ||
[method]: paths[path2][method] | ||
[method]: { | ||
operation, | ||
schemas: this.getSchemas(operation) | ||
} | ||
}; | ||
@@ -469,5 +349,5 @@ } | ||
methods.forEach((method) => { | ||
const operation = oas.operation(path2, method); | ||
const { operation, schemas } = filterdPaths[path2][method]; | ||
const options = __privateMethod(this, _getOptions, getOptions_fn).call(this, operation, method); | ||
const promise = __privateGet(this, _methods, methods_get)[method].call(this, operation, this.getSchemas(operation), { ...this.options, ...options }); | ||
const promise = __privateGet(this, _methods, methods_get)[method].call(this, operation, schemas, { ...this.options, ...options }); | ||
if (promise) { | ||
@@ -483,3 +363,3 @@ acc.push(promise); | ||
const files = await Promise.all(promises); | ||
return FileManager.combineFiles(files.flat()); | ||
return files.flat().filter(Boolean); | ||
} | ||
@@ -489,4 +369,4 @@ }; | ||
getOptions_fn = function(operation, method) { | ||
const { overrideBy = [] } = this.context; | ||
return overrideBy.find(({ pattern, type }) => { | ||
const { override = [] } = this.context; | ||
return override.find(({ pattern, type }) => { | ||
if (type === "tag") { | ||
@@ -527,5 +407,6 @@ return !!operation.getTags()[0]?.name.match(pattern); | ||
pathParameters: pathParameters.deprecated, | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | ||
example: pathParameters.example, | ||
required: [...schema.required || [], pathParameters.required ? pathParameters.name : void 0].filter(Boolean), | ||
required: [...schema.required || [], pathParameters.required ? pathParameters.name : void 0].filter( | ||
Boolean | ||
), | ||
properties: { | ||
@@ -608,32 +489,7 @@ ...schema.properties, | ||
// src/resolve.ts | ||
function resolve2({ operation, name, tag, type, pluginKey: pluginKey2, resolveName, resolvePath }) { | ||
if (!name && !operation?.getOperationId()) { | ||
throw new Error("name or operation should be set"); | ||
} | ||
const resolvedName = name ? name : resolveName({ name: operation?.getOperationId(), type, pluginKey: pluginKey2 }); | ||
if (!resolvedName) { | ||
throw new Error(`Name ${name || operation?.getOperationId()} should be defined`); | ||
} | ||
const baseName = `${resolvedName}.ts`; | ||
const path2 = resolvePath({ | ||
baseName, | ||
pluginKey: pluginKey2, | ||
options: { pluginKey: pluginKey2, type, tag: tag || operation?.getTags()[0]?.name } | ||
}); | ||
if (!path2) { | ||
throw new Error(`Filepath should be defined for resolvedName "${resolvedName}" and pluginKey [${JSON.stringify(pluginKey2)}]`); | ||
} | ||
return { | ||
name: resolvedName, | ||
baseName, | ||
path: path2 | ||
}; | ||
} | ||
// src/index.ts | ||
var src_default = definePlugin; | ||
export { ImportsGenerator, OasBuilder, OasManager, OperationGenerator, src_default as default, definePlugin, pluginKey, pluginName, resolve2 as resolve }; | ||
export { OasBuilder, OasManager, OperationGenerator, src_default as default, definePlugin, pluginKey, pluginName }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=index.js.map |
@@ -1,7 +0,11 @@ | ||
import { OASDocument } from 'oas/rmoas.types'; | ||
import Operation from 'oas/operation'; | ||
import * as OasTypes from 'oas/types'; | ||
import { OASDocument, SchemaObject, ParameterObject } from 'oas/types'; | ||
import { Operation } from 'oas/operation'; | ||
import { KubbFile, KubbPlugin } from '@kubb/core'; | ||
import { Logger } from '@kubb/core/logger'; | ||
import { FunctionParamsAST } from '@kubb/core/utils'; | ||
import { PluginFactoryOptions, KubbPlugin } from '@kubb/core'; | ||
import { b as OperationSchema, f as Refs } from './types-BaLUOV9R.js'; | ||
export { G as GetSchemasProps, j as getSchemas } from './types-BaLUOV9R.js'; | ||
import Oas from 'oas'; | ||
import { OpenAPIV3, OpenAPI } from 'openapi-types'; | ||
import { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types'; | ||
@@ -12,67 +16,26 @@ declare function convertSwagger2ToOpenApi(document: OASDocument): Promise<OASDocument>; | ||
type Mode = 'schemas' | 'responses' | 'requestBodies'; | ||
type GetSchemasProps = { | ||
oas: Oas; | ||
contentType?: ContentType; | ||
includes?: Mode[]; | ||
}; | ||
declare function getSchemas({ oas, contentType, includes, }: GetSchemasProps): Record<string, OpenAPIV3.SchemaObject>; | ||
type ContentType = 'application/json' | (string & {}); | ||
type API = { | ||
getOas: () => Promise<Oas>; | ||
getSchemas: (options?: Pick<GetSchemasProps, 'includes'>) => Promise<Record<string, OpenAPIV3.SchemaObject>>; | ||
getBaseURL: () => Promise<string | undefined>; | ||
contentType?: ContentType; | ||
}; | ||
type Options = { | ||
logger?: Logger; | ||
files: KubbFile.File[]; | ||
plugin: KubbPlugin; | ||
template: string; | ||
exportAs: string; | ||
/** | ||
* Validate your input(see kubb.config) based on @apidevtools/swagger-parser | ||
* @default true | ||
* Root based on root and output.path specified in the config | ||
*/ | ||
validate?: boolean; | ||
root: string; | ||
/** | ||
* Relative path to save the JSON models. | ||
* False will not generate the schema JSON's. | ||
* @default 'schemas' | ||
* Output for plugin | ||
*/ | ||
output?: string | false; | ||
/** | ||
* Which server to use from the array of `servers.url[serverIndex]` | ||
* @example `0` will return `http://petstore.swagger.io/api` and `1` will return `http://localhost:3000` | ||
* servers: | ||
- url: http://petstore.swagger.io/api | ||
- url: http://localhost:3000 | ||
* @default 0 | ||
*/ | ||
serverIndex?: number; | ||
/** | ||
* Override ContentType that will be used for requests and responses. | ||
*/ | ||
contentType?: ContentType; | ||
}; | ||
type PluginOptions = PluginFactoryOptions<'swagger', 'schema', Options, false, API>; | ||
type OperationSchema = { | ||
/** | ||
* Converted name, contains already `PathParams`, `QueryParams`, ... | ||
*/ | ||
name: string; | ||
/** | ||
* OperationName in PascalCase, only being used in OperationGenerator | ||
*/ | ||
operationName?: string; | ||
description?: string; | ||
schema: OpenAPIV3.SchemaObject & { | ||
$ref?: OpenAPIV3.ReferenceObject['$ref']; | ||
output: { | ||
path: string; | ||
exportAs?: string; | ||
extName?: string; | ||
}; | ||
statusCode?: number; | ||
keys?: string[]; | ||
keysToOmit?: string[]; | ||
}; | ||
declare module '@kubb/core' { | ||
interface _Register { | ||
['@kubb/swagger']: PluginOptions; | ||
} | ||
} | ||
type FileMeta = { | ||
pluginKey?: KubbPlugin['key']; | ||
tag?: string; | ||
}; | ||
declare function getGroupedByTagFiles({ logger, files, plugin, template, exportAs, root, output, }: Options): Promise<KubbFile.File<FileMeta>[]>; | ||
@@ -94,24 +57,26 @@ declare function getASTParams(operationSchema: OperationSchema | undefined, { typed, override, asObject }?: { | ||
declare function isOpenApiV3Document(doc: OpenAPI.Document): doc is OpenAPIV3.Document; | ||
declare function isParameterObject(obj: OpenAPIV3.ParameterObject | OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject): obj is OpenAPIV3.ParameterObject; | ||
declare function isReference(obj: OpenAPIV3.ParameterObject | OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject): obj is OpenAPIV3.ReferenceObject; | ||
/** | ||
* `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(swagger-ts) for a mock file(swagger-faker) | ||
* Make it possible to narrow down the schema based on a specific version(3 or 3.1) | ||
*/ | ||
type Ref = { | ||
propertyName: string; | ||
originalName: string; | ||
pluginKey?: KubbPlugin['key']; | ||
type SchemaResult<TWithRef extends boolean = false> = { | ||
schema?: TWithRef extends true ? OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject : OpenAPIV3.SchemaObject; | ||
version: '3.0'; | ||
} | { | ||
schema?: TWithRef extends true ? OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject : OpenAPIV3_1.SchemaObject; | ||
version: '3.1'; | ||
}; | ||
type Refs = Record<string, Ref>; | ||
declare function getSchemaFactory<TWithRef extends boolean = false>(oas: Oas): (schema?: OasTypes.SchemaObject) => SchemaResult<TWithRef>; | ||
declare function isJSONSchema(obj?: unknown): obj is SchemaObject; | ||
declare function isOpenApiV3_1Document(doc: OpenAPIV3.Document | OpenAPIV3_1.Document): doc is OpenAPIV3_1.Document; | ||
declare function isOpenApiV3Document(doc: OpenAPIV3.Document | OpenAPIV3_1.Document): doc is OpenAPIV3.Document; | ||
declare function isParameterObject(obj: ParameterObject | SchemaObject): obj is ParameterObject; | ||
declare function isReference(obj?: unknown): obj is OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject; | ||
declare function isRequired(schema?: OasTypes.SchemaObject): boolean; | ||
type Generated = { | ||
@@ -125,2 +90,2 @@ import: { | ||
export { GetSchemasProps, convertSwagger2ToOpenApi, getASTParams, getComments, getParams, getSchemas, isOpenApiV3Document, isParameterObject, isReference, refsSorter }; | ||
export { convertSwagger2ToOpenApi, getASTParams, getComments, getGroupedByTagFiles, getParams, getSchemaFactory, isJSONSchema, isOpenApiV3Document, isOpenApiV3_1Document, isParameterObject, isReference, isRequired, refsSorter }; |
import { createRequire } from 'module'; | ||
import swagger2openapi from 'swagger2openapi'; | ||
import { URLPath, FunctionParams } from '@kubb/core/utils'; | ||
import { camelCase, camelCaseTransformMerge } from 'change-case'; | ||
export { convertSwagger2ToOpenApi, getSchemas, isOpenApiV3Document, isReference } from './chunk-AWEHKPOS.js'; | ||
import './chunk-PUSDFDIP.js'; | ||
import transformers from '@kubb/core/transformers'; | ||
import { URLPath, renderTemplate, FunctionParams } from '@kubb/core/utils'; | ||
import path from 'path'; | ||
import { FileManager } from '@kubb/core'; | ||
import { getRelativePath } from '@kubb/core/fs'; | ||
import { LogLevel } from '@kubb/core/logger'; | ||
import { isSchema } from 'oas/types'; | ||
createRequire(import.meta.url); | ||
function convertSwagger2ToOpenApi(document) { | ||
const options = { anchors: true }; | ||
return new Promise((resolve, reject) => { | ||
swagger2openapi.convertObj(document, options, (err, value) => { | ||
if (err) { | ||
reject(err); | ||
} else { | ||
resolve(value.openapi); | ||
} | ||
}); | ||
}); | ||
} | ||
function getComments(operation) { | ||
@@ -25,4 +19,43 @@ return [ | ||
operation.isDeprecated() && `@deprecated` | ||
].filter(Boolean); | ||
].filter(Boolean).map((text) => transformers.trim(text)); | ||
} | ||
async function getGroupedByTagFiles({ | ||
logger, | ||
files, | ||
plugin, | ||
template, | ||
exportAs, | ||
root, | ||
output | ||
}) { | ||
const mode = FileManager.getMode(path.resolve(root, output.path)); | ||
if (mode === "file") { | ||
return []; | ||
} | ||
return files.filter((file) => { | ||
const name = file.meta?.pluginKey?.[0]; | ||
return name === plugin.name; | ||
}).map((file) => { | ||
if (!file.meta?.tag) { | ||
if (logger?.logLevel === LogLevel.debug) { | ||
logger?.debug(`Could not find a tagName for ${JSON.stringify(file, void 0, 2)}`); | ||
} | ||
return; | ||
} | ||
const tag = file.meta?.tag && transformers.camelCase(file.meta.tag); | ||
const tagPath = getRelativePath(path.resolve(root, output.path), path.resolve(root, renderTemplate(template, { tag }))); | ||
const tagName = renderTemplate(exportAs, { tag }); | ||
if (tagName) { | ||
return { | ||
baseName: "index.ts", | ||
path: path.resolve(root, output.path, "index.ts"), | ||
source: "", | ||
exports: [{ path: output.extName ? `${tagPath}/index${output.extName}` : `${tagPath}/index`, asAlias: true, name: tagName }], | ||
meta: { | ||
pluginKey: plugin.key | ||
} | ||
}; | ||
} | ||
}).filter(Boolean); | ||
} | ||
@@ -40,3 +73,3 @@ // src/utils/isParameterObject.ts | ||
if (asObject) { | ||
const nameText = getASTParams(operationSchema).map((item) => item.name ? camelCase(item.name, { delimiter: "", transform: camelCaseTransformMerge }) : item.name).join(", "); | ||
const nameText = getASTParams(operationSchema).map((item) => item.name ? transformers.camelCase(item.name) : item.name).join(", "); | ||
return [ | ||
@@ -67,45 +100,27 @@ { | ||
// src/utils/getSchemas.ts | ||
function getSchemas({ | ||
oas, | ||
contentType, | ||
includes = ["schemas", "requestBodies", "responses"] | ||
}) { | ||
const components = oas.getDefinition().components; | ||
let schemas = {}; | ||
if (includes.includes("schemas")) { | ||
schemas = { | ||
...schemas, | ||
...components?.schemas || {} | ||
}; | ||
} | ||
const requestBodies = components?.requestBodies || {}; | ||
if (includes.includes("responses")) { | ||
const responses = components?.responses || {}; | ||
Object.entries(responses).forEach(([name, response]) => { | ||
if (response.content && !schemas[name]) { | ||
const firstContentType = Object.keys(response.content)[0] || "application/json"; | ||
schemas[name] = response.content?.[contentType || firstContentType]?.schema; | ||
} | ||
}); | ||
} | ||
if (includes.includes("requestBodies")) { | ||
Object.entries(requestBodies).forEach(([name, request]) => { | ||
if (request.content && !schemas[name]) { | ||
const firstContentType = Object.keys(request.content)[0] || "application/json"; | ||
schemas[name] = request.content?.[contentType || firstContentType]?.schema; | ||
} | ||
}); | ||
} | ||
return schemas; | ||
// src/utils/isOpenApiV3_1Document.ts | ||
function isOpenApiV3_1Document(doc) { | ||
return doc && "openapi" in doc && doc.openapi.startsWith("3.1"); | ||
} | ||
// src/utils/isOpenApiV3Document.ts | ||
function isOpenApiV3Document(doc) { | ||
return "openapi" in doc; | ||
// src/utils/getSchemaFactory.ts | ||
function getSchemaFactory(oas) { | ||
return (schema) => { | ||
const version = isOpenApiV3_1Document(oas.api) ? "3.1" : "3.0"; | ||
return { | ||
schema, | ||
version | ||
}; | ||
}; | ||
} | ||
function isJSONSchema(obj) { | ||
return !!obj && isSchema(obj); | ||
} | ||
// src/utils/isReference.ts | ||
function isReference(obj) { | ||
return obj && "$ref" in obj; | ||
// src/utils/isRequired.ts | ||
function isRequired(schema) { | ||
if (!schema) { | ||
return false; | ||
} | ||
return Array.isArray(schema.required) ? !!schema.required?.length : !!schema.required; | ||
} | ||
@@ -124,4 +139,4 @@ | ||
export { convertSwagger2ToOpenApi, getASTParams, getComments, getParams, getSchemas, isOpenApiV3Document, isParameterObject, isReference, refsSorter }; | ||
export { getASTParams, getComments, getGroupedByTagFiles, getParams, getSchemaFactory, isJSONSchema, isOpenApiV3_1Document, isParameterObject, isRequired, refsSorter }; | ||
//# sourceMappingURL=out.js.map | ||
//# sourceMappingURL=utils.js.map |
{ | ||
"name": "@kubb/swagger", | ||
"version": "2.0.0-canary.20231030T125048", | ||
"version": "2.0.0", | ||
"description": "Generator swagger", | ||
@@ -38,2 +38,7 @@ "keywords": [ | ||
}, | ||
"./oas": { | ||
"import": "./dist/oas.js", | ||
"require": "./dist/oas.cjs", | ||
"default": "./dist/oas.cjs" | ||
}, | ||
"./package.json": "./package.json", | ||
@@ -46,2 +51,3 @@ "./*": "./*" | ||
"files": [ | ||
"src", | ||
"dist", | ||
@@ -53,24 +59,23 @@ "!/**/**.test.**", | ||
"@apidevtools/swagger-parser": "^10.1.0", | ||
"@kubb/core": "canary", | ||
"@kubb/react": "canary", | ||
"change-case": "^4.1.2", | ||
"js-yaml": "^4.1.0", | ||
"oas": "23.0.0", | ||
"oas": "^24.1.0", | ||
"oas-normalize": "^11.0.1", | ||
"swagger2openapi": "^7.0.8" | ||
"openapi-types": "^12.1.3", | ||
"swagger2openapi": "^7.0.8", | ||
"@kubb/core": "2.0.0", | ||
"@kubb/react": "2.0.0" | ||
}, | ||
"devDependencies": { | ||
"@kubb/eslint-config": "canary", | ||
"@kubb/ts-config": "canary", | ||
"@kubb/tsup-config": "canary", | ||
"@types/js-yaml": "^4.0.8", | ||
"@types/react": "^18.2.33", | ||
"@types/swagger2openapi": "^7.0.3", | ||
"eslint": "^8.52.0", | ||
"openapi-types": "^12.1.3", | ||
"tsup": "^7.2.0", | ||
"typescript": "^5.2.2" | ||
"@types/js-yaml": "^4.0.9", | ||
"@types/react": "^18.2.42", | ||
"@types/swagger2openapi": "^7.0.4", | ||
"eslint": "^8.55.0", | ||
"tsup": "^8.0.1", | ||
"typescript": "^5.3.3", | ||
"@kubb/eslint-config": "1.1.8", | ||
"@kubb/ts-config": "0.1.0", | ||
"@kubb/tsup-config": "1.1.8" | ||
}, | ||
"peerDependencies": { | ||
"@kubb/react": "canary" | ||
"@kubb/react": "2.0.0" | ||
}, | ||
@@ -92,4 +97,3 @@ "packageManager": "pnpm@8.3.0", | ||
"release": "pnpm publish --no-git-check", | ||
"release:canary": "bash ../../.github/canary.sh && node ../../scripts/build.js canary && pnpm publish --no-git-check -tag canary", | ||
"release:alpha": "bash ../../.github/canary.sh && node ../../scripts/build.js alpha && pnpm publish --no-git-check -tag alpha", | ||
"release:canary": "bash ../../.github/canary.sh && node ../../scripts/build.js canary && pnpm publish --no-git-check", | ||
"start": "tsup --watch", | ||
@@ -96,0 +100,0 @@ "test": "vitest --passWithNoTests", |
@@ -21,3 +21,3 @@ <div align="center"> | ||
<h4> | ||
<a href="https://codesandbox.io/s/github/kubb-project/kubb/tree/main/examples/typescript" target="_blank">View Demo</a> | ||
<a href="https://codesandbox.io/s/github/kubb-project/kubb/tree/alpha/examples/typescript" target="_blank">View Demo</a> | ||
<span> · </span> | ||
@@ -24,0 +24,0 @@ <a href="https://kubb.dev/" target="_blank">Documentation</a> |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
226747
7.16%9
-10%62
195.24%2840
36.34%1
-50%6
100%1
Infinity%+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated
Updated
Updated