@kubb/plugin-react-query
Version:
React Query hooks generator plugin for Kubb, creating type-safe API client hooks from OpenAPI specifications for React applications.
1,412 lines (1,411 loc) • 42.4 kB
TypeScript
import * as OasTypes from "oas/types";
import { HttpMethods as HttpMethod, OASDocument, SchemaObject, User } from "oas/types";
import { Operation, Operation as Operation$1 } from "oas/operation";
import { OpenAPIV3 } from "openapi-types";
import * as oas_normalize_lib_types0 from "oas-normalize/lib/types";
import BaseOas from "oas";
import { ConsolaInstance, LogLevel } from "consola";
//#region ../oas/src/types.d.ts
type contentType = 'application/json' | (string & {});
type SchemaObject$1 = OasTypes.SchemaObject & {
'x-nullable'?: boolean;
$ref?: string;
};
//#endregion
//#region ../oas/src/Oas.d.ts
type Options$4 = {
contentType?: contentType;
discriminator?: 'strict' | 'inherit';
};
declare class Oas<const TOAS = unknown> extends BaseOas {
#private;
document: TOAS;
constructor({
oas,
user
}: {
oas: TOAS | OASDocument | string;
user?: User;
});
setOptions(options: Options$4): void;
get options(): Options$4;
get($ref: string): any;
getKey($ref: string): string | undefined;
set($ref: string, value: unknown): false | undefined;
getDiscriminator(schema: OasTypes.SchemaObject): OpenAPIV3.DiscriminatorObject | undefined;
dereferenceWithRef(schema?: unknown): any;
getResponseSchema(operation: Operation, statusCode: string | number): SchemaObject;
getRequestSchema(operation: Operation): SchemaObject | undefined;
getParametersSchema(operation: Operation, inKey: 'path' | 'query' | 'header'): SchemaObject | null;
valdiate(): Promise<oas_normalize_lib_types0.ValidationResult>;
}
//#endregion
//#region ../core/src/BaseGenerator.d.ts
/**
* Abstract class that contains the building blocks for plugins to create their own Generator
* @link idea based on https://github.com/colinhacks/zod/blob/master/src/types.ts#L137
*/
declare abstract class BaseGenerator<TOptions = unknown, TContext = unknown> {
#private;
constructor(options?: TOptions, context?: TContext);
get options(): TOptions;
get context(): TContext;
set options(options: TOptions);
abstract build(...params: unknown[]): unknown;
}
//#endregion
//#region ../core/src/fs/types.d.ts
type BasePath<T extends string = string> = `${T}/`;
type Import = {
/**
* Import name to be used
* @example ["useState"]
* @example "React"
*/
name: string | Array<string | {
propertyName: string;
name?: string;
}>;
/**
* Path for the import
* @example '@kubb/core'
*/
path: string;
/**
* Add `type` prefix to the import, this will result in: `import type { Type } from './path'`.
*/
isTypeOnly?: boolean;
isNameSpace?: boolean;
/**
* When root is set it will get the path with relative getRelativePath(root, path).
*/
root?: string;
};
type Source = {
name?: string;
value?: string;
isTypeOnly?: boolean;
/**
* Has const or type 'export'
* @default false
*/
isExportable?: boolean;
/**
* When set, barrel generation will add this
* @default false
*/
isIndexable?: boolean;
};
type Export = {
/**
* Export name to be used.
* @example ["useState"]
* @example "React"
*/
name?: string | Array<string>;
/**
* Path for the import.
* @example '@kubb/core'
*/
path: string;
/**
* Add `type` prefix to the export, this will result in: `export type { Type } from './path'`.
*/
isTypeOnly?: boolean;
/**
* Make it possible to override the name, this will result in: `export * as aliasName from './path'`.
*/
asAlias?: boolean;
};
type Extname = '.ts' | '.js' | '.tsx' | '.json' | `.${string}`;
type Mode = 'single' | 'split';
/**
* Name to be used to dynamicly create the baseName(based on input.path)
* Based on UNIX basename
* @link https://nodejs.org/api/path.html#pathbasenamepath-suffix
*/
type BaseName = `${string}.${string}`;
/**
* Path will be full qualified path to a specified file
*/
type Path = string;
type AdvancedPath<T extends BaseName = BaseName> = `${BasePath}${T}`;
type OptionalPath = Path | undefined | null;
type File<TMeta extends object = object> = {
/**
* Name to be used to create the path
* Based on UNIX basename, `${name}.extname`
* @link https://nodejs.org/api/path.html#pathbasenamepath-suffix
*/
baseName: BaseName;
/**
* Path will be full qualified path to a specified file
*/
path: AdvancedPath<BaseName> | Path;
sources: Array<Source>;
imports?: Array<Import>;
exports?: Array<Export>;
/**
* Use extra meta, this is getting used to generate the barrel/index files.
*/
meta?: TMeta;
banner?: string;
footer?: string;
};
type ResolvedImport = Import;
type ResolvedExport = Export;
type ResolvedFile<TMeta extends object = object> = File<TMeta> & {
/**
* @default object-hash
*/
id: string;
/**
* Contains the first part of the baseName, generated based on baseName
* @link https://nodejs.org/api/path.html#pathformatpathobject
*/
name: string;
extname: Extname;
imports: Array<ResolvedImport>;
exports: Array<ResolvedExport>;
};
//#endregion
//#region ../core/src/utils/EventEmitter.d.ts
declare class EventEmitter<TEvents extends Record<string, any>> {
#private;
constructor();
emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArg: TEvents[TEventName]): void;
on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void;
off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void;
removeAll(): void;
}
//#endregion
//#region ../core/src/logger.d.ts
type DebugEvent = {
date: Date;
logs: string[];
fileName?: string;
};
type Events$1 = {
start: [message: string];
success: [message: string];
error: [message: string, cause: Error];
warning: [message: string];
debug: [DebugEvent];
info: [message: string];
progress_start: [{
id: string;
size: number;
message?: string;
}];
progressed: [{
id: string;
message?: string;
}];
progress_stop: [{
id: string;
}];
};
type Logger = {
/**
* Optional config name to show in CLI output
*/
name?: string;
logLevel: LogLevel;
consola?: ConsolaInstance;
on: EventEmitter<Events$1>['on'];
emit: EventEmitter<Events$1>['emit'];
writeLogs: () => Promise<string[]>;
};
//#endregion
//#region ../core/src/utils/types.d.ts
type PossiblePromise<T> = Promise<T> | T;
type ArrayWithLength<T extends number, U extends any[] = []> = U['length'] extends T ? U : ArrayWithLength<T, [true, ...U]>;
type GreaterThan<T extends number, U extends number> = ArrayWithLength<U> extends [...ArrayWithLength<T>, ...infer _] ? false : true;
//#endregion
//#region ../core/src/types.d.ts
type InputPath = {
/**
* Specify your Swagger/OpenAPI file, either as an absolute path or a path relative to the root.
*/
path: string;
};
type InputData = {
/**
* A `string` or `object` that contains your Swagger/OpenAPI data.
*/
data: string | unknown;
};
type Input = InputPath | InputData | Array<InputPath>;
type BarrelType = 'all' | 'named' | 'propagate';
/**
* @private
*/
type Config<TInput = Input> = {
/**
* The name to display in the CLI output.
*/
name?: string;
/**
* The project root directory, which can be either an absolute path or a path relative to the location of your `kubb.config.ts` file.
* @default process.cwd()
*/
root: string;
/**
* You can use either `input.path` or `input.data`, depending on your specific needs.
*/
input: TInput;
output: {
/**
* The path where all generated files will be exported.
* This can be an absolute path or a path relative to the specified root option.
*/
path: string;
/**
* Clean the output directory before each build.
*/
clean?: boolean;
/**
* Save files to the file system.
* @default true
*/
write?: boolean;
/**
* Specifies the formatting tool to be used.
* @default prettier
*
* Possible values:
* - 'prettier': Uses Prettier for code formatting.
* - 'biome': Uses Biome for code formatting.
*
*/
format?: 'prettier' | 'biome' | false;
/**
* Specifies the linter that should be used to analyze the code.
* The accepted values indicate different linting tools.
*
* Possible values:
* - 'eslint': Represents the use of ESLint, a widely used JavaScript linter.
* - 'biome': Represents the Biome linter, a modern tool for code scanning.
* - 'oxlint': Represents the Oxlint tool for linting purposes.
*
*/
lint?: 'eslint' | 'biome' | 'oxlint' | false;
/**
* Override the extension to the generated imports and exports, by default each plugin will add an extension
* @default { '.ts': '.ts'}
*/
extension?: Record<Extname, Extname | ''>;
/**
* Specify how `index.ts` files should be created. You can also disable the generation of barrel files here. While each plugin has its own `barrelType` option, this setting controls the creation of the root barrel file, such as` src/gen/index.ts`.
* @default 'named'
*/
barrelType?: Exclude<BarrelType, 'propagate'> | false;
/**
* Add a default banner to the beginning of every generated file. This makes it clear that the file was generated by Kubb.
* - 'simple': will only add banner with link to Kubb
* - 'full': will add source, title, description and the OpenAPI version used
* @default 'simple'
*/
defaultBanner?: 'simple' | 'full' | false;
};
/**
* An array of Kubb plugins that will be used in the generation.
* Each plugin may include additional configurable options(defined in the plugin itself).
* If a plugin depends on another plugin, an error will be returned if the required dependency is missing. See pre for more details.
*/
plugins?: Array<Plugin>;
/**
* Hooks that will be called when a specific action is triggered in Kubb.
*/
hooks?: {
/**
* Hook that will be triggered at the end of all executions.
* Useful for running Prettier or ESLint to format/lint your code.
*/
done?: string | Array<string>;
};
};
type PluginFactoryOptions<
/**
* Name to be used for the plugin, this will also be used for they key.
*/
TName extends string = string,
/**
* Options of the plugin.
*/
TOptions extends object = object,
/**
* Options of the plugin that can be used later on, see `options` inside your plugin config.
*/
TResolvedOptions extends object = TOptions,
/**
* Context that you want to expose to other plugins.
*/
TContext = any,
/**
* When calling `resolvePath` you can specify better types.
*/
TResolvePathOptions extends object = object> = {
name: TName;
/**
* Same behaviour like what has been done with `QueryKey` in `@tanstack/react-query`
*/
key: PluginKey<TName | string>;
options: TOptions;
resolvedOptions: TResolvedOptions;
context: TContext;
resolvePathOptions: TResolvePathOptions;
};
type PluginKey<TName> = [name: TName, identifier?: string | number];
type UserPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
/**
* Unique name used for the plugin
* The name of the plugin follows the format scope:foo-bar or foo-bar, adding scope: can avoid naming conflicts with other plugins.
* @example @kubb/typescript
*/
name: TOptions['name'];
/**
* Options set for a specific plugin(see kubb.config.js), passthrough of options.
*/
options: TOptions['resolvedOptions'];
/**
* Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin will be executed after these plugins.
* Can be used to validate dependent plugins.
*/
pre?: Array<string>;
/**
* Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin will be executed before these plugins.
*/
post?: Array<string>;
} & (TOptions['context'] extends never ? {
context?: never;
} : {
context: (this: TOptions['name'] extends 'core' ? null : Omit<PluginContext<TOptions>, 'addFile'>) => TOptions['context'];
});
type UserPluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = UserPlugin<TOptions> & PluginLifecycle<TOptions>;
type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
/**
* Unique name used for the plugin
* @example @kubb/typescript
*/
name: TOptions['name'];
/**
* Internal key used when a developer uses more than one of the same plugin
* @private
*/
key: TOptions['key'];
/**
* Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin will be executed after these plugins.
* Can be used to validate dependent plugins.
*/
pre?: Array<string>;
/**
* Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin will be executed before these plugins.
*/
post?: Array<string>;
/**
* Options set for a specific plugin(see kubb.config.js), passthrough of options.
*/
options: TOptions['resolvedOptions'];
} & (TOptions['context'] extends never ? {
context?: never;
} : {
context: TOptions['context'];
});
type PluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & PluginLifecycle<TOptions>;
type PluginLifecycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
/**
* Start of the lifecycle of a plugin.
* @type hookParallel
*/
buildStart?: (this: PluginContext<TOptions>, Config: Config) => PossiblePromise<void>;
/**
* Resolve to a Path based on a baseName(example: `./Pet.ts`) and directory(example: `./models`).
* Options can als be included.
* @type hookFirst
* @example ('./Pet.ts', './src/gen/') => '/src/gen/Pet.ts'
*/
resolvePath?: (this: PluginContext<TOptions>, baseName: BaseName, mode?: Mode, options?: TOptions['resolvePathOptions']) => OptionalPath;
/**
* Resolve to a name based on a string.
* Useful when converting to PascalCase or camelCase.
* @type hookFirst
* @example ('pet') => 'Pet'
*/
resolveName?: (this: PluginContext<TOptions>, name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string;
/**
* End of the plugin lifecycle.
* @type hookParallel
*/
buildEnd?: (this: PluginContext<TOptions>) => PossiblePromise<void>;
};
type PluginLifecycleHooks = keyof PluginLifecycle;
type PluginParameter<H extends PluginLifecycleHooks> = Parameters<Required<PluginLifecycle>[H]>;
type ResolvePathParams<TOptions = object> = {
pluginKey?: Plugin['key'];
baseName: BaseName;
mode?: Mode;
/**
* Options to be passed to 'resolvePath' 3th parameter
*/
options?: TOptions;
};
type ResolveNameParams = {
name: string;
pluginKey?: Plugin['key'];
/**
* `file` will be used to customize the name of the created file(use of camelCase)
* `function` can be used to customize the exported functions(use of camelCase)
* `type` is a special type for TypeScript(use of PascalCase)
* `const` can be used for variables(use of camelCase)
*/
type?: 'file' | 'function' | 'type' | 'const';
};
type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
config: Config;
fileManager: FileManager;
pluginManager: PluginManager;
addFile: (...file: Array<File>) => Promise<Array<ResolvedFile>>;
resolvePath: (params: ResolvePathParams<TOptions['resolvePathOptions']>) => OptionalPath;
resolveName: (params: ResolveNameParams) => string;
logger: Logger;
/**
* All plugins
*/
plugins: Plugin[];
/**
* Current plugin
*/
plugin: Plugin<TOptions>;
};
/**
* Specify the export location for the files and define the behavior of the output
*/
type Output<TOptions> = {
/**
* Path to the output folder or file that will contain the generated code
*/
path: string;
/**
* Define what needs to be exported, here you can also disable the export of barrel files
* @default 'named'
*/
barrelType?: BarrelType | false;
/**
* Add a banner text in the beginning of every file
*/
banner?: string | ((options: TOptions) => string);
/**
* Add a footer text in the beginning of every file
*/
footer?: string | ((options: TOptions) => string);
};
type GroupContext = {
group: string;
};
type Group = {
/**
* Define a type where to group the files on
*/
type: 'tag' | 'path';
/**
* Return the name of a group based on the group name, this will be used for the file and name generation
*/
name?: (context: GroupContext) => string;
};
//#endregion
//#region ../core/src/FileManager.d.ts
type FileMetaBase = {
pluginKey?: Plugin['key'];
};
type AddResult<T extends Array<File>> = Promise<Awaited<GreaterThan<T['length'], 1> extends true ? Promise<ResolvedFile[]> : Promise<ResolvedFile>>>;
type AddIndexesProps = {
type: BarrelType | false | undefined;
/**
* Root based on root and output.path specified in the config
*/
root: string;
/**
* Output for plugin
*/
output: {
path: string;
};
group?: {
output: string;
exportAs: string;
};
logger?: Logger;
meta?: FileMetaBase;
};
type WriteFilesProps = {
root: Config['root'];
extension?: Record<Extname, Extname | ''>;
logger?: Logger;
dryRun?: boolean;
};
declare class FileManager {
#private;
constructor();
add<T extends Array<File> = Array<File>>(...files: T): AddResult<T>;
getByPath(path: Path): Promise<ResolvedFile | null>;
deleteByPath(path: Path): Promise<void>;
clear(): Promise<void>;
getFiles(): Promise<Array<ResolvedFile>>;
processFiles({
dryRun,
root,
extension,
logger
}: WriteFilesProps): Promise<Array<ResolvedFile>>;
getBarrelFiles({
type,
meta,
root,
output,
logger
}: AddIndexesProps): Promise<File[]>;
static getMode(path: string | undefined | null): Mode;
}
//#endregion
//#region ../core/src/PluginManager.d.ts
type RequiredPluginLifecycle = Required<PluginLifecycle>;
type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq';
type Executer<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
message: string;
strategy: Strategy;
hookName: H;
plugin: Plugin;
parameters?: unknown[] | undefined;
output?: unknown;
};
type ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H];
type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {
result: Result;
plugin: Plugin;
};
type Options$3 = {
logger: Logger;
/**
* @default Number.POSITIVE_INFINITY
*/
concurrency?: number;
};
type Events = {
executing: [executer: Executer];
executed: [executer: Executer];
error: [error: Error];
};
type GetFileProps<TOptions = object> = {
name: string;
mode?: Mode;
extname: Extname;
pluginKey: Plugin['key'];
options?: TOptions;
};
declare class PluginManager {
#private;
readonly plugins: Set<Plugin<PluginFactoryOptions<string, object, object, any, object>>>;
readonly fileManager: FileManager;
readonly events: EventEmitter<Events>;
readonly config: Config;
readonly executed: Array<Executer>;
readonly logger: Logger;
readonly options: Options$3;
constructor(config: Config, options: Options$3);
getFile<TOptions = object>({
name,
mode,
extname,
pluginKey,
options
}: GetFileProps<TOptions>): File<{
pluginKey: Plugin['key'];
}>;
resolvePath: <TOptions = object>(params: ResolvePathParams<TOptions>) => OptionalPath;
resolveName: (params: ResolveNameParams) => string;
/**
* Instead of calling `pluginManager.events.on` you can use `pluginManager.on`. This one also has better types.
*/
on<TEventName extends keyof Events & string>(eventName: TEventName, handler: (...eventArg: Events[TEventName]) => void): void;
/**
* Run a specific hookName for plugin x.
*/
hookForPlugin<H extends PluginLifecycleHooks>({
pluginKey,
hookName,
parameters,
message
}: {
pluginKey: Plugin['key'];
hookName: H;
parameters: PluginParameter<H>;
message: string;
}): Promise<Array<ReturnType<ParseResult<H>> | null>>;
/**
* Run a specific hookName for plugin x.
*/
hookForPluginSync<H extends PluginLifecycleHooks>({
pluginKey,
hookName,
parameters,
message
}: {
pluginKey: Plugin['key'];
hookName: H;
parameters: PluginParameter<H>;
message: string;
}): Array<ReturnType<ParseResult<H>>> | null;
/**
* First non-null result stops and will return it's value.
*/
hookFirst<H extends PluginLifecycleHooks>({
hookName,
parameters,
skipped,
message
}: {
hookName: H;
parameters: PluginParameter<H>;
skipped?: ReadonlySet<Plugin> | null;
message: string;
}): Promise<SafeParseResult<H>>;
/**
* First non-null result stops and will return it's value.
*/
hookFirstSync<H extends PluginLifecycleHooks>({
hookName,
parameters,
skipped,
message
}: {
hookName: H;
parameters: PluginParameter<H>;
skipped?: ReadonlySet<Plugin> | null;
message: string;
}): SafeParseResult<H>;
/**
* Run all plugins in parallel(order will be based on `this.plugin` and if `pre` or `post` is set).
*/
hookParallel<H extends PluginLifecycleHooks, TOuput = void>({
hookName,
parameters,
message
}: {
hookName: H;
parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined;
message: string;
}): Promise<Awaited<TOuput>[]>;
/**
* Chains plugins
*/
hookSeq<H extends PluginLifecycleHooks>({
hookName,
parameters,
message
}: {
hookName: H;
parameters?: PluginParameter<H>;
message: string;
}): Promise<void>;
getPluginByKey(pluginKey: Plugin['key']): Plugin | undefined;
getPluginsByKey(hookName: keyof PluginWithLifeCycle, pluginKey: Plugin['key']): Plugin[];
static getDependedPlugins<T1 extends PluginFactoryOptions, T2 extends PluginFactoryOptions = never, T3 extends PluginFactoryOptions = never, TOutput = (T3 extends never ? (T2 extends never ? [T1: Plugin<T1>] : [T1: Plugin<T1>, T2: Plugin<T2>]) : [T1: Plugin<T1>, T2: Plugin<T2>, T3: Plugin<T3>])>(plugins: Array<Plugin>, dependedPluginNames: string | string[]): TOutput;
static get hooks(): readonly ["buildStart", "resolvePath", "resolveName", "buildEnd"];
}
//#endregion
//#region ../plugin-oas/src/SchemaMapper.d.ts
type SchemaKeywordMapper = {
object: {
keyword: 'object';
args: {
properties: {
[x: string]: Schema[];
};
additionalProperties: Schema[];
strict?: boolean;
};
};
url: {
keyword: 'url';
};
readOnly: {
keyword: 'readOnly';
};
writeOnly: {
keyword: 'writeOnly';
};
uuid: {
keyword: 'uuid';
};
email: {
keyword: 'email';
};
firstName: {
keyword: 'firstName';
};
lastName: {
keyword: 'lastName';
};
phone: {
keyword: 'phone';
};
password: {
keyword: 'password';
};
date: {
keyword: 'date';
args: {
type?: 'date' | 'string';
};
};
time: {
keyword: 'time';
args: {
type?: 'date' | 'string';
};
};
datetime: {
keyword: 'datetime';
args: {
offset?: boolean;
local?: boolean;
};
};
tuple: {
keyword: 'tuple';
args: {
items: Schema[];
min?: number;
max?: number;
rest?: Schema;
};
};
array: {
keyword: 'array';
args: {
items: Schema[];
min?: number;
max?: number;
unique?: boolean;
};
};
enum: {
keyword: 'enum';
args: {
name: string;
typeName: string;
asConst: boolean;
items: Array<{
name: string | number;
format: 'string' | 'number' | 'boolean';
value?: string | number | boolean;
}>;
};
};
and: {
keyword: 'and';
args: Schema[];
};
const: {
keyword: 'const';
args: {
name: string | number;
format: 'string' | 'number' | 'boolean';
value?: string | number | boolean;
};
};
union: {
keyword: 'union';
args: Schema[];
};
ref: {
keyword: 'ref';
args: {
name: string;
$ref: string;
/**
* Full qualified path.
*/
path: OptionalPath;
/**
* When true `File.Import` will be used.
* When false a reference will be used inside the current file.
*/
isImportable: boolean;
};
};
matches: {
keyword: 'matches';
args?: string;
};
boolean: {
keyword: 'boolean';
};
default: {
keyword: 'default';
args: string | number | boolean;
};
string: {
keyword: 'string';
};
integer: {
keyword: 'integer';
};
number: {
keyword: 'number';
};
max: {
keyword: 'max';
args: number;
};
min: {
keyword: 'min';
args: number;
};
describe: {
keyword: 'describe';
args: string;
};
example: {
keyword: 'example';
args: string;
};
deprecated: {
keyword: 'deprecated';
};
optional: {
keyword: 'optional';
};
undefined: {
keyword: 'undefined';
};
nullish: {
keyword: 'nullish';
};
nullable: {
keyword: 'nullable';
};
null: {
keyword: 'null';
};
any: {
keyword: 'any';
};
unknown: {
keyword: 'unknown';
};
void: {
keyword: 'void';
};
blob: {
keyword: 'blob';
};
schema: {
keyword: 'schema';
args: {
type: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object';
format?: string;
};
};
name: {
keyword: 'name';
args: string;
};
catchall: {
keyword: 'catchall';
};
interface: {
keyword: 'interface';
};
};
type Schema = {
keyword: string;
} | SchemaKeywordMapper[keyof SchemaKeywordMapper];
//#endregion
//#region ../plugin-oas/src/types.d.ts
type ResolvePathOptions = {
pluginKey?: Plugin['key'];
group?: {
tag?: string;
path?: string;
};
type?: ResolveNameParams['type'];
};
/**
* `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: OptionalPath;
pluginKey?: Plugin['key'];
};
type Refs = Record<string, Ref>;
type OperationSchema = {
/**
* Converted name, contains already `PathParams`, `QueryParams`, ...
*/
name: string;
schema: SchemaObject$1;
operation?: Operation$1;
/**
* 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$1 = ByTag | ByOperationId | ByPath | ByMethod | ByContentType;
type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType;
type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
options: Partial<TOptions>;
};
//#endregion
//#region ../plugin-oas/src/SchemaGenerator.d.ts
type Context$1<TOptions, TPluginOptions extends PluginFactoryOptions> = {
oas: Oas;
pluginManager: PluginManager;
/**
* Current plugin
*/
plugin: Plugin<TPluginOptions>;
mode: Mode;
include?: Array<'schemas' | 'responses' | 'requestBodies'>;
override: Array<Override<TOptions>> | undefined;
contentType?: contentType;
output?: string;
};
type SchemaGeneratorOptions = {
dateType: false | 'string' | 'stringOffset' | 'stringLocal' | 'date';
unknownType: 'any' | 'unknown' | 'void';
emptySchemaType: 'any' | 'unknown' | 'void';
enumType?: 'enum' | 'asConst' | 'asPascalConst' | 'constEnum' | 'literal';
enumSuffix?: string;
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(propertName) and return FakerMeta array
* TODO TODO add docs
* @beta
*/
schema?: (schemaProps: SchemaProps$1, defaultSchemas: Schema[]) => Schema[] | undefined;
};
};
type SchemaProps$1 = {
schemaObject?: SchemaObject$1;
name?: string;
parentName?: string;
};
declare class SchemaGenerator<TOptions extends SchemaGeneratorOptions = SchemaGeneratorOptions, TPluginOptions extends PluginFactoryOptions = PluginFactoryOptions, TFileMeta extends FileMetaBase = FileMetaBase> extends BaseGenerator<TOptions, Context$1<TOptions, TPluginOptions>> {
#private;
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[];
deepSearch<T extends keyof SchemaKeywordMapper>(tree: Schema[] | undefined, keyword: T): Array<SchemaKeywordMapper[T]>;
find<T extends keyof SchemaKeywordMapper>(tree: Schema[] | undefined, keyword: T): SchemaKeywordMapper[T] | undefined;
static deepSearch<T extends keyof SchemaKeywordMapper>(tree: Schema[] | undefined, keyword: T): Array<SchemaKeywordMapper[T]>;
static findInObject<T extends keyof SchemaKeywordMapper>(tree: Schema[] | undefined, keyword: T): SchemaKeywordMapper[T] | undefined;
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>>): Promise<Array<File<TFileMeta>>>;
}
//#endregion
//#region ../plugin-oas/src/generator.d.ts
type OperationsProps<TOptions extends PluginFactoryOptions> = {
instance: Omit<OperationGenerator<TOptions>, 'build'>;
options: TOptions['resolvedOptions'];
operations: Array<Operation$1>;
};
type OperationProps<TOptions extends PluginFactoryOptions> = {
instance: Omit<OperationGenerator<TOptions>, 'build'>;
options: TOptions['resolvedOptions'];
operation: Operation$1;
};
type SchemaProps<TOptions extends PluginFactoryOptions> = {
instance: Omit<SchemaGenerator<SchemaGeneratorOptions, TOptions>, 'build'>;
options: TOptions['resolvedOptions'];
schema: {
name: string;
tree: Array<Schema>;
value: SchemaObject$1;
};
};
type GeneratorOptions<TOptions extends PluginFactoryOptions> = {
name: string;
operations?: (this: GeneratorOptions<TOptions>, props: OperationsProps<TOptions>) => Promise<File[]>;
operation?: (this: GeneratorOptions<TOptions>, props: OperationProps<TOptions>) => Promise<File[]>;
schema?: (this: GeneratorOptions<TOptions>, props: SchemaProps<TOptions>) => Promise<File[]>;
};
type Generator<TOptions extends PluginFactoryOptions> = GeneratorOptions<TOptions>;
//#endregion
//#region ../plugin-oas/src/OperationGenerator.d.ts
type Context<TOptions, TPluginOptions extends PluginFactoryOptions> = {
oas: Oas;
exclude: Array<Exclude$1> | undefined;
include: Array<Include> | undefined;
override: Array<Override<TOptions>> | undefined;
contentType: contentType | undefined;
pluginManager: PluginManager;
/**
* Current plugin
*/
plugin: Plugin<TPluginOptions>;
mode: Mode;
};
declare class OperationGenerator<TPluginOptions extends PluginFactoryOptions = PluginFactoryOptions, TFileMeta extends FileMetaBase = FileMetaBase> extends BaseGenerator<TPluginOptions['resolvedOptions'], Context<TPluginOptions['resolvedOptions'], TPluginOptions>> {
#private;
getSchemas(operation: Operation$1, {
resolveName
}?: {
resolveName?: (name: string) => string;
}): OperationSchemas;
getOperations(): Promise<Array<{
path: string;
method: HttpMethod;
operation: Operation$1;
}>>;
build(...generators: Array<Generator<TPluginOptions>>): Promise<Array<File<TFileMeta>>>;
}
//#endregion
//#region ../plugin-client/src/types.d.ts
type Options$2 = {
/**
* Specify the export location for the files and define the behavior of the output
* @default { path: 'clients', barrelType: 'named' }
*/
output?: Output<Oas>;
/**
* Define which contentType should be used.
* By default, the first JSON valid mediaType will be used
*/
contentType?: contentType;
/**
* Group the clients based on the provided name.
*/
group?: Group;
/**
* Array containing exclude parameters to exclude/skip tags/operations/methods/paths.
*/
exclude?: Array<Exclude$1>;
/**
* Array containing include parameters to include tags/operations/methods/paths.
*/
include?: Array<Include>;
/**
* Array containing override parameters to override `options` based on tags/operations/methods/paths.
*/
override?: Array<Override<ResolvedOptions$1>>;
/**
* Create `operations.ts` file with all operations grouped by methods.
* @default false
*/
operations?: boolean;
/**
* Export urls that are used by operation x
* `export` will make them part of your barrel file
* false will not make them exportable
* @example getGetPetByIdUrl
*/
urlType?: 'export' | false;
/**
* Path to the client import path that will be used to do the API calls.
* It will be used as `import client from '${client.importPath}'`.
* It allows both relative and absolute path but be aware that we will not change the path.
* @default '@kubb/plugin-client/clients/axios'
*/
importPath?: string;
/**
* Allows you to set a custom base url for all generated calls.
*/
baseURL?: string;
/**
* ReturnType that will be used when calling the client.
* - 'data' will return ResponseConfig[data].
* - 'full' will return ResponseConfig.
* @default 'data'
*/
dataReturnType?: 'data' | 'full';
/**
* How to style your params, by default no casing is applied
* - 'camelcase' will use camelcase for the params names
*/
paramsCasing?: 'camelcase';
/**
* How to pass your params
* - 'object' will return the params and pathParams as an object.
* - 'inline' will return the params as comma separated params.
* @default 'inline'
*/
paramsType?: 'object' | 'inline';
/**
* How to pass your pathParams.
* - 'object' will return the pathParams as an object.
* - 'inline' will return the pathParams as comma separated params.
* @default 'inline'
*/
pathParamsType?: 'object' | 'inline';
/**
* Which parser can be used before returning the data
* - 'zod' will use `@kubb/plugin-zod` to parse the data.
* @default 'client'
*/
parser?: 'client' | 'zod';
/**
* Which client should be used to do the HTTP calls
* - 'axios' will use `@kubb/plugin-client/clients/axios` to fetch data.
* - 'fetch' will use `@kubb/plugin-client/clients/fetch` to fetch data.
* @default 'axios'
*/
client?: 'axios' | 'fetch';
transformers?: {
/**
* Customize the names based on the type that is provided by the plugin.
*/
name?: (name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string;
};
/**
* Define some generators next to the client generators
*/
generators?: Array<Generator<PluginClient>>;
};
type ResolvedOptions$1 = {
output: Output<Oas>;
group?: Options$2['group'];
baseURL: string | undefined;
parser: NonNullable<Options$2['parser']>;
urlType: NonNullable<Options$2['urlType']>;
importPath: NonNullable<Options$2['importPath']>;
dataReturnType: NonNullable<Options$2['dataReturnType']>;
pathParamsType: NonNullable<Options$2['pathParamsType']>;
paramsType: NonNullable<Options$2['paramsType']>;
paramsCasing: Options$2['paramsCasing'];
};
type PluginClient = PluginFactoryOptions<'plugin-client', Options$2, ResolvedOptions$1, never, ResolvePathOptions>;
//#endregion
//#region src/types.d.ts
type TransformerProps = {
operation: Operation$1;
schemas: OperationSchemas;
casing: 'camelcase' | undefined;
};
type Transformer = (props: TransformerProps) => unknown[];
type Suspense = object;
/**
* Customize the queryKey
*/
type QueryKey = Transformer;
/**
* Customize the mutationKey
*/
type MutationKey = Transformer;
type Query = {
/**
* Define which HttpMethods can be used for queries
* @default ['get']
*/
methods: Array<HttpMethod>;
/**
* Path to the useQuery that will be used to do the useQuery functionality.
* It will be used as `import { useQuery } from '${importPath}'`.
* It allows both relative and absolute path.
* the path will be applied as is, so relative path should be based on the file being generated.
* @default '@tanstack/react-query'
*/
importPath?: string;
};
type Mutation = {
/**
* Define which HttpMethods can be used for mutations
* @default ['post', 'put', 'delete']
*/
methods: Array<HttpMethod>;
/**
* Path to the useQuery that will be used to do the useQuery functionality.
* It will be used as `import { useQuery } from '${importPath}'`.
* It allows both relative and absolute path.
* the path will be applied as is, so relative path should be based on the file being generated.
* @default '@tanstack/react-query'
*/
importPath?: string;
};
type Infinite = {
/**
* Specify the params key used for `pageParam`.
* @default 'id'
*/
queryParam: string;
/**
* Which field of the data will be used, set it to undefined when no cursor is known.
*/
cursorParam?: string | undefined;
/**
* The initial value, the value of the first page.
* @default 0
*/
initialPageParam: unknown;
};
type Options$1 = {
/**
* Specify the export location for the files and define the behavior of the output
* @default { path: 'hooks', barrelType: 'named' }
*/
output?: Output<Oas>;
/**
* Define which contentType should be used.
* By default, the first JSON valid mediaType will be used
*/
contentType?: contentType;
/**
* Group the @tanstack/query hooks based on the provided name.
*/
group?: Group;
client?: Pick<PluginClient['options'], 'dataReturnType' | 'importPath' | 'baseURL'>;
/**
* Array containing exclude parameters to exclude/skip tags/operations/methods/paths.
*/
exclude?: Array<Exclude$1>;
/**
* Array containing include parameters to include tags/operations/methods/paths.
*/
include?: Array<Include>;
/**
* Array containing override parameters to override `options` based on tags/operations/methods/paths.
*/
override?: Array<Override<ResolvedOptions>>;
/**
* How to style your params, by default no casing is applied
* - 'camelcase' will use camelcase for the params names
*/
paramsCasing?: 'camelcase';
/**
* How to pass your params
* - 'object' will return the params and pathParams as an object.
* - 'inline' will return the params as comma separated params.
* @default 'inline'
*/
paramsType?: 'object' | 'inline';
/**
* How to pass your pathParams.
* - 'object' will return the pathParams as an object.
* - 'inline' will return the pathParams as comma separated params.
* @default 'inline'
*/
pathParamsType?: PluginClient['options']['pathParamsType'];
/**
* When set, an infiniteQuery hooks will be added.
*/
infinite?: Partial<Infinite> | false;
/**
* When set, a suspenseQuery hooks will be added.
*/
suspense?: Partial<Suspense> | false;
queryKey?: QueryKey;
/**
* Override some useQuery behaviours.
*/
query?: Partial<Query> | false;
mutationKey?: MutationKey;
/**
* Override some useMutation behaviours.
*/
mutation?: Partial<Mutation> | false;
/**
* Which parser should be used before returning the data to `@tanstack/query`.
* `'zod'` will use `@kubb/plugin-zod` to parse the data.
*/
parser?: PluginClient['options']['parser'];
transformers?: {
/**
* Customize the names based on the type that is provided by the plugin.
*/
name?: (name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string;
};
/**
* Define some generators next to the react-query generators
*/
generators?: Array<Generator<PluginReactQuery>>;
};
type ResolvedOptions = {
output: Output<Oas>;
group: Options$1['group'];
client: Required<Omit<NonNullable<PluginReactQuery['options']['client']>, 'baseURL'>> & {
baseURL?: string;
};
parser: Required<NonNullable<Options$1['parser']>>;
pathParamsType: NonNullable<Options$1['pathParamsType']>;
paramsCasing: Options$1['paramsCasing'];
paramsType: NonNullable<Options$1['paramsType']>;
/**
* Only used of infinite
*/
infinite: NonNullable<Infinite> | false;
suspense: Suspense | false;
queryKey: QueryKey | undefined;
query: NonNullable<Required<Query>> | false;
mutationKey: MutationKey | undefined;
mutation: NonNullable<Required<Mutation>> | false;
};
type PluginReactQuery = PluginFactoryOptions<'plugin-react-query', Options$1, ResolvedOptions, never, ResolvePathOptions>;
//#endregion
export { Generator, Infinite, type Operation$1 as Operation, OperationSchemas, Options$1 as Options, PluginReactQuery, Transformer, UserPluginWithLifeCycle };
//# sourceMappingURL=types-CaU9WTtM.d.ts.map