@kubb/plugin-oas 5.0.0-alpha.31 → 5.0.0-alpha.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/SchemaMapper-CeavHZlp.cjs.map +1 -1
- package/dist/SchemaMapper-CqMkO2T1.js.map +1 -1
- package/dist/{SchemaMapper-gGBRHCTB.d.ts → SchemaMapper-KHABtXIZ.d.ts} +2 -3
- package/dist/{createGenerator-eLDSS4c0.d.ts → createGenerator-CRvsKIrl.d.ts} +26 -28
- package/dist/{generators-85sP4GIS.cjs → generators-DGutWnSj.cjs} +5 -4
- package/dist/generators-DGutWnSj.cjs.map +1 -0
- package/dist/{generators-hPE06pZB.js → generators-rtdUsxQh.js} +5 -4
- package/dist/generators-rtdUsxQh.js.map +1 -0
- package/dist/generators.cjs +1 -1
- package/dist/generators.d.ts +1 -1
- package/dist/generators.js +1 -1
- package/dist/hooks.cjs +2 -3
- package/dist/hooks.cjs.map +1 -1
- package/dist/hooks.d.ts +8 -7
- package/dist/hooks.js +2 -3
- package/dist/hooks.js.map +1 -1
- package/dist/index.cjs +9 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +13 -8
- package/dist/index.js +9 -7
- package/dist/index.js.map +1 -1
- package/dist/mocks.d.ts +1 -1
- package/dist/{requestBody-BO3N7fWH.js → requestBody-DMoaqEak.js} +57 -49
- package/dist/requestBody-DMoaqEak.js.map +1 -0
- package/dist/{requestBody-94hwM4b-.cjs → requestBody-h1zQvUgJ.cjs} +57 -49
- package/dist/requestBody-h1zQvUgJ.cjs.map +1 -0
- package/dist/utils.cjs +4 -3
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.ts +5 -5
- package/dist/utils.js +4 -3
- package/dist/utils.js.map +1 -1
- package/package.json +6 -7
- package/src/OperationGenerator.ts +15 -12
- package/src/SchemaGenerator.ts +11 -10
- package/src/SchemaMapper.ts +1 -2
- package/src/generators/createGenerator.ts +8 -7
- package/src/generators/createReactGenerator.ts +7 -7
- package/src/generators/jsonGenerator.ts +4 -3
- package/src/hooks/useOas.ts +2 -5
- package/src/hooks/useOperationManager.ts +5 -4
- package/src/hooks/useSchemaManager.ts +6 -5
- package/src/plugin.ts +0 -2
- package/src/types.ts +5 -4
- package/src/utils/getImports.ts +5 -4
- package/src/utils/getParams.ts +1 -2
- package/src/utils.tsx +48 -37
- package/dist/generators-85sP4GIS.cjs.map +0 -1
- package/dist/generators-hPE06pZB.js.map +0 -1
- package/dist/requestBody-94hwM4b-.cjs.map +0 -1
- package/dist/requestBody-BO3N7fWH.js.map +0 -1
package/dist/utils.cjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
require("./chunk-ByKO4r7w.cjs");
|
|
3
3
|
const require_getFooter = require("./getFooter-gshcRE1-.cjs");
|
|
4
|
-
const require_requestBody = require("./requestBody-
|
|
4
|
+
const require_requestBody = require("./requestBody-h1zQvUgJ.cjs");
|
|
5
5
|
const require_SchemaMapper = require("./SchemaMapper-CeavHZlp.cjs");
|
|
6
6
|
let _kubb_oas = require("@kubb/oas");
|
|
7
|
+
let _kubb_ast = require("@kubb/ast");
|
|
7
8
|
//#region ../../internals/utils/src/reserved.ts
|
|
8
9
|
/**
|
|
9
10
|
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
@@ -191,10 +192,10 @@ function getImports(tree) {
|
|
|
191
192
|
if (!refs) return [];
|
|
192
193
|
return refs.map((item) => {
|
|
193
194
|
if (!item.args.path || !item.args.isImportable) return;
|
|
194
|
-
return {
|
|
195
|
+
return (0, _kubb_ast.createImport)({
|
|
195
196
|
name: [item.args.name],
|
|
196
197
|
path: item.args.path
|
|
197
|
-
};
|
|
198
|
+
});
|
|
198
199
|
}).filter((x) => x !== void 0);
|
|
199
200
|
}
|
|
200
201
|
//#endregion
|
package/dist/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":["#options","camelCase","#transformParam","#eachParam","SchemaGenerator","schemaKeywords","camelCase","camelCase"],"sources":["../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/utils/getComments.ts","../src/utils/getImports.ts","../src/utils/getParams.ts","../src/utils/getSchemas.ts","../src/utils/paramsCasing.ts"],"sourcesContent":["/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return true\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import { URLPath } from '@internals/utils'\nimport type { Operation } from '@kubb/oas'\n\nexport function getComments(operation: Operation): string[] {\n return [\n operation.getDescription() && `@description ${operation.getDescription()}`,\n operation.getSummary() && `@summary ${operation.getSummary()}`,\n operation.path && `{@link ${new URLPath(operation.path).URL}}`,\n operation.isDeprecated() && '@deprecated',\n ]\n .filter((x): x is string => Boolean(x))\n .flatMap((text) => {\n return text.split(/\\r?\\n/).map((line) => line.trim())\n })\n .filter((x): x is string => Boolean(x))\n}\n","import type { KubbFile } from '@kubb/core'\nimport { SchemaGenerator } from '../SchemaGenerator.ts'\nimport type { Schema } from '../SchemaMapper'\nimport { schemaKeywords } from '../SchemaMapper'\n\n/**\n * Get imports from a schema tree by extracting all ref schemas that are importable\n */\nexport function getImports(tree: Array<Schema>): Array<KubbFile.Import> {\n const refs = SchemaGenerator.deepSearch(tree, schemaKeywords.ref)\n\n if (!refs) return []\n\n return refs\n .map((item) => {\n if (!item.args.path || !item.args.isImportable) {\n return undefined\n }\n\n return {\n name: [item.args.name],\n path: item.args.path,\n } satisfies KubbFile.Import\n })\n .filter((x): x is NonNullable<typeof x> => x !== undefined)\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { FunctionParamsAST } from '@kubb/core'\nimport type { OasTypes } from '@kubb/oas'\nimport type { Params } from '@kubb/react-fabric/types'\nimport type { OperationSchema } from '../types.ts'\n/**\n *\n * @deprecated\n * TODO move to operationManager hook\n */\nexport function getASTParams(\n operationSchema: OperationSchema | undefined,\n {\n typed = false,\n casing,\n override,\n }: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n): FunctionParamsAST[] {\n if (!operationSchema?.schema.properties || !operationSchema.name) {\n return []\n }\n\n const requiredFields = Array.isArray(operationSchema.schema.required) ? operationSchema.schema.required : []\n\n return Object.entries(operationSchema.schema.properties).map(([name]: [string, OasTypes.SchemaObject]) => {\n // Use camelCase name for indexed access if casing is enabled\n const accessName = casing === 'camelcase' ? camelCase(name) : name\n\n const data: FunctionParamsAST = {\n name,\n enabled: !!name,\n required: requiredFields.includes(name),\n type: typed ? `${operationSchema.name}[\"${accessName}\"]` : undefined,\n }\n\n return override ? override(data) : data\n })\n}\n\nexport function getPathParams(\n operationSchema: OperationSchema | undefined,\n options: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n) {\n return getASTParams(operationSchema, options).reduce((acc, curr) => {\n if (curr.name && curr.enabled) {\n let name = curr.name\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n name = camelCase(name)\n } else if (!isValidVarName(name)) {\n // If not valid variable name and casing not set, still need to make it valid\n name = camelCase(name)\n }\n\n acc[name] = {\n default: curr.default,\n type: curr.type,\n optional: !curr.required,\n }\n }\n\n return acc\n }, {} as Params)\n}\n\n/**\n * Get a mapping of camelCase parameter names to their original names\n * Used for mapping function parameters to backend parameter names\n */\nexport function getParamsMapping(\n operationSchema: OperationSchema | undefined,\n options: {\n casing?: 'camelcase'\n } = {},\n): Record<string, string> | undefined {\n if (!operationSchema?.schema.properties) {\n return undefined\n }\n\n const allEntries: Array<[string, string]> = []\n let hasTransformation = false\n\n Object.entries(operationSchema.schema.properties).forEach(([originalName]) => {\n let transformedName = originalName\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name and casing not set, still need to make it valid\n transformedName = camelCase(originalName)\n }\n\n allEntries.push([originalName, transformedName])\n\n if (transformedName !== originalName) {\n hasTransformation = true\n }\n })\n\n // When using explicit casing and there are transformations, include ALL params so that\n // mappedParams contains every parameter (not just the ones whose names changed).\n // This prevents params with already-camelCase names (e.g. 'page', 'search') from being\n // silently dropped when other params in the same schema do need transformation.\n if (options.casing === 'camelcase' && hasTransformation) {\n return Object.fromEntries(allEntries)\n }\n\n // When casing is not specified or no transformations are needed, only return changed entries\n const mapping: Record<string, string> = {}\n allEntries.forEach(([originalName, transformedName]) => {\n if (transformedName !== originalName) {\n mapping[originalName] = transformedName\n }\n })\n\n return Object.keys(mapping).length > 0 ? mapping : undefined\n}\n","import type { contentType, Oas, OasTypes } from '@kubb/oas'\n\nexport type GetSchemasResult = {\n schemas: Record<string, OasTypes.SchemaObject>\n /**\n * Mapping from original component name to resolved name after collision handling\n * e.g., { 'Order': 'OrderSchema', 'variant': 'variant2' }\n */\n nameMapping: Map<string, string>\n}\n\ntype Mode = 'schemas' | 'responses' | 'requestBodies'\n\ntype GetSchemasProps = {\n oas: Oas\n contentType?: contentType\n includes?: Mode[]\n /**\n * Whether to resolve name collisions with suffixes.\n * If not provided, uses oas.options.collisionDetection\n * @default false (from oas.options or fallback)\n */\n collisionDetection?: boolean\n}\n\n/**\n * Collect schemas from OpenAPI components (schemas, responses, requestBodies)\n * and return them in dependency order along with name mapping for collision resolution.\n *\n * This function is a wrapper around the oas.getSchemas() method for backward compatibility.\n * New code should use oas.getSchemas() directly.\n *\n * @deprecated Use oas.getSchemas() instead\n */\nexport function getSchemas({ oas, contentType, includes = ['schemas', 'requestBodies', 'responses'], collisionDetection }: GetSchemasProps): GetSchemasResult {\n return oas.getSchemas({\n contentType,\n includes,\n collisionDetection,\n })\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { SchemaObject } from '@kubb/oas'\n\n/**\n * Apply casing transformation to schema properties\n * Only transforms property names, not nested schemas\n */\nexport function applyParamsCasing(schema: SchemaObject, casing: 'camelcase' | undefined): SchemaObject {\n if (!casing || !schema.properties) {\n return schema\n }\n\n const transformedProperties: Record<string, any> = {}\n const transformedRequired: string[] = []\n\n // Transform property names\n Object.entries(schema.properties).forEach(([originalName, propertySchema]) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name, make it valid\n transformedName = camelCase(originalName)\n }\n\n transformedProperties[transformedName] = propertySchema\n })\n\n // Transform required field names\n if (Array.isArray(schema.required)) {\n schema.required.forEach((originalName) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n transformedName = camelCase(originalName)\n }\n\n transformedRequired.push(transformedName)\n })\n }\n\n // Return a new schema with transformed properties and required fields\n return {\n ...schema,\n properties: transformedProperties,\n ...(transformedRequired.length > 0 && { required: transformedRequired }),\n } as SchemaObject\n}\n\n/**\n * Check if this schema is a parameter schema (pathParams, queryParams, or headerParams)\n * Only these should be transformed, not response/data/body\n */\nexport function isParameterSchema(schemaName: string): boolean {\n const lowerName = schemaName.toLowerCase()\n return lowerName.includes('pathparams') || lowerName.includes('queryparams') || lowerName.includes('headerparams')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoHA,SAAgB,eAAe,MAAuB;AACpD,KAAI;AACF,MAAI,SAAS,OAAO,OAAO;SACrB;AACN,SAAO;;AAET,QAAO;;;;;;;;;;;;ACvET,IAAa,UAAb,MAAqB;;;;CAInB;CAEA;CAEA,YAAY,MAAc,UAAmB,EAAE,EAAE;AAC/C,OAAK,OAAO;AACZ,QAAA,UAAgB;;;;;;;;;CAUlB,IAAI,MAAc;AAChB,SAAO,KAAK,WAAW;;;;;;;;;;CAWzB,IAAI,QAAiB;AACnB,MAAI;AACF,UAAO,CAAC,CAAC,IAAI,IAAI,KAAK,KAAK,CAAC;UACtB;AACN,UAAO;;;;;;;;;;CAWX,IAAI,WAAmB;AACrB,SAAO,KAAK,kBAAkB;;;;;;;;;;CAWhC,IAAI,SAA6B;AAC/B,SAAO,KAAK,UAAU;;;;;;;;;;CAWxB,IAAI,SAA6C;AAC/C,SAAO,KAAK,WAAW;;CAGzB,gBAAgB,KAAqB;EACnC,MAAM,QAAQ,eAAe,IAAI,GAAG,MAAMC,kBAAAA,UAAU,IAAI;AACxD,SAAO,MAAA,QAAc,WAAW,cAAcA,kBAAAA,UAAU,MAAM,GAAG;;;;;CAMnE,WAAW,IAAgD;AACzD,OAAK,MAAM,SAAS,KAAK,KAAK,SAAS,eAAe,EAAE;GACtD,MAAM,MAAM,MAAM;AAClB,MAAG,KAAK,MAAA,eAAqB,IAAI,CAAC;;;CAItC,SAAS,EAAE,OAAO,QAAQ,UAAU,cAA6B,EAAE,EAAsB;EACvF,MAAM,SAAS;GACb,KAAK,SAAS,SAAS,KAAK,WAAW,GAAG,KAAK,iBAAiB,EAAE,UAAU,CAAC;GAC7E,QAAQ,KAAK,WAAW;GACzB;AAED,MAAI,WAAW;AACb,OAAI,SAAS,WACX,QAAO,KAAK,UAAU,OAAO,CAAC,WAAW,KAAK,GAAG,CAAC,W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AM,QAAQ,OAAO,SAAS,CAChC,QAAO,SAAS,SAAS,iBAAiB;EACxC,IAAI,kBAAkB;AAEtB,MAAI,WAAW,YACb,mBAAkBA,kBAAAA,UAAU,aAAa;WAChC,CAAC,eAAe,aAAa,CACtC,mBAAkBA,kBAAAA,UAAU,aAAa;AAG3C,sBAAoB,KAAK,gBAAgB;GACzC;AAIJ,QAAO;EACL,GAAG;EACH,YAAY;EACZ,GAAI,oBAAoB,SAAS,KAAK,EAAE,UAAU,qBAAqB;EACxE;;;;;;AAOH,SAAgB,kBAAkB,YAA6B;CAC7D,MAAM,YAAY,WAAW,aAAa;AAC1C,QAAO,UAAU,SAAS,aAAa,IAAI,UAAU,SAAS,cAAc,IAAI,UAAU,SAAS,eAAe"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["#options","camelCase","#transformParam","#eachParam","SchemaGenerator","schemaKeywords","camelCase","camelCase"],"sources":["../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/utils/getComments.ts","../src/utils/getImports.ts","../src/utils/getParams.ts","../src/utils/getSchemas.ts","../src/utils/paramsCasing.ts"],"sourcesContent":["/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return true\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import { URLPath } from '@internals/utils'\nimport type { Operation } from '@kubb/oas'\n\nexport function getComments(operation: Operation): string[] {\n return [\n operation.getDescription() && `@description ${operation.getDescription()}`,\n operation.getSummary() && `@summary ${operation.getSummary()}`,\n operation.path && `{@link ${new URLPath(operation.path).URL}}`,\n operation.isDeprecated() && '@deprecated',\n ]\n .filter((x): x is string => Boolean(x))\n .flatMap((text) => {\n return text.split(/\\r?\\n/).map((line) => line.trim())\n })\n .filter((x): x is string => Boolean(x))\n}\n","import { createImport } from '@kubb/ast'\nimport type { ImportNode } from '@kubb/ast/types'\nimport { SchemaGenerator } from '../SchemaGenerator.ts'\nimport type { Schema } from '../SchemaMapper'\nimport { schemaKeywords } from '../SchemaMapper'\n\n/**\n * Get imports from a schema tree by extracting all ref schemas that are importable\n */\nexport function getImports(tree: Array<Schema>): Array<ImportNode> {\n const refs = SchemaGenerator.deepSearch(tree, schemaKeywords.ref)\n\n if (!refs) return []\n\n return refs\n .map((item) => {\n if (!item.args.path || !item.args.isImportable) {\n return undefined\n }\n\n return createImport({\n name: [item.args.name],\n path: item.args.path,\n })\n })\n .filter((x): x is NonNullable<typeof x> => x !== undefined)\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { FunctionParamsAST, Params } from '@kubb/core'\nimport type { OasTypes } from '@kubb/oas'\nimport type { OperationSchema } from '../types.ts'\n/**\n *\n * @deprecated\n * TODO move to operationManager hook\n */\nexport function getASTParams(\n operationSchema: OperationSchema | undefined,\n {\n typed = false,\n casing,\n override,\n }: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n): FunctionParamsAST[] {\n if (!operationSchema?.schema.properties || !operationSchema.name) {\n return []\n }\n\n const requiredFields = Array.isArray(operationSchema.schema.required) ? operationSchema.schema.required : []\n\n return Object.entries(operationSchema.schema.properties).map(([name]: [string, OasTypes.SchemaObject]) => {\n // Use camelCase name for indexed access if casing is enabled\n const accessName = casing === 'camelcase' ? camelCase(name) : name\n\n const data: FunctionParamsAST = {\n name,\n enabled: !!name,\n required: requiredFields.includes(name),\n type: typed ? `${operationSchema.name}[\"${accessName}\"]` : undefined,\n }\n\n return override ? override(data) : data\n })\n}\n\nexport function getPathParams(\n operationSchema: OperationSchema | undefined,\n options: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n) {\n return getASTParams(operationSchema, options).reduce((acc, curr) => {\n if (curr.name && curr.enabled) {\n let name = curr.name\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n name = camelCase(name)\n } else if (!isValidVarName(name)) {\n // If not valid variable name and casing not set, still need to make it valid\n name = camelCase(name)\n }\n\n acc[name] = {\n default: curr.default,\n type: curr.type,\n optional: !curr.required,\n }\n }\n\n return acc\n }, {} as Params)\n}\n\n/**\n * Get a mapping of camelCase parameter names to their original names\n * Used for mapping function parameters to backend parameter names\n */\nexport function getParamsMapping(\n operationSchema: OperationSchema | undefined,\n options: {\n casing?: 'camelcase'\n } = {},\n): Record<string, string> | undefined {\n if (!operationSchema?.schema.properties) {\n return undefined\n }\n\n const allEntries: Array<[string, string]> = []\n let hasTransformation = false\n\n Object.entries(operationSchema.schema.properties).forEach(([originalName]) => {\n let transformedName = originalName\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name and casing not set, still need to make it valid\n transformedName = camelCase(originalName)\n }\n\n allEntries.push([originalName, transformedName])\n\n if (transformedName !== originalName) {\n hasTransformation = true\n }\n })\n\n // When using explicit casing and there are transformations, include ALL params so that\n // mappedParams contains every parameter (not just the ones whose names changed).\n // This prevents params with already-camelCase names (e.g. 'page', 'search') from being\n // silently dropped when other params in the same schema do need transformation.\n if (options.casing === 'camelcase' && hasTransformation) {\n return Object.fromEntries(allEntries)\n }\n\n // When casing is not specified or no transformations are needed, only return changed entries\n const mapping: Record<string, string> = {}\n allEntries.forEach(([originalName, transformedName]) => {\n if (transformedName !== originalName) {\n mapping[originalName] = transformedName\n }\n })\n\n return Object.keys(mapping).length > 0 ? mapping : undefined\n}\n","import type { contentType, Oas, OasTypes } from '@kubb/oas'\n\nexport type GetSchemasResult = {\n schemas: Record<string, OasTypes.SchemaObject>\n /**\n * Mapping from original component name to resolved name after collision handling\n * e.g., { 'Order': 'OrderSchema', 'variant': 'variant2' }\n */\n nameMapping: Map<string, string>\n}\n\ntype Mode = 'schemas' | 'responses' | 'requestBodies'\n\ntype GetSchemasProps = {\n oas: Oas\n contentType?: contentType\n includes?: Mode[]\n /**\n * Whether to resolve name collisions with suffixes.\n * If not provided, uses oas.options.collisionDetection\n * @default false (from oas.options or fallback)\n */\n collisionDetection?: boolean\n}\n\n/**\n * Collect schemas from OpenAPI components (schemas, responses, requestBodies)\n * and return them in dependency order along with name mapping for collision resolution.\n *\n * This function is a wrapper around the oas.getSchemas() method for backward compatibility.\n * New code should use oas.getSchemas() directly.\n *\n * @deprecated Use oas.getSchemas() instead\n */\nexport function getSchemas({ oas, contentType, includes = ['schemas', 'requestBodies', 'responses'], collisionDetection }: GetSchemasProps): GetSchemasResult {\n return oas.getSchemas({\n contentType,\n includes,\n collisionDetection,\n })\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { SchemaObject } from '@kubb/oas'\n\n/**\n * Apply casing transformation to schema properties\n * Only transforms property names, not nested schemas\n */\nexport function applyParamsCasing(schema: SchemaObject, casing: 'camelcase' | undefined): SchemaObject {\n if (!casing || !schema.properties) {\n return schema\n }\n\n const transformedProperties: Record<string, any> = {}\n const transformedRequired: string[] = []\n\n // Transform property names\n Object.entries(schema.properties).forEach(([originalName, propertySchema]) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name, make it valid\n transformedName = camelCase(originalName)\n }\n\n transformedProperties[transformedName] = propertySchema\n })\n\n // Transform required field names\n if (Array.isArray(schema.required)) {\n schema.required.forEach((originalName) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n transformedName = camelCase(originalName)\n }\n\n transformedRequired.push(transformedName)\n })\n }\n\n // Return a new schema with transformed properties and required fields\n return {\n ...schema,\n properties: transformedProperties,\n ...(transformedRequired.length > 0 && { required: transformedRequired }),\n } as SchemaObject\n}\n\n/**\n * Check if this schema is a parameter schema (pathParams, queryParams, or headerParams)\n * Only these should be transformed, not response/data/body\n */\nexport function isParameterSchema(schemaName: string): boolean {\n const lowerName = schemaName.toLowerCase()\n return lowerName.includes('pathparams') || lowerName.includes('queryparams') || lowerName.includes('headerparams')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoHA,SAAgB,eAAe,MAAuB;AACpD,KAAI;AACF,MAAI,SAAS,OAAO,OAAO;SACrB;AACN,SAAO;;AAET,QAAO;;;;;;;;;;;;ACvET,IAAa,UAAb,MAAqB;;;;CAInB;CAEA;CAEA,YAAY,MAAc,UAAmB,EAAE,EAAE;AAC/C,OAAK,OAAO;AACZ,QAAA,UAAgB;;;;;;;;;CAUlB,IAAI,MAAc;AAChB,SAAO,KAAK,WAAW;;;;;;;;;;CAWzB,IAAI,QAAiB;AACnB,MAAI;AACF,UAAO,CAAC,CAAC,IAAI,IAAI,KAAK,KAAK,CAAC;UACtB;AACN,UAAO;;;;;;;;;;CAWX,IAAI,WAAmB;AACrB,SAAO,KAAK,kBAAkB;;;;;;;;;;CAWhC,IAAI,SAA6B;AAC/B,SAAO,KAAK,UAAU;;;;;;;;;;CAWxB,IAAI,SAA6C;AAC/C,SAAO,KAAK,WAAW;;CAGzB,gBAAgB,KAAqB;EACnC,MAAM,QAAQ,eAAe,IAAI,GAAG,MAAMC,kBAAAA,UAAU,IAAI;AACxD,SAAO,MAAA,QAAc,WA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AW;CAAC;CAAW;CAAiB;CAAY,EAAE,sBAAyD;AAC5J,QAAO,IAAI,WAAW;EACpB;EACA;EACA;EACD,CAAC;;;;;;;;AChCJ,SAAgB,kBAAkB,QAAsB,QAA+C;AACrG,KAAI,CAAC,UAAU,CAAC,OAAO,WACrB,QAAO;CAGT,MAAM,wBAA6C,EAAE;CACrD,MAAM,sBAAgC,EAAE;AAGxC,QAAO,QAAQ,OAAO,WAAW,CAAC,SAAS,CAAC,cAAc,oBAAoB;EAC5E,IAAI,kBAAkB;AAEtB,MAAI,WAAW,YACb,mBAAkBC,kBAAAA,UAAU,aAAa;WAChC,CAAC,eAAe,aAAa,CAEtC,mBAAkBA,kBAAAA,UAAU,aAAa;AAG3C,wBAAsB,mBAAmB;GACzC;AAGF,KAAI,MAAM,QAAQ,OAAO,SAAS,CAChC,QAAO,SAAS,SAAS,iBAAiB;EACxC,IAAI,kBAAkB;AAEtB,MAAI,WAAW,YACb,mBAAkBA,kBAAAA,UAAU,aAAa;WAChC,CAAC,eAAe,aAAa,CACtC,mBAAkBA,kBAAAA,UAAU,aAAa;AAG3C,sBAAoB,KAAK,gBAAgB;GACzC;AAIJ,QAAO;EACL,GAAG;EACH,YAAY;EACZ,GAAI,oBAAoB,SAAS,KAAK,EAAE,UAAU,qBAAqB;EACxE;;;;;;AAOH,SAAgB,kBAAkB,YAA6B;CAC7D,MAAM,YAAY,WAAW,aAAa;AAC1C,QAAO,UAAU,SAAS,aAAa,IAAI,UAAU,SAAS,cAAc,IAAI,UAAU,SAAS,eAAe"}
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as __name } from "./chunk--u3MIqq1.js";
|
|
2
|
-
import { h as OperationSchema } from "./createGenerator-
|
|
3
|
-
import { t as Schema } from "./SchemaMapper-
|
|
2
|
+
import { h as OperationSchema } from "./createGenerator-CRvsKIrl.js";
|
|
3
|
+
import { t as Schema } from "./SchemaMapper-KHABtXIZ.js";
|
|
4
4
|
import { Oas, OasTypes, OpenAPIV3, OpenAPIV3_1, Operation, SchemaObject, contentType, isOptional } from "@kubb/oas";
|
|
5
|
-
import { Config, FunctionParamsAST,
|
|
6
|
-
import {
|
|
5
|
+
import { Config, FunctionParamsAST, Output, Params } from "@kubb/core";
|
|
6
|
+
import { ImportNode } from "@kubb/ast/types";
|
|
7
7
|
|
|
8
8
|
//#region src/utils/getBanner.d.ts
|
|
9
9
|
type Props$1<TOas extends Oas> = {
|
|
@@ -34,7 +34,7 @@ declare function getFooter<TOas extends Oas>({
|
|
|
34
34
|
/**
|
|
35
35
|
* Get imports from a schema tree by extracting all ref schemas that are importable
|
|
36
36
|
*/
|
|
37
|
-
declare function getImports(tree: Array<Schema>): Array<
|
|
37
|
+
declare function getImports(tree: Array<Schema>): Array<ImportNode>;
|
|
38
38
|
//#endregion
|
|
39
39
|
//#region src/utils/getParams.d.ts
|
|
40
40
|
declare function getPathParams(operationSchema: OperationSchema | undefined, options?: {
|
package/dist/utils.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import "./chunk--u3MIqq1.js";
|
|
2
2
|
import { n as getBanner, r as camelCase, t as getFooter } from "./getFooter-Dz4u5Mg4.js";
|
|
3
|
-
import { n as withRequiredRequestBodySchema, r as SchemaGenerator, s as getSchemaFactory, t as isRequestBodyRequired } from "./requestBody-
|
|
3
|
+
import { n as withRequiredRequestBodySchema, r as SchemaGenerator, s as getSchemaFactory, t as isRequestBodyRequired } from "./requestBody-DMoaqEak.js";
|
|
4
4
|
import { n as schemaKeywords } from "./SchemaMapper-CqMkO2T1.js";
|
|
5
5
|
import { isOptional } from "@kubb/oas";
|
|
6
|
+
import { createImport } from "@kubb/ast";
|
|
6
7
|
//#region ../../internals/utils/src/reserved.ts
|
|
7
8
|
/**
|
|
8
9
|
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
@@ -190,10 +191,10 @@ function getImports(tree) {
|
|
|
190
191
|
if (!refs) return [];
|
|
191
192
|
return refs.map((item) => {
|
|
192
193
|
if (!item.args.path || !item.args.isImportable) return;
|
|
193
|
-
return {
|
|
194
|
+
return createImport({
|
|
194
195
|
name: [item.args.name],
|
|
195
196
|
path: item.args.path
|
|
196
|
-
};
|
|
197
|
+
});
|
|
197
198
|
}).filter((x) => x !== void 0);
|
|
198
199
|
}
|
|
199
200
|
//#endregion
|
package/dist/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["#options","#transformParam","#eachParam"],"sources":["../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/utils/getComments.ts","../src/utils/getImports.ts","../src/utils/getParams.ts","../src/utils/getSchemas.ts","../src/utils/paramsCasing.ts"],"sourcesContent":["/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return true\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import { URLPath } from '@internals/utils'\nimport type { Operation } from '@kubb/oas'\n\nexport function getComments(operation: Operation): string[] {\n return [\n operation.getDescription() && `@description ${operation.getDescription()}`,\n operation.getSummary() && `@summary ${operation.getSummary()}`,\n operation.path && `{@link ${new URLPath(operation.path).URL}}`,\n operation.isDeprecated() && '@deprecated',\n ]\n .filter((x): x is string => Boolean(x))\n .flatMap((text) => {\n return text.split(/\\r?\\n/).map((line) => line.trim())\n })\n .filter((x): x is string => Boolean(x))\n}\n","import type { KubbFile } from '@kubb/core'\nimport { SchemaGenerator } from '../SchemaGenerator.ts'\nimport type { Schema } from '../SchemaMapper'\nimport { schemaKeywords } from '../SchemaMapper'\n\n/**\n * Get imports from a schema tree by extracting all ref schemas that are importable\n */\nexport function getImports(tree: Array<Schema>): Array<KubbFile.Import> {\n const refs = SchemaGenerator.deepSearch(tree, schemaKeywords.ref)\n\n if (!refs) return []\n\n return refs\n .map((item) => {\n if (!item.args.path || !item.args.isImportable) {\n return undefined\n }\n\n return {\n name: [item.args.name],\n path: item.args.path,\n } satisfies KubbFile.Import\n })\n .filter((x): x is NonNullable<typeof x> => x !== undefined)\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { FunctionParamsAST } from '@kubb/core'\nimport type { OasTypes } from '@kubb/oas'\nimport type { Params } from '@kubb/react-fabric/types'\nimport type { OperationSchema } from '../types.ts'\n/**\n *\n * @deprecated\n * TODO move to operationManager hook\n */\nexport function getASTParams(\n operationSchema: OperationSchema | undefined,\n {\n typed = false,\n casing,\n override,\n }: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n): FunctionParamsAST[] {\n if (!operationSchema?.schema.properties || !operationSchema.name) {\n return []\n }\n\n const requiredFields = Array.isArray(operationSchema.schema.required) ? operationSchema.schema.required : []\n\n return Object.entries(operationSchema.schema.properties).map(([name]: [string, OasTypes.SchemaObject]) => {\n // Use camelCase name for indexed access if casing is enabled\n const accessName = casing === 'camelcase' ? camelCase(name) : name\n\n const data: FunctionParamsAST = {\n name,\n enabled: !!name,\n required: requiredFields.includes(name),\n type: typed ? `${operationSchema.name}[\"${accessName}\"]` : undefined,\n }\n\n return override ? override(data) : data\n })\n}\n\nexport function getPathParams(\n operationSchema: OperationSchema | undefined,\n options: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n) {\n return getASTParams(operationSchema, options).reduce((acc, curr) => {\n if (curr.name && curr.enabled) {\n let name = curr.name\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n name = camelCase(name)\n } else if (!isValidVarName(name)) {\n // If not valid variable name and casing not set, still need to make it valid\n name = camelCase(name)\n }\n\n acc[name] = {\n default: curr.default,\n type: curr.type,\n optional: !curr.required,\n }\n }\n\n return acc\n }, {} as Params)\n}\n\n/**\n * Get a mapping of camelCase parameter names to their original names\n * Used for mapping function parameters to backend parameter names\n */\nexport function getParamsMapping(\n operationSchema: OperationSchema | undefined,\n options: {\n casing?: 'camelcase'\n } = {},\n): Record<string, string> | undefined {\n if (!operationSchema?.schema.properties) {\n return undefined\n }\n\n const allEntries: Array<[string, string]> = []\n let hasTransformation = false\n\n Object.entries(operationSchema.schema.properties).forEach(([originalName]) => {\n let transformedName = originalName\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name and casing not set, still need to make it valid\n transformedName = camelCase(originalName)\n }\n\n allEntries.push([originalName, transformedName])\n\n if (transformedName !== originalName) {\n hasTransformation = true\n }\n })\n\n // When using explicit casing and there are transformations, include ALL params so that\n // mappedParams contains every parameter (not just the ones whose names changed).\n // This prevents params with already-camelCase names (e.g. 'page', 'search') from being\n // silently dropped when other params in the same schema do need transformation.\n if (options.casing === 'camelcase' && hasTransformation) {\n return Object.fromEntries(allEntries)\n }\n\n // When casing is not specified or no transformations are needed, only return changed entries\n const mapping: Record<string, string> = {}\n allEntries.forEach(([originalName, transformedName]) => {\n if (transformedName !== originalName) {\n mapping[originalName] = transformedName\n }\n })\n\n return Object.keys(mapping).length > 0 ? mapping : undefined\n}\n","import type { contentType, Oas, OasTypes } from '@kubb/oas'\n\nexport type GetSchemasResult = {\n schemas: Record<string, OasTypes.SchemaObject>\n /**\n * Mapping from original component name to resolved name after collision handling\n * e.g., { 'Order': 'OrderSchema', 'variant': 'variant2' }\n */\n nameMapping: Map<string, string>\n}\n\ntype Mode = 'schemas' | 'responses' | 'requestBodies'\n\ntype GetSchemasProps = {\n oas: Oas\n contentType?: contentType\n includes?: Mode[]\n /**\n * Whether to resolve name collisions with suffixes.\n * If not provided, uses oas.options.collisionDetection\n * @default false (from oas.options or fallback)\n */\n collisionDetection?: boolean\n}\n\n/**\n * Collect schemas from OpenAPI components (schemas, responses, requestBodies)\n * and return them in dependency order along with name mapping for collision resolution.\n *\n * This function is a wrapper around the oas.getSchemas() method for backward compatibility.\n * New code should use oas.getSchemas() directly.\n *\n * @deprecated Use oas.getSchemas() instead\n */\nexport function getSchemas({ oas, contentType, includes = ['schemas', 'requestBodies', 'responses'], collisionDetection }: GetSchemasProps): GetSchemasResult {\n return oas.getSchemas({\n contentType,\n includes,\n collisionDetection,\n })\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { SchemaObject } from '@kubb/oas'\n\n/**\n * Apply casing transformation to schema properties\n * Only transforms property names, not nested schemas\n */\nexport function applyParamsCasing(schema: SchemaObject, casing: 'camelcase' | undefined): SchemaObject {\n if (!casing || !schema.properties) {\n return schema\n }\n\n const transformedProperties: Record<string, any> = {}\n const transformedRequired: string[] = []\n\n // Transform property names\n Object.entries(schema.properties).forEach(([originalName, propertySchema]) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name, make it valid\n transformedName = camelCase(originalName)\n }\n\n transformedProperties[transformedName] = propertySchema\n })\n\n // Transform required field names\n if (Array.isArray(schema.required)) {\n schema.required.forEach((originalName) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n transformedName = camelCase(originalName)\n }\n\n transformedRequired.push(transformedName)\n })\n }\n\n // Return a new schema with transformed properties and required fields\n return {\n ...schema,\n properties: transformedProperties,\n ...(transformedRequired.length > 0 && { required: transformedRequired }),\n } as SchemaObject\n}\n\n/**\n * Check if this schema is a parameter schema (pathParams, queryParams, or headerParams)\n * Only these should be transformed, not response/data/body\n */\nexport function isParameterSchema(schemaName: string): boolean {\n const lowerName = schemaName.toLowerCase()\n return lowerName.includes('pathparams') || lowerName.includes('queryparams') || lowerName.includes('headerparams')\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoHA,SAAgB,eAAe,MAAuB;AACpD,KAAI;AACF,MAAI,SAAS,OAAO,OAAO;SACrB;AACN,SAAO;;AAET,QAAO;;;;;;;;;;;;ACvET,IAAa,UAAb,MAAqB;;;;CAInB;CAEA;CAEA,YAAY,MAAc,UAAmB,EAAE,EAAE;AAC/C,OAAK,OAAO;AACZ,QAAA,UAAgB;;;;;;;;;CAUlB,IAAI,MAAc;AAChB,SAAO,KAAK,WAAW;;;;;;;;;;CAWzB,IAAI,QAAiB;AACnB,MAAI;AACF,UAAO,CAAC,CAAC,IAAI,IAAI,KAAK,KAAK,CAAC;UACtB;AACN,UAAO;;;;;;;;;;CAWX,IAAI,WAAmB;AACrB,SAAO,KAAK,kBAAkB;;;;;;;;;;CAWhC,IAAI,SAA6B;AAC/B,SAAO,KAAK,UAAU;;;;;;;;;;CAWxB,IAAI,SAA6C;AAC/C,SAAO,KAAK,WAAW;;CAGzB,gBAAgB,KAAqB;EACnC,MAAM,QAAQ,eAAe,IAAI,GAAG,MAAM,UAAU,IAAI;AACxD,SAAO,MAAA,QAAc,WAAW,cAAc,UAAU,MAAM,GAAG;;;;;CAMnE,WAAW,IAAgD;AACzD,OAAK,MAAM,SAAS,KAAK,KAAK,SAAS,eAAe,EAAE;GACtD,MAAM,MAAM,MAAM;AAClB,MAAG,KAAK,MAAA,eAAqB,IAAI,CAAC;;;CAItC,SAAS,EAAE,OAAO,QAAQ,UAAU,cAA6B,EAAE,EAAsB;EACvF,MAA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YACb,mBAAkB,UAAU,aAAa;WAChC,CAAC,eAAe,aAAa,CAEtC,mBAAkB,UAAU,aAAa;AAG3C,wBAAsB,mBAAmB;GACzC;AAGF,KAAI,MAAM,QAAQ,OAAO,SAAS,CAChC,QAAO,SAAS,SAAS,iBAAiB;EACxC,IAAI,kBAAkB;AAEtB,MAAI,WAAW,YACb,mBAAkB,UAAU,aAAa;WAChC,CAAC,eAAe,aAAa,CACtC,mBAAkB,UAAU,aAAa;AAG3C,sBAAoB,KAAK,gBAAgB;GACzC;AAIJ,QAAO;EACL,GAAG;EACH,YAAY;EACZ,GAAI,oBAAoB,SAAS,KAAK,EAAE,UAAU,qBAAqB;EACxE;;;;;;AAOH,SAAgB,kBAAkB,YAA6B;CAC7D,MAAM,YAAY,WAAW,aAAa;AAC1C,QAAO,UAAU,SAAS,aAAa,IAAI,UAAU,SAAS,cAAc,IAAI,UAAU,SAAS,eAAe"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["#options","#transformParam","#eachParam"],"sources":["../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/utils/getComments.ts","../src/utils/getImports.ts","../src/utils/getParams.ts","../src/utils/getSchemas.ts","../src/utils/paramsCasing.ts"],"sourcesContent":["/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n try {\n new Function(`var ${name}`)\n } catch {\n return false\n }\n return true\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({ prefix = '', replacer }: { prefix?: string; replacer?: (pathParam: string) => string } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import { URLPath } from '@internals/utils'\nimport type { Operation } from '@kubb/oas'\n\nexport function getComments(operation: Operation): string[] {\n return [\n operation.getDescription() && `@description ${operation.getDescription()}`,\n operation.getSummary() && `@summary ${operation.getSummary()}`,\n operation.path && `{@link ${new URLPath(operation.path).URL}}`,\n operation.isDeprecated() && '@deprecated',\n ]\n .filter((x): x is string => Boolean(x))\n .flatMap((text) => {\n return text.split(/\\r?\\n/).map((line) => line.trim())\n })\n .filter((x): x is string => Boolean(x))\n}\n","import { createImport } from '@kubb/ast'\nimport type { ImportNode } from '@kubb/ast/types'\nimport { SchemaGenerator } from '../SchemaGenerator.ts'\nimport type { Schema } from '../SchemaMapper'\nimport { schemaKeywords } from '../SchemaMapper'\n\n/**\n * Get imports from a schema tree by extracting all ref schemas that are importable\n */\nexport function getImports(tree: Array<Schema>): Array<ImportNode> {\n const refs = SchemaGenerator.deepSearch(tree, schemaKeywords.ref)\n\n if (!refs) return []\n\n return refs\n .map((item) => {\n if (!item.args.path || !item.args.isImportable) {\n return undefined\n }\n\n return createImport({\n name: [item.args.name],\n path: item.args.path,\n })\n })\n .filter((x): x is NonNullable<typeof x> => x !== undefined)\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { FunctionParamsAST, Params } from '@kubb/core'\nimport type { OasTypes } from '@kubb/oas'\nimport type { OperationSchema } from '../types.ts'\n/**\n *\n * @deprecated\n * TODO move to operationManager hook\n */\nexport function getASTParams(\n operationSchema: OperationSchema | undefined,\n {\n typed = false,\n casing,\n override,\n }: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n): FunctionParamsAST[] {\n if (!operationSchema?.schema.properties || !operationSchema.name) {\n return []\n }\n\n const requiredFields = Array.isArray(operationSchema.schema.required) ? operationSchema.schema.required : []\n\n return Object.entries(operationSchema.schema.properties).map(([name]: [string, OasTypes.SchemaObject]) => {\n // Use camelCase name for indexed access if casing is enabled\n const accessName = casing === 'camelcase' ? camelCase(name) : name\n\n const data: FunctionParamsAST = {\n name,\n enabled: !!name,\n required: requiredFields.includes(name),\n type: typed ? `${operationSchema.name}[\"${accessName}\"]` : undefined,\n }\n\n return override ? override(data) : data\n })\n}\n\nexport function getPathParams(\n operationSchema: OperationSchema | undefined,\n options: {\n typed?: boolean\n casing?: 'camelcase'\n override?: (data: FunctionParamsAST) => FunctionParamsAST\n } = {},\n) {\n return getASTParams(operationSchema, options).reduce((acc, curr) => {\n if (curr.name && curr.enabled) {\n let name = curr.name\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n name = camelCase(name)\n } else if (!isValidVarName(name)) {\n // If not valid variable name and casing not set, still need to make it valid\n name = camelCase(name)\n }\n\n acc[name] = {\n default: curr.default,\n type: curr.type,\n optional: !curr.required,\n }\n }\n\n return acc\n }, {} as Params)\n}\n\n/**\n * Get a mapping of camelCase parameter names to their original names\n * Used for mapping function parameters to backend parameter names\n */\nexport function getParamsMapping(\n operationSchema: OperationSchema | undefined,\n options: {\n casing?: 'camelcase'\n } = {},\n): Record<string, string> | undefined {\n if (!operationSchema?.schema.properties) {\n return undefined\n }\n\n const allEntries: Array<[string, string]> = []\n let hasTransformation = false\n\n Object.entries(operationSchema.schema.properties).forEach(([originalName]) => {\n let transformedName = originalName\n\n // Only transform to camelCase if explicitly requested\n if (options.casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name and casing not set, still need to make it valid\n transformedName = camelCase(originalName)\n }\n\n allEntries.push([originalName, transformedName])\n\n if (transformedName !== originalName) {\n hasTransformation = true\n }\n })\n\n // When using explicit casing and there are transformations, include ALL params so that\n // mappedParams contains every parameter (not just the ones whose names changed).\n // This prevents params with already-camelCase names (e.g. 'page', 'search') from being\n // silently dropped when other params in the same schema do need transformation.\n if (options.casing === 'camelcase' && hasTransformation) {\n return Object.fromEntries(allEntries)\n }\n\n // When casing is not specified or no transformations are needed, only return changed entries\n const mapping: Record<string, string> = {}\n allEntries.forEach(([originalName, transformedName]) => {\n if (transformedName !== originalName) {\n mapping[originalName] = transformedName\n }\n })\n\n return Object.keys(mapping).length > 0 ? mapping : undefined\n}\n","import type { contentType, Oas, OasTypes } from '@kubb/oas'\n\nexport type GetSchemasResult = {\n schemas: Record<string, OasTypes.SchemaObject>\n /**\n * Mapping from original component name to resolved name after collision handling\n * e.g., { 'Order': 'OrderSchema', 'variant': 'variant2' }\n */\n nameMapping: Map<string, string>\n}\n\ntype Mode = 'schemas' | 'responses' | 'requestBodies'\n\ntype GetSchemasProps = {\n oas: Oas\n contentType?: contentType\n includes?: Mode[]\n /**\n * Whether to resolve name collisions with suffixes.\n * If not provided, uses oas.options.collisionDetection\n * @default false (from oas.options or fallback)\n */\n collisionDetection?: boolean\n}\n\n/**\n * Collect schemas from OpenAPI components (schemas, responses, requestBodies)\n * and return them in dependency order along with name mapping for collision resolution.\n *\n * This function is a wrapper around the oas.getSchemas() method for backward compatibility.\n * New code should use oas.getSchemas() directly.\n *\n * @deprecated Use oas.getSchemas() instead\n */\nexport function getSchemas({ oas, contentType, includes = ['schemas', 'requestBodies', 'responses'], collisionDetection }: GetSchemasProps): GetSchemasResult {\n return oas.getSchemas({\n contentType,\n includes,\n collisionDetection,\n })\n}\n","import { camelCase, isValidVarName } from '@internals/utils'\nimport type { SchemaObject } from '@kubb/oas'\n\n/**\n * Apply casing transformation to schema properties\n * Only transforms property names, not nested schemas\n */\nexport function applyParamsCasing(schema: SchemaObject, casing: 'camelcase' | undefined): SchemaObject {\n if (!casing || !schema.properties) {\n return schema\n }\n\n const transformedProperties: Record<string, any> = {}\n const transformedRequired: string[] = []\n\n // Transform property names\n Object.entries(schema.properties).forEach(([originalName, propertySchema]) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n // If not valid variable name, make it valid\n transformedName = camelCase(originalName)\n }\n\n transformedProperties[transformedName] = propertySchema\n })\n\n // Transform required field names\n if (Array.isArray(schema.required)) {\n schema.required.forEach((originalName) => {\n let transformedName = originalName\n\n if (casing === 'camelcase') {\n transformedName = camelCase(originalName)\n } else if (!isValidVarName(originalName)) {\n transformedName = camelCase(originalName)\n }\n\n transformedRequired.push(transformedName)\n })\n }\n\n // Return a new schema with transformed properties and required fields\n return {\n ...schema,\n properties: transformedProperties,\n ...(transformedRequired.length > 0 && { required: transformedRequired }),\n } as SchemaObject\n}\n\n/**\n * Check if this schema is a parameter schema (pathParams, queryParams, or headerParams)\n * Only these should be transformed, not response/data/body\n */\nexport function isParameterSchema(schemaName: string): boolean {\n const lowerName = schemaName.toLowerCase()\n return lowerName.includes('pathparams') || lowerName.includes('queryparams') || lowerName.includes('headerparams')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoHA,SAAgB,eAAe,MAAuB;AACpD,KAAI;AACF,MAAI,SAAS,OAAO,OAAO;SACrB;AACN,SAAO;;AAET,QAAO;;;;;;;;;;;;ACvET,IAAa,UAAb,MAAqB;;;;CAInB;CAEA;CAEA,YAAY,MAAc,UAAmB,EAAE,EAAE;AAC/C,OAAK,OAAO;AACZ,QAAA,UAAgB;;;;;;;;;CAUlB,IAAI,MAAc;AAChB,SAAO,KAAK,WAAW;;;;;;;;;;CAWzB,IAAI,QAAiB;AACnB,MAAI;AACF,UAAO,CAAC,CAAC,IAAI,IAAI,KAAK,KAAK,CAAC;UACtB;AACN,UAAO;;;;;;;;;;CAWX,IAAI,WAAmB;AACrB,SAAO,KAAK,kBAAkB;;;;;;;;;;CAWhC,IAAI,SAA6B;AAC/B,SAAO,KAAK,UAAU;;;;;;;;;;CAWxB,IAAI,SAA6C;AAC/C,SAAO,KAAK,WAAW;;CAGzB,gBAAgB,KAAqB;EACnC,MAAM,QAAQ,eAAe,IAAI,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yD;AAC5J,QAAO,IAAI,WAAW;EACpB;EACA;EACA;EACD,CAAC;;;;;;;;AChCJ,SAAgB,kBAAkB,QAAsB,QAA+C;AACrG,KAAI,CAAC,UAAU,CAAC,OAAO,WACrB,QAAO;CAGT,MAAM,wBAA6C,EAAE;CACrD,MAAM,sBAAgC,EAAE;AAGxC,QAAO,QAAQ,OAAO,WAAW,CAAC,SAAS,CAAC,cAAc,oBAAoB;EAC5E,IAAI,kBAAkB;AAEtB,MAAI,WAAW,YACb,mBAAkB,UAAU,aAAa;WAChC,CAAC,eAAe,aAAa,CAEtC,mBAAkB,UAAU,aAAa;AAG3C,wBAAsB,mBAAmB;GACzC;AAGF,KAAI,MAAM,QAAQ,OAAO,SAAS,CAChC,QAAO,SAAS,SAAS,iBAAiB;EACxC,IAAI,kBAAkB;AAEtB,MAAI,WAAW,YACb,mBAAkB,UAAU,aAAa;WAChC,CAAC,eAAe,aAAa,CACtC,mBAAkB,UAAU,aAAa;AAG3C,sBAAoB,KAAK,gBAAgB;GACzC;AAIJ,QAAO;EACL,GAAG;EACH,YAAY;EACZ,GAAI,oBAAoB,SAAS,KAAK,EAAE,UAAU,qBAAqB;EACxE;;;;;;AAOH,SAAgB,kBAAkB,YAA6B;CAC7D,MAAM,YAAY,WAAW,aAAa;AAC1C,QAAO,UAAU,SAAS,aAAa,IAAI,UAAU,SAAS,cAAc,IAAI,UAAU,SAAS,eAAe"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/plugin-oas",
|
|
3
|
-
"version": "5.0.0-alpha.
|
|
3
|
+
"version": "5.0.0-alpha.33",
|
|
4
4
|
"description": "OpenAPI Specification (OAS) plugin for Kubb, providing core functionality for parsing and processing OpenAPI/Swagger schemas for code generation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"openapi",
|
|
@@ -81,15 +81,14 @@
|
|
|
81
81
|
}
|
|
82
82
|
],
|
|
83
83
|
"dependencies": {
|
|
84
|
-
"@kubb/fabric-core": "0.15.1",
|
|
85
|
-
"@kubb/react-fabric": "0.15.1",
|
|
86
84
|
"remeda": "^2.33.7",
|
|
87
|
-
"@kubb/
|
|
88
|
-
"@kubb/
|
|
85
|
+
"@kubb/ast": "5.0.0-alpha.33",
|
|
86
|
+
"@kubb/core": "5.0.0-alpha.33",
|
|
87
|
+
"@kubb/oas": "5.0.0-alpha.33",
|
|
88
|
+
"@kubb/renderer-jsx": "5.0.0-alpha.33"
|
|
89
89
|
},
|
|
90
90
|
"peerDependencies": {
|
|
91
|
-
"@kubb/
|
|
92
|
-
"@kubb/react-fabric": "0.15.1"
|
|
91
|
+
"@kubb/renderer-jsx": "5.0.0-alpha.33"
|
|
93
92
|
},
|
|
94
93
|
"engines": {
|
|
95
94
|
"node": ">=22"
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AsyncEventEmitter } from '@internals/utils'
|
|
2
2
|
import { pascalCase } from '@internals/utils'
|
|
3
|
-
import type {
|
|
4
|
-
import type {
|
|
3
|
+
import type { FileNode } from '@kubb/ast/types'
|
|
4
|
+
import type { FileMetaBase, KubbEvents, Plugin, PluginDriver, PluginFactoryOptions } from '@kubb/core'
|
|
5
5
|
import type { contentType, HttpMethod, Oas, OasTypes, Operation, SchemaObject } from '@kubb/oas'
|
|
6
6
|
import type { CoreGenerator } from './generators/createGenerator.ts'
|
|
7
7
|
import type { ReactGenerator } from './generators/createReactGenerator.ts'
|
|
@@ -10,10 +10,9 @@ import type { Exclude, Include, OperationSchemas, Override } from './types.ts'
|
|
|
10
10
|
import { withRequiredRequestBodySchema } from './utils/requestBody.ts'
|
|
11
11
|
import { renderOperation, renderOperations } from './utils.tsx'
|
|
12
12
|
|
|
13
|
-
export type OperationMethodResult<TFileMeta extends FileMetaBase> = Promise<
|
|
13
|
+
export type OperationMethodResult<TFileMeta extends FileMetaBase> = Promise<FileNode<TFileMeta> | Array<FileNode<TFileMeta>> | null>
|
|
14
14
|
|
|
15
15
|
type Context<TOptions, TPluginOptions extends PluginFactoryOptions> = {
|
|
16
|
-
fabric: FabricType
|
|
17
16
|
oas: Oas
|
|
18
17
|
exclude: Array<Exclude> | undefined
|
|
19
18
|
include: Array<Include> | undefined
|
|
@@ -25,7 +24,7 @@ type Context<TOptions, TPluginOptions extends PluginFactoryOptions> = {
|
|
|
25
24
|
* Current plugin
|
|
26
25
|
*/
|
|
27
26
|
plugin: Plugin<TPluginOptions>
|
|
28
|
-
mode:
|
|
27
|
+
mode: 'single' | 'split'
|
|
29
28
|
UNSTABLE_NAMING?: true
|
|
30
29
|
}
|
|
31
30
|
|
|
@@ -205,7 +204,7 @@ export class OperationGenerator<TPluginOptions extends PluginFactoryOptions = Pl
|
|
|
205
204
|
)
|
|
206
205
|
}
|
|
207
206
|
|
|
208
|
-
async build(...generators: Array<Generator<TPluginOptions>>): Promise<Array<
|
|
207
|
+
async build(...generators: Array<Generator<TPluginOptions>>): Promise<Array<FileNode<TFileMeta>>> {
|
|
209
208
|
const operations = await this.getOperations()
|
|
210
209
|
|
|
211
210
|
this.context.events?.emit('debug', {
|
|
@@ -213,7 +212,7 @@ export class OperationGenerator<TPluginOptions extends PluginFactoryOptions = Pl
|
|
|
213
212
|
logs: [`Building ${operations.length} operations`, ` • Generators: ${generators.length}`],
|
|
214
213
|
})
|
|
215
214
|
|
|
216
|
-
const results: Array<
|
|
215
|
+
const results: Array<FileNode<TFileMeta>> = []
|
|
217
216
|
|
|
218
217
|
for (const generator of generators) {
|
|
219
218
|
if (!('type' in generator)) {
|
|
@@ -223,7 +222,7 @@ export class OperationGenerator<TPluginOptions extends PluginFactoryOptions = Pl
|
|
|
223
222
|
// After the v2 guard above, all generators here are v1
|
|
224
223
|
const v1Generator = generator as ReactGenerator<TPluginOptions> | CoreGenerator<TPluginOptions>
|
|
225
224
|
|
|
226
|
-
const opResultsFlat: Array<
|
|
225
|
+
const opResultsFlat: Array<FileNode<TFileMeta>> = []
|
|
227
226
|
|
|
228
227
|
for (const { operation, method } of operations) {
|
|
229
228
|
const options = this.getOptions(operation, method)
|
|
@@ -231,7 +230,9 @@ export class OperationGenerator<TPluginOptions extends PluginFactoryOptions = Pl
|
|
|
231
230
|
if (v1Generator.type === 'react') {
|
|
232
231
|
await renderOperation(operation, {
|
|
233
232
|
config: this.context.driver.config,
|
|
234
|
-
|
|
233
|
+
driver: this.context.driver,
|
|
234
|
+
oas: this.context.oas,
|
|
235
|
+
mode: this.context.mode,
|
|
235
236
|
Component: v1Generator.Operation,
|
|
236
237
|
generator: this,
|
|
237
238
|
plugin: {
|
|
@@ -256,7 +257,7 @@ export class OperationGenerator<TPluginOptions extends PluginFactoryOptions = Pl
|
|
|
256
257
|
},
|
|
257
258
|
})
|
|
258
259
|
|
|
259
|
-
opResultsFlat.push(...([result ?? []].flat() as Array<
|
|
260
|
+
opResultsFlat.push(...([result ?? []].flat() as Array<FileNode<TFileMeta>>))
|
|
260
261
|
}
|
|
261
262
|
}
|
|
262
263
|
|
|
@@ -264,8 +265,10 @@ export class OperationGenerator<TPluginOptions extends PluginFactoryOptions = Pl
|
|
|
264
265
|
await renderOperations(
|
|
265
266
|
operations.map((op) => op.operation),
|
|
266
267
|
{
|
|
267
|
-
|
|
268
|
+
driver: this.context.driver,
|
|
268
269
|
config: this.context.driver.config,
|
|
270
|
+
oas: this.context.oas,
|
|
271
|
+
mode: this.context.mode,
|
|
269
272
|
Component: v1Generator.Operations,
|
|
270
273
|
generator: this,
|
|
271
274
|
plugin: this.context.plugin,
|
|
@@ -282,7 +285,7 @@ export class OperationGenerator<TPluginOptions extends PluginFactoryOptions = Pl
|
|
|
282
285
|
plugin: this.context.plugin,
|
|
283
286
|
})
|
|
284
287
|
|
|
285
|
-
results.push(...opResultsFlat, ...((operationsResult ?? []) as unknown as Array<
|
|
288
|
+
results.push(...opResultsFlat, ...((operationsResult ?? []) as unknown as Array<FileNode<TFileMeta>>))
|
|
286
289
|
}
|
|
287
290
|
|
|
288
291
|
return results
|
package/src/SchemaGenerator.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AsyncEventEmitter } from '@internals/utils'
|
|
2
2
|
import { getUniqueName, pascalCase, stringify } from '@internals/utils'
|
|
3
|
-
import type {
|
|
4
|
-
import type {
|
|
3
|
+
import type { FileNode } from '@kubb/ast/types'
|
|
4
|
+
import type { FileMetaBase, KubbEvents, Plugin, PluginDriver, PluginFactoryOptions, ResolveNameParams } from '@kubb/core'
|
|
5
5
|
import type { contentType, Oas, OasTypes, OpenAPIV3, SchemaObject } from '@kubb/oas'
|
|
6
6
|
import { isDiscriminator, isNullable, isReference, KUBB_INLINE_REF_PREFIX } from '@kubb/oas'
|
|
7
7
|
import { isDeepEqual, isNumber, uniqueWith } from 'remeda'
|
|
@@ -15,10 +15,9 @@ import { renderSchema } from './utils.tsx'
|
|
|
15
15
|
|
|
16
16
|
export type GetSchemaGeneratorOptions<T extends SchemaGenerator<any, any, any>> = T extends SchemaGenerator<infer Options, any, any> ? Options : never
|
|
17
17
|
|
|
18
|
-
export type SchemaMethodResult<TFileMeta extends FileMetaBase> = Promise<
|
|
18
|
+
export type SchemaMethodResult<TFileMeta extends FileMetaBase> = Promise<FileNode<TFileMeta> | Array<FileNode<TFileMeta>> | null>
|
|
19
19
|
|
|
20
20
|
type Context<TOptions, TPluginOptions extends PluginFactoryOptions> = {
|
|
21
|
-
fabric: FabricType
|
|
22
21
|
oas: Oas
|
|
23
22
|
driver: PluginDriver
|
|
24
23
|
events?: AsyncEventEmitter<KubbEvents>
|
|
@@ -26,7 +25,7 @@ type Context<TOptions, TPluginOptions extends PluginFactoryOptions> = {
|
|
|
26
25
|
* Current plugin
|
|
27
26
|
*/
|
|
28
27
|
plugin: Plugin<TPluginOptions>
|
|
29
|
-
mode:
|
|
28
|
+
mode: 'single' | 'split'
|
|
30
29
|
include?: Array<'schemas' | 'responses' | 'requestBodies'>
|
|
31
30
|
override: Array<Override<TOptions>> | undefined
|
|
32
31
|
contentType?: contentType
|
|
@@ -1331,7 +1330,7 @@ export class SchemaGenerator<
|
|
|
1331
1330
|
return [{ keyword: emptyType }, ...baseItems]
|
|
1332
1331
|
}
|
|
1333
1332
|
|
|
1334
|
-
async build(...generators: Array<Generator<TPluginOptions>>): Promise<Array<
|
|
1333
|
+
async build(...generators: Array<Generator<TPluginOptions>>): Promise<Array<FileNode<TFileMeta>>> {
|
|
1335
1334
|
const { oas, contentType, include } = this.context
|
|
1336
1335
|
|
|
1337
1336
|
// Initialize the name mapping if not already done
|
|
@@ -1354,10 +1353,10 @@ export class SchemaGenerator<
|
|
|
1354
1353
|
return this.#doBuild(schemas, generators)
|
|
1355
1354
|
}
|
|
1356
1355
|
|
|
1357
|
-
async #doBuild(schemas: Record<string, OasTypes.SchemaObject>, generators: Array<Generator<TPluginOptions>>): Promise<Array<
|
|
1356
|
+
async #doBuild(schemas: Record<string, OasTypes.SchemaObject>, generators: Array<Generator<TPluginOptions>>): Promise<Array<FileNode<TFileMeta>>> {
|
|
1358
1357
|
const schemaEntries = Object.entries(schemas)
|
|
1359
1358
|
|
|
1360
|
-
const results: Array<
|
|
1359
|
+
const results: Array<FileNode<TFileMeta>> = []
|
|
1361
1360
|
|
|
1362
1361
|
for (const generator of generators) {
|
|
1363
1362
|
if (!('type' in generator)) {
|
|
@@ -1381,7 +1380,9 @@ export class SchemaGenerator<
|
|
|
1381
1380
|
},
|
|
1382
1381
|
{
|
|
1383
1382
|
config: this.context.driver.config,
|
|
1384
|
-
|
|
1383
|
+
driver: this.context.driver,
|
|
1384
|
+
oas: this.context.oas,
|
|
1385
|
+
mode: this.context.mode,
|
|
1385
1386
|
Component: v1Generator.Schema,
|
|
1386
1387
|
generator: this,
|
|
1387
1388
|
plugin: {
|
|
@@ -1411,7 +1412,7 @@ export class SchemaGenerator<
|
|
|
1411
1412
|
},
|
|
1412
1413
|
})
|
|
1413
1414
|
|
|
1414
|
-
results.push(...([result ?? []].flat() as Array<
|
|
1415
|
+
results.push(...([result ?? []].flat() as Array<FileNode<TFileMeta>>))
|
|
1415
1416
|
}
|
|
1416
1417
|
}
|
|
1417
1418
|
}
|
package/src/SchemaMapper.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { KubbFile } from '@kubb/core'
|
|
2
1
|
import type { SchemaObject } from '@kubb/oas'
|
|
3
2
|
|
|
4
3
|
export type SchemaKeywordMapper = {
|
|
@@ -59,7 +58,7 @@ export type SchemaKeywordMapper = {
|
|
|
59
58
|
/**
|
|
60
59
|
* Full qualified path.
|
|
61
60
|
*/
|
|
62
|
-
path:
|
|
61
|
+
path: string
|
|
63
62
|
/**
|
|
64
63
|
* When true `File.Import` is used.
|
|
65
64
|
* When false a reference is used inside the current file.
|
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { FileNode } from '@kubb/ast/types'
|
|
2
|
+
import type { PluginFactoryOptions } from '@kubb/core'
|
|
2
3
|
import type { OperationProps, OperationsProps, SchemaProps } from './types.ts'
|
|
3
4
|
|
|
4
5
|
type UserGenerator<TOptions extends PluginFactoryOptions> = {
|
|
5
6
|
name: string
|
|
6
|
-
operations?: (props: OperationsProps<TOptions>) => Promise<
|
|
7
|
-
operation?: (props: OperationProps<TOptions>) => Promise<
|
|
8
|
-
schema?: (props: SchemaProps<TOptions>) => Promise<
|
|
7
|
+
operations?: (props: OperationsProps<TOptions>) => Promise<FileNode[]>
|
|
8
|
+
operation?: (props: OperationProps<TOptions>) => Promise<FileNode[]>
|
|
9
|
+
schema?: (props: SchemaProps<TOptions>) => Promise<FileNode[]>
|
|
9
10
|
}
|
|
10
11
|
|
|
11
12
|
export type CoreGenerator<TOptions extends PluginFactoryOptions> = {
|
|
12
13
|
name: string
|
|
13
14
|
type: 'core'
|
|
14
15
|
version: '1'
|
|
15
|
-
operations: (props: OperationsProps<TOptions>) => Promise<
|
|
16
|
-
operation: (props: OperationProps<TOptions>) => Promise<
|
|
17
|
-
schema: (props: SchemaProps<TOptions>) => Promise<
|
|
16
|
+
operations: (props: OperationsProps<TOptions>) => Promise<FileNode[]>
|
|
17
|
+
operation: (props: OperationProps<TOptions>) => Promise<FileNode[]>
|
|
18
|
+
schema: (props: SchemaProps<TOptions>) => Promise<FileNode[]>
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
export function createGenerator<TOptions extends PluginFactoryOptions>(generator: UserGenerator<TOptions>): CoreGenerator<TOptions> {
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import type { PluginFactoryOptions } from '@kubb/core'
|
|
2
|
-
import type {
|
|
2
|
+
import type { KubbReactNode } from '@kubb/renderer-jsx/types'
|
|
3
3
|
import type { OperationProps, OperationsProps, SchemaProps } from './types.ts'
|
|
4
4
|
|
|
5
5
|
type UserGenerator<TOptions extends PluginFactoryOptions> = {
|
|
6
6
|
name: string
|
|
7
|
-
Operations?: (props: OperationsProps<TOptions>) =>
|
|
8
|
-
Operation?: (props: OperationProps<TOptions>) =>
|
|
9
|
-
Schema?: (props: SchemaProps<TOptions>) =>
|
|
7
|
+
Operations?: (props: OperationsProps<TOptions>) => KubbReactNode
|
|
8
|
+
Operation?: (props: OperationProps<TOptions>) => KubbReactNode
|
|
9
|
+
Schema?: (props: SchemaProps<TOptions>) => KubbReactNode
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
export type ReactGenerator<TOptions extends PluginFactoryOptions> = {
|
|
13
13
|
name: string
|
|
14
14
|
type: 'react'
|
|
15
15
|
version: '1'
|
|
16
|
-
Operations: (props: OperationsProps<TOptions>) =>
|
|
17
|
-
Operation: (props: OperationProps<TOptions>) =>
|
|
18
|
-
Schema: (props: SchemaProps<TOptions>) =>
|
|
16
|
+
Operations: (props: OperationsProps<TOptions>) => KubbReactNode
|
|
17
|
+
Operation: (props: OperationProps<TOptions>) => KubbReactNode
|
|
18
|
+
Schema: (props: SchemaProps<TOptions>) => KubbReactNode
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
/****
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { camelCase } from '@internals/utils'
|
|
2
|
+
import { createSource, createText } from '@kubb/ast'
|
|
2
3
|
import type { PluginOas } from '../types.ts'
|
|
3
4
|
import { getBanner } from '../utils/getBanner.ts'
|
|
4
5
|
import { getFooter } from '../utils/getFooter.ts'
|
|
@@ -19,12 +20,12 @@ export const jsonGenerator = createGenerator<PluginOas>({
|
|
|
19
20
|
{
|
|
20
21
|
...file,
|
|
21
22
|
sources: [
|
|
22
|
-
{
|
|
23
|
+
createSource({
|
|
23
24
|
name: camelCase(schema.name),
|
|
24
25
|
isExportable: false,
|
|
25
26
|
isIndexable: false,
|
|
26
|
-
|
|
27
|
-
},
|
|
27
|
+
nodes: [createText(JSON.stringify(schema.value))],
|
|
28
|
+
}),
|
|
28
29
|
],
|
|
29
30
|
banner: getBanner({
|
|
30
31
|
oas: generator.context.oas,
|
package/src/hooks/useOas.ts
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import type { Oas } from '@kubb/oas'
|
|
2
|
-
|
|
3
|
-
import { useFabric } from '@kubb/react-fabric'
|
|
2
|
+
import { inject, OasContext } from '@kubb/renderer-jsx'
|
|
4
3
|
|
|
5
4
|
/**
|
|
6
5
|
* @deprecated use schemaNode or operationNode instead
|
|
7
6
|
*/
|
|
8
7
|
export function useOas(): Oas {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
return meta.oas
|
|
8
|
+
return inject(OasContext) as Oas
|
|
12
9
|
}
|