@kubb/plugin-msw 5.0.0-alpha.9 → 5.0.0-beta.3

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.
Files changed (43) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +1 -3
  3. package/dist/components-CLQ77DVn.cjs +584 -0
  4. package/dist/components-CLQ77DVn.cjs.map +1 -0
  5. package/dist/components-vO0FIb2i.js +519 -0
  6. package/dist/components-vO0FIb2i.js.map +1 -0
  7. package/dist/components.cjs +1 -1
  8. package/dist/components.d.ts +17 -21
  9. package/dist/components.js +1 -1
  10. package/dist/generators-BPJCs1x1.js +176 -0
  11. package/dist/generators-BPJCs1x1.js.map +1 -0
  12. package/dist/generators-CrmMwWE4.cjs +186 -0
  13. package/dist/generators-CrmMwWE4.cjs.map +1 -0
  14. package/dist/generators.cjs +1 -1
  15. package/dist/generators.d.ts +4 -500
  16. package/dist/generators.js +1 -1
  17. package/dist/index.cjs +54 -65
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +51 -65
  21. package/dist/index.js.map +1 -1
  22. package/dist/types-Dxu0KMQ4.d.ts +89 -0
  23. package/package.json +59 -57
  24. package/src/components/Handlers.tsx +3 -3
  25. package/src/components/Mock.tsx +36 -28
  26. package/src/components/MockWithFaker.tsx +36 -24
  27. package/src/components/Response.tsx +23 -17
  28. package/src/generators/handlersGenerator.tsx +18 -18
  29. package/src/generators/mswGenerator.tsx +49 -60
  30. package/src/index.ts +1 -1
  31. package/src/plugin.ts +48 -85
  32. package/src/resolvers/resolverMsw.ts +19 -0
  33. package/src/types.ts +45 -22
  34. package/src/utils.ts +109 -0
  35. package/dist/components-8XBwMbFa.cjs +0 -343
  36. package/dist/components-8XBwMbFa.cjs.map +0 -1
  37. package/dist/components-DgtTZkWX.js +0 -277
  38. package/dist/components-DgtTZkWX.js.map +0 -1
  39. package/dist/generators-CY1SNd5X.cjs +0 -171
  40. package/dist/generators-CY1SNd5X.cjs.map +0 -1
  41. package/dist/generators-CvyZTxOm.js +0 -161
  42. package/dist/generators-CvyZTxOm.js.map +0 -1
  43. package/dist/types-MdHRNpgi.d.ts +0 -68
@@ -0,0 +1 @@
1
+ {"version":3,"file":"components-CLQ77DVn.cjs","names":["#options","#transformParam","#eachParam","File","declarationPrinter","ast","File","Function","declarationPrinter","ast","File","Function","ast","File","Function"],"sources":["../../../internals/utils/src/casing.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/components/Handlers.tsx","../src/utils.ts","../src/components/Mock.tsx","../src/components/MockWithFaker.tsx","../src/components/Response.tsx"],"sourcesContent":["type Options = {\n /**\n * When `true`, dot-separated segments are split on `.` and joined with `/` after casing.\n */\n isFile?: boolean\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const normalized = text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n\n const words = normalized.split(/[\\s\\-_./\\\\:]+/).filter(Boolean)\n\n return words\n .map((word, i) => {\n const allUpper = word.length > 1 && word === word.toUpperCase()\n if (allUpper) return word\n if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1)\n return word.charAt(0).toUpperCase() + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Splits `text` on `.` and applies `transformPart` to each segment.\n * The last segment receives `isLast = true`, all earlier segments receive `false`.\n * Segments are joined with `/` to form a file path.\n *\n * Only splits on dots followed by a letter so that version numbers\n * embedded in operationIds (e.g. `v2025.0`) are kept intact.\n */\nfunction applyToFileParts(text: string, transformPart: (part: string, isLast: boolean) => string): string {\n const parts = text.split(/\\.(?=[a-zA-Z])/)\n return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join('/')\n}\n\n/**\n * Converts `text` to camelCase.\n * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.\n *\n * @example\n * camelCase('hello-world') // 'helloWorld'\n * camelCase('pet.petId', { isFile: true }) // 'pet/petId'\n */\nexport function camelCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? { prefix, suffix } : {}))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.\n *\n * @example\n * pascalCase('hello-world') // 'HelloWorld'\n * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'\n */\nexport function pascalCase(text: string, { isFile, prefix = '', suffix = '' }: Options = {}): string {\n if (isFile) {\n return applyToFileParts(text, (part, isLast) => (isLast ? pascalCase(part, { prefix, suffix }) : camelCase(part)))\n }\n\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n\n/**\n * Converts `text` to snake_case.\n *\n * @example\n * snakeCase('helloWorld') // 'hello_world'\n * snakeCase('Hello-World') // 'hello_world'\n */\nexport function snakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n const processed = `${prefix} ${text} ${suffix}`.trim()\n return processed\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .replace(/[^a-zA-Z0-9_]/g, '')\n .toLowerCase()\n .split('_')\n .filter(Boolean)\n .join('_')\n}\n\n/**\n * Converts `text` to SCREAMING_SNAKE_CASE.\n *\n * @example\n * screamingSnakeCase('helloWorld') // 'HELLO_WORLD'\n */\nexport function screamingSnakeCase(text: string, { prefix = '', suffix = '' }: Omit<Options, 'isFile'> = {}): string {\n return snakeCase(text, { prefix, suffix }).toUpperCase()\n}\n","/**\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 * 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 if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\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 { File } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\n\ntype HandlersProps = {\n /**\n * Name of the function\n */\n name: string\n // custom\n handlers: string[]\n}\n\nexport function Handlers({ name, handlers }: HandlersProps): KubbReactNode {\n return (\n <File.Source name={name} isIndexable isExportable>\n {`export const ${name} = ${JSON.stringify(handlers).replaceAll(`\"`, '')} as const`}\n </File.Source>\n )\n}\n","import type { ast } from '@kubb/core'\nimport type { ResolverFaker } from '@kubb/plugin-faker'\nimport type { ResolverTs } from '@kubb/plugin-ts'\nimport type { PluginMsw } from './types.ts'\n\n/**\n * Applies a name transformer function to a name if configured, otherwise returns it unchanged.\n */\nexport function transformName(name: string, type: 'function' | 'type' | 'file' | 'const', transformers?: PluginMsw['resolvedOptions']['transformers']): string {\n return transformers?.name?.(name, type) || name\n}\n\n/**\n * Filters responses to only those with 2xx status codes.\n */\nexport function getSuccessResponses(node: ast.OperationNode): ast.ResponseNode[] {\n return node.responses.filter((response) => {\n const code = Number.parseInt(response.statusCode, 10)\n return !Number.isNaN(code) && code >= 200 && code < 300\n })\n}\n\n/**\n * Returns the first 2xx response for an operation, if any.\n */\nexport function getPrimarySuccessResponse(node: ast.OperationNode): ast.ResponseNode | undefined {\n return getSuccessResponses(node)[0]\n}\n\n/**\n * Gets the content type from a response, defaulting to 'application/json' if a schema exists.\n */\nexport function getContentType(response: ast.ResponseNode | undefined): string | undefined {\n return getResponseContentType(response) ?? (hasResponseSchema(response) ? 'application/json' : undefined)\n}\n\n/**\n * Determines if a response has a schema that is not void or any.\n */\nexport function hasResponseSchema(response: ast.ResponseNode | undefined): boolean {\n return !!getResponseContentType(response) || (!!response?.schema && response.schema.type !== 'void' && response.schema.type !== 'any')\n}\n\nfunction getResponseContentType(response: ast.ResponseNode | undefined): string | undefined {\n const contentType = response as unknown as { mediaType?: string | null; contentType?: string | null } | undefined\n const value = contentType?.mediaType ?? contentType?.contentType\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Maps all operation responses to their type names, including status code or 'default' for default responses.\n */\nexport function getResponseTypes(node: ast.OperationNode, tsResolver: ResolverTs): Array<[statusCode: number | 'default', typeName: string]> {\n const types: Array<[number | 'default', string]> = []\n\n for (const response of node.responses) {\n if (response.statusCode === 'default') {\n types.push(['default', tsResolver.resolveResponseName(node)])\n continue\n }\n\n const code = Number.parseInt(response.statusCode, 10)\n if (Number.isNaN(code)) continue\n\n if (code >= 200 && code < 300) {\n types.push([code, tsResolver.resolveResponseName(node)])\n continue\n }\n\n types.push([code, tsResolver.resolveResponseStatusName(node, response.statusCode)])\n }\n\n return types\n}\n\n/**\n * Converts an HTTP method to its lowercase MSW equivalent (e.g., 'POST' → 'post').\n */\nexport function getMswMethod(node: ast.OperationNode): string {\n return node.method.toLowerCase()\n}\n\n/**\n * Converts an OpenAPI-style path to an Express/MSW-style path by replacing `{param}` with `:param`.\n */\nexport function getMswUrl(node: ast.OperationNode): string {\n return node.path.replaceAll('{', ':').replaceAll('}', '')\n}\n\n/**\n * Resolves faker metadata for an MSW operation, including response name and file path.\n */\nexport function resolveFakerMeta(\n node: ast.OperationNode,\n options: {\n root: string\n fakerResolver: ResolverFaker\n fakerOutput: PluginMsw['resolvedOptions']['output']\n fakerGroup: PluginMsw['resolvedOptions']['group']\n },\n): { name: string; file: { path: string } } {\n const { root, fakerResolver, fakerOutput, fakerGroup } = options\n const tag = node.tags[0] ?? 'default'\n\n return {\n name: fakerResolver.resolveResponseName(node),\n file: fakerResolver.resolveFile({ name: node.operationId, extname: '.ts', tag, path: node.path }, { root, output: fakerOutput, group: fakerGroup }),\n }\n}\n","import { URLPath } from '@internals/utils'\nimport { ast } from '@kubb/core'\nimport { functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\nimport { getContentType, getMswMethod, getMswUrl, getPrimarySuccessResponse, hasResponseSchema } from '../utils.ts'\n\ntype Props = {\n name: string\n typeName: string\n requestTypeName?: string\n baseURL: string | undefined\n node: ast.OperationNode\n}\n\nconst declarationPrinter = functionPrinter({ mode: 'declaration' })\n\nexport function Mock({ baseURL = '', name, typeName, requestTypeName, node }: Props): KubbReactNode {\n const method = getMswMethod(node)\n const successResponse = getPrimarySuccessResponse(node)\n const statusCode = successResponse ? Number(successResponse.statusCode) : 200\n const contentType = getContentType(successResponse)\n const url = new URLPath(getMswUrl(node)).toURLPath()\n\n const headers = [contentType ? `'Content-Type': '${contentType}'` : undefined].filter(Boolean)\n const responseHasSchema = hasResponseSchema(successResponse)\n const dataType = responseHasSchema ? typeName : 'string | number | boolean | null | object'\n\n const callbackType = requestTypeName\n ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>`\n : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`\n\n const params = declarationPrinter.print(\n ast.createFunctionParameters({\n params: [\n ast.createFunctionParameter({\n name: 'data',\n type: ast.createParamsType({\n variant: 'reference',\n name: `${dataType} | ${callbackType}`,\n }),\n optional: true,\n }),\n ],\n }),\n )\n\n const httpCall = requestTypeName ? `http.${method}<Record<string, string>, ${requestTypeName}, any>` : `http.${method}`\n\n return (\n <File.Source name={name} isIndexable isExportable>\n <Function name={name} export params={params ?? ''}>\n {`return ${httpCall}(\\`${baseURL}${url.replace(/([^/]):/g, '$1\\\\\\\\:')}\\`, function handler(info) {\n if(typeof data === 'function') return data(info)\n\n return new Response(JSON.stringify(data), {\n status: ${statusCode},\n ${\n headers.length\n ? ` headers: {\n ${headers.join(', \\n')}\n },`\n : ''\n }\n })\n })`}\n </Function>\n </File.Source>\n )\n}\n","import { URLPath } from '@internals/utils'\nimport { ast } from '@kubb/core'\nimport { functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\nimport { getContentType, getMswMethod, getMswUrl, getPrimarySuccessResponse } from '../utils.ts'\n\ntype Props = {\n name: string\n typeName: string\n requestTypeName?: string\n fakerName: string\n baseURL: string | undefined\n node: ast.OperationNode\n}\n\nconst declarationPrinter = functionPrinter({ mode: 'declaration' })\n\nexport function MockWithFaker({ baseURL = '', name, fakerName, typeName, requestTypeName, node }: Props): KubbReactNode {\n const method = getMswMethod(node)\n const successResponse = getPrimarySuccessResponse(node)\n const statusCode = successResponse ? Number(successResponse.statusCode) : 200\n const contentType = getContentType(successResponse)\n const url = new URLPath(getMswUrl(node)).toURLPath()\n\n const headers = [contentType ? `'Content-Type': '${contentType}'` : undefined].filter(Boolean)\n\n const callbackType = requestTypeName\n ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>`\n : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`\n\n const params = declarationPrinter.print(\n ast.createFunctionParameters({\n params: [\n ast.createFunctionParameter({\n name: 'data',\n type: ast.createParamsType({\n variant: 'reference',\n name: `${typeName} | ${callbackType}`,\n }),\n optional: true,\n }),\n ],\n }),\n )\n\n const httpCall = requestTypeName ? `http.${method}<Record<string, string>, ${requestTypeName}, any>` : `http.${method}`\n\n return (\n <File.Source name={name} isIndexable isExportable>\n <Function name={name} export params={params ?? ''}>\n {`return ${httpCall}('${baseURL}${url.replace(/([^/]):/g, '$1\\\\\\\\:')}', function handler(info) {\n if(typeof data === 'function') return data(info)\n\n return new Response(JSON.stringify(data || ${fakerName}(data)), {\n status: ${statusCode},\n ${\n headers.length\n ? ` headers: {\n ${headers.join(', \\n')}\n },`\n : ''\n }\n })\n })`}\n </Function>\n </File.Source>\n )\n}\n","import { ast } from '@kubb/core'\nimport { functionPrinter } from '@kubb/plugin-ts'\nimport { File, Function } from '@kubb/renderer-jsx'\nimport type { KubbReactNode } from '@kubb/renderer-jsx/types'\nimport { getContentType, hasResponseSchema } from '../utils.ts'\n\ntype Props = {\n typeName: string\n name: string\n response: ast.ResponseNode\n key?: string | number | null\n}\n\nconst declarationPrinter = functionPrinter({ mode: 'declaration' })\n\nexport function Response({ name, typeName, response }: Props): KubbReactNode {\n const statusCode = Number(response.statusCode)\n const contentType = getContentType(response)\n const headers = [contentType ? `'Content-Type': '${contentType}'` : undefined].filter(Boolean)\n\n const params = declarationPrinter.print(\n ast.createFunctionParameters({\n params: [\n ast.createFunctionParameter({\n name: 'data',\n type: ast.createParamsType({ variant: 'reference', name: typeName }),\n optional: !hasResponseSchema(response),\n }),\n ],\n }),\n )\n\n const responseName = `${name}Response${statusCode}`\n\n return (\n <File.Source name={responseName} isIndexable isExportable>\n <Function name={responseName} export params={params ?? ''}>\n {`\n return new Response(JSON.stringify(data), {\n status: ${statusCode},\n ${\n headers.length\n ? ` headers: {\n ${headers.join(', \\n')}\n },`\n : ''\n }\n })`}\n </Function>\n </File.Source>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,MAAc,QAAyB;AAS9D,QARmB,KAChB,MAAM,CACN,QAAQ,qBAAqB,QAAQ,CACrC,QAAQ,yBAAyB,QAAQ,CACzC,QAAQ,gBAAgB,QAEH,CAAC,MAAM,gBAAgB,CAAC,OAAO,QAE3C,CACT,KAAK,MAAM,MAAM;AAEhB,MADiB,KAAK,SAAS,KAAK,SAAS,K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MAAM,eAAe,CAAC;AAEnE,SAAgB,SAAS,EAAE,MAAM,UAAU,YAAkC;CAC3E,MAAM,aAAa,OAAO,SAAS,WAAW;CAC9C,MAAM,cAAc,eAAe,SAAS;CAC5C,MAAM,UAAU,CAAC,cAAc,oBAAoB,YAAY,KAAK,KAAA,EAAU,CAAC,OAAO,QAAQ;CAE9F,MAAM,SAAS,mBAAmB,MAChCC,WAAAA,IAAI,yBAAyB,EAC3B,QAAQ,CACNA,WAAAA,IAAI,wBAAwB;EAC1B,MAAM;EACN,MAAMA,WAAAA,IAAI,iBAAiB;GAAE,SAAS;GAAa,MAAM;GAAU,CAAC;EACpE,UAAU,CAAC,kBAAkB,SAAS;EACvC,CAAC,CACH,EACF,CAAC,CACH;CAED,MAAM,eAAe,GAAG,KAAK,UAAU;AAEvC,QACE,iBAAA,GAAA,+BAAA,KAACC,mBAAAA,KAAK,QAAN;EAAa,MAAM;EAAc,aAAA;EAAY,cAAA;YAC3C,iBAAA,GAAA,+BAAA,KAACC,mBAAAA,UAAD;GAAU,MAAM;GAAc,QAAA;GAAO,QAAQ,UAAU;aACpD;;gBAEO,WAAW;QAEnB,QAAQ,SACJ;UACF,QAAQ,KAAK,OAAO,CAAC;YAEnB,GACL;;GAEU,CAAA;EACC,CAAA"}
@@ -0,0 +1,519 @@
1
+ import "./chunk--u3MIqq1.js";
2
+ import { ast } from "@kubb/core";
3
+ import { functionPrinter } from "@kubb/plugin-ts";
4
+ import { File, Function } from "@kubb/renderer-jsx";
5
+ import { jsx } from "@kubb/renderer-jsx/jsx-runtime";
6
+ //#region ../../internals/utils/src/casing.ts
7
+ /**
8
+ * Shared implementation for camelCase and PascalCase conversion.
9
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
10
+ * and capitalizes each word according to `pascal`.
11
+ *
12
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
13
+ */
14
+ function toCamelOrPascal(text, pascal) {
15
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
16
+ if (word.length > 1 && word === word.toUpperCase()) return word;
17
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
18
+ return word.charAt(0).toUpperCase() + word.slice(1);
19
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
20
+ }
21
+ /**
22
+ * Splits `text` on `.` and applies `transformPart` to each segment.
23
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
24
+ * Segments are joined with `/` to form a file path.
25
+ *
26
+ * Only splits on dots followed by a letter so that version numbers
27
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
28
+ */
29
+ function applyToFileParts(text, transformPart) {
30
+ const parts = text.split(/\.(?=[a-zA-Z])/);
31
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
32
+ }
33
+ /**
34
+ * Converts `text` to camelCase.
35
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
36
+ *
37
+ * @example
38
+ * camelCase('hello-world') // 'helloWorld'
39
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
40
+ */
41
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
42
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
43
+ prefix,
44
+ suffix
45
+ } : {}));
46
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
47
+ }
48
+ //#endregion
49
+ //#region ../../internals/utils/src/reserved.ts
50
+ /**
51
+ * JavaScript and Java reserved words.
52
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
53
+ */
54
+ const reservedWords = new Set([
55
+ "abstract",
56
+ "arguments",
57
+ "boolean",
58
+ "break",
59
+ "byte",
60
+ "case",
61
+ "catch",
62
+ "char",
63
+ "class",
64
+ "const",
65
+ "continue",
66
+ "debugger",
67
+ "default",
68
+ "delete",
69
+ "do",
70
+ "double",
71
+ "else",
72
+ "enum",
73
+ "eval",
74
+ "export",
75
+ "extends",
76
+ "false",
77
+ "final",
78
+ "finally",
79
+ "float",
80
+ "for",
81
+ "function",
82
+ "goto",
83
+ "if",
84
+ "implements",
85
+ "import",
86
+ "in",
87
+ "instanceof",
88
+ "int",
89
+ "interface",
90
+ "let",
91
+ "long",
92
+ "native",
93
+ "new",
94
+ "null",
95
+ "package",
96
+ "private",
97
+ "protected",
98
+ "public",
99
+ "return",
100
+ "short",
101
+ "static",
102
+ "super",
103
+ "switch",
104
+ "synchronized",
105
+ "this",
106
+ "throw",
107
+ "throws",
108
+ "transient",
109
+ "true",
110
+ "try",
111
+ "typeof",
112
+ "var",
113
+ "void",
114
+ "volatile",
115
+ "while",
116
+ "with",
117
+ "yield",
118
+ "Array",
119
+ "Date",
120
+ "hasOwnProperty",
121
+ "Infinity",
122
+ "isFinite",
123
+ "isNaN",
124
+ "isPrototypeOf",
125
+ "length",
126
+ "Math",
127
+ "name",
128
+ "NaN",
129
+ "Number",
130
+ "Object",
131
+ "prototype",
132
+ "String",
133
+ "toString",
134
+ "undefined",
135
+ "valueOf"
136
+ ]);
137
+ /**
138
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * isValidVarName('status') // true
143
+ * isValidVarName('class') // false (reserved word)
144
+ * isValidVarName('42foo') // false (starts with digit)
145
+ * ```
146
+ */
147
+ function isValidVarName(name) {
148
+ if (!name || reservedWords.has(name)) return false;
149
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
150
+ }
151
+ //#endregion
152
+ //#region ../../internals/utils/src/urlPath.ts
153
+ /**
154
+ * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
155
+ *
156
+ * @example
157
+ * const p = new URLPath('/pet/{petId}')
158
+ * p.URL // '/pet/:petId'
159
+ * p.template // '`/pet/${petId}`'
160
+ */
161
+ var URLPath = class {
162
+ /**
163
+ * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.
164
+ */
165
+ path;
166
+ #options;
167
+ constructor(path, options = {}) {
168
+ this.path = path;
169
+ this.#options = options;
170
+ }
171
+ /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * new URLPath('/pet/{petId}').URL // '/pet/:petId'
176
+ * ```
177
+ */
178
+ get URL() {
179
+ return this.toURLPath();
180
+ }
181
+ /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true
186
+ * new URLPath('/pet/{petId}').isURL // false
187
+ * ```
188
+ */
189
+ get isURL() {
190
+ try {
191
+ return !!new URL(this.path).href;
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+ /**
197
+ * Converts the OpenAPI path to a TypeScript template literal string.
198
+ *
199
+ * @example
200
+ * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
201
+ * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
202
+ */
203
+ get template() {
204
+ return this.toTemplateString();
205
+ }
206
+ /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * new URLPath('/pet/{petId}').object
211
+ * // { url: '/pet/:petId', params: { petId: 'petId' } }
212
+ * ```
213
+ */
214
+ get object() {
215
+ return this.toObject();
216
+ }
217
+ /** Returns a map of path parameter names, or `undefined` when the path has no parameters.
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * new URLPath('/pet/{petId}').params // { petId: 'petId' }
222
+ * new URLPath('/pet').params // undefined
223
+ * ```
224
+ */
225
+ get params() {
226
+ return this.getParams();
227
+ }
228
+ #transformParam(raw) {
229
+ const param = isValidVarName(raw) ? raw : camelCase(raw);
230
+ return this.#options.casing === "camelcase" ? camelCase(param) : param;
231
+ }
232
+ /**
233
+ * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.
234
+ */
235
+ #eachParam(fn) {
236
+ for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
237
+ const raw = match[1];
238
+ fn(raw, this.#transformParam(raw));
239
+ }
240
+ }
241
+ toObject({ type = "path", replacer, stringify } = {}) {
242
+ const object = {
243
+ url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
244
+ params: this.getParams()
245
+ };
246
+ if (stringify) {
247
+ if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
248
+ if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
249
+ return `{ url: '${object.url}' }`;
250
+ }
251
+ return object;
252
+ }
253
+ /**
254
+ * Converts the OpenAPI path to a TypeScript template literal string.
255
+ * An optional `replacer` can transform each extracted parameter name before interpolation.
256
+ *
257
+ * @example
258
+ * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
259
+ */
260
+ toTemplateString({ prefix = "", replacer } = {}) {
261
+ return `\`${prefix}${this.path.split(/\{([^}]+)\}/).map((part, i) => {
262
+ if (i % 2 === 0) return part;
263
+ const param = this.#transformParam(part);
264
+ return `\${${replacer ? replacer(param) : param}}`;
265
+ }).join("")}\``;
266
+ }
267
+ /**
268
+ * Extracts all `{param}` segments from the path and returns them as a key-value map.
269
+ * An optional `replacer` transforms each parameter name in both key and value positions.
270
+ * Returns `undefined` when no path parameters are found.
271
+ *
272
+ * @example
273
+ * ```ts
274
+ * new URLPath('/pet/{petId}/tag/{tagId}').getParams()
275
+ * // { petId: 'petId', tagId: 'tagId' }
276
+ * ```
277
+ */
278
+ getParams(replacer) {
279
+ const params = {};
280
+ this.#eachParam((_raw, param) => {
281
+ const key = replacer ? replacer(param) : param;
282
+ params[key] = key;
283
+ });
284
+ return Object.keys(params).length > 0 ? params : void 0;
285
+ }
286
+ /** Converts the OpenAPI path to Express-style colon syntax.
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'
291
+ * ```
292
+ */
293
+ toURLPath() {
294
+ return this.path.replace(/\{([^}]+)\}/g, ":$1");
295
+ }
296
+ };
297
+ //#endregion
298
+ //#region src/components/Handlers.tsx
299
+ function Handlers({ name, handlers }) {
300
+ return /* @__PURE__ */ jsx(File.Source, {
301
+ name,
302
+ isIndexable: true,
303
+ isExportable: true,
304
+ children: `export const ${name} = ${JSON.stringify(handlers).replaceAll(`"`, "")} as const`
305
+ });
306
+ }
307
+ //#endregion
308
+ //#region src/utils.ts
309
+ /**
310
+ * Applies a name transformer function to a name if configured, otherwise returns it unchanged.
311
+ */
312
+ function transformName(name, type, transformers) {
313
+ return transformers?.name?.(name, type) || name;
314
+ }
315
+ /**
316
+ * Filters responses to only those with 2xx status codes.
317
+ */
318
+ function getSuccessResponses(node) {
319
+ return node.responses.filter((response) => {
320
+ const code = Number.parseInt(response.statusCode, 10);
321
+ return !Number.isNaN(code) && code >= 200 && code < 300;
322
+ });
323
+ }
324
+ /**
325
+ * Returns the first 2xx response for an operation, if any.
326
+ */
327
+ function getPrimarySuccessResponse(node) {
328
+ return getSuccessResponses(node)[0];
329
+ }
330
+ /**
331
+ * Gets the content type from a response, defaulting to 'application/json' if a schema exists.
332
+ */
333
+ function getContentType(response) {
334
+ return getResponseContentType(response) ?? (hasResponseSchema(response) ? "application/json" : void 0);
335
+ }
336
+ /**
337
+ * Determines if a response has a schema that is not void or any.
338
+ */
339
+ function hasResponseSchema(response) {
340
+ return !!getResponseContentType(response) || !!response?.schema && response.schema.type !== "void" && response.schema.type !== "any";
341
+ }
342
+ function getResponseContentType(response) {
343
+ const contentType = response;
344
+ const value = contentType?.mediaType ?? contentType?.contentType;
345
+ return typeof value === "string" && value.length > 0 ? value : void 0;
346
+ }
347
+ /**
348
+ * Maps all operation responses to their type names, including status code or 'default' for default responses.
349
+ */
350
+ function getResponseTypes(node, tsResolver) {
351
+ const types = [];
352
+ for (const response of node.responses) {
353
+ if (response.statusCode === "default") {
354
+ types.push(["default", tsResolver.resolveResponseName(node)]);
355
+ continue;
356
+ }
357
+ const code = Number.parseInt(response.statusCode, 10);
358
+ if (Number.isNaN(code)) continue;
359
+ if (code >= 200 && code < 300) {
360
+ types.push([code, tsResolver.resolveResponseName(node)]);
361
+ continue;
362
+ }
363
+ types.push([code, tsResolver.resolveResponseStatusName(node, response.statusCode)]);
364
+ }
365
+ return types;
366
+ }
367
+ /**
368
+ * Converts an HTTP method to its lowercase MSW equivalent (e.g., 'POST' → 'post').
369
+ */
370
+ function getMswMethod(node) {
371
+ return node.method.toLowerCase();
372
+ }
373
+ /**
374
+ * Converts an OpenAPI-style path to an Express/MSW-style path by replacing `{param}` with `:param`.
375
+ */
376
+ function getMswUrl(node) {
377
+ return node.path.replaceAll("{", ":").replaceAll("}", "");
378
+ }
379
+ /**
380
+ * Resolves faker metadata for an MSW operation, including response name and file path.
381
+ */
382
+ function resolveFakerMeta(node, options) {
383
+ const { root, fakerResolver, fakerOutput, fakerGroup } = options;
384
+ const tag = node.tags[0] ?? "default";
385
+ return {
386
+ name: fakerResolver.resolveResponseName(node),
387
+ file: fakerResolver.resolveFile({
388
+ name: node.operationId,
389
+ extname: ".ts",
390
+ tag,
391
+ path: node.path
392
+ }, {
393
+ root,
394
+ output: fakerOutput,
395
+ group: fakerGroup
396
+ })
397
+ };
398
+ }
399
+ //#endregion
400
+ //#region src/components/Mock.tsx
401
+ const declarationPrinter$2 = functionPrinter({ mode: "declaration" });
402
+ function Mock({ baseURL = "", name, typeName, requestTypeName, node }) {
403
+ const method = getMswMethod(node);
404
+ const successResponse = getPrimarySuccessResponse(node);
405
+ const statusCode = successResponse ? Number(successResponse.statusCode) : 200;
406
+ const contentType = getContentType(successResponse);
407
+ const url = new URLPath(getMswUrl(node)).toURLPath();
408
+ const headers = [contentType ? `'Content-Type': '${contentType}'` : void 0].filter(Boolean);
409
+ const dataType = hasResponseSchema(successResponse) ? typeName : "string | number | boolean | null | object";
410
+ const callbackType = requestTypeName ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>` : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`;
411
+ const params = declarationPrinter$2.print(ast.createFunctionParameters({ params: [ast.createFunctionParameter({
412
+ name: "data",
413
+ type: ast.createParamsType({
414
+ variant: "reference",
415
+ name: `${dataType} | ${callbackType}`
416
+ }),
417
+ optional: true
418
+ })] }));
419
+ const httpCall = requestTypeName ? `http.${method}<Record<string, string>, ${requestTypeName}, any>` : `http.${method}`;
420
+ return /* @__PURE__ */ jsx(File.Source, {
421
+ name,
422
+ isIndexable: true,
423
+ isExportable: true,
424
+ children: /* @__PURE__ */ jsx(Function, {
425
+ name,
426
+ export: true,
427
+ params: params ?? "",
428
+ children: `return ${httpCall}(\`${baseURL}${url.replace(/([^/]):/g, "$1\\\\:")}\`, function handler(info) {
429
+ if(typeof data === 'function') return data(info)
430
+
431
+ return new Response(JSON.stringify(data), {
432
+ status: ${statusCode},
433
+ ${headers.length ? ` headers: {
434
+ ${headers.join(", \n")}
435
+ },` : ""}
436
+ })
437
+ })`
438
+ })
439
+ });
440
+ }
441
+ //#endregion
442
+ //#region src/components/MockWithFaker.tsx
443
+ const declarationPrinter$1 = functionPrinter({ mode: "declaration" });
444
+ function MockWithFaker({ baseURL = "", name, fakerName, typeName, requestTypeName, node }) {
445
+ const method = getMswMethod(node);
446
+ const successResponse = getPrimarySuccessResponse(node);
447
+ const statusCode = successResponse ? Number(successResponse.statusCode) : 200;
448
+ const contentType = getContentType(successResponse);
449
+ const url = new URLPath(getMswUrl(node)).toURLPath();
450
+ const headers = [contentType ? `'Content-Type': '${contentType}'` : void 0].filter(Boolean);
451
+ const callbackType = requestTypeName ? `HttpResponseResolver<Record<string, string>, ${requestTypeName}, any>` : `((info: Parameters<Parameters<typeof http.${method}>[1]>[0]) => Response | Promise<Response>)`;
452
+ const params = declarationPrinter$1.print(ast.createFunctionParameters({ params: [ast.createFunctionParameter({
453
+ name: "data",
454
+ type: ast.createParamsType({
455
+ variant: "reference",
456
+ name: `${typeName} | ${callbackType}`
457
+ }),
458
+ optional: true
459
+ })] }));
460
+ const httpCall = requestTypeName ? `http.${method}<Record<string, string>, ${requestTypeName}, any>` : `http.${method}`;
461
+ return /* @__PURE__ */ jsx(File.Source, {
462
+ name,
463
+ isIndexable: true,
464
+ isExportable: true,
465
+ children: /* @__PURE__ */ jsx(Function, {
466
+ name,
467
+ export: true,
468
+ params: params ?? "",
469
+ children: `return ${httpCall}('${baseURL}${url.replace(/([^/]):/g, "$1\\\\:")}', function handler(info) {
470
+ if(typeof data === 'function') return data(info)
471
+
472
+ return new Response(JSON.stringify(data || ${fakerName}(data)), {
473
+ status: ${statusCode},
474
+ ${headers.length ? ` headers: {
475
+ ${headers.join(", \n")}
476
+ },` : ""}
477
+ })
478
+ })`
479
+ })
480
+ });
481
+ }
482
+ //#endregion
483
+ //#region src/components/Response.tsx
484
+ const declarationPrinter = functionPrinter({ mode: "declaration" });
485
+ function Response({ name, typeName, response }) {
486
+ const statusCode = Number(response.statusCode);
487
+ const contentType = getContentType(response);
488
+ const headers = [contentType ? `'Content-Type': '${contentType}'` : void 0].filter(Boolean);
489
+ const params = declarationPrinter.print(ast.createFunctionParameters({ params: [ast.createFunctionParameter({
490
+ name: "data",
491
+ type: ast.createParamsType({
492
+ variant: "reference",
493
+ name: typeName
494
+ }),
495
+ optional: !hasResponseSchema(response)
496
+ })] }));
497
+ const responseName = `${name}Response${statusCode}`;
498
+ return /* @__PURE__ */ jsx(File.Source, {
499
+ name: responseName,
500
+ isIndexable: true,
501
+ isExportable: true,
502
+ children: /* @__PURE__ */ jsx(Function, {
503
+ name: responseName,
504
+ export: true,
505
+ params: params ?? "",
506
+ children: `
507
+ return new Response(JSON.stringify(data), {
508
+ status: ${statusCode},
509
+ ${headers.length ? ` headers: {
510
+ ${headers.join(", \n")}
511
+ },` : ""}
512
+ })`
513
+ })
514
+ });
515
+ }
516
+ //#endregion
517
+ export { getSuccessResponses as a, Handlers as c, getResponseTypes as i, camelCase as l, MockWithFaker as n, resolveFakerMeta as o, Mock as r, transformName as s, Response as t };
518
+
519
+ //# sourceMappingURL=components-vO0FIb2i.js.map