@sdk-it/typescript 0.20.0 → 0.21.0
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/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2072 -541
- package/dist/index.js.map +4 -4
- package/dist/lib/client.d.ts.map +1 -1
- package/dist/lib/emitters/interface.d.ts +1 -1
- package/dist/lib/emitters/interface.d.ts.map +1 -1
- package/dist/lib/emitters/snippet.d.ts +24 -0
- package/dist/lib/emitters/snippet.d.ts.map +1 -0
- package/dist/lib/emitters/zod.d.ts +1 -1
- package/dist/lib/emitters/zod.d.ts.map +1 -1
- package/dist/lib/generate.d.ts +6 -18
- package/dist/lib/generate.d.ts.map +1 -1
- package/dist/lib/generator.d.ts +2 -4
- package/dist/lib/generator.d.ts.map +1 -1
- package/dist/lib/options.d.ts +27 -0
- package/dist/lib/options.d.ts.map +1 -0
- package/dist/lib/sdk.d.ts +5 -2
- package/dist/lib/sdk.d.ts.map +1 -1
- package/dist/lib/style.d.ts +2 -1
- package/dist/lib/style.d.ts.map +1 -1
- package/dist/lib/typescript-snippet.d.ts +17 -0
- package/dist/lib/typescript-snippet.d.ts.map +1 -0
- package/dist/lib/utils.d.ts +2 -2
- package/dist/lib/utils.d.ts.map +1 -1
- package/package.json +4 -3
- package/dist/lib/readme.d.ts +0 -19
- package/dist/lib/readme.d.ts.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/generate.ts", "
|
|
4
|
-
"sourcesContent": ["import { template } from 'lodash-es';\nimport { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { spinalcase } from 'stringcase';\n\nimport { methods, pascalcase } from '@sdk-it/core';\nimport {\n type WriteContent,\n getFolderExports,\n writeFiles,\n} from '@sdk-it/core/file-system.js';\n\nimport backend from './client.ts';\nimport { generateCode } from './generator.ts';\nimport interceptors from './http/interceptors.txt';\nimport parseResponse from './http/parse-response.txt';\nimport parserTxt from './http/parser.txt';\nimport requestTxt from './http/request.txt';\nimport responseTxt from './http/response.txt';\nimport sendRequestTxt from './http/send-request.txt';\nimport { toReadme } from './readme.ts';\nimport { generateInputs } from './sdk.ts';\nimport type { Style } from './style.ts';\nimport { exclude, securityToOptions } from './utils.ts';\n\nfunction security(spec: OpenAPIObject) {\n const security = spec.security || [];\n const components = spec.components || {};\n const securitySchemes = components.securitySchemes || {};\n const paths = Object.values(spec.paths ?? {});\n\n const options = securityToOptions(security, securitySchemes);\n\n for (const it of paths) {\n for (const method of methods) {\n const operation = it[method];\n if (!operation) {\n continue;\n }\n Object.assign(\n options,\n securityToOptions(operation.security || [], securitySchemes, 'input'),\n );\n }\n }\n return options;\n}\n\nexport async function generate(\n spec: OpenAPIObject,\n settings: {\n readme?: boolean;\n style?: Style;\n output: string;\n useTsExtension?: boolean;\n name?: string;\n /**\n * full: generate a full project including package.json and tsconfig.json. useful for monorepo/workspaces\n * minimal: generate only the client sdk\n */\n mode?: 'full' | 'minimal';\n formatCode?: (options: {\n output: string;\n env: ReturnType<typeof npmRunPathEnv>;\n }) => void | Promise<void>;\n },\n) {\n const style = Object.assign(\n {},\n {\n errorAsValue: true,\n name: 'github',\n outputType: 'default',\n },\n settings.style ?? {},\n );\n\n settings.useTsExtension ??= true;\n const makeImport = (moduleSpecifier: string) => {\n return settings.useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;\n };\n const { commonSchemas, endpoints, groups, outputs, commonZod } = generateCode(\n {\n spec,\n style,\n makeImport,\n },\n );\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n const options = security(spec);\n const clientName = settings.name?.trim()\n ? pascalcase(settings.name)\n : 'Client';\n\n const readme = settings.readme ? toReadme(spec) : '';\n\n // FIXME: inputs, outputs should be generated before hand.\n const inputFiles = generateInputs(groups, commonZod, makeImport);\n\n console.log('Writing to', output);\n\n await writeFiles(output, {\n 'outputs/.gitkeep': '',\n 'inputs/.gitkeep': '',\n 'models/.getkeep': '',\n });\n\n await writeFiles(join(output, 'http'), {\n 'interceptors.ts': `\n import type { RequestConfig, HeadersInit } from './${makeImport('request')}';\n ${interceptors}`,\n 'parse-response.ts': parseResponse,\n 'send-request.ts': `import z from 'zod';\nimport type { Interceptor } from './${makeImport('interceptors')}';\nimport { buffered } from './${makeImport('parse-response')}';\nimport { parseInput } from './${makeImport('parser')}';\nimport type { RequestConfig } from './${makeImport('request')}';\nimport { APIError, APIResponse } from './${makeImport('response')}';\n\n${template(sendRequestTxt, {})({ throwError: !style.errorAsValue, outputType: style.outputType })}`,\n 'response.ts': responseTxt,\n 'parser.ts': parserTxt,\n 'request.ts': requestTxt,\n });\n\n await writeFiles(join(output, 'outputs'), outputs);\n const modelsImports = Object.entries(commonSchemas).map(([name]) => name);\n await writeFiles(output, {\n 'client.ts': backend(\n {\n name: clientName,\n servers: (spec.servers ?? []).map((server) => server.url) || [],\n options: options,\n makeImport,\n },\n style,\n ),\n ...inputFiles,\n ...endpoints,\n ...Object.fromEntries(\n Object.entries(commonSchemas).map(([name, schema]) => [\n `models/${name}.ts`,\n [\n `import { z } from 'zod';`,\n ...exclude(modelsImports, [name]).map(\n (it) => `import type { ${it} } from './${it}.ts';`,\n ),\n `export type ${name} = ${schema};`,\n ].join('\\n'),\n ]),\n ),\n });\n\n const folders = [\n getFolderExports(join(output, 'outputs'), settings.useTsExtension),\n getFolderExports(\n join(output, 'inputs'),\n settings.useTsExtension,\n ['ts'],\n (dirent) => dirent.isDirectory() && ['schemas'].includes(dirent.name),\n ),\n getFolderExports(join(output, 'api'), settings.useTsExtension),\n getFolderExports(\n join(output, 'http'),\n settings.useTsExtension,\n ['ts'],\n (dirent) => !['response.ts', 'parser.ts'].includes(dirent.name),\n ),\n ];\n if (modelsImports.length) {\n folders.push(\n getFolderExports(join(output, 'models'), settings.useTsExtension),\n );\n }\n const [outputIndex, inputsIndex, apiIndex, httpIndex, modelsIndex] =\n await Promise.all(folders);\n await writeFiles(output, {\n 'api/index.ts': apiIndex,\n 'outputs/index.ts': outputIndex,\n 'inputs/index.ts': inputsIndex || null,\n 'http/index.ts': httpIndex,\n ...(modelsImports.length ? { 'models/index.ts': modelsIndex } : {}),\n });\n await writeFiles(output, {\n 'index.ts': await getFolderExports(output, settings.useTsExtension, ['ts']),\n });\n if (settings.mode === 'full') {\n const configFiles: WriteContent = {\n 'package.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n name: settings.name\n ? `@${spinalcase(clientName.toLowerCase())}/sdk`\n : 'sdk',\n type: 'module',\n main: './src/index.ts',\n dependencies: {\n 'fast-content-type-parse': '^3.0.0',\n zod: '^3.24.2',\n },\n },\n null,\n 2,\n ),\n },\n 'tsconfig.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n compilerOptions: {\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n target: 'ESNext',\n module: 'ESNext',\n noEmit: true,\n strict: true,\n allowImportingTsExtensions: true,\n verbatimModuleSyntax: true,\n baseUrl: '.',\n moduleResolution: 'bundler',\n },\n include: ['**/*.ts'],\n },\n null,\n 2,\n ),\n },\n };\n if (readme) {\n configFiles['README.md'] = {\n ignoreIfExists: true,\n content: readme,\n };\n }\n await writeFiles(settings.output, configFiles);\n }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n}\n", "import { toLitObject } from '@sdk-it/core';\n\nimport type { Spec } from './sdk.ts';\nimport type { Style } from './style.ts';\n\nexport default (spec: Omit<Spec, 'operations'>, style: Style) => {\n const optionsEntries = Object.entries(spec.options).map(\n ([key, value]) => [`'${key}'`, value] as const,\n );\n const defaultHeaders = `{${optionsEntries\n .filter(([, value]) => value.in === 'header')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${optionsEntries\n .filter(([, value]) => value.in === 'input')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const specOptions: Record<string, { schema: string }> = {\n ...Object.fromEntries(\n optionsEntries.map(([key, value]) => [value.optionName ?? key, value]),\n ),\n fetch: {\n schema: 'fetchType',\n },\n baseUrl: {\n schema: spec.servers.length\n ? `z.enum(servers).default(servers[0])`\n : 'z.string()',\n },\n };\n\n return `\nimport type { HeadersInit, RequestConfig } from './http/${spec.makeImport('request')}';\nimport { fetchType, dispatch, parse } from './http/${spec.makeImport('send-request')}';\nimport z from 'zod';\nimport type { Endpoints } from './api/${spec.makeImport('endpoints')}';\nimport schemas from './api/${spec.makeImport('schemas')}';\nimport {\n createBaseUrlInterceptor,\n createHeadersInterceptor,\n} from './http/${spec.makeImport('interceptors')}';\n\nimport { parseInput, type ParseError } from './http/${spec.makeImport('parser')}';\n\n${spec.servers.length ? `export const servers = ${JSON.stringify(spec.servers, null, 2)} as const` : ''}\nconst optionsSchema = z.object(${toLitObject(specOptions, (x) => x.schema)});\n${spec.servers.length ? `export type Servers = typeof servers[number];` : ''}\n\ntype ${spec.name}Options = z.infer<typeof optionsSchema>;\n\nexport class ${spec.name} {\n public options: ${spec.name}Options\n constructor(options: ${spec.name}Options) {\n this.options = optionsSchema.parse(options);\n }\n\n async request<E extends keyof Endpoints>(\n endpoint: E,\n input: Endpoints[E]['input'],\n options?: { signal?: AbortSignal, headers?: HeadersInit },\n ) ${style.errorAsValue ? `: Promise<readonly [Endpoints[E]['output'], Endpoints[E]['error'] | null]>` : `: Promise<Endpoints[E]['output']>`} {\n const route = schemas[endpoint];\n const result = await dispatch(Object.assign(this.#defaultInputs, input), route, {\n fetch: this.options.fetch,\n interceptors: [\n createHeadersInterceptor(() => this.defaultHeaders, options?.headers ?? {}),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ],\n signal: options?.signal,\n });\n return ${style.errorAsValue ? `result as [Endpoints[E]['output'], Endpoints[E]['error'] | null]` : `result as Endpoints[E]['output']`};\n }\n\n async prepare<E extends keyof Endpoints>(\n endpoint: E,\n input: Endpoints[E]['input'],\n options?: { headers?: HeadersInit },\n ): ${\n style.errorAsValue\n ? `Promise<\n readonly [\n RequestConfig & {\n parse: (response: Response) => ReturnType<typeof parse>;\n },\n ParseError<(typeof schemas)[E]['schema']> | null,\n ]\n >`\n : `Promise<RequestConfig & {\n parse: (response: Response) => ReturnType<typeof parse>;\n }>`\n } {\n const route = schemas[endpoint];\n\n const interceptors = [\n createHeadersInterceptor(\n () => this.defaultHeaders,\n options?.headers ?? {},\n ),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ];\n const [parsedInput, parseError] = parseInput(route.schema, input);\n if (parseError) {\n ${style.errorAsValue ? 'return [null as never, parseError as never] as const;' : 'throw parseError;'}\n }\n\n let config = route.toRequest(parsedInput as never);\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n const prepared = { ...config, parse: (response: Response) => parse(route, response) };\n return ${style.errorAsValue ? '[prepared, null as never] as const;' : 'prepared'}\n }\n\n get defaultHeaders() {\n return ${defaultHeaders}\n }\n\n get #defaultInputs() {\n return ${defaultInputs}\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n const validated = optionsSchema.partial().parse(options);\n\n for (const key of Object.keys(validated) as (keyof ${spec.name}Options)[]) {\n if (validated[key] !== undefined) {\n (this.options[key] as typeof validated[typeof key]) = validated[key]!;\n }\n }\n }\n}`;\n};\n", "import { merge, template } from 'lodash-es';\nimport { join } from 'node:path';\nimport type {\n OpenAPIObject,\n ParameterLocation,\n ParameterObject,\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef } from '@sdk-it/core';\nimport {\n type GenerateSdkConfig,\n forEachOperation,\n} from '@sdk-it/spec/operation.js';\n\nimport { ZodDeserialzer } from './emitters/zod.ts';\nimport {\n type Operation,\n type OperationInput,\n type Spec,\n toEndpoint,\n} from './sdk.ts';\nimport endpointsTxt from './styles/github/endpoints.txt';\nimport {\n importsToString,\n mergeImports,\n securityToOptions,\n useImports,\n} from './utils.ts';\n\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly: boolean;\n}\nexport interface Import {\n isTypeOnly: boolean;\n moduleSpecifier: string;\n defaultImport: string | undefined;\n namedImports: NamedImport[];\n namespaceImport: string | undefined;\n}\n\nexport function generateCode(\n config: GenerateSdkConfig & {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n style?: { name?: 'github'; outputType?: 'default' | 'status' };\n makeImport: (module: string) => string;\n },\n) {\n const commonZod = new Map<string, string>();\n const commonZodImports: Import[] = [];\n const zodDeserialzer = new ZodDeserialzer(config.spec, (model, schema) => {\n commonZod.set(model, schema);\n commonZodImports.push({\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `./${config.makeImport(model)}`,\n namedImports: [{ isTypeOnly: true, name: model }],\n namespaceImport: undefined,\n });\n });\n\n const groups: Spec['operations'] = {};\n const outputs: Record<string, string> = {};\n const endpoints: Record<string, ReturnType<typeof toEndpoint>[]> = {};\n\n forEachOperation(config, (entry, operation) => {\n console.log(`Processing ${entry.method} ${entry.path}`);\n groups[entry.groupName] ??= [];\n endpoints[entry.groupName] ??= [];\n const inputs: Operation['inputs'] = {};\n\n const additionalProperties: Record<string, ParameterObject> = {};\n for (const param of operation.parameters ?? []) {\n if (isRef(param)) {\n throw new Error(`Found reference in parameter ${param.$ref}`);\n }\n if (!param.schema) {\n throw new Error(`Schema not found for parameter ${param.name}`);\n }\n inputs[param.name] = {\n in: param.in,\n schema: '',\n };\n additionalProperties[param.name] = param;\n }\n\n const security = operation.security ?? [];\n const securitySchemes = config.spec.components?.securitySchemes ?? {};\n const securityOptions = securityToOptions(security, securitySchemes);\n\n Object.assign(inputs, securityOptions);\n\n // the spec might have explict security param for security set\n // which we need to overwrite it by ours. (avoid having it mandatory)\n Object.entries(securityOptions).forEach(([name, value]) => {\n additionalProperties[name] = {\n name: name,\n required: false,\n schema: {\n type: 'string',\n },\n in: value.in as ParameterLocation,\n } satisfies ParameterObject;\n });\n\n const schemas: Record<string, string> = {};\n const shortContenTypeMap: Record<string, string> = {\n 'application/json': 'json',\n 'application/*+json': 'json', // type specific of json like application/vnd.api+json (from the generation pov it shouldn't matter)\n 'text/json': 'json', // non standard - later standardized to application/json\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'multipart/form-data': 'formdata',\n 'application/xml': 'xml',\n 'text/plain': 'text',\n };\n let outgoingContentType: string | undefined;\n\n if (!isEmpty(operation.requestBody)) {\n const requestBody = isRef(operation.requestBody)\n ? followRef<RequestBodyObject>(config.spec, operation.requestBody.$ref)\n : operation.requestBody;\n\n for (const type in requestBody.content) {\n const ctSchema = isRef(requestBody.content[type].schema)\n ? followRef(config.spec, requestBody.content[type].schema.$ref)\n : requestBody.content[type].schema;\n if (!ctSchema) {\n console.warn(\n `Schema not found for ${type} in ${entry.method} ${entry.path}`,\n );\n continue;\n }\n\n let objectSchema = ctSchema;\n if (objectSchema.type !== 'object') {\n objectSchema = {\n type: 'object',\n required: [requestBody.required ? '$body' : ''],\n properties: {\n $body: ctSchema,\n },\n };\n }\n const schema = merge({}, objectSchema, {\n required: Object.values(additionalProperties)\n .filter((p) => p.required)\n .map((p) => p.name),\n properties: Object.entries(additionalProperties).reduce<\n Record<string, unknown>\n >(\n (acc, [, p]) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n ),\n });\n\n Object.assign(inputs, bodyInputs(config, objectSchema));\n schemas[shortContenTypeMap[type]] = zodDeserialzer.handle(schema, true);\n }\n\n if (requestBody.content['application/json']) {\n outgoingContentType = 'json';\n } else if (requestBody.content['application/x-www-form-urlencoded']) {\n outgoingContentType = 'urlencoded';\n } else if (requestBody.content['multipart/form-data']) {\n outgoingContentType = 'formdata';\n } else {\n outgoingContentType = 'json';\n }\n } else {\n const properties = Object.entries(additionalProperties).reduce<\n Record<string, any>\n >(\n (acc, [, p]) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n );\n schemas[shortContenTypeMap['application/json']] = zodDeserialzer.handle(\n {\n type: 'object',\n required: Object.values(additionalProperties)\n .filter((p) => p.required)\n .map((p) => p.name),\n properties,\n },\n true,\n );\n }\n\n const endpoint = toEndpoint(\n entry.groupName,\n config.spec,\n operation,\n {\n outgoingContentType,\n name: operation.operationId,\n type: 'http',\n trigger: entry,\n schemas,\n inputs,\n },\n { makeImport: config.makeImport },\n );\n\n const output = [\n `import z from 'zod';`,\n `import type * as http from '../http';`,\n ];\n const responses = endpoint.responses.flatMap((it) => it.responses);\n const responsesImports = endpoint.responses.flatMap((it) =>\n Object.values(it.imports),\n );\n if (responses.length) {\n output.push(\n ...responses.map(\n (it) =>\n `${it.description ? `\\n/** \\n * ${it.description}\\n */\\n` : ''} export type ${it.name} = ${it.schema};`,\n ),\n );\n } else {\n output.push(\n `export type ${pascalcase(operation.operationId + ' output')} = void;`,\n );\n }\n\n output.unshift(...useImports(output.join(''), ...responsesImports));\n\n outputs[`${spinalcase(operation.operationId)}.ts`] = output.join('\\n');\n\n endpoints[entry.groupName].push(endpoint);\n\n groups[entry.groupName].push({\n name: operation.operationId,\n type: 'http',\n inputs,\n outgoingContentType,\n schemas,\n trigger: entry,\n });\n });\n const commonSchemas = Object.values(endpoints).reduce<Record<string, string>>(\n (acc, endpoint) => ({\n ...acc,\n ...endpoint.reduce<Record<string, string>>(\n (acc, { responses }) => ({\n ...acc,\n ...responses.reduce<Record<string, string>>(\n (acc, it) => ({ ...acc, ...it.schemas }),\n {},\n ),\n }),\n {},\n ),\n }),\n {},\n );\n\n const allSchemas = Object.keys(endpoints).map((it) => ({\n import: `import ${camelcase(it)} from './${config.makeImport(spinalcase(it))}';`,\n use: ` ...${camelcase(it)}`,\n }));\n\n const imports = [\n 'import z from \"zod\";',\n `import type { ParseError } from '${config.makeImport('../http/parser')}';`,\n `import type { ServerError } from '${config.makeImport('../http/response')}';`,\n `import type { OutputType, Parser, Type } from '../http/send-request.ts';`,\n ];\n return {\n groups,\n commonSchemas,\n commonZod,\n outputs,\n endpoints: {\n [join('api', 'endpoints.ts')]: `\n\n\nimport type z from 'zod';\nimport type { ParseError } from '${config.makeImport('../http/parser')}';\nimport type { ProblematicResponse, SuccessfulResponse } from '${config.makeImport(\n '../http/response',\n )}';\nimport type { OutputType, Parser, Type } from '${config.makeImport(\n '../http/send-request',\n )}';\n\nimport schemas from '${config.makeImport('./schemas')}';\n\n ${template(endpointsTxt)({ outputType: config.style?.outputType })}`,\n [`${join('api', 'schemas.ts')}`]:\n `${allSchemas.map((it) => it.import).join('\\n')}\nimport { KIND } from \"${config.makeImport('../http/index')}\";\nexport default {\\n${allSchemas.map((it) => it.use).join(',\\n')}\\n};\n\n`.trim(),\n ...Object.fromEntries(\n Object.entries(endpoints)\n .map(([name, endpoint]) => {\n const imps = importsToString(\n ...mergeImports(\n ...endpoint.flatMap((it) =>\n it.responses.flatMap((it) =>\n Object.values(it.endpointImports),\n ),\n ),\n ),\n );\n return [\n [\n join('api', `${spinalcase(name)}.ts`),\n `${[\n ...imps,\n `import z from 'zod';`,\n `import * as http from '${config.makeImport('../http/response')}';`,\n `import { toRequest, json, urlencoded, nobody, formdata, createUrl } from '${config.makeImport('../http/request')}';`,\n `import { chunked, buffered } from \"${config.makeImport('../http/parse-response')}\";`,\n `import * as ${camelcase(name)} from '../inputs/${config.makeImport(spinalcase(name))}';`,\n ].join(\n '\\n',\n )}\\nexport default {\\n${endpoint.flatMap((it) => it.schemas).join(',\\n')}\\n}`,\n ],\n ];\n })\n .flat(),\n ),\n },\n };\n}\n\nfunction toProps(\n spec: OpenAPIObject,\n schemaOrRef: SchemaObject | ReferenceObject,\n aggregator: string[] = [],\n) {\n if (isRef(schemaOrRef)) {\n const schema = followRef(spec, schemaOrRef.$ref);\n return toProps(spec, schema, aggregator);\n } else if (schemaOrRef.type === 'object') {\n for (const [name] of Object.entries(schemaOrRef.properties ?? {})) {\n aggregator.push(name);\n }\n return void 0;\n } else if (\n (schemaOrRef.type === 'array' || schemaOrRef.type?.includes('array')) &&\n schemaOrRef.items\n ) {\n toProps(spec, schemaOrRef.items, aggregator);\n return void 0;\n } else if (schemaOrRef.allOf) {\n for (const it of schemaOrRef.allOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n } else if (schemaOrRef.oneOf) {\n for (const it of schemaOrRef.oneOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n } else if (schemaOrRef.anyOf) {\n for (const it of schemaOrRef.anyOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n }\n console.warn('Unknown schema in body', schemaOrRef);\n return void 0;\n}\n\nfunction bodyInputs(\n config: GenerateSdkConfig,\n ctSchema: SchemaObject | ReferenceObject,\n) {\n const props: string[] = [];\n toProps(config.spec, ctSchema, props);\n return props.reduce<Record<string, OperationInput>>(\n (acc, prop) => ({\n ...acc,\n [prop]: {\n in: 'body',\n schema: '',\n },\n }),\n {},\n );\n}\n", "import type {\n OpenAPIObject,\n OperationObject,\n ParameterObject,\n ReferenceObject,\n ResponseObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport { followRef, isRef } from '@sdk-it/core';\n\nexport const defaults: Partial<GenerateSdkConfig> &\n Required<Pick<GenerateSdkConfig, 'operationId' | 'tag'>> = {\n operationId: (operation, path, method) => {\n if (operation.operationId) {\n return camelcase(operation.operationId);\n }\n const metadata = operation['x-oaiMeta'];\n if (metadata && metadata.name) {\n return camelcase(metadata.name);\n }\n return camelcase(\n [method, ...path.replace(/[\\\\/\\\\{\\\\}]/g, ' ').split(' ')]\n .filter(Boolean)\n .join(' ')\n .trim(),\n );\n },\n tag: (operation, path) => {\n return operation.tags?.[0]\n ? sanitizeTag(operation.tags?.[0])\n : determineGenericTag(path, operation);\n },\n};\n\nexport type TunedOperationObject = Omit<\n OperationObject,\n 'operationId' | 'parameters' | 'responses'\n> & {\n operationId: string;\n parameters: (ParameterObject | ReferenceObject)[];\n responses: Record<string, ResponseObject>;\n};\n\nexport interface OperationEntry {\n name?: string;\n method: string;\n path: string;\n groupName: string;\n tag: string;\n}\nexport type Operation = {\n entry: OperationEntry;\n operation: TunedOperationObject;\n};\n\nfunction resolveResponses(spec: OpenAPIObject, operation: OperationObject) {\n const responses = operation.responses ?? {};\n const resolved: Record<string, ResponseObject> = {};\n for (const status in responses) {\n const response = isRef(responses[status] as ReferenceObject)\n ? followRef<ResponseObject>(spec, responses[status].$ref)\n : (responses[status] as ResponseObject);\n resolved[status] = response;\n }\n return resolved;\n}\n\nexport function forEachOperation<T>(\n config: GenerateSdkConfig,\n callback: (entry: OperationEntry, operation: TunedOperationObject) => T,\n) {\n const result: T[] = [];\n for (const [path, pathItem] of Object.entries(config.spec.paths ?? {})) {\n const { parameters = [], ...methods } = pathItem;\n\n // Convert Express-style routes (:param) to OpenAPI-style routes ({param})\n const fixedPath = path.replace(/:([^/]+)/g, '{$1}');\n\n for (const [method, operation] of Object.entries(methods) as [\n string,\n OperationObject,\n ][]) {\n const formatOperationId = config.operationId ?? defaults.operationId;\n const formatTag = config.tag ?? defaults.tag;\n const operationName = formatOperationId(operation, fixedPath, method);\n const operationTag = formatTag(operation, fixedPath);\n const metadata = operation['x-oaiMeta'] ?? {};\n\n result.push(\n callback(\n {\n name: metadata.name,\n method,\n path: fixedPath,\n groupName: operationTag,\n tag: operationTag,\n },\n {\n ...operation,\n parameters: [...parameters, ...(operation.parameters ?? [])],\n operationId: operationName,\n responses: resolveResponses(config.spec, operation),\n },\n ),\n );\n }\n }\n return result;\n}\n\nexport interface GenerateSdkConfig {\n spec: OpenAPIObject;\n operationId?: (\n operation: OperationObject,\n path: string,\n method: string,\n ) => string;\n tag?: (operation: OperationObject, path: string) => string;\n}\n\n/**\n * Set of reserved TypeScript keywords and common verbs potentially used as tags.\n */\n\nconst reservedKeywords = new Set([\n 'await', // Reserved in async functions\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'enum',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'implements', // Strict mode\n 'import',\n 'in',\n 'instanceof',\n 'interface', // Strict mode\n 'let', // Strict mode\n 'new',\n 'null',\n 'package', // Strict mode\n 'private', // Strict mode\n 'protected', // Strict mode\n 'public', // Strict mode\n 'return',\n 'static', // Strict mode\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield', // Strict mode / Generator functions\n // 'arguments' is not technically a reserved word, but it's a special identifier within functions\n // and assigning to it or declaring it can cause issues or unexpected behavior.\n 'arguments',\n]);\n\n/**\n * Sanitizes a potential tag name (assumed to be already camelCased)\n * to avoid conflicts with reserved keywords or invalid starting characters (numbers).\n * Appends an underscore if the tag matches a reserved keyword.\n * Prepends an underscore if the tag starts with a number.\n * @param camelCasedTag The potential tag name, already camelCased.\n * @returns The sanitized tag name.\n */\nfunction sanitizeTag(camelCasedTag: string): string {\n // Prepend underscore if starts with a number\n if (/^\\d/.test(camelCasedTag)) {\n return `_${camelCasedTag}`;\n }\n // Append underscore if it's a reserved keyword\n return reservedKeywords.has(camelcase(camelCasedTag))\n ? `${camelCasedTag}_`\n : camelCasedTag;\n}\n\n/**\n * Attempts to determine a generic tag for an OpenAPI operation based on path and operationId.\n * Rules and fallbacks are documented within the code.\n * @param pathString The path string.\n * @param operation The OpenAPI Operation Object.\n * @returns A sanitized, camelCased tag name string.\n */\nexport function determineGenericTag(\n pathString: string,\n operation: OperationObject,\n): string {\n const operationId = operation.operationId || '';\n const VERSION_REGEX = /^[vV]\\d+$/;\n const commonVerbs = new Set([\n // Verbs to potentially strip from operationId prefix\n 'get',\n 'list',\n 'create',\n 'update',\n 'delete',\n 'post',\n 'put',\n 'patch',\n 'do',\n 'send',\n 'add',\n 'remove',\n 'set',\n 'find',\n 'search',\n 'check',\n 'make',\n ]);\n\n const segments = pathString.split('/').filter(Boolean);\n\n const potentialCandidates = segments.filter(\n (segment) =>\n segment &&\n !segment.startsWith('{') &&\n !segment.endsWith('}') &&\n !VERSION_REGEX.test(segment),\n );\n\n // --- Heuristic 1: Last non-'@' path segment ---\n for (let i = potentialCandidates.length - 1; i >= 0; i--) {\n const segment = potentialCandidates[i];\n if (!segment.startsWith('@')) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(segment));\n }\n }\n\n const canFallbackToPathSegment = potentialCandidates.length > 0;\n\n // --- Heuristic 2: OperationId parsing ---\n if (operationId) {\n const lowerOpId = operationId.toLowerCase();\n const parts = operationId\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n .replace(/([a-zA-Z])(\\d)/g, '$1_$2')\n .replace(/(\\d)([a-zA-Z])/g, '$1_$2')\n .toLowerCase()\n .split(/[_-\\s]+/);\n\n const validParts = parts.filter(Boolean);\n\n // Quick skip: If opId is just a verb and we can use Heuristic 3, prefer that.\n if (\n commonVerbs.has(lowerOpId) &&\n validParts.length === 1 &&\n canFallbackToPathSegment\n ) {\n // Proceed directly to Heuristic 3\n }\n // Only process if there are valid parts and the quick skip didn't happen\n else if (validParts.length > 0) {\n const firstPart = validParts[0];\n const isFirstPartVerb = commonVerbs.has(firstPart);\n\n // Case 2a: Starts with verb, has following parts\n if (isFirstPartVerb && validParts.length > 1) {\n const verbPrefixLength = firstPart.length;\n let nextPartStartIndex = -1;\n if (operationId.length > verbPrefixLength) {\n // Simplified check for next part start\n const charAfterPrefix = operationId[verbPrefixLength];\n if (charAfterPrefix >= 'A' && charAfterPrefix <= 'Z') {\n nextPartStartIndex = verbPrefixLength;\n } else if (charAfterPrefix >= '0' && charAfterPrefix <= '9') {\n nextPartStartIndex = verbPrefixLength;\n } else if (['_', '-'].includes(charAfterPrefix)) {\n nextPartStartIndex = verbPrefixLength + 1;\n } else {\n const match = operationId\n .substring(verbPrefixLength)\n .match(/[A-Z0-9]/);\n if (match && match.index !== undefined) {\n nextPartStartIndex = verbPrefixLength + match.index;\n }\n if (\n nextPartStartIndex === -1 &&\n operationId.length > verbPrefixLength\n ) {\n nextPartStartIndex = verbPrefixLength; // Default guess\n }\n }\n }\n\n if (\n nextPartStartIndex !== -1 &&\n nextPartStartIndex < operationId.length\n ) {\n const remainingOriginalSubstring =\n operationId.substring(nextPartStartIndex);\n const potentialTag = camelcase(remainingOriginalSubstring);\n if (potentialTag) {\n // Sanitize just before returning\n return sanitizeTag(potentialTag);\n }\n }\n\n // Fallback: join remaining lowercased parts\n const potentialTagJoined = camelcase(validParts.slice(1).join('_'));\n if (potentialTagJoined) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagJoined);\n }\n }\n\n // Case 2b: Doesn't start with verb, or only one part (might be verb)\n const potentialTagFull = camelcase(operationId);\n if (potentialTagFull) {\n const isResultSingleVerb = validParts.length === 1 && isFirstPartVerb;\n\n // Avoid returning only a verb if Heuristic 3 is possible\n if (!(isResultSingleVerb && canFallbackToPathSegment)) {\n if (potentialTagFull.length > 0) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagFull);\n }\n }\n }\n\n // Case 2c: Further fallbacks within OpId if above failed/skipped\n const firstPartCamel = camelcase(firstPart);\n if (firstPartCamel) {\n const isFirstPartCamelVerb = commonVerbs.has(firstPartCamel);\n if (\n !isFirstPartCamelVerb ||\n validParts.length === 1 ||\n !canFallbackToPathSegment\n ) {\n // Sanitize just before returning\n return sanitizeTag(firstPartCamel);\n }\n }\n if (\n isFirstPartVerb &&\n validParts.length > 1 &&\n validParts[1] &&\n canFallbackToPathSegment\n ) {\n const secondPartCamel = camelcase(validParts[1]);\n if (secondPartCamel) {\n // Sanitize just before returning\n return sanitizeTag(secondPartCamel);\n }\n }\n } // End if(validParts.length > 0) after quick skip check\n } // End if(operationId)\n\n // --- Heuristic 3: First path segment (stripping '@') ---\n if (potentialCandidates.length > 0) {\n let firstCandidate = potentialCandidates[0];\n if (firstCandidate.startsWith('@')) {\n firstCandidate = firstCandidate.substring(1);\n }\n if (firstCandidate) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(firstCandidate));\n }\n }\n\n // --- Heuristic 4: Default ---\n console.warn(\n `Could not determine a suitable tag for path: ${pathString}, operationId: ${operationId}. Using 'unknown'.`,\n );\n return 'unknown'; // 'unknown' is safe\n}\n\nexport function parseJsonContentType(contentType: string | null | undefined) {\n if (!contentType) {\n return null;\n }\n\n // 1. Trim whitespace\n let mainType = contentType.trim();\n\n // 2. Remove parameters (anything after the first ';')\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n mainType = mainType.substring(0, semicolonIndex).trim(); // Trim potential space before ';'\n }\n\n // 3. Convert to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n if (mainType.endsWith('/json')) {\n return mainType.split('/')[1];\n } else if (mainType.endsWith('+json')) {\n return mainType.split('+')[1];\n }\n return null;\n}\n\n/**\n * Checks if a given content type string represents Server-Sent Events (SSE).\n * Handles case-insensitivity, parameters (like charset), and leading/trailing whitespace.\n *\n * @param contentType The content type string to check (e.g., from a Content-Type header).\n * @returns True if the content type is 'text/event-stream', false otherwise.\n */\nexport function isSseContentType(\n contentType: string | null | undefined,\n): boolean {\n if (!contentType) {\n return false; // Handle null, undefined, or empty string\n }\n\n // 1. Trim whitespace from the input string\n let mainType = contentType.trim();\n\n // 2. Find the position of the first semicolon (if any) to remove parameters\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n // Extract the part before the semicolon and trim potential space\n mainType = mainType.substring(0, semicolonIndex).trim();\n }\n\n // 3. Convert the main type part to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n // 4. Compare against the standard SSE MIME type\n return mainType === 'text/event-stream';\n}\n\nexport function isStreamingContentType(\n contentType: string | null | undefined,\n): boolean {\n return contentType === 'application/octet-stream';\n}\n\nexport function isSuccessStatusCode(statusCode: number | string): boolean {\n statusCode = Number(statusCode);\n return statusCode >= 200 && statusCode < 300;\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, content: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n * adapted for OpenAPI 3.1 (fully aligned with JSON Schema 2020-12).\n */\nexport class ZodDeserialzer {\n generatedRefs = new Set<string>();\n #spec: OpenAPIObject;\n #onRef?: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef?: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n /**\n * Handle objects (properties, additionalProperties).\n */\n object(schema: SchemaObject): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n return `'${key}': ${this.handle(propSchema, isRequired)}`;\n });\n\n let additionalProps = '';\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n // e.g. z.record() if it\u2019s an object schema\n const addPropZod = this.handle(schema.additionalProperties, true);\n additionalProps = `.catchall(${addPropZod})`;\n } else if (schema.additionalProperties === true) {\n // free-form additional props\n additionalProps = `.catchall(z.unknown())`;\n }\n }\n\n return `z.object({${propEntries.join(', ')}})${additionalProps}`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple (array of schemas)).\n * In JSON Schema 2020-12, `items` can be an array \u2192 tuple style.\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => z.array(z.unknown())\n return `z.array(z.unknown())${appendOptional(required)}`;\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n // Build a Zod tuple\n const tupleItems = items.map((sub) => this.handle(sub, true));\n const base = `z.tuple([${tupleItems.join(', ')}])`;\n // // If we have additionalItems: false => that\u2019s a fixed length\n // // If additionalItems is a schema => rest(...)\n // if (schema.additionalItems) {\n // if (typeof schema.additionalItems === 'object') {\n // const restSchema = jsonSchemaToZod(spec, schema.additionalItems, true);\n // base += `.rest(${restSchema})`;\n // }\n // // If `additionalItems: false`, no rest is allowed => do nothing\n // }\n return `${base}${appendOptional(required)}`;\n }\n\n // If items is a single schema => standard z.array(...)\n const itemsSchema = this.handle(items, true);\n return `z.array(${itemsSchema})${appendOptional(required)}`;\n }\n\n #suffixes = (defaultValue: unknown, required: boolean, nullable: boolean) => {\n return `${nullable ? '.nullable()' : ''}${appendDefault(defaultValue)}${appendOptional(required)}`;\n };\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to Zod.\n * We'll also handle .optional() if needed.\n */\n normal(\n type: string,\n schema: SchemaObject,\n required = false,\n nullable = false,\n ): string {\n switch (type) {\n case 'string':\n return `${this.string(schema)}${this.#suffixes(JSON.stringify(schema.default), required, nullable)}`;\n case 'number':\n case 'integer': {\n const { base, defaultValue } = this.number(schema);\n return `${base}${this.#suffixes(defaultValue, required, nullable)}`;\n }\n case 'boolean':\n return `z.boolean()${this.#suffixes(schema.default, required, nullable)}`;\n case 'object':\n return `${this.object(schema)}${this.#suffixes(JSON.stringify(schema.default), required, nullable)}`;\n // required always\n case 'array':\n return this.array(schema, required);\n case 'null':\n // If \"type\": \"null\" alone, this is basically z.null()\n return `z.null()${appendOptional(required)}`;\n default:\n // Unknown type -> fallback\n return `z.unknown()${appendOptional(required)}`;\n }\n }\n\n ref($ref: string, required: boolean) {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.generatedRefs.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef<SchemaObject>(this.#spec, $ref), required),\n );\n\n return schemaName;\n }\n allOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const allOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (allOfSchemas.length === 0) {\n return `z.unknown()`;\n }\n if (allOfSchemas.length === 1) {\n return `${allOfSchemas[0]}${appendOptional(required)}`;\n }\n return `${this.#toIntersection(allOfSchemas)}${appendOptional(required)}`;\n }\n\n #toIntersection(schemas: string[]): string {\n const [left, ...right] = schemas;\n if (!right.length) {\n return left;\n }\n return `z.intersection(${left}, ${this.#toIntersection(right)})`;\n }\n\n anyOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const anyOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (anyOfSchemas.length === 1) {\n return `${anyOfSchemas[0]}${appendOptional(required)}`;\n }\n return `z.union([${anyOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n oneOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const oneOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (oneOfSchemas.length === 1) {\n return `${oneOfSchemas[0]}${appendOptional(required)}`;\n }\n return `z.union([${oneOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n enum(type: string, values: any[]) {\n if (values.length === 1) {\n return `z.literal(${values.join(', ')})`;\n }\n if (type === 'integer') {\n // Zod doesn\u2019t have a direct enum for numbers, so we use union of literals\n return `z.union([${values.map((val) => `z.literal(${val})`).join(', ')}])`;\n }\n\n return `z.enum([${values.join(', ')}])`;\n }\n\n /**\n * Handle a `string` schema with possible format keywords (JSON Schema).\n */\n string(schema: SchemaObject): string {\n let base = 'z.string()';\n\n // 3.1 replaces `example` in the schema with `examples` (array).\n // We do not strictly need them for the Zod type, so they\u2019re optional\n // for validation. However, we could keep them as metadata if you want.\n\n if (schema.contentEncoding === 'binary') {\n base = 'z.instanceof(Blob)';\n return base;\n }\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n // parse to JS Date\n base = 'z.coerce.date()';\n break;\n case 'date':\n base =\n 'z.coerce.date() /* or z.string() if you want raw date strings */';\n break;\n case 'time':\n base =\n 'z.string() /* optionally add .regex(...) for HH:MM:SS format */';\n break;\n case 'email':\n base = 'z.string().email()';\n break;\n case 'uuid':\n base = 'z.string().uuid()';\n break;\n case 'url':\n case 'uri':\n base = 'z.string().url()';\n break;\n case 'ipv4':\n base = 'z.string().ip({version: \"v4\"})';\n break;\n case 'ipv6':\n base = 'z.string().ip({version: \"v6\"})';\n break;\n case 'phone':\n base = 'z.string() /* or add .regex(...) for phone formats */';\n break;\n case 'byte':\n case 'binary':\n base = 'z.instanceof(Blob)';\n break;\n case 'int64':\n // JS numbers can't reliably store int64, consider z.bigint() or keep as string\n base = 'z.string() /* or z.bigint() if your app can handle it */';\n break;\n default:\n // No special format\n break;\n }\n\n return base;\n }\n\n /**\n * Handle number/integer constraints from OpenAPI/JSON Schema.\n * In 3.1, exclusiveMinimum/Maximum hold the actual numeric threshold,\n * rather than a boolean toggling `minimum`/`maximum`.\n */\n number(schema: SchemaObject) {\n let defaultValue = schema.default;\n let base = 'z.number()';\n if (schema.format === 'int64') {\n base = 'z.bigint()';\n if (schema.default !== undefined) {\n defaultValue = `BigInt(${schema.default})`;\n }\n }\n\n if (schema.format === 'int32') {\n // 32-bit integer\n base += '.int()';\n }\n\n // If we see exclusiveMinimum as a number in 3.1:\n if (typeof schema.exclusiveMinimum === 'number') {\n // Zod doesn\u2019t have a direct \"exclusiveMinimum\" method, so we can do .gt()\n // If exclusiveMinimum=7 => .gt(7)\n base += `.gt(${schema.exclusiveMinimum})`;\n }\n // Similarly for exclusiveMaximum\n if (typeof schema.exclusiveMaximum === 'number') {\n // If exclusiveMaximum=10 => .lt(10)\n base += `.lt(${schema.exclusiveMaximum})`;\n }\n\n // If standard minimum/maximum\n if (typeof schema.minimum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.min(BigInt(${schema.minimum}))`\n : `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.max(BigInt(${schema.maximum}))`\n : `.max(${schema.maximum})`;\n }\n\n // multipleOf\n if (typeof schema.multipleOf === 'number') {\n // There's no direct multipleOf in Zod. Some folks do a custom refine.\n // For example:\n base += `.refine((val) => Number.isInteger(val / ${schema.multipleOf}), \"Must be a multiple of ${schema.multipleOf}\")`;\n }\n\n return { base, defaultValue };\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return `${this.ref(schema.$ref, true)}${appendOptional(required)}`;\n }\n\n // Handle allOf \u2192 intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf ?? [], required);\n }\n\n // anyOf \u2192 union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf ?? [], required);\n }\n\n // oneOf \u2192 union\n if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length) {\n return this.oneOf(schema.oneOf ?? [], required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n const enumVals = schema.enum.map((val) => JSON.stringify(val));\n const defaultValue = enumVals.includes(JSON.stringify(schema.default))\n ? JSON.stringify(schema.default)\n : undefined;\n return `${this.enum(schema.type as string, enumVals)}${this.#suffixes(defaultValue, required, false)}`;\n }\n\n // 3.1 can have type: string or type: string[] (e.g. [\"string\",\"null\"])\n // Let's parse that carefully.\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to unknown\n if (!types.length) {\n return `z.unknown()${appendOptional(required)}`;\n }\n\n // If it's a union type (like [\"string\", \"null\"]), we'll build a Zod union\n // or apply .nullable() if it's just \"type + null\".\n\n // backward compatibility with openapi 3.0\n if ('nullable' in schema && schema.nullable) {\n types.push('null');\n } else if (schema.default === null) {\n types.push('null');\n }\n\n if (types.length > 1) {\n // If it\u2019s exactly one real type plus \"null\", we can do e.g. `z.string().nullable()`\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n return this.normal(realTypes[0], schema, required, true);\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) => this.normal(t, schema, false));\n return `z.union([${subSchemas.join(', ')}])${appendOptional(required)}`;\n }\n return this.normal(types[0], schema, required, false);\n }\n}\n\n/**\n * Append .optional() if not required\n */\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n\n// Todo: convert openapi 3.0 to 3.1 before proccesing\n", "import { get } from 'lodash-es';\nimport type {\n OpenAPIObject,\n OperationObject,\n ReferenceObject,\n ResponseObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { followRef, isRef, toLitObject } from '@sdk-it/core';\n\nimport { TypeScriptDeserialzer } from './emitters/interface.ts';\nimport { type Import, type MakeImportFn } from './utils.ts';\n\nexport type Parser = 'chunked' | 'buffered';\n\nexport interface SdkConfig {\n /**\n * The name of the sdk client\n */\n name: string;\n packageName?: string;\n options?: Record<string, any>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport type Options = Record<\n string,\n {\n in: string;\n schema: string;\n optionName?: string;\n }\n>;\nexport interface Spec {\n name: string;\n options: Options;\n servers: string[];\n operations: Record<string, Operation[]>;\n makeImport: MakeImportFn;\n}\n\nexport interface OperationInput {\n in: string;\n schema: string;\n}\nexport interface Operation {\n name: string;\n type: string;\n trigger: Record<string, any>;\n schemas: Record<string, string>;\n inputs: Record<string, OperationInput>;\n outgoingContentType?: string;\n}\n\nexport function generateInputs(\n operationsSet: Spec['operations'],\n commonZod: Map<string, string>,\n makeImport: MakeImportFn,\n) {\n const commonImports = commonZod.keys().toArray();\n const inputs: Record<string, string> = {};\n for (const [name, operations] of Object.entries(operationsSet)) {\n const output: string[] = [];\n const imports = new Set(['import { z } from \"zod\";']);\n\n for (const operation of operations) {\n const schemaName = camelcase(`${operation.name} schema`);\n\n const schema = `export const ${schemaName} = ${\n Object.keys(operation.schemas).length === 1\n ? Object.values(operation.schemas)[0]\n : toLitObject(operation.schemas)\n };`;\n\n const inputContent = schema;\n\n for (const schema of commonImports) {\n if (inputContent.includes(schema)) {\n imports.add(\n `import { ${schema} } from './schemas/${makeImport(spinalcase(schema))}';`,\n );\n }\n }\n output.push(inputContent);\n }\n inputs[`inputs/${spinalcase(name)}.ts`] =\n [...imports, ...output].join('\\n') + '\\n';\n }\n\n const schemas = commonZod\n .entries()\n .reduce<string[][]>((acc, [name, schema]) => {\n const output = [`import { z } from 'zod';`];\n const content = `export const ${name} = ${schema};`;\n for (const schema of commonImports) {\n const preciseMatch = new RegExp(`\\\\b${schema}\\\\b`);\n if (preciseMatch.test(content) && schema !== name) {\n output.push(\n `import { ${schema} } from './${makeImport(spinalcase(schema))}';`,\n );\n }\n }\n\n output.push(content);\n return [\n [`inputs/schemas/${spinalcase(name)}.ts`, output.join('\\n')],\n ...acc,\n ];\n }, []);\n\n return {\n ...Object.fromEntries(schemas),\n ...inputs,\n };\n}\n\nexport function toEndpoint(\n groupName: string,\n spec: OpenAPIObject,\n specOperation: OperationObject,\n operation: Operation,\n utils: {\n makeImport: MakeImportFn;\n },\n) {\n const schemaName = camelcase(`${operation.name} schema`);\n const schemaRef = `${camelcase(groupName)}.${schemaName}`;\n\n const inputHeaders: string[] = [];\n const inputQuery: string[] = [];\n const inputBody: string[] = [];\n const inputParams: string[] = [];\n const schemas: string[] = [];\n const responses: ReturnType<typeof handleResponse>[] = [];\n for (const [name, prop] of Object.entries(operation.inputs)) {\n if (prop.in === 'headers' || prop.in === 'header') {\n inputHeaders.push(`\"${name}\"`);\n } else if (prop.in === 'query') {\n inputQuery.push(`\"${name}\"`);\n } else if (prop.in === 'body') {\n inputBody.push(`\"${name}\"`);\n } else if (prop.in === 'path') {\n inputParams.push(`\"${name}\"`);\n } else if (prop.in === 'internal') {\n // ignore internal sources\n continue;\n } else {\n throw new Error(\n `Unknown source ${prop.in} in ${name} ${JSON.stringify(\n prop,\n )} in ${operation.name}`,\n );\n }\n }\n\n specOperation.responses ??= {};\n const outputs: string[] = [];\n\n const statusesCount =\n Object.keys(specOperation.responses).filter((status) => {\n const statusCode = +status;\n return statusCode >= 200 && statusCode < 300;\n }).length > 1;\n for (const status in specOperation.responses) {\n const response = isRef(specOperation.responses[status] as ReferenceObject)\n ? followRef<ResponseObject>(spec, specOperation.responses[status].$ref)\n : (specOperation.responses[status] as ResponseObject);\n const handled = handleResponse(\n spec,\n operation.name,\n status,\n response,\n utils,\n true,\n // statusesCount,\n );\n responses.push(handled);\n outputs.push(...handled.outputs);\n }\n\n const addTypeParser = Object.keys(operation.schemas).length > 1;\n for (const type in operation.schemas ?? {}) {\n let typePrefix = '';\n if (addTypeParser && type !== 'json') {\n typePrefix = `${type} `;\n }\n\n const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;\n\n schemas.push(\n `\"${endpoint}\": {\n schema: ${schemaRef}${addTypeParser ? `.${type}` : ''},\n output:[${outputs.join(',')}],\n toRequest(input: z.infer<typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}>) {\n const endpoint = '${endpoint}';\n return toRequest(endpoint, ${operation.outgoingContentType || 'nobody'}(input, {\n inputHeaders: [${inputHeaders}],\n inputQuery: [${inputQuery}],\n inputBody: [${inputBody}],\n inputParams: [${inputParams}],\n }));\n },\n }`,\n );\n }\n return { responses, schemas };\n}\n\nconst statusCodeToResponseMap: Record<string, string> = {\n '200': 'Ok',\n '201': 'Created',\n '202': 'Accepted',\n '204': 'NoContent',\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '413': 'PayloadTooLarge',\n '410': 'Gone',\n '422': 'UnprocessableEntity',\n '429': 'TooManyRequests',\n '500': 'InternalServerError',\n '501': 'NotImplemented',\n '502': 'BadGateway',\n '503': 'ServiceUnavailable',\n '504': 'GatewayTimeout',\n};\nfunction handleResponse(\n spec: OpenAPIObject,\n operationName: string,\n status: string,\n response: ResponseObject,\n utils: { makeImport: MakeImportFn },\n numbered: boolean,\n) {\n const schemas: Record<string, string> = {};\n const imports: Record<string, Import> = {};\n const endpointImports: Record<string, Import> = {\n ParseError: {\n defaultImport: undefined,\n isTypeOnly: false,\n moduleSpecifier: utils.makeImport(`../http/parser`),\n namedImports: [{ isTypeOnly: false, name: 'ParseError' }],\n namespaceImport: undefined,\n },\n };\n const responses: { name: string; schema: string; description?: string }[] =\n [];\n const outputs: string[] = [];\n const typeScriptDeserialzer = new TypeScriptDeserialzer(\n spec,\n (schemaName, zod) => {\n schemas[schemaName] = zod;\n imports[schemaName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../models/${utils.makeImport(schemaName)}`,\n namedImports: [{ isTypeOnly: true, name: schemaName }],\n namespaceImport: undefined,\n };\n },\n );\n const statusCode = +status;\n const parser: Parser = (response.headers ?? {})['Transfer-Encoding']\n ? 'chunked'\n : 'buffered';\n const statusName = `http.${statusCodeToResponseMap[status] || 'APIResponse'}`;\n const interfaceName = pascalcase(\n operationName + ` output${numbered ? status : ''}`,\n );\n\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n if (status.endsWith('XX')) {\n outputs.push(`http.APIError<${interfaceName}>`);\n } else {\n outputs.push(\n parser !== 'buffered'\n ? `{type: ${statusName}<${interfaceName}>, parser: ${parser}}`\n : `${statusName}<${interfaceName}>`,\n );\n }\n }\n const responseContent = get(response, ['content']);\n const isJson = responseContent && responseContent['application/json'];\n let responseSchema = parser === 'chunked' ? 'ReadableStream' : 'void';\n if (isJson) {\n const schema = responseContent['application/json'].schema!;\n const isObject = !isRef(schema) && schema.type === 'object';\n if (isObject && schema.properties) {\n schema.properties['[http.KIND]'] = {\n 'x-internal': true,\n const: `typeof ${statusName}.kind`,\n type: 'string',\n };\n schema.required ??= [];\n schema.required.push('[http.KIND]');\n }\n responseSchema = typeScriptDeserialzer.handle(schema, true);\n }\n\n responses.push({\n name: interfaceName,\n schema: responseSchema,\n description: response.description,\n });\n const statusGroup = +status.slice(0, 1);\n if (statusCode >= 400 || statusGroup >= 4) {\n endpointImports[statusCodeToResponseMap[status] ?? 'APIError'] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [{ name: statusCodeToResponseMap[status] ?? 'APIError' }],\n };\n\n endpointImports[interfaceName] = {\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n };\n } else if (\n (statusCode >= 200 && statusCode < 300) ||\n statusCode >= 2 ||\n statusGroup <= 3\n ) {\n endpointImports[interfaceName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n namespaceImport: undefined,\n };\n }\n return { schemas, imports, endpointImports, responses, outputs };\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, interfaceContent: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into TypeScript interfaces,\n */\nexport class TypeScriptDeserialzer {\n generatedRefs = new Set<string>();\n #spec: OpenAPIObject;\n #onRef: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n #stringifyKey = (value: string): string => {\n return `'${value}'`;\n };\n\n #isInternal = (schema: SchemaObject | ReferenceObject): boolean => {\n return isRef(schema) ? false : !!schema['x-internal'];\n };\n\n /**\n * Handle objects (properties)\n */\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n // Add question mark for optional properties\n return `${this.#isInternal(propSchema) ? key : this.#stringifyKey(key)}: ${tsType}`;\n });\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n const indexType = this.handle(schema.additionalProperties, true);\n propEntries.push(`[key: string]: ${indexType}`);\n } else if (schema.additionalProperties === true) {\n propEntries.push('[key: string]: any');\n }\n }\n\n return `{ ${propEntries.join('; ')} }`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple)\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => any[]\n return 'any[]';\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n const tupleItems = items.map((sub) => this.handle(sub, true));\n return `[${tupleItems.join(', ')}]`;\n }\n\n // If items is a single schema => standard array\n const itemsType = this.handle(items, true);\n return `${itemsType}[]`;\n }\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to TypeScript\n */\n normal(type: string, schema: SchemaObject, required = false): string {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return appendOptional('boolean', required);\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.array(schema, required);\n case 'null':\n return 'null';\n default:\n console.warn(`Unknown type: ${type}`);\n // Unknown type -> fallback\n return appendOptional('any', required);\n }\n }\n\n ref($ref: string, required: boolean): string {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.generatedRefs.add(schemaName);\n\n this.#onRef?.(\n schemaName,\n this.handle(followRef<SchemaObject>(this.#spec, $ref), required),\n );\n\n return appendOptional(schemaName, required);\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[]): string {\n // For TypeScript we use intersection types for allOf\n const allOfTypes = schemas.map((sub) => this.handle(sub, true));\n return allOfTypes.length > 1 ? `${allOfTypes.join(' & ')}` : allOfTypes[0];\n }\n\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const anyOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n anyOfTypes.length > 1 ? `${anyOfTypes.join(' | ')}` : anyOfTypes[0],\n required,\n );\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const oneOfTypes = schemas.map((sub) => {\n return this.handle(sub, false);\n });\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n\n enum(values: any[], required: boolean): string {\n // For TypeScript enums as union of literals\n const enumValues = values\n .map((val) => (typeof val === 'string' ? `'${val}'` : `${val}`))\n .join(' | ');\n return appendOptional(enumValues, required);\n }\n\n /**\n * Handle string type with formats\n */\n string(schema: SchemaObject, required?: boolean): string {\n let type: string;\n\n if (schema.contentEncoding === 'binary') {\n return appendOptional('Blob', required);\n }\n \n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n case 'date':\n type = 'Date';\n break;\n case 'binary':\n case 'byte':\n type = 'Blob';\n break;\n case 'int64':\n type = 'bigint';\n break;\n default:\n type = 'string';\n }\n\n return appendOptional(type, required);\n }\n\n /**\n * Handle number/integer types with formats\n */\n number(schema: SchemaObject, required?: boolean): string {\n const type = schema.format === 'int64' ? 'bigint' : 'number';\n return appendOptional(type, required);\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.ref(schema.$ref, required);\n }\n\n // Handle allOf (intersection in TypeScript)\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n\n // anyOf (union in TypeScript)\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf, required);\n }\n\n // oneOf (union in TypeScript)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf, required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n if (schema.const) {\n if (schema['x-internal']) {\n return `${schema.const}`;\n }\n return this.enum([schema.const], required);\n }\n\n // Handle types, in TypeScript we can have union types directly\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to any\n if (!types.length) {\n // unless properties are defined then assume object\n if ('properties' in schema) {\n return this.object(schema, required);\n }\n return appendOptional('any', required);\n }\n\n // Handle union types (multiple types)\n if (types.length > 1) {\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const tsType = this.normal(realTypes[0], schema, false);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, false));\n return appendOptional(typeResults.join(' | '), required);\n }\n\n // Single type\n return this.normal(types[0], schema, required);\n }\n}\n\n/**\n * Append \"| undefined\" if not required\n */\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import type {\n ComponentsObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\n\nimport { isRef, removeDuplicates } from '@sdk-it/core';\n\nimport { type Options } from './sdk.ts';\n\nexport function securityToOptions(\n security: SecurityRequirementObject[],\n securitySchemes: ComponentsObject['securitySchemes'],\n staticIn?: string,\n) {\n securitySchemes ??= {};\n const options: Options = {};\n for (const it of security) {\n const [name] = Object.keys(it);\n if (!name) {\n // this means the operation doesn't necessarily require security\n continue;\n }\n const schema = securitySchemes[name];\n if (isRef(schema)) {\n throw new Error(`Ref security schemas are not supported`);\n }\n if (schema.type === 'http') {\n options['authorization'] = {\n in: staticIn ?? 'header',\n schema:\n 'z.string().optional().transform((val) => (val ? `Bearer ${val}` : undefined))',\n optionName: 'token',\n };\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n options[schema.name] = {\n in: staticIn ?? schema.in,\n schema: 'z.string().optional()',\n };\n continue;\n }\n }\n return options;\n}\n\nexport function mergeImports(...imports: Import[]) {\n const merged: Record<string, Import> = {};\n\n for (const it of imports) {\n merged[it.moduleSpecifier] = merged[it.moduleSpecifier] ?? {\n moduleSpecifier: it.moduleSpecifier,\n defaultImport: it.defaultImport,\n namespaceImport: it.namespaceImport,\n namedImports: [],\n };\n for (const named of it.namedImports) {\n if (\n !merged[it.moduleSpecifier].namedImports.some(\n (x) => x.name === named.name,\n )\n ) {\n merged[it.moduleSpecifier].namedImports.push(named);\n }\n }\n }\n\n return Object.values(merged);\n}\n\nexport interface Import {\n isTypeOnly?: boolean;\n moduleSpecifier: string;\n defaultImport?: string | undefined;\n namedImports: NamedImport[];\n namespaceImport?: string | undefined;\n}\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly?: boolean;\n}\n\nexport function importsToString(...imports: Import[]) {\n return imports.map((it) => {\n if (it.defaultImport) {\n return `import ${it.defaultImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namespaceImport) {\n return `import * as ${it.namespaceImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namedImports) {\n return `import {${removeDuplicates(it.namedImports, (it) => it.name)\n .map((n) => `${n.isTypeOnly ? 'type' : ''} ${n.name}`)\n .join(', ')}} from '${it.moduleSpecifier}'`;\n }\n throw new Error(`Invalid import ${JSON.stringify(it)}`);\n });\n}\n\nexport function exclude<T>(list: T[], exclude: T[]): T[] {\n return list.filter((it) => !exclude.includes(it));\n}\n\nexport function useImports(content: string, ...imports: Import[]) {\n const output: string[] = [];\n for (const it of mergeImports(...imports)) {\n const singleImport = it.defaultImport ?? it.namespaceImport;\n if (singleImport && content.includes(singleImport)) {\n output.push(importsToString(it).join('\\n'));\n } else if (it.namedImports.length) {\n for (const namedImport of it.namedImports) {\n if (content.includes(namedImport.name)) {\n output.push(importsToString(it).join('\\n'));\n }\n }\n }\n }\n return output;\n}\n\nexport type MakeImportFn = (moduleSpecifier: string) => string;\n", "type Output<T extends OutputType> = T extends {\n parser: Parser;\n type: Type<unknown>;\n}\n ? InstanceType<T['type']>\n : T extends Type<unknown>\n ? InstanceType<T>\n : never;\n\ntype Unionize<T> = T extends [infer Single extends OutputType]\n ? Output<Single>\n : T extends readonly [...infer Tuple extends OutputType[]]\n ? { [I in keyof Tuple]: Output<Tuple[I]> }[number]\n : never;\n\ntype EndpointOutput<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n SuccessfulResponse\n>;\n\ntype EndpointError<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n ProblematicResponse\n>;\n\nexport type Endpoints = {\n [K in keyof typeof schemas]: {\n input: z.infer<(typeof schemas)[K]['schema']>;\n output: <% if (outputType === 'default') { %>EndpointOutput<K>['data']<% } else { %>EndpointOutput<K><% } %>;\n error: EndpointError<K> | ParseError<(typeof schemas)[K]['schema']>;\n };\n};", "export interface Interceptor {\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createHeadersInterceptor = (\n defaultHeaders: () => Record<string, string | undefined>,\n requestHeaders: HeadersInit,\n):Interceptor => {\n return {\n before({init, url}) {\n // Priority Levels\n // 1. Headers Input\n // 2. Request Headers\n // 3. Default Headers\n const headers = defaultHeaders();\n\n for (const [key, value] of new Headers(requestHeaders)) {\n // Only set the header if it doesn't already exist and has a value\n // even though these headers are passed at operation level\n // still they are lower priority compared to the headers input\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n return {init, url};\n },\n };\n};\n\nexport const createBaseUrlInterceptor = (\n getBaseUrl: () => string,\n): Interceptor => {\n return {\n before({ init, url }) {\n const baseUrl = getBaseUrl();\n if (url.protocol === 'local:') {\n return {\n init,\n url: new URL(url.href.replace('local://', baseUrl))\n };\n }\n return { init, url };\n },\n };\n};\n\nexport const logInterceptor: Interceptor = {\n before({ url, init }) {\n console.log('Request:', { url, init });\n return { url, init };\n },\n after(response) {\n console.log('Response:', response);\n return response;\n },\n};\n\n/**\n * Creates an interceptor that logs detailed information about requests and responses.\n * @param options Configuration options for the logger\n * @returns An interceptor object with before and after handlers\n */\nexport const createDetailedLogInterceptor = (options?: {\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n includeRequestBody?: boolean;\n includeResponseBody?: boolean;\n}) => {\n const logLevel = options?.logLevel || 'info';\n const includeRequestBody = options?.includeRequestBody || false;\n const includeResponseBody = options?.includeResponseBody || false;\n\n return {\n async before(request: Request) {\n const logData = {\n url: request.url,\n method: request.method,\n contentType: request.headers.get('Content-Type'),\n headers: Object.fromEntries([...request.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDE80 Outgoing Request:', logData);\n\n if (includeRequestBody) {\n try {\n // Clone the request to avoid consuming the body stream\n const clonedRequest = request.clone();\n if (clonedRequest.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedRequest.json().catch(() => null);\n console[logLevel]('Request Body:', body);\n } else {\n const body = await clonedRequest.text().catch(() => null);\n console[logLevel]('Request Body:', body);\n }\n } catch (error) {\n console.error('Could not log request body:', error);\n }\n }\n\n return request;\n },\n\n async after(response: Response) {\n const logData = {\n status: response.status,\n statusText: response.statusText,\n url: response.url,\n headers: Object.fromEntries([...response.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDCE5 Incoming Response:', logData);\n\n if (includeResponseBody && response.body) {\n try {\n // Clone the response to avoid consuming the body stream\n const clonedResponse = response.clone();\n if (clonedResponse.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedResponse.json().catch(() => null);\n console[logLevel]('Response Body:', body);\n } else {\n const body = await clonedResponse.text().catch(() => null);\n if (body) {\n console[logLevel]('Response Body:', body.substring(0, 500) + (body.length > 500 ? '...' : ''));\n } else {\n console[logLevel]('No response body');\n }\n }\n } catch (error) {\n console.error('Could not log response body:', error);\n }\n }\n\n return response;\n },\n };\n};\n", "import { parse } from \"fast-content-type-parse\";\n\nasync function handleChunkedResponse(response: Response, contentType: string) {\n\tconst { type } = parse(contentType);\n\n\tswitch (type) {\n\t\tcase \"application/json\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn JSON.parse(buffer);\n\t\t}\n\t\tcase \"text/html\":\n\t\tcase \"text/plain\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn buffer;\n\t\t}\n\t\tdefault:\n\t\t\treturn response.body;\n\t}\n}\n\nexport function chunked(response: Response) {\n\treturn response.body!;\n}\n\nexport async function buffered(response: Response) {\n\tconst contentType = response.headers.get(\"Content-Type\");\n\tif (!contentType) {\n\t\tthrow new Error(\"Content-Type header is missing\");\n\t}\n\n\tif (response.status === 204) {\n\t\treturn null;\n\t}\n\n\tconst { type } = parse(contentType);\n\tswitch (type) {\n\t\tcase \"application/json\":\n\t\t\treturn response.json();\n\t\tcase \"text/plain\":\n\t\t\treturn response.text();\n\t\tcase \"text/html\":\n\t\t\treturn response.text();\n\t\tcase \"text/xml\":\n\t\tcase \"application/xml\":\n\t\t\treturn response.text();\n\t\tcase \"application/x-www-form-urlencoded\": {\n\t\t\tconst text = await response.text();\n\t\t\treturn Object.fromEntries(new URLSearchParams(text));\n\t\t}\n\t\tcase \"multipart/form-data\":\n\t\t\treturn response.formData();\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported content type: ${contentType}`);\n\t}\n}\n", "import { z } from 'zod';\n\nexport class ParseError<T extends z.ZodType<any, any, any>> {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType<any, any, any>>(\n schema: T,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n return [null, new ParseError(error)];\n }\n return [result.data as z.infer<T>, null];\n}\n", "type Init = Omit<RequestInit, 'headers'> & { headers: Headers; };\nexport type RequestConfig = { init: Init; url: URL };\nexport type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart' | 'formdata';\nexport type HeadersInit = [string, string][] | Record<string, string>;\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(\n input: Input,\n props: Props,\n ) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n if (\n this.props.inputBody.length === 1 &&\n this.props.inputBody[0] === '$body'\n ) {\n return JSON.stringify(this.input.$body);\n }\n\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n };\n }\n}\n\nclass NoBodySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n Accept: 'application/json',\n };\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function nobody(input: Input, props: Props) {\n return new NoBodySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): RequestConfig {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n return {\n url: createUrl(pathVariable, input.query),\n init: {\n method: method,\n headers: new Headers(input.headers),\n body: method === 'GET' ? undefined : input.body,\n },\n }\n}\n", "export const KIND = Symbol('APIDATA');\n\nexport class APIResponse<Body = unknown, Status extends number = number> {\n static readonly status: number;\n static readonly kind: symbol = Symbol.for(\"APIResponse\");\n status: Status;\n data: Body;\n\n constructor(status: Status, data: Body) {\n this.status = status;\n this.data = data;\n }\n\n static create<Body = unknown>(status: number, data: Body) {\n return new this(status, data);\n }\n\n}\n\nexport class APIError<Body, Status extends number = number> extends APIResponse<\n Body,\n Status\n> {\n static override create<T>(status: number, data: T) {\n return new this(status, data);\n }\n}\n\n\n// 2xx Success\nexport class Ok<T> extends APIResponse<T, 200> {\n static override readonly kind = Symbol.for(\"Ok\");\n static override readonly status = 200 as const;\n constructor(data: T) {\n super(Ok.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]:typeof Ok['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\n\nexport class Created<T> extends APIResponse<T, 201> {\n static override readonly kind = Symbol.for(\"Created\");\n static override status = 201 as const;\n constructor(data: T) {\n super(Created.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Created['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Accepted<T> extends APIResponse<T, 202> {\n static override readonly kind = Symbol.for(\"Accepted\");\n static override status = 202 as const;\n constructor(data: T) {\n super(Accepted.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Accepted['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NoContent extends APIResponse<never, 204> {\n static override readonly kind = Symbol.for(\"NoContent\");\n static override status = 204 as const;\n constructor() {\n super(NoContent.status, null as never);\n }\n static override create(status: number, data: never): NoContent {\n return new this();\n }\n\n static is<T extends {[KIND]: typeof NoContent['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\n// 4xx Client Errors\nexport class BadRequest<T> extends APIError<T, 400> {\n static override readonly kind = Symbol.for(\"BadRequest\");\n static override status = 400 as const;\n constructor(data: T) {\n super(BadRequest.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof BadRequest['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {\n static override readonly kind = Symbol.for(\"Unauthorized\");\n static override status = 401 as const;\n constructor(data: T) {\n super(Unauthorized.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Unauthorized['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class PaymentRequired<T = { message: string }> extends APIError<T, 402> {\n static override readonly kind = Symbol.for(\"PaymentRequired\");\n static override status = 402 as const;\n constructor(data: T) {\n super(PaymentRequired.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof PaymentRequired['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {\n static override readonly kind = Symbol.for(\"Forbidden\");\n static override status = 403 as const;\n constructor(data: T) {\n super(Forbidden.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Forbidden['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {\n static override readonly kind = Symbol.for(\"NotFound\");\n static override status = 404 as const;\n constructor(data: T) {\n super(NotFound.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof NotFound['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class MethodNotAllowed<T = { message: string }> extends APIError<\n T,\n 405\n> {\n static override readonly kind = Symbol.for(\"MethodNotAllowed\");\n static override status = 405 as const;\n constructor(data: T) {\n super(MethodNotAllowed.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof MethodNotAllowed['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {\n static override readonly kind = Symbol.for(\"NotAcceptable\");\n static override status = 406 as const;\n constructor(data: T) {\n super(NotAcceptable.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof NotAcceptable['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {\n static override readonly kind = Symbol.for(\"Conflict\");\n static override status = 409 as const;\n constructor(data: T) {\n super(Conflict.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Conflict['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Gone<T = { message: string }> extends APIError<T, 410> {\n static override readonly kind = Symbol.for(\"Gone\");\n static override status = 410 as const;\n constructor(data: T) {\n super(Gone.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Gone['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class UnprocessableEntity<\n T = { message: string; errors?: Record<string, string[]> },\n> extends APIError<T, 422> {\n static override readonly kind = Symbol.for(\"UnprocessableEntity\");\n static override status = 422 as const;\n constructor(data: T) {\n super(UnprocessableEntity.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof UnprocessableEntity['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class TooManyRequests<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 429> {\n static override readonly kind = Symbol.for(\"TooManyRequests\");\n static override status = 429 as const;\n constructor(data: T) {\n super(TooManyRequests.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof TooManyRequests['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\n static override readonly kind = Symbol.for(\"PayloadTooLarge\");\n static override status = 413 as const;\n constructor(data: T) {\n super(PayloadTooLarge.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof PayloadTooLarge['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class UnsupportedMediaType<T = { message: string }> extends APIError<\n T,\n 415\n> {\n static override readonly kind = Symbol.for(\"UnsupportedMediaType\");\n static override status = 415 as const;\n constructor(data: T) {\n super(UnsupportedMediaType.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof UnsupportedMediaType['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\n// 5xx Server Errors\nexport class InternalServerError<T = { message: string }> extends APIError<\n T,\n 500\n> {\n static override readonly kind = Symbol.for(\"InternalServerError\");\n static override status = 500 as const;\n constructor(data: T) {\n super(InternalServerError.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof InternalServerError['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {\n static override readonly kind = Symbol.for(\"NotImplemented\");\n static override status = 501 as const;\n constructor(data: T) {\n super(NotImplemented.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof NotImplemented['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {\n static override readonly kind = Symbol.for(\"BadGateway\");\n static override status = 502 as const;\n constructor(data: T) {\n super(BadGateway.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof BadGateway['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class ServiceUnavailable<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 503> {\n static override readonly kind = Symbol.for(\"ServiceUnavailable\");\n static override status = 503 as const;\n constructor(data: T) {\n super(ServiceUnavailable.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof ServiceUnavailable['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\n static override readonly kind = Symbol.for(\"GatewayTimeout\");\n static override status = 504 as const;\n constructor(data: T) {\n super(GatewayTimeout.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof GatewayTimeout['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\nexport type ClientError =\n | BadRequest<{ message: string }>\n | Unauthorized<unknown>\n | PaymentRequired<unknown>\n | Forbidden<unknown>\n | NotFound<unknown>\n | MethodNotAllowed<unknown>\n | NotAcceptable<unknown>\n | Conflict<unknown>\n | Gone<unknown>\n | UnprocessableEntity<unknown>\n | TooManyRequests<unknown>;\n\nexport type ServerError =\n | InternalServerError<unknown>\n | NotImplemented<unknown>\n | BadGateway<unknown>\n | ServiceUnavailable<unknown>\n | GatewayTimeout<unknown>;\n\nexport type ProblematicResponse = ClientError | ServerError;\n\nexport type SuccessfulResponse =\n | Ok<unknown>\n | Created<unknown>\n | Accepted<unknown>\n | NoContent;\n", "export interface Type<T> {\n new (...args: any[]): T;\n}\nexport type Parser = (\n response: Response,\n) => Promise<unknown> | ReadableStream<any>;\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse> };\n\nexport interface RequestSchema {\n schema: z.ZodType;\n toRequest: (input: any) => RequestConfig;\n output: OutputType[];\n}\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\nexport async function dispatch(\n input: unknown,\n route: RequestSchema,\n options: {\n fetch?: z.infer<typeof fetchType>;\n interceptors?: Interceptor[];\n signal?: AbortSignal;\n },\n) {\n const { interceptors = [] } = options;\n const [parsedInput, parseError] = parseInput(route.schema, input);\n if (parseError) {\n <% if(throwError) { %>\n throw parseError;\n <% } else { %>\n return [null as never, parseError as never] as const;\n <% } %>\n }\n\n let config = route.toRequest(parsedInput as never);\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n\n let response = await (options.fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: options.signal,\n },\n );\n\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n return await parse(route, response);\n}\n\nexport async function parse(route: RequestSchema, response: Response) {\n let output: typeof APIResponse | null = null;\n let parser: Parser = buffered;\n for (const outputType of route.output) {\n if ('parser' in outputType) {\n parser = outputType.parser;\n if (isTypeOf(outputType.type, APIResponse)) {\n if (response.status === outputType.type.status) {\n output = outputType.type;\n break;\n }\n }\n } else if (isTypeOf(outputType, APIResponse)) {\n if (response.status === outputType.status) {\n output = outputType;\n break;\n }\n }\n }\n\n if (response.ok) {\n const apiresponse = (output || APIResponse).create(\n response.status,\n await parser(response),\n );\n <% if(throwError) { %>\n return <% if (outputType === 'default') { %>apiresponse.data<% } else { %>apiresponse<% } %>;\n <% } else { %>\n return [<% if (outputType === 'default') { %>apiresponse.data<% } else { %>apiresponse<% } %> , null] as const;\n <% } %>\n }\n<% if(throwError) { %>\n throw (output || APIError).create(\n response.status,\n await parser(response),\n );\n<% } else { %>\n const data = (output || APIError).create(\n response.status,\n await parser(response),\n );\n return [null as never, data as never] as const;\n<% } %>\n}\n\nexport function isTypeOf<T extends Type<APIResponse>>(\n instance: any,\n baseType: T,\n): instance is T {\n if (instance === baseType) {\n return true;\n }\n const prototype = Object.getPrototypeOf(instance);\n if (prototype === null) {\n return false;\n }\n return isTypeOf(prototype, baseType);\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef } from '@sdk-it/core';\nimport { forEachOperation } from '@sdk-it/spec/operation.js';\n\n/**\n * PropEmitter handles converting OpenAPI schemas to Markdown documentation\n * Similar structure to ZodDeserializer but for generating markdown props documentation\n */\nexport class PropEmitter {\n #spec: OpenAPIObject;\n\n constructor(spec: OpenAPIObject) {\n this.#spec = spec;\n }\n\n /**\n * Handle objects (properties)\n */\n #object(schema: SchemaObject): string[] {\n const lines: string[] = [];\n const properties = schema.properties || {};\n\n if (Object.keys(properties).length > 0) {\n lines.push(`**Properties:**`);\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const isRequired = (schema.required ?? []).includes(propName);\n lines.push(...this.#property(propName, propSchema, isRequired));\n }\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n lines.push(`**Additional Properties:**`);\n if (typeof schema.additionalProperties === 'boolean') {\n lines.push(`- Allowed: ${schema.additionalProperties}`);\n } else {\n // Indent the schema documentation for additional properties\n lines.push(\n ...this.handle(schema.additionalProperties).map((l) => ` ${l}`),\n );\n }\n }\n\n return lines;\n }\n\n /**\n * Format a property with its type and description\n */\n #property(\n name: string,\n schema: SchemaObject | ReferenceObject,\n required: boolean,\n ): string[] {\n const requiredMark = required ? ' (required)' : '';\n const propNameLine = `- \\`${name}\\`${requiredMark}:`;\n const lines = [propNameLine];\n\n // Get detailed documentation for the property's schema\n const schemaDocs = this.handle(schema);\n\n // Indent the schema documentation under the property name\n lines.push(...schemaDocs.map((line) => ` ${line}`));\n\n return lines;\n }\n\n /**\n * Handle array schemas\n */\n #array(schema: SchemaObject): string[] {\n const lines: string[] = [];\n lines.push(`**Array items:**`);\n\n if (schema.items) {\n // Get documentation for the items schema\n const itemDocs = this.handle(schema.items);\n // Indent item documentation\n lines.push(...itemDocs.map((line) => ` ${line}`));\n } else {\n lines.push(` **Type:** \\`unknown\\``); // Array of unknown items\n }\n // Add array constraints\n if (schema.minItems !== undefined)\n lines.push(`- Minimum items: ${schema.minItems}`);\n if (schema.maxItems !== undefined)\n lines.push(`- Maximum items: ${schema.maxItems}`);\n if (schema.uniqueItems) lines.push(`- Items must be unique.`);\n\n return lines;\n }\n\n #ref($ref: string): string[] {\n const schemaName = $ref.split('/').pop() || 'object';\n const resolved = followRef<SchemaObject>(this.#spec, $ref);\n // Link to the schema definition (assuming heading anchors are generated elsewhere)\n const lines = [\n `**Type:** [\\`${schemaName}\\`](#${schemaName.toLowerCase()})`,\n ];\n if (resolved.description) {\n lines.push(resolved.description);\n }\n // Avoid deep recursion by default, just link and show description.\n // If more detail is needed, the linked definition should provide it.\n return lines;\n }\n\n #allOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**All of (Intersection):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Constraint ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`)); // Indent sub-schema docs\n });\n return lines;\n }\n\n #anyOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**Any of (Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #oneOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**One of (Exclusive Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #enum(schema: SchemaObject): string[] {\n const lines = [`**Type:** \\`${schema.type || 'unknown'}\\` (enum)`];\n if (schema.description) lines.push(schema.description);\n lines.push('**Allowed values:**');\n lines.push(\n ...(schema.enum || []).map((val) => `- \\`${JSON.stringify(val)}\\``),\n );\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines;\n }\n\n #normal(type: string, schema: SchemaObject, nullable: boolean): string[] {\n const lines: string[] = [];\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const description = schema.description ? [schema.description] : [];\n\n switch (type) {\n case 'string':\n lines.push(\n `**Type:** \\`string\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n if (schema.minLength !== undefined)\n lines.push(`- Minimum length: ${schema.minLength}`);\n if (schema.maxLength !== undefined)\n lines.push(`- Maximum length: ${schema.maxLength}`);\n if (schema.pattern !== undefined)\n lines.push(`- Pattern: \\`${schema.pattern}\\``);\n break;\n case 'number':\n case 'integer':\n lines.push(\n `**Type:** \\`${type}\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n // Add number constraints (OpenAPI 3.1)\n if (schema.minimum !== undefined) {\n // Check if exclusiveMinimum is a number (OAS 3.1)\n const exclusiveMin = typeof schema.exclusiveMinimum === 'number';\n lines.push(\n `- Minimum: ${schema.minimum}${exclusiveMin ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMin) {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n } else if (typeof schema.exclusiveMinimum === 'number') {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n\n if (schema.maximum !== undefined) {\n // Check if exclusiveMaximum is a number (OAS 3.1)\n const exclusiveMax = typeof schema.exclusiveMaximum === 'number';\n lines.push(\n `- Maximum: ${schema.maximum}${exclusiveMax ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMax) {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n } else if (typeof schema.exclusiveMaximum === 'number') {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n if (schema.multipleOf !== undefined)\n lines.push(`- Must be a multiple of: ${schema.multipleOf}`);\n break;\n case 'boolean':\n lines.push(`**Type:** \\`boolean\\`${nullableSuffix}`);\n lines.push(...description);\n break;\n case 'object':\n lines.push(`**Type:** \\`object\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#object(schema));\n break;\n case 'array':\n lines.push(`**Type:** \\`array\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#array(schema));\n break;\n case 'null':\n lines.push(`**Type:** \\`null\\``);\n lines.push(...description);\n break;\n default:\n lines.push(`**Type:** \\`${type}\\`${nullableSuffix}`);\n lines.push(...description);\n }\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines.filter((l) => l); // Filter out empty description lines\n }\n\n /**\n * Handle schemas by resolving references and delegating to appropriate handler\n */\n public handle(schemaOrRef: SchemaObject | ReferenceObject): string[] {\n if (isRef(schemaOrRef)) {\n return this.#ref(schemaOrRef.$ref);\n }\n\n const schema = schemaOrRef;\n\n // Handle composition keywords first\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.#allOf(schema.allOf);\n }\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.#anyOf(schema.anyOf);\n }\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.#oneOf(schema.oneOf);\n }\n\n // Handle enums\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.#enum(schema);\n }\n\n // Determine type(s) and nullability\n let types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n let nullable = false; // Default to false\n\n if (types.includes('null')) {\n nullable = true;\n types = types.filter((t) => t !== 'null');\n }\n\n // Infer type if not explicitly set\n if (types.length === 0) {\n if (schema.properties || schema.additionalProperties) {\n types = ['object'];\n } else if (schema.items) {\n types = ['array'];\n }\n // Add other inferences if needed (e.g., based on format)\n }\n\n // If still no type, treat as unknown or any\n if (types.length === 0) {\n const lines = ['**Type:** `unknown`'];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n // Handle single type (potentially nullable)\n if (types.length === 1) {\n return this.#normal(types[0], schema, nullable);\n }\n\n // Handle union of multiple non-null types (potentially nullable overall)\n const typeString = types.join(' | ');\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const lines = [`**Type:** \\`${typeString}\\`${nullableSuffix}`];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n /**\n * Process a request body and return markdown documentation\n */\n requestBody(requestBody?: RequestBodyObject | ReferenceObject): string[] {\n if (!requestBody) return [];\n\n const resolvedBody = isRef(requestBody)\n ? followRef<RequestBodyObject>(this.#spec, requestBody.$ref)\n : requestBody;\n\n const lines: string[] = [];\n lines.push(`##### Request Body`);\n\n if (resolvedBody.description) {\n lines.push(resolvedBody.description);\n }\n if (resolvedBody.required) {\n lines.push(`*This request body is required.*`);\n }\n\n if (resolvedBody.content) {\n for (const [contentType, mediaType] of Object.entries(\n resolvedBody.content,\n )) {\n lines.push(`**Content Type:** \\`${contentType}\\``);\n\n if (mediaType.schema) {\n // Use the main handle method here\n const schemaDocs = this.handle(mediaType.schema);\n lines.push(...schemaDocs); // Add schema docs directly\n }\n }\n }\n\n return lines;\n }\n}\n\nexport function toReadme(spec: OpenAPIObject) {\n // table of content is the navigation headers in apiref\n const markdown: string[] = [];\n const propEmitter = new PropEmitter(spec);\n\n forEachOperation({ spec }, ({ method, path, name }, operation) => {\n spec.components ??= {};\n spec.components.schemas ??= {};\n const statuses: string[] = [];\n markdown.push(\n `#### ${name || operation.operationId} | ${`_${method.toUpperCase()} ${path}_`}`,\n );\n markdown.push(operation.summary || '');\n\n // Process request body using the refactored emitter\n const requestBodyContent = propEmitter.requestBody(operation.requestBody);\n if (requestBodyContent.length > 1) {\n // Check if more than just the header was added\n markdown.push(requestBodyContent.join('\\n\\n'));\n }\n\n markdown.push(`##### Responses`);\n for (const status in operation.responses) {\n const response = operation.responses[status];\n const resolvedResponse = isRef(response)\n ? followRef(spec, response.$ref)\n : response;\n statuses.push(`**${status}**\\t_${resolvedResponse.description}_`);\n }\n markdown.push(`<small>${statuses.join('\\n\\n')}</small>`);\n });\n return markdown.join('\\n\\n');\n}\n", "import { watch as nodeWatch } from 'node:fs/promises';\nimport { debounceTime, from } from 'rxjs';\n\nexport function watch(path: string) {\n return from(\n nodeWatch(path, {\n persistent: true,\n recursive: true,\n }),\n ).pipe(debounceTime(400));\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,QAAAC,aAAY;AACrB,SAAS,qBAAqB;AAE9B,SAAS,cAAAC,mBAAkB;AAE3B,SAAS,SAAS,cAAAC,mBAAkB;AACpC;AAAA,EAEE;AAAA,EACA;AAAA,OACK;;;ACXP,SAAS,mBAAmB;AAK5B,IAAO,iBAAQ,CAAC,MAAgC,UAAiB;AAC/D,QAAM,iBAAiB,OAAO,QAAQ,KAAK,OAAO,EAAE;AAAA,IAClD,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,IAAI,GAAG,KAAK,KAAK;AAAA,EACtC;AACA,QAAM,iBAAiB,IAAI,eACxB,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,MAAM,OAAO,QAAQ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,EAC/C;AAEA,QAAM,SAAS,aAAa;AAAA,IAC1B;AAAA,IACA,KAAK,cAAc;AAAA,EACrB,CAAC;AACH;;;AgBpPA,SAAS,SAAS,iBAAiB;AACnC,SAAS,cAAc,YAAY;AAE5B,SAAS,MAAM,MAAc;AAClC,SAAO;AAAA,IACL,UAAU,MAAM;AAAA,MACd,YAAY;AAAA,MACZ,WAAW;AAAA,IACb,CAAC;AAAA,EACH,EAAE,KAAK,aAAa,GAAG,CAAC;AAC1B;",
|
|
6
|
-
"names": ["template", "join", "spinalcase", "pascalcase", "
|
|
3
|
+
"sources": ["../../../node_modules/pluralize/pluralize.js", "../src/lib/generate.ts", "../../readme/src/lib/readme.ts", "../../spec/src/lib/operation.ts", "../../spec/src/lib/pagination/pagination.ts", "../../spec/src/lib/pagination/pagination-result.ts", "../../readme/src/lib/prop.emitter.ts", "../../spec/src/lib/operation.ts", "../../spec/src/lib/pagination/pagination.ts", "../../spec/src/lib/pagination/pagination-result.ts", "../src/lib/client.ts", "../src/lib/generator.ts", "../src/lib/emitters/zod.ts", "../src/lib/sdk.ts", "../src/lib/emitters/interface.ts", "../src/lib/utils.ts", "../src/lib/styles/github/endpoints.txt", "../src/lib/http/dispatcher.txt", "../src/lib/http/interceptors.txt", "../src/lib/http/parse-response.txt", "../src/lib/http/parser.txt", "../src/lib/http/request.txt", "../src/lib/http/response.txt", "../src/lib/paginations/cursor-pagination.txt", "../src/lib/paginations/offset-pagination.txt", "../src/lib/paginations/page-pagination.txt", "../src/lib/typescript-snippet.ts", "../src/lib/emitters/snippet.ts"],
|
|
4
|
+
"sourcesContent": ["/* global define */\n\n(function (root, pluralize) {\n /* istanbul ignore else */\n if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {\n // Node.\n module.exports = pluralize();\n } else if (typeof define === 'function' && define.amd) {\n // AMD, registers as an anonymous module.\n define(function () {\n return pluralize();\n });\n } else {\n // Browser global.\n root.pluralize = pluralize();\n }\n})(this, function () {\n // Rule storage - pluralize and singularize need to be run sequentially,\n // while other rules can be optimized using an object for instant lookups.\n var pluralRules = [];\n var singularRules = [];\n var uncountables = {};\n var irregularPlurals = {};\n var irregularSingles = {};\n\n /**\n * Sanitize a pluralization rule to a usable regular expression.\n *\n * @param {(RegExp|string)} rule\n * @return {RegExp}\n */\n function sanitizeRule (rule) {\n if (typeof rule === 'string') {\n return new RegExp('^' + rule + '$', 'i');\n }\n\n return rule;\n }\n\n /**\n * Pass in a word token to produce a function that can replicate the case on\n * another word.\n *\n * @param {string} word\n * @param {string} token\n * @return {Function}\n */\n function restoreCase (word, token) {\n // Tokens are an exact match.\n if (word === token) return token;\n\n // Lower cased words. E.g. \"hello\".\n if (word === word.toLowerCase()) return token.toLowerCase();\n\n // Upper cased words. E.g. \"WHISKY\".\n if (word === word.toUpperCase()) return token.toUpperCase();\n\n // Title cased words. E.g. \"Title\".\n if (word[0] === word[0].toUpperCase()) {\n return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();\n }\n\n // Lower cased words. E.g. \"test\".\n return token.toLowerCase();\n }\n\n /**\n * Interpolate a regexp string.\n *\n * @param {string} str\n * @param {Array} args\n * @return {string}\n */\n function interpolate (str, args) {\n return str.replace(/\\$(\\d{1,2})/g, function (match, index) {\n return args[index] || '';\n });\n }\n\n /**\n * Replace a word using a rule.\n *\n * @param {string} word\n * @param {Array} rule\n * @return {string}\n */\n function replace (word, rule) {\n return word.replace(rule[0], function (match, index) {\n var result = interpolate(rule[1], arguments);\n\n if (match === '') {\n return restoreCase(word[index - 1], result);\n }\n\n return restoreCase(match, result);\n });\n }\n\n /**\n * Sanitize a word by passing in the word and sanitization rules.\n *\n * @param {string} token\n * @param {string} word\n * @param {Array} rules\n * @return {string}\n */\n function sanitizeWord (token, word, rules) {\n // Empty string or doesn't need fixing.\n if (!token.length || uncountables.hasOwnProperty(token)) {\n return word;\n }\n\n var len = rules.length;\n\n // Iterate over the sanitization rules and use the first one to match.\n while (len--) {\n var rule = rules[len];\n\n if (rule[0].test(word)) return replace(word, rule);\n }\n\n return word;\n }\n\n /**\n * Replace a word with the updated word.\n *\n * @param {Object} replaceMap\n * @param {Object} keepMap\n * @param {Array} rules\n * @return {Function}\n */\n function replaceWord (replaceMap, keepMap, rules) {\n return function (word) {\n // Get the correct token and case restoration functions.\n var token = word.toLowerCase();\n\n // Check against the keep object map.\n if (keepMap.hasOwnProperty(token)) {\n return restoreCase(word, token);\n }\n\n // Check against the replacement map for a direct word replacement.\n if (replaceMap.hasOwnProperty(token)) {\n return restoreCase(word, replaceMap[token]);\n }\n\n // Run all the rules against the word.\n return sanitizeWord(token, word, rules);\n };\n }\n\n /**\n * Check if a word is part of the map.\n */\n function checkWord (replaceMap, keepMap, rules, bool) {\n return function (word) {\n var token = word.toLowerCase();\n\n if (keepMap.hasOwnProperty(token)) return true;\n if (replaceMap.hasOwnProperty(token)) return false;\n\n return sanitizeWord(token, token, rules) === token;\n };\n }\n\n /**\n * Pluralize or singularize a word based on the passed in count.\n *\n * @param {string} word The word to pluralize\n * @param {number} count How many of the word exist\n * @param {boolean} inclusive Whether to prefix with the number (e.g. 3 ducks)\n * @return {string}\n */\n function pluralize (word, count, inclusive) {\n var pluralized = count === 1\n ? pluralize.singular(word) : pluralize.plural(word);\n\n return (inclusive ? count + ' ' : '') + pluralized;\n }\n\n /**\n * Pluralize a word.\n *\n * @type {Function}\n */\n pluralize.plural = replaceWord(\n irregularSingles, irregularPlurals, pluralRules\n );\n\n /**\n * Check if a word is plural.\n *\n * @type {Function}\n */\n pluralize.isPlural = checkWord(\n irregularSingles, irregularPlurals, pluralRules\n );\n\n /**\n * Singularize a word.\n *\n * @type {Function}\n */\n pluralize.singular = replaceWord(\n irregularPlurals, irregularSingles, singularRules\n );\n\n /**\n * Check if a word is singular.\n *\n * @type {Function}\n */\n pluralize.isSingular = checkWord(\n irregularPlurals, irregularSingles, singularRules\n );\n\n /**\n * Add a pluralization rule to the collection.\n *\n * @param {(string|RegExp)} rule\n * @param {string} replacement\n */\n pluralize.addPluralRule = function (rule, replacement) {\n pluralRules.push([sanitizeRule(rule), replacement]);\n };\n\n /**\n * Add a singularization rule to the collection.\n *\n * @param {(string|RegExp)} rule\n * @param {string} replacement\n */\n pluralize.addSingularRule = function (rule, replacement) {\n singularRules.push([sanitizeRule(rule), replacement]);\n };\n\n /**\n * Add an uncountable word rule.\n *\n * @param {(string|RegExp)} word\n */\n pluralize.addUncountableRule = function (word) {\n if (typeof word === 'string') {\n uncountables[word.toLowerCase()] = true;\n return;\n }\n\n // Set singular and plural references for the word.\n pluralize.addPluralRule(word, '$0');\n pluralize.addSingularRule(word, '$0');\n };\n\n /**\n * Add an irregular word definition.\n *\n * @param {string} single\n * @param {string} plural\n */\n pluralize.addIrregularRule = function (single, plural) {\n plural = plural.toLowerCase();\n single = single.toLowerCase();\n\n irregularSingles[single] = plural;\n irregularPlurals[plural] = single;\n };\n\n /**\n * Irregular rules.\n */\n [\n // Pronouns.\n ['I', 'we'],\n ['me', 'us'],\n ['he', 'they'],\n ['she', 'they'],\n ['them', 'them'],\n ['myself', 'ourselves'],\n ['yourself', 'yourselves'],\n ['itself', 'themselves'],\n ['herself', 'themselves'],\n ['himself', 'themselves'],\n ['themself', 'themselves'],\n ['is', 'are'],\n ['was', 'were'],\n ['has', 'have'],\n ['this', 'these'],\n ['that', 'those'],\n // Words ending in with a consonant and `o`.\n ['echo', 'echoes'],\n ['dingo', 'dingoes'],\n ['volcano', 'volcanoes'],\n ['tornado', 'tornadoes'],\n ['torpedo', 'torpedoes'],\n // Ends with `us`.\n ['genus', 'genera'],\n ['viscus', 'viscera'],\n // Ends with `ma`.\n ['stigma', 'stigmata'],\n ['stoma', 'stomata'],\n ['dogma', 'dogmata'],\n ['lemma', 'lemmata'],\n ['schema', 'schemata'],\n ['anathema', 'anathemata'],\n // Other irregular rules.\n ['ox', 'oxen'],\n ['axe', 'axes'],\n ['die', 'dice'],\n ['yes', 'yeses'],\n ['foot', 'feet'],\n ['eave', 'eaves'],\n ['goose', 'geese'],\n ['tooth', 'teeth'],\n ['quiz', 'quizzes'],\n ['human', 'humans'],\n ['proof', 'proofs'],\n ['carve', 'carves'],\n ['valve', 'valves'],\n ['looey', 'looies'],\n ['thief', 'thieves'],\n ['groove', 'grooves'],\n ['pickaxe', 'pickaxes'],\n ['passerby', 'passersby']\n ].forEach(function (rule) {\n return pluralize.addIrregularRule(rule[0], rule[1]);\n });\n\n /**\n * Pluralization rules.\n */\n [\n [/s?$/i, 's'],\n [/[^\\u0000-\\u007F]$/i, '$0'],\n [/([^aeiou]ese)$/i, '$1'],\n [/(ax|test)is$/i, '$1es'],\n [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'],\n [/(e[mn]u)s?$/i, '$1s'],\n [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'],\n [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'],\n [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'],\n [/(seraph|cherub)(?:im)?$/i, '$1im'],\n [/(her|at|gr)o$/i, '$1oes'],\n [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'],\n [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'],\n [/sis$/i, 'ses'],\n [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'],\n [/([^aeiouy]|qu)y$/i, '$1ies'],\n [/([^ch][ieo][ln])ey$/i, '$1ies'],\n [/(x|ch|ss|sh|zz)$/i, '$1es'],\n [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'],\n [/\\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'],\n [/(pe)(?:rson|ople)$/i, '$1ople'],\n [/(child)(?:ren)?$/i, '$1ren'],\n [/eaux$/i, '$0'],\n [/m[ae]n$/i, 'men'],\n ['thou', 'you']\n ].forEach(function (rule) {\n return pluralize.addPluralRule(rule[0], rule[1]);\n });\n\n /**\n * Singularization rules.\n */\n [\n [/s$/i, ''],\n [/(ss)$/i, '$1'],\n [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\\w]|^)li)ves$/i, '$1fe'],\n [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'],\n [/ies$/i, 'y'],\n [/\\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'],\n [/\\b(mon|smil)ies$/i, '$1ey'],\n [/\\b((?:tit)?m|l)ice$/i, '$1ouse'],\n [/(seraph|cherub)im$/i, '$1'],\n [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, '$1'],\n [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, '$1sis'],\n [/(movie|twelve|abuse|e[mn]u)s$/i, '$1'],\n [/(test)(?:is|es)$/i, '$1is'],\n [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'],\n [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'],\n [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'],\n [/(alumn|alg|vertebr)ae$/i, '$1a'],\n [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'],\n [/(matr|append)ices$/i, '$1ix'],\n [/(pe)(rson|ople)$/i, '$1rson'],\n [/(child)ren$/i, '$1'],\n [/(eau)x?$/i, '$1'],\n [/men$/i, 'man']\n ].forEach(function (rule) {\n return pluralize.addSingularRule(rule[0], rule[1]);\n });\n\n /**\n * Uncountable rules.\n */\n [\n // Singular words with no plurals.\n 'adulthood',\n 'advice',\n 'agenda',\n 'aid',\n 'aircraft',\n 'alcohol',\n 'ammo',\n 'analytics',\n 'anime',\n 'athletics',\n 'audio',\n 'bison',\n 'blood',\n 'bream',\n 'buffalo',\n 'butter',\n 'carp',\n 'cash',\n 'chassis',\n 'chess',\n 'clothing',\n 'cod',\n 'commerce',\n 'cooperation',\n 'corps',\n 'debris',\n 'diabetes',\n 'digestion',\n 'elk',\n 'energy',\n 'equipment',\n 'excretion',\n 'expertise',\n 'firmware',\n 'flounder',\n 'fun',\n 'gallows',\n 'garbage',\n 'graffiti',\n 'hardware',\n 'headquarters',\n 'health',\n 'herpes',\n 'highjinks',\n 'homework',\n 'housework',\n 'information',\n 'jeans',\n 'justice',\n 'kudos',\n 'labour',\n 'literature',\n 'machinery',\n 'mackerel',\n 'mail',\n 'media',\n 'mews',\n 'moose',\n 'music',\n 'mud',\n 'manga',\n 'news',\n 'only',\n 'personnel',\n 'pike',\n 'plankton',\n 'pliers',\n 'police',\n 'pollution',\n 'premises',\n 'rain',\n 'research',\n 'rice',\n 'salmon',\n 'scissors',\n 'series',\n 'sewage',\n 'shambles',\n 'shrimp',\n 'software',\n 'species',\n 'staff',\n 'swine',\n 'tennis',\n 'traffic',\n 'transportation',\n 'trout',\n 'tuna',\n 'wealth',\n 'welfare',\n 'whiting',\n 'wildebeest',\n 'wildlife',\n 'you',\n /pok[e\u00E9]mon$/i,\n // Regexes.\n /[^aeiou]ese$/i, // \"chinese\", \"japanese\"\n /deer$/i, // \"deer\", \"reindeer\"\n /fish$/i, // \"fish\", \"blowfish\", \"angelfish\"\n /measles$/i,\n /o[iu]s$/i, // \"carnivorous\"\n /pox$/i, // \"chickpox\", \"smallpox\"\n /sheep$/i\n ].forEach(pluralize.addUncountableRule);\n\n return pluralize;\n});\n", "import { template } from 'lodash-es';\nimport { readFile, readdir, unlink, writeFile } from 'node:fs/promises';\nimport { join, relative, sep } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { spinalcase } from 'stringcase';\n\nimport { methods, pascalcase } from '@sdk-it/core';\nimport {\n type WriteContent,\n addLeadingSlash,\n exist,\n getFolderExports,\n readFolder,\n writeFiles,\n} from '@sdk-it/core/file-system.js';\nimport { toReadme } from '@sdk-it/readme';\nimport { augmentSpec } from '@sdk-it/spec/operation.js';\n\nimport backend from './client.ts';\nimport { generateCode } from './generator.ts';\nimport dispatcherTxt from './http/dispatcher.txt';\nimport interceptors from './http/interceptors.txt';\nimport parseResponse from './http/parse-response.txt';\nimport parserTxt from './http/parser.txt';\nimport requestTxt from './http/request.txt';\nimport responseTxt from './http/response.txt';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\nimport cursorPaginationTxt from './paginations/cursor-pagination.txt';\nimport offsetPaginationTxt from './paginations/offset-pagination.txt';\nimport paginationTxt from './paginations/page-pagination.txt';\nimport { generateInputs } from './sdk.ts';\nimport { TypeScriptGenerator } from './typescript-snippet.ts';\nimport { exclude, securityToOptions } from './utils.ts';\n\nconst ALWAYS_AVAILABLE_FILES = [\n /readme\\.md$/i, // match readme.md, case-insensitive\n /^tsconfig.*\\.json$/, // match any tsconfig*.json\n /package\\.json$/, // exact package.json\n /metadata\\.json$/, // exact metadata.json\n];\n\nfunction security(spec: OpenAPIObject) {\n const security = spec.security || [];\n const components = spec.components || {};\n const securitySchemes = components.securitySchemes || {};\n const paths = Object.values(spec.paths ?? {});\n\n const options = securityToOptions(spec, security, securitySchemes);\n\n for (const it of paths) {\n for (const method of methods) {\n const operation = it[method];\n if (!operation) {\n continue;\n }\n Object.assign(\n options,\n securityToOptions(\n spec,\n operation.security || [],\n securitySchemes,\n 'input',\n ),\n );\n }\n }\n return options;\n}\n\nexport async function generate(\n spec: OpenAPIObject,\n settings: TypeScriptGeneratorOptions,\n) {\n spec = 'x-sdk-augmented' in spec ? spec : augmentSpec({ spec });\n const generator = new TypeScriptGenerator(spec, settings);\n const style = Object.assign(\n {},\n {\n errorAsValue: true,\n name: 'github',\n outputType: 'default',\n },\n settings.style ?? {},\n );\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n\n settings.useTsExtension ??= true;\n // FIXME: there should not be default here\n // instead export this function from the cli package with\n // defaults for programmatic usage\n const writtenFiles = new Set<string>();\n settings.writer ??= writeFiles;\n const originalWriter = settings.writer;\n settings.writer = async (dir: string, contents: WriteContent) => {\n await originalWriter(dir, contents);\n for (const file of Object.keys(contents)) {\n if (contents[file] !== null) {\n writtenFiles.add(\n addLeadingSlash(`${relative(settings.output, dir)}/${file}`),\n );\n }\n }\n };\n settings.readFolder ??= async (folder: string) => {\n const files = await readdir(folder, { withFileTypes: true });\n return files.map((file) => ({\n fileName: file.name,\n filePath: join(file.parentPath, file.name),\n isFolder: file.isDirectory(),\n }));\n };\n const makeImport = (moduleSpecifier: string) => {\n return settings.useTsExtension ? `${moduleSpecifier}.ts` : moduleSpecifier;\n };\n const { commonSchemas, endpoints, groups, outputs, commonZod } = generateCode(\n {\n spec,\n style,\n makeImport,\n },\n );\n const options = security(spec);\n const clientName = pascalcase((settings.name || 'client').trim());\n\n const packageName = settings.name\n ? `@${spinalcase(settings.name.trim().toLowerCase())}/sdk`\n : 'sdk';\n\n // FIXME: inputs, outputs should be generated before hand.\n const inputFiles = generateInputs(groups, commonZod, makeImport);\n\n await settings.writer(output, {\n 'outputs/.gitkeep': '',\n 'inputs/.gitkeep': '',\n 'models/.getkeep': '',\n });\n\n await settings.writer(join(output, 'http'), {\n 'parse-response.ts': parseResponse,\n 'response.ts': responseTxt,\n 'parser.ts': parserTxt,\n 'request.ts': requestTxt,\n 'dispatcher.ts': `import z from 'zod';\nimport { type Interceptor } from '${makeImport('../http/interceptors')}';\nimport { type RequestConfig } from '${makeImport('../http/request')}';\nimport { buffered } from '${makeImport('./parse-response')}';\nimport { APIError, APIResponse, type SuccessfulResponse, type ProblematicResponse } from '${makeImport('./response')}';\n\n${template(dispatcherTxt, {})({ throwError: !style.errorAsValue, outputType: style.outputType })}`,\n\n 'interceptors.ts': `\n import type { RequestConfig, HeadersInit } from './${makeImport('request')}';\n ${interceptors}`,\n });\n\n await settings.writer(join(output, 'outputs'), outputs);\n const modelsImports = Object.entries(commonSchemas).map(([name]) => name);\n await settings.writer(output, {\n 'client.ts': backend(\n {\n name: clientName,\n servers: (spec.servers ?? []).map((server) => server.url) || [],\n options: options,\n makeImport,\n },\n style,\n ),\n ...inputFiles,\n ...endpoints,\n ...Object.fromEntries(\n Object.entries(commonSchemas).map(([name, schema]) => [\n `models/${name}.ts`,\n [\n `import { z } from 'zod';`,\n ...exclude(modelsImports, [name]).map(\n (it) => `import type { ${it} } from './${it}.ts';`,\n ),\n `export type ${name} = ${schema};`,\n ].join('\\n'),\n ]),\n ),\n });\n\n await settings.writer(join(output, 'pagination'), {\n 'cursor-pagination.ts': cursorPaginationTxt,\n 'offset-pagination.ts': offsetPaginationTxt,\n 'page-pagination.ts': paginationTxt,\n });\n\n const metadata = await readJson(join(settings.output, 'metadata.json'));\n metadata.content.generatedFiles = Array.from(writtenFiles);\n metadata.content.userFiles ??= [];\n await metadata.write(metadata.content);\n\n if (settings.cleanup !== false && metadata.content.generatedFiles) {\n const generated = metadata.content.generatedFiles as string[];\n const user = metadata.content.userFiles as string[];\n const keep = new Set<string>([...generated, ...user]);\n const actualFiles = await readFolder(settings.output, true);\n const toRemove = actualFiles\n .filter((f) => !keep.has(addLeadingSlash(f)))\n .filter(\n (f) => !ALWAYS_AVAILABLE_FILES.some((pattern) => pattern.test(f)),\n );\n for (const file of toRemove) {\n if (file.endsWith(`${sep}index.ts`)) {\n continue;\n }\n const filePath = join(settings.output, file);\n await unlink(filePath);\n }\n }\n\n const folders = [\n getFolderExports(\n join(output, 'outputs'),\n settings.readFolder,\n settings.useTsExtension,\n ),\n getFolderExports(\n join(output, 'inputs'),\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n (dirent) => dirent.isFolder && ['schemas'].includes(dirent.fileName),\n ),\n getFolderExports(\n join(output, 'api'),\n settings.readFolder,\n settings.useTsExtension,\n ),\n getFolderExports(\n join(output, 'http'),\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n (dirent) => !['response.ts', 'parser.ts'].includes(dirent.fileName),\n ),\n ];\n if (modelsImports.length) {\n folders.push(\n getFolderExports(\n join(output, 'models'),\n settings.readFolder,\n settings.useTsExtension,\n ),\n );\n }\n const [outputIndex, inputsIndex, apiIndex, httpIndex, modelsIndex] =\n await Promise.all(folders);\n\n await settings.writer(join(output, 'pagination'), {\n 'index.ts': await getFolderExports(\n join(output, 'pagination'),\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n ),\n });\n await settings.writer(output, {\n 'api/index.ts': apiIndex,\n 'outputs/index.ts': outputIndex,\n 'inputs/index.ts': inputsIndex || null,\n 'http/index.ts': httpIndex,\n ...(modelsImports.length ? { 'models/index.ts': modelsIndex } : {}),\n });\n await settings.writer(output, {\n 'index.ts': await getFolderExports(\n output,\n settings.readFolder,\n settings.useTsExtension,\n ['ts'],\n (config) => config.fileName.endsWith('pagination'),\n ),\n });\n if (settings.mode === 'full') {\n const configFiles: WriteContent = {\n 'package.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n name: packageName,\n version: '0.0.1',\n type: 'module',\n main: './src/index.ts',\n module: './src/index.ts',\n types: './src/index.ts',\n publishConfig: {\n access: 'public',\n },\n exports: {\n './package.json': './package.json',\n '.': {\n types: './src/index.ts',\n import: './src/index.ts',\n default: './src/index.ts',\n },\n },\n dependencies: {\n 'fast-content-type-parse': '^3.0.0',\n zod: '^3.24.2',\n },\n },\n null,\n 2,\n ),\n },\n 'tsconfig.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n compilerOptions: {\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n target: 'ESNext',\n module: 'ESNext',\n noEmit: true,\n strict: true,\n allowImportingTsExtensions: true,\n verbatimModuleSyntax: true,\n baseUrl: '.',\n moduleResolution: 'bundler',\n },\n include: ['**/*.ts'],\n },\n null,\n 2,\n ),\n },\n };\n if (settings.readme) {\n configFiles['README.md'] = {\n ignoreIfExists: false,\n content: toReadme(spec, {\n generateSnippet: (...args) => generator.snippet(...args),\n }),\n };\n }\n await settings.writer(settings.output, configFiles);\n }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n}\n\nexport async function readJson(path: string) {\n const content = (await exist(path))\n ? JSON.parse(await readFile(path, 'utf-8'))\n : { content: {} };\n return {\n content,\n write: (value: Record<string, any> = content) =>\n writeFile(path, JSON.stringify(value, null, 2), 'utf-8'),\n };\n}\n", "import type { OpenAPIObject } from 'openapi3-ts/oas31';\n\nimport { isEmpty } from '@sdk-it/core';\nimport {\n type OperationEntry,\n type TunedOperationObject,\n forEachOperation,\n} from '@sdk-it/spec/operation.js';\n\nimport { PropEmitter } from './prop.emitter.ts';\n\nexport function toReadme(\n spec: OpenAPIObject,\n generators: {\n generateSnippet: (\n entry: OperationEntry,\n operation: TunedOperationObject,\n ) => string;\n },\n) {\n // table of content is the navigation headers in apiref\n const markdown: string[] = [];\n const propEmitter = new PropEmitter(spec);\n\n forEachOperation({ spec }, (entry, operation) => {\n const { method, path, name } = entry;\n spec.components ??= {};\n spec.components.schemas ??= {};\n markdown.push(\n `#### ${name || operation.operationId} | ${`_${method.toUpperCase()} ${path}_`}`,\n );\n markdown.push(operation.summary || '');\n\n const snippet = generators.generateSnippet(entry, operation);\n markdown.push(`##### Example usage`);\n markdown.push(snippet);\n\n // Process request body using the refactored emitter\n const requestBodyContent = propEmitter.requestBody(operation.requestBody);\n if (requestBodyContent.length > 1) {\n // Check if more than just the header was added\n markdown.push(requestBodyContent.join('\\n\\n'));\n }\n\n markdown.push(`##### Responses`);\n for (const status in operation.responses) {\n const response = operation.responses[status];\n // Wrap each response in its own toggle\n markdown.push(`<details>`);\n markdown.push(\n `<summary><b>${status}</b> <i>${response.description}</i></summary>`,\n );\n if (!isEmpty(response.content)) {\n for (const [contentType, mediaType] of Object.entries(\n response.content,\n )) {\n markdown.push(`\\n**Content Type:** \\`${contentType}\\``);\n if (mediaType.schema) {\n const schemaDocs = propEmitter.handle(mediaType.schema);\n // hide emitter output under the toggle\n markdown.push(...schemaDocs.map((l) => `\\n${l}`));\n }\n }\n }\n markdown.push(`</details>`);\n }\n });\n return markdown.join('\\n\\n');\n}\n", "import type {\n ComponentsObject,\n OpenAPIObject,\n OperationObject,\n ParameterLocation,\n ParameterObject,\n PathsObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport type { Method } from '@sdk-it/core/paths.js';\nimport { followRef, isRef } from '@sdk-it/core/ref.js';\n\nimport {\n type PaginationGuess,\n guessPagination,\n} from './pagination/pagination.js';\n\nexport function augmentSpec(config: GenerateSdkConfig) {\n config.spec.paths ??= {};\n const paths: PathsObject = {};\n for (const [path, pathItem] of Object.entries(config.spec.paths)) {\n const { parameters = [], ...methods } = pathItem;\n\n // Convert Express-style routes (:param) to OpenAPI-style routes ({param})\n const fixedPath = path.replace(/:([^/]+)/g, '{$1}');\n for (const [method, operation] of Object.entries(methods) as [\n Method,\n OperationObject,\n ][]) {\n const formatOperationId = config.operationId ?? defaults.operationId;\n const formatTag = config.tag ?? defaults.tag;\n const operationId = formatOperationId(operation, fixedPath, method);\n const operationTag = formatTag(operation, fixedPath);\n const requestBody = isRef(operation.requestBody)\n ? followRef<RequestBodyObject>(config.spec, operation.requestBody.$ref)\n : operation.requestBody;\n const tunedOperation: TunedOperationObject = {\n ...operation,\n parameters: [...parameters, ...(operation.parameters ?? [])].map(\n (it) =>\n isRef(it) ? followRef<ParameterObject>(config.spec, it.$ref) : it,\n ),\n tags: [operationTag],\n operationId: operationId,\n responses: resolveResponses(config.spec, operation),\n requestBody: requestBody,\n };\n\n tunedOperation['x-pagination'] = toPagination(\n config.spec,\n tunedOperation,\n );\n\n Object.assign(paths, {\n [fixedPath]: {\n ...paths[fixedPath],\n [method]: tunedOperation,\n },\n });\n }\n }\n return { ...config.spec, paths };\n}\n\nexport type OperationPagination = PaginationGuess & {\n items: string;\n};\n\nfunction toPagination(\n spec: OpenAPIObject,\n tunedOperation: TunedOperationObject,\n) {\n if (tunedOperation['x-pagination']) {\n return tunedOperation['x-pagination'];\n }\n const schema = getResponseContentSchema(\n spec,\n tunedOperation.responses['200'],\n 'application/json',\n );\n const pagination = guessPagination(\n tunedOperation,\n tunedOperation.requestBody\n ? getRequestContentSchema(\n spec,\n tunedOperation.requestBody,\n 'application/json',\n )\n : undefined,\n schema,\n );\n if (pagination && pagination.type !== 'none' && schema) {\n // console.dir({\n // [`${method.toUpperCase()} ${fixedPath}`]: {\n // ...pagination,\n // },\n // });\n return pagination;\n }\n return undefined;\n}\n\nfunction getResponseContentSchema(\n spec: OpenAPIObject,\n response: ResponseObject,\n type: string,\n) {\n if (!response) {\n return undefined;\n }\n const content = response.content;\n if (!content) {\n return undefined;\n }\n for (const contentType in content) {\n if (contentType.toLowerCase() === type.toLowerCase()) {\n return isRef(content[contentType].schema)\n ? followRef<SchemaObject>(spec, content[contentType].schema.$ref)\n : content[contentType].schema;\n }\n }\n return undefined;\n}\n\nfunction getRequestContentSchema(\n spec: OpenAPIObject,\n requestBody: RequestBodyObject,\n type: string,\n) {\n const content = requestBody.content;\n if (!content) {\n return undefined;\n }\n for (const contentType in content) {\n if (contentType.toLowerCase() === type.toLowerCase()) {\n return isRef(content[contentType].schema)\n ? followRef<SchemaObject>(spec, content[contentType].schema.$ref)\n : content[contentType].schema;\n }\n }\n return undefined;\n}\n\nexport const defaults: Partial<GenerateSdkConfig> &\n Required<Pick<GenerateSdkConfig, 'operationId' | 'tag'>> = {\n operationId: (operation, path, method) => {\n if (operation.operationId) {\n return camelcase(operation.operationId);\n }\n const metadata = operation['x-oaiMeta'];\n if (metadata && metadata.name) {\n return camelcase(metadata.name);\n }\n return camelcase(\n [method, ...path.replace(/[\\\\/\\\\{\\\\}]/g, ' ').split(' ')]\n .filter(Boolean)\n .join(' ')\n .trim(),\n );\n },\n tag: (operation, path) => {\n return operation.tags?.[0]\n ? sanitizeTag(operation.tags?.[0])\n : determineGenericTag(path, operation);\n },\n};\n\nexport type TunedOperationObject = Omit<\n OperationObject,\n 'operationId' | 'parameters' | 'responses'\n> & {\n operationId: string;\n parameters: ParameterObject[];\n responses: Record<string, ResponseObject>;\n requestBody: RequestBodyObject | undefined;\n};\n\nexport interface OperationEntry {\n name?: string;\n method: string;\n path: string;\n groupName: string;\n tag: string;\n}\nexport type Operation = {\n entry: OperationEntry;\n operation: TunedOperationObject;\n};\n\nfunction resolveResponses(spec: OpenAPIObject, operation: OperationObject) {\n const responses = operation.responses ?? {};\n const resolved: Record<string, ResponseObject> = {};\n for (const status in responses) {\n const response = isRef(responses[status] as ReferenceObject)\n ? followRef<ResponseObject>(spec, responses[status].$ref)\n : (responses[status] as ResponseObject);\n resolved[status] = response;\n }\n return resolved;\n}\n\nexport function forEachOperation<T>(\n config: GenerateSdkConfig,\n callback: (entry: OperationEntry, operation: TunedOperationObject) => T,\n) {\n const result: T[] = [];\n for (const [path, pathItem] of Object.entries(config.spec.paths ?? {})) {\n const { parameters = [], ...methods } = pathItem;\n\n for (const [method, operation] of Object.entries(methods) as [\n string,\n OperationObject,\n ][]) {\n const metadata = operation['x-oaiMeta'] ?? {};\n const operationTag = operation.tags?.[0] as string;\n\n result.push(\n callback(\n {\n name: metadata.name,\n method,\n path: path,\n groupName: operationTag,\n tag: operationTag,\n },\n operation as TunedOperationObject,\n ),\n );\n }\n }\n return result;\n}\n\nexport interface GenerateSdkConfig {\n spec: OpenAPIObject;\n operationId?: (\n operation: OperationObject,\n path: string,\n method: string,\n ) => string;\n tag?: (operation: OperationObject, path: string) => string;\n}\n\n/**\n * Set of reserved TypeScript keywords and common verbs potentially used as tags.\n */\n\nconst reservedKeywords = new Set([\n 'await', // Reserved in async functions\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'enum',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'implements', // Strict mode\n 'import',\n 'in',\n 'instanceof',\n 'interface', // Strict mode\n 'let', // Strict mode\n 'new',\n 'null',\n 'package', // Strict mode\n 'private', // Strict mode\n 'protected', // Strict mode\n 'public', // Strict mode\n 'return',\n 'static', // Strict mode\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield', // Strict mode / Generator functions\n // 'arguments' is not technically a reserved word, but it's a special identifier within functions\n // and assigning to it or declaring it can cause issues or unexpected behavior.\n 'arguments',\n]);\n\n/**\n * Sanitizes a potential tag name (assumed to be already camelCased)\n * to avoid conflicts with reserved keywords or invalid starting characters (numbers).\n * Appends an underscore if the tag matches a reserved keyword.\n * Prepends an underscore if the tag starts with a number.\n * @param camelCasedTag The potential tag name, already camelCased.\n * @returns The sanitized tag name.\n */\nfunction sanitizeTag(camelCasedTag: string): string {\n // Prepend underscore if starts with a number\n if (/^\\d/.test(camelCasedTag)) {\n return `_${camelCasedTag}`;\n }\n // Append underscore if it's a reserved keyword\n return reservedKeywords.has(camelcase(camelCasedTag))\n ? `${camelCasedTag}_`\n : camelCasedTag;\n}\n\n/**\n * Attempts to determine a generic tag for an OpenAPI operation based on path and operationId.\n * Rules and fallbacks are documented within the code.\n * @param pathString The path string.\n * @param operation The OpenAPI Operation Object.\n * @returns A sanitized, camelCased tag name string.\n */\nexport function determineGenericTag(\n pathString: string,\n operation: OperationObject,\n): string {\n const operationId = operation.operationId || '';\n const VERSION_REGEX = /^[vV]\\d+$/;\n const commonVerbs = new Set([\n // Verbs to potentially strip from operationId prefix\n 'get',\n 'list',\n 'create',\n 'update',\n 'delete',\n 'post',\n 'put',\n 'patch',\n 'do',\n 'send',\n 'add',\n 'remove',\n 'set',\n 'find',\n 'search',\n 'check',\n 'make',\n ]);\n\n const segments = pathString.split('/').filter(Boolean);\n\n const potentialCandidates = segments.filter(\n (segment) =>\n segment &&\n !segment.startsWith('{') &&\n !segment.endsWith('}') &&\n !VERSION_REGEX.test(segment),\n );\n\n // --- Heuristic 1: Last non-'@' path segment ---\n for (let i = potentialCandidates.length - 1; i >= 0; i--) {\n const segment = potentialCandidates[i];\n if (!segment.startsWith('@')) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(segment));\n }\n }\n\n const canFallbackToPathSegment = potentialCandidates.length > 0;\n\n // --- Heuristic 2: OperationId parsing ---\n if (operationId) {\n const lowerOpId = operationId.toLowerCase();\n const parts = operationId\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n .replace(/([a-zA-Z])(\\d)/g, '$1_$2')\n .replace(/(\\d)([a-zA-Z])/g, '$1_$2')\n .toLowerCase()\n .split(/[_-\\s]+/);\n\n const validParts = parts.filter(Boolean);\n\n // Quick skip: If opId is just a verb and we can use Heuristic 3, prefer that.\n if (\n commonVerbs.has(lowerOpId) &&\n validParts.length === 1 &&\n canFallbackToPathSegment\n ) {\n // Proceed directly to Heuristic 3\n }\n // Only process if there are valid parts and the quick skip didn't happen\n else if (validParts.length > 0) {\n const firstPart = validParts[0];\n const isFirstPartVerb = commonVerbs.has(firstPart);\n\n // Case 2a: Starts with verb, has following parts\n if (isFirstPartVerb && validParts.length > 1) {\n const verbPrefixLength = firstPart.length;\n let nextPartStartIndex = -1;\n if (operationId.length > verbPrefixLength) {\n // Simplified check for next part start\n const charAfterPrefix = operationId[verbPrefixLength];\n if (charAfterPrefix >= 'A' && charAfterPrefix <= 'Z') {\n nextPartStartIndex = verbPrefixLength;\n } else if (charAfterPrefix >= '0' && charAfterPrefix <= '9') {\n nextPartStartIndex = verbPrefixLength;\n } else if (['_', '-'].includes(charAfterPrefix)) {\n nextPartStartIndex = verbPrefixLength + 1;\n } else {\n const match = operationId\n .substring(verbPrefixLength)\n .match(/[A-Z0-9]/);\n if (match && match.index !== undefined) {\n nextPartStartIndex = verbPrefixLength + match.index;\n }\n if (\n nextPartStartIndex === -1 &&\n operationId.length > verbPrefixLength\n ) {\n nextPartStartIndex = verbPrefixLength; // Default guess\n }\n }\n }\n\n if (\n nextPartStartIndex !== -1 &&\n nextPartStartIndex < operationId.length\n ) {\n const remainingOriginalSubstring =\n operationId.substring(nextPartStartIndex);\n const potentialTag = camelcase(remainingOriginalSubstring);\n if (potentialTag) {\n // Sanitize just before returning\n return sanitizeTag(potentialTag);\n }\n }\n\n // Fallback: join remaining lowercased parts\n const potentialTagJoined = camelcase(validParts.slice(1).join('_'));\n if (potentialTagJoined) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagJoined);\n }\n }\n\n // Case 2b: Doesn't start with verb, or only one part (might be verb)\n const potentialTagFull = camelcase(operationId);\n if (potentialTagFull) {\n const isResultSingleVerb = validParts.length === 1 && isFirstPartVerb;\n\n // Avoid returning only a verb if Heuristic 3 is possible\n if (!(isResultSingleVerb && canFallbackToPathSegment)) {\n if (potentialTagFull.length > 0) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagFull);\n }\n }\n }\n\n // Case 2c: Further fallbacks within OpId if above failed/skipped\n const firstPartCamel = camelcase(firstPart);\n if (firstPartCamel) {\n const isFirstPartCamelVerb = commonVerbs.has(firstPartCamel);\n if (\n !isFirstPartCamelVerb ||\n validParts.length === 1 ||\n !canFallbackToPathSegment\n ) {\n // Sanitize just before returning\n return sanitizeTag(firstPartCamel);\n }\n }\n if (\n isFirstPartVerb &&\n validParts.length > 1 &&\n validParts[1] &&\n canFallbackToPathSegment\n ) {\n const secondPartCamel = camelcase(validParts[1]);\n if (secondPartCamel) {\n // Sanitize just before returning\n return sanitizeTag(secondPartCamel);\n }\n }\n } // End if(validParts.length > 0) after quick skip check\n } // End if(operationId)\n\n // --- Heuristic 3: First path segment (stripping '@') ---\n if (potentialCandidates.length > 0) {\n let firstCandidate = potentialCandidates[0];\n if (firstCandidate.startsWith('@')) {\n firstCandidate = firstCandidate.substring(1);\n }\n if (firstCandidate) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(firstCandidate));\n }\n }\n\n // --- Heuristic 4: Default ---\n console.warn(\n `Could not determine a suitable tag for path: ${pathString}, operationId: ${operationId}. Using 'unknown'.`,\n );\n return 'unknown'; // 'unknown' is safe\n}\n\nexport function parseJsonContentType(contentType: string | null | undefined) {\n if (!contentType) {\n return null;\n }\n\n // 1. Trim whitespace\n let mainType = contentType.trim();\n\n // 2. Remove parameters (anything after the first ';')\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n mainType = mainType.substring(0, semicolonIndex).trim(); // Trim potential space before ';'\n }\n\n // 3. Convert to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n if (mainType.endsWith('/json')) {\n return mainType.split('/')[1];\n } else if (mainType.endsWith('+json')) {\n return mainType.split('+')[1];\n }\n return null;\n}\n\n/**\n * Checks if a given content type string represents Server-Sent Events (SSE).\n * Handles case-insensitivity, parameters (like charset), and leading/trailing whitespace.\n *\n * @param contentType The content type string to check (e.g., from a Content-Type header).\n * @returns True if the content type is 'text/event-stream', false otherwise.\n */\nexport function isSseContentType(\n contentType: string | null | undefined,\n): boolean {\n if (!contentType) {\n return false; // Handle null, undefined, or empty string\n }\n\n // 1. Trim whitespace from the input string\n let mainType = contentType.trim();\n\n // 2. Find the position of the first semicolon (if any) to remove parameters\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n // Extract the part before the semicolon and trim potential space\n mainType = mainType.substring(0, semicolonIndex).trim();\n }\n\n // 3. Convert the main type part to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n // 4. Compare against the standard SSE MIME type\n return mainType === 'text/event-stream';\n}\n\nexport function isStreamingContentType(\n contentType: string | null | undefined,\n): boolean {\n return contentType === 'application/octet-stream';\n}\n\nexport function isSuccessStatusCode(statusCode: number | string): boolean {\n statusCode = Number(statusCode);\n return statusCode >= 200 && statusCode < 300;\n}\n\nexport function patchParameters(\n spec: OpenAPIObject,\n objectSchema: SchemaObject,\n operation: TunedOperationObject,\n) {\n const securitySchemes = spec.components?.securitySchemes ?? {};\n const securityOptions = securityToOptions(\n spec,\n operation.security ?? [],\n securitySchemes,\n );\n\n objectSchema.properties ??= {};\n objectSchema.required ??= [];\n for (const param of operation.parameters) {\n if (param.required) {\n objectSchema.required.push(param.name);\n }\n objectSchema.properties[param.name] = isRef(param.schema)\n ? followRef<SchemaObject>(spec, param.schema.$ref)\n : (param.schema ?? { type: 'string' });\n }\n for (const param of securityOptions) {\n objectSchema.required = (objectSchema.required ?? []).filter(\n (name) => name !== param.name,\n );\n objectSchema.properties[param.name] = isRef(param.schema)\n ? followRef<SchemaObject>(spec, param.schema.$ref)\n : (param.schema ?? { type: 'string' });\n }\n}\n\nexport function securityToOptions(\n spec: OpenAPIObject,\n security: SecurityRequirementObject[],\n securitySchemes: ComponentsObject['securitySchemes'],\n staticIn?: ParameterLocation,\n) {\n securitySchemes ??= {};\n const parameters: ParameterObject[] = [];\n for (const it of security) {\n const [name] = Object.keys(it);\n if (!name) {\n // this means the operation doesn't necessarily require security\n continue;\n }\n const schema = isRef(securitySchemes[name])\n ? followRef(spec, securitySchemes[name].$ref)\n : securitySchemes[name];\n\n if (schema.type === 'http') {\n parameters.push({\n in: staticIn ?? 'header',\n name: 'authorization',\n schema: { type: 'string' },\n });\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n parameters.push({\n in: staticIn ?? (schema.in as ParameterLocation),\n name: schema.name,\n schema: { type: 'string' },\n });\n continue;\n }\n }\n return parameters;\n}\n", "import type { SchemaObject, SchemasObject } from 'openapi3-ts/oas31';\n\nimport { isRef } from '@sdk-it/core/ref.js';\nimport { isEmpty } from '@sdk-it/core/utils.js';\n\nimport type { TunedOperationObject } from '../operation';\nimport { getHasMoreName, getItemsName } from './pagination-result.js';\n\ninterface PaginationResultBase {\n type: 'offset' | 'page' | 'cursor' | 'none';\n}\n\nexport interface OffsetPaginationResult extends PaginationResultBase {\n type: 'offset';\n offsetParamName: string;\n offsetKeyword: string; // The actual part of param name that matched\n limitParamName: string;\n limitKeyword: string; // The actual part of param name that matched\n}\n\nexport interface PagePaginationResult extends PaginationResultBase {\n type: 'page';\n pageNumberParamName: string;\n pageNumberKeyword: string;\n pageSizeParamName: string;\n pageSizeKeyword: string;\n}\n\nexport interface CursorPaginationResult extends PaginationResultBase {\n type: 'cursor';\n cursorParamName: string;\n cursorKeyword: string;\n limitParamName: string;\n limitKeyword: string;\n}\n\nexport interface NoPaginationResult extends PaginationResultBase {\n type: 'none';\n reason: string;\n}\n\nexport type PaginationGuess =\n | ((\n | OffsetPaginationResult\n | PagePaginationResult\n | CursorPaginationResult\n ) & { items: string; hasMore: string })\n | NoPaginationResult;\n\n// --- Keyword Regex Definitions ---\n\nexport const OFFSET_PARAM_REGEXES: RegExp[] = [\n /\\boffset\\b/i,\n /\\bskip\\b/i,\n /\\bstart(?:ing_at|_index)?\\b/i, // e.g., start, starting_at, start_index\n /\\bfrom\\b/i,\n];\n\nexport const GENERIC_LIMIT_PARAM_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\b(?:page_?)?size\\b/i, // e.g., size, page_size, pagesize\n /\\bmax_results\\b/i,\n /\\bnum_results\\b/i,\n /\\bshow\\b/i, // Can sometimes mean limit\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\btake\\b/i,\n];\n\nexport const PAGE_NUMBER_REGEXES: RegExp[] = [\n /^page$/i, // Exact match for \"page\"\n /^p$/i, // Exact match for \"p\" (common shorthand)\n /\\bpage_?(?:number|num|idx|index)\\b/i, // e.g., page_number, pageNumber, page_num, page_idx\n];\n\n// Regexes for parameters indicating page size (when used with page number)\nexport const PAGE_SIZE_REGEXES: RegExp[] = [\n /\\bpage_?size\\b/i, // e.g., page_size, pagesize\n /^size$/i, // Exact \"size\"\n // /\\bsize\\b/i, // Broader \"size\" - can be ambiguous, prefer more specific ones first\n /\\blimit\\b/i, // Limit is often used for page size\n /\\bcount\\b/i, // Count can also be used for page size\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items, numitems\n /\\bresults_?per_?page\\b/i,\n];\n\n// Regexes for parameters indicating a cursor\nexport const CURSOR_REGEXES: RegExp[] = [\n /\\bcursor\\b/i,\n /\\bafter(?:_?cursor)?\\b/i, // e.g., after, after_cursor\n /\\bbefore(?:_?cursor)?\\b/i, // e.g., before, before_cursor\n /\\b(next|prev|previous)_?(?:page_?)?token\\b/i, // e.g., next_page_token, nextPageToken, prev_token\n /\\b(next|prev|previous)_?cursor\\b/i, // e.g., next_cursor, previousCursor\n /\\bcontinuation(?:_?token)?\\b/i, // e.g., continuation, continuation_token\n /\\bpage(?:_?(token|id))?\\b/i, // e.g., after, after_cursor\n\n /\\bstart_?(?:key|cursor|token|after)\\b/i, // e.g., start_key, startCursor, startToken, startAfter\n];\n\n// Regexes for parameters indicating a limit when used with cursors\nexport const CURSOR_LIMIT_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\bsize\\b/i, // General size\n /\\bfirst\\b/i, // Common in Relay-style cursor pagination (forward pagination)\n /\\blast\\b/i, // Common in Relay-style cursor pagination (backward pagination)\n /\\bpage_?size\\b/i, // Sometimes page_size is used with cursors\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items\n /\\bmax_?items\\b/i,\n /\\btake\\b/i,\n];\n\n// --- Helper Function ---\nfunction findParamAndKeyword(\n queryParams: { name: string }[],\n regexes: RegExp[],\n excludeParamName?: string,\n) {\n for (const param of queryParams) {\n if (param.name === excludeParamName) {\n continue;\n }\n for (const regex of regexes) {\n const match = param.name.match(regex);\n if (match) {\n return { param, keyword: match[0] }; // match[0] is the actual matched substring\n }\n }\n }\n return null;\n}\n\nfunction isOffsetPagination(\n operation: TunedOperationObject,\n parameters: { name: string }[],\n): OffsetPaginationResult | null {\n const offsetMatch = findParamAndKeyword(parameters, OFFSET_PARAM_REGEXES);\n if (!offsetMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n parameters,\n GENERIC_LIMIT_PARAM_REGEXES,\n offsetMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'offset',\n offsetParamName: offsetMatch.param.name,\n offsetKeyword: offsetMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\nfunction isPagePagination(\n operation: TunedOperationObject,\n): PagePaginationResult | null {\n const queryParams = operation.parameters\n .filter((p) => p.in === 'query')\n .filter(\n (it) => it.schema && !isRef(it.schema) && it.schema.type === 'integer',\n );\n\n if (queryParams.length < 2) return null;\n\n const pageNoMatch = findParamAndKeyword(queryParams, PAGE_NUMBER_REGEXES);\n if (!pageNoMatch) return null;\n\n const pageSizeMatch = findParamAndKeyword(\n queryParams,\n PAGE_SIZE_REGEXES,\n pageNoMatch.param.name,\n );\n if (!pageSizeMatch) return null;\n\n return {\n type: 'page',\n pageNumberParamName: pageNoMatch.param.name,\n pageNumberKeyword: pageNoMatch.keyword,\n pageSizeParamName: pageSizeMatch.param.name,\n pageSizeKeyword: pageSizeMatch.keyword,\n };\n}\n\nfunction isCursorPagination(\n operation: TunedOperationObject,\n): CursorPaginationResult | null {\n const queryParams = operation.parameters.filter((p) => p.in === 'query');\n if (queryParams.length < 2) return null; // Need at least a cursor and a limit-like param\n\n const cursorMatch = findParamAndKeyword(queryParams, CURSOR_REGEXES);\n if (!cursorMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n queryParams,\n CURSOR_LIMIT_REGEXES,\n cursorMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'cursor',\n cursorParamName: cursorMatch.param.name,\n cursorKeyword: cursorMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\n/**\n * Guesses the pagination strategy of an OpenAPI operation based on its query parameters.\n * It checks for offset, page-based, and cursor-based pagination in that order.\n *\n * @param operation The OpenAPI operation object.\n * @returns A PaginationGuess object indicating the detected type and relevant parameters.\n */\nexport function guessPagination(\n operation: TunedOperationObject,\n body?: SchemaObject,\n response?: SchemaObject,\n): PaginationGuess {\n const bodyParameters =\n body && body.properties\n ? Object.keys(body.properties).map((it) => ({ name: it }))\n : [];\n const parameters = operation.parameters;\n if (isEmpty(operation.parameters) && isEmpty(bodyParameters)) {\n return { type: 'none', reason: 'no parameters' };\n }\n if (!response) {\n return { type: 'none', reason: 'no response' };\n }\n if (!response.properties) {\n return { type: 'none', reason: 'empty response' };\n }\n const properties = response.properties as SchemasObject;\n\n const itemsKey = getItemsName(properties);\n if (!itemsKey) {\n return { type: 'none', reason: 'no items key' };\n }\n const hasMoreKey = getHasMoreName(excludeKey(properties, itemsKey));\n\n if (!hasMoreKey) {\n return { type: 'none', reason: 'no hasMore key' };\n }\n const pagination =\n isOffsetPagination(operation, [...parameters, ...bodyParameters]) ||\n isPagePagination(operation) ||\n isCursorPagination(operation);\n return pagination\n ? { ...pagination, items: itemsKey, hasMore: hasMoreKey }\n : { type: 'none', reason: 'no pagination' };\n}\n\nfunction excludeKey<T extends Record<string, any>>(\n obj: T,\n key: string,\n): Omit<T, typeof key> {\n const { [key]: _, ...rest } = obj;\n return rest;\n}\n", "import type { SchemaObject, SchemasObject } from 'openapi3-ts/oas31';\nimport pluralize from 'pluralize';\n\nconst PRIMARY_TOP_TIER_KEYWORDS: string[] = [\n 'data',\n 'items',\n 'results',\n 'value',\n];\nconst PRIMARY_OTHER_KEYWORDS: string[] = [\n 'records',\n 'content',\n 'list',\n 'payload',\n 'entities',\n 'collection',\n 'users',\n 'products',\n 'orders',\n 'bookings',\n 'articles',\n 'posts',\n 'documents',\n 'events',\n];\nconst SECONDARY_KEYWORDS: string[] = ['entries', 'rows', 'elements'];\n\nconst PLURAL_DEPRIORITIZE_LIST: string[] = [\n 'status',\n 'success',\n 'address',\n 'details',\n 'properties',\n 'params',\n 'headers',\n 'cookies',\n 'series',\n 'links',\n 'meta',\n 'metadata',\n 'statistics',\n 'settings',\n 'options',\n 'permissions',\n 'credentials',\n 'diagnostics',\n 'warnings',\n 'errors',\n 'actions',\n 'attributes',\n 'categories',\n 'features',\n 'includes',\n 'tags',\n];\n\n// For exact matches (normalized: lowercase, no underscores/hyphens)\nconst HAS_MORE_PRIMARY_POSITIVE_EXACT: string[] = [\n 'hasmore',\n 'hasnext',\n 'hasnextpage',\n 'moreitems',\n 'moreitemsavailable',\n 'nextpage',\n 'nextpageexists',\n 'nextpageavailable',\n 'hasadditionalresults',\n 'moreresultsavailable',\n 'canloadmore',\n 'hasadditional',\n 'additionalitems',\n 'fetchmore',\n];\n\nconst HAS_MORE_SECONDARY_POSITIVE_EXACT: string[] = ['more', 'next'];\n\nconst HAS_MORE_PRIMARY_INVERTED_EXACT: string[] = [\n 'islast',\n 'lastpage',\n 'endofresults',\n 'endoflist',\n 'nomoreitems',\n 'nomoredata',\n 'allitemsloaded',\n 'iscomplete',\n 'completed',\n];\n\n// For regex-based sub-phrase matching (tested against original propName, case-insensitive)\n// These regexes look for meaningful phrases, often using word boundaries (\\b)\n// and allowing for optional underscores.\nconst HAS_MORE_POSITIVE_REGEX_PATTERNS: string[] = [\n '\\\\bhas_?more\\\\b',\n '\\\\bhas_?next\\\\b', // e.g., itemsHasNext, items_has_next\n '\\\\bmore_?items\\\\b',\n '\\\\bnext_?page\\\\b', // e.g., userNextPageFlag\n '\\\\badditional\\\\b', // e.g., hasAdditionalData, additional_results_exist\n '\\\\bcontinuation\\\\b', // e.g., continuationAvailable, has_continuation_token\n '\\\\bmore_?results\\\\b',\n '\\\\bpage_?available\\\\b',\n '\\\\bnext(?:_?(page))?\\\\b',\n];\nconst COMPILED_HAS_MORE_POSITIVE_REGEXES: RegExp[] =\n HAS_MORE_POSITIVE_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\nconst HAS_MORE_INVERTED_REGEX_PATTERNS: string[] = [\n '\\\\bis_?last\\\\b', // e.g., pageIsLast\n '\\\\blast_?page\\\\b', // e.g., resultsAreLastPage\n '\\\\bend_?of_?(data|results|list|items|stream)\\\\b',\n '\\\\bno_?more_?(items|data|results)?\\\\b',\n '\\\\ball_?(items_?)?loaded\\\\b',\n '\\\\bis_?complete\\\\b',\n];\nconst COMPILED_HAS_MORE_INVERTED_REGEXES: RegExp[] =\n HAS_MORE_INVERTED_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\n/**\n * Tries to guess the name of the property that holds the main list of items\n * within an object schema using a series of heuristics.\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely property containing the items array,\n * or null if no array properties are found in the schema.\n */\nexport function getItemsName(\n properties: Record<string, SchemaObject>,\n): string | null {\n const arrayPropertyNames: string[] = [];\n for (const propName in properties) {\n if (propName in properties) {\n const propSchema = properties[propName] as SchemaObject;\n if (propSchema && propSchema.type === 'array') {\n arrayPropertyNames.push(propName);\n }\n }\n }\n\n // Heuristic 0: No array properties at all.\n if (arrayPropertyNames.length === 0) {\n return null;\n }\n\n // Heuristic 1: Exactly one array property. This is the strongest signal.\n if (arrayPropertyNames.length === 1) {\n return arrayPropertyNames[0];\n }\n\n // Multiple array properties exist. Apply ranked heuristics:\n let bestCandidate: string | null = null;\n let candidateRank = Infinity; // Lower is better\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of arrayPropertyNames) {\n const lowerPropName = propName.toLowerCase();\n\n // Heuristic 2: Top-tier primary keywords (e.g., \"data\", \"items\")\n if (PRIMARY_TOP_TIER_KEYWORDS.includes(lowerPropName)) {\n updateCandidate(propName, 2);\n continue; // Move to next property, this is a strong match for this prop\n }\n\n // Heuristic 3: Other primary keywords\n if (candidateRank > 3 && PRIMARY_OTHER_KEYWORDS.includes(lowerPropName)) {\n updateCandidate(propName, 3);\n continue;\n }\n\n // Heuristic 4: Secondary keywords\n if (candidateRank > 4 && SECONDARY_KEYWORDS.includes(lowerPropName)) {\n updateCandidate(propName, 4);\n continue;\n }\n\n // Heuristic 5: Pluralized name, not on the deprioritize list\n if (\n candidateRank > 5 &&\n pluralize.isPlural(propName) &&\n !PLURAL_DEPRIORITIZE_LIST.includes(lowerPropName)\n ) {\n updateCandidate(propName, 5);\n continue;\n }\n\n // Heuristic 6: Pluralized name, IS on the deprioritize list (less preferred plural)\n if (\n candidateRank > 6 &&\n pluralize.isPlural(propName) &&\n PLURAL_DEPRIORITIZE_LIST.includes(lowerPropName)\n ) {\n updateCandidate(propName, 6);\n continue;\n }\n }\n\n // If any of the above heuristics found a candidate, return it.\n if (bestCandidate) {\n return bestCandidate;\n }\n\n // Heuristic 7: Fallback - If no keywords or clear plurals,\n // and multiple arrays exist, return the first array property encountered.\n // This ensures we always return a name if arrays are present.\n return arrayPropertyNames[0];\n}\n\nfunction guess(properties: Record<string, SchemaObject>) {\n const booleanPropertyNames: string[] = [];\n for (const propName in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, propName)) {\n const propSchema = properties[propName] as SchemaObject;\n if (\n (propSchema && propSchema.type === 'boolean') ||\n propSchema.type === 'integer'\n ) {\n booleanPropertyNames.push(propName);\n }\n }\n }\n\n if (booleanPropertyNames.length === 0) {\n return null;\n }\n\n if (booleanPropertyNames.length === 1) {\n return booleanPropertyNames[0];\n }\n\n let bestCandidate: string | null = null;\n let candidateRank = Infinity;\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of booleanPropertyNames) {\n const normalizedForExactMatch = propName.toLowerCase().replace(/[-_]/g, '');\n let currentPropRank = Infinity;\n\n // Rank 1: Primary Exact Positive Match\n if (HAS_MORE_PRIMARY_POSITIVE_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 1;\n }\n // Rank 2: Secondary Exact Positive Match\n else if (\n HAS_MORE_SECONDARY_POSITIVE_EXACT.includes(normalizedForExactMatch)\n ) {\n currentPropRank = 2;\n }\n // Rank 3: Positive Regex Match (sub-phrase)\n else {\n let foundPositiveRegex = false;\n for (const regex of COMPILED_HAS_MORE_POSITIVE_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 3;\n foundPositiveRegex = true;\n break;\n }\n }\n\n // Only proceed to inverted matches if no positive match of any kind (Rank 1, 2, or 3) was found\n if (!foundPositiveRegex) {\n // Rank 4: Primary Exact Inverted Match\n if (HAS_MORE_PRIMARY_INVERTED_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 4;\n }\n // Rank 5: Inverted Regex Match (sub-phrase)\n else {\n for (const regex of COMPILED_HAS_MORE_INVERTED_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 5;\n break;\n }\n }\n }\n }\n }\n\n updateCandidate(propName, currentPropRank);\n }\n return bestCandidate;\n}\n\n/**\n * Tries to guess the name of a boolean property that indicates if there are more items\n * to fetch (e.g., for pagination).\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely boolean property indicating \"has more\",\n * or null if no suitable boolean property is found.\n */\nexport function getHasMoreName(properties: SchemasObject): string | null {\n const rootGuess = guess(properties);\n if (rootGuess) {\n return rootGuess;\n }\n for (const propName in properties) {\n const propSchema = properties[propName];\n if (propSchema.type === 'object' && propSchema.properties) {\n const nested = getHasMoreName(propSchema.properties as SchemasObject);\n if (nested) {\n return propName + '.' + nested;\n }\n }\n }\n return null;\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n RequestBodyObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef } from '@sdk-it/core';\n\n/**\n * PropEmitter handles converting OpenAPI schemas to Markdown documentation\n * Similar structure to ZodDeserializer but for generating markdown props documentation\n */\nexport class PropEmitter {\n #spec: OpenAPIObject;\n\n constructor(spec: OpenAPIObject) {\n this.#spec = spec;\n }\n\n /**\n * Handle objects (properties)\n */\n #object(schema: SchemaObject): string[] {\n const lines: string[] = [];\n const properties = schema.properties || {};\n\n if (Object.keys(properties).length > 0) {\n lines.push(`**Properties:**`);\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const isRequired = (schema.required ?? []).includes(propName);\n lines.push(...this.#property(propName, propSchema, isRequired));\n }\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n lines.push(`**Additional Properties:**`);\n if (typeof schema.additionalProperties === 'boolean') {\n lines.push(`- Allowed: ${schema.additionalProperties}`);\n } else {\n // Indent the schema documentation for additional properties\n lines.push(\n ...this.handle(schema.additionalProperties).map((l) => ` ${l}`),\n );\n }\n }\n\n return lines;\n }\n\n /**\n * Format a property with its type and description\n */\n #property(\n name: string,\n schema: SchemaObject | ReferenceObject,\n required: boolean,\n ): string[] {\n // get full docs and extract the type line\n const docs = this.handle(schema);\n const rawType = docs[0]\n .replace('**Type:** ', '')\n .replace(' (nullable)', '|null');\n\n // detect default if present on the schema\n const defaultVal =\n !isRef(schema) && (schema as SchemaObject).default !== undefined\n ? ` default: ${JSON.stringify((schema as SchemaObject).default)}`\n : '';\n\n // build summary line\n const reqMark = required ? ' required' : '';\n const summary = `- \\`${name}\\` ${rawType}${reqMark}${defaultVal}:`;\n\n // assemble final lines (skip the type and any default in details)\n const detailLines = docs\n .slice(1)\n .filter((l) => !l.startsWith('**Default:**'))\n .map((l) => ` ${l}`);\n\n return [summary, ...detailLines];\n }\n\n /**\n * Handle array schemas\n */\n #array(schema: SchemaObject): string[] {\n const lines: string[] = [];\n lines.push(`**Array items:**`);\n\n if (schema.items) {\n // Get documentation for the items schema\n const itemDocs = this.handle(schema.items);\n // Indent item documentation\n lines.push(...itemDocs.map((line) => ` ${line}`));\n } else {\n lines.push(` **Type:** \\`unknown\\``); // Array of unknown items\n }\n // Add array constraints\n if (schema.minItems !== undefined)\n lines.push(`- Minimum items: ${schema.minItems}`);\n if (schema.maxItems !== undefined)\n lines.push(`- Maximum items: ${schema.maxItems}`);\n if (schema.uniqueItems) lines.push(`- Items must be unique.`);\n\n return lines;\n }\n\n #ref($ref: string): string[] {\n const schemaName = $ref.split('/').pop() || 'object';\n const resolved = followRef<SchemaObject>(this.#spec, $ref);\n // Link to the schema definition (assuming heading anchors are generated elsewhere)\n const lines = [\n `**Type:** [\\`${schemaName}\\`](#${schemaName.toLowerCase()})`,\n ];\n if (resolved.description) {\n lines.push(resolved.description);\n }\n // Avoid deep recursion by default, just link and show description.\n // If more detail is needed, the linked definition should provide it.\n return lines;\n }\n\n #allOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**All of (Intersection):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Constraint ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`)); // Indent sub-schema docs\n });\n return lines;\n }\n\n #anyOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**Any of (Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #oneOf(schemas: (SchemaObject | ReferenceObject)[]): string[] {\n const lines = ['**One of (Exclusive Union):**'];\n schemas.forEach((subSchema, index) => {\n lines.push(`- **Option ${index + 1}:**`);\n const subLines = this.handle(subSchema);\n lines.push(...subLines.map((l) => ` ${l}`));\n });\n return lines;\n }\n\n #enum(schema: SchemaObject): string[] {\n const lines = [`**Type:** \\`${schema.type || 'unknown'}\\` (enum)`];\n if (schema.description) lines.push(schema.description);\n lines.push('**Allowed values:**');\n lines.push(\n ...(schema.enum || []).map((val) => `- \\`${JSON.stringify(val)}\\``),\n );\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines;\n }\n\n #normal(type: string, schema: SchemaObject, nullable: boolean): string[] {\n const lines: string[] = [];\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const description = schema.description ? [schema.description] : [];\n\n switch (type) {\n case 'string':\n lines.push(\n `**Type:** \\`string\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n if (schema.minLength !== undefined)\n lines.push(`- Minimum length: ${schema.minLength}`);\n if (schema.maxLength !== undefined)\n lines.push(`- Maximum length: ${schema.maxLength}`);\n if (schema.pattern !== undefined)\n lines.push(`- Pattern: \\`${schema.pattern}\\``);\n break;\n case 'number':\n case 'integer':\n lines.push(\n `**Type:** \\`${type}\\`${schema.format ? ` (format: ${schema.format})` : ''}${nullableSuffix}`,\n );\n lines.push(...description);\n // Add number constraints (OpenAPI 3.1)\n if (schema.minimum !== undefined) {\n // Check if exclusiveMinimum is a number (OAS 3.1)\n const exclusiveMin = typeof schema.exclusiveMinimum === 'number';\n lines.push(\n `- Minimum: ${schema.minimum}${exclusiveMin ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMin) {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n } else if (typeof schema.exclusiveMinimum === 'number') {\n lines.push(\n `- Must be strictly greater than: ${schema.exclusiveMinimum}`,\n );\n }\n\n if (schema.maximum !== undefined) {\n // Check if exclusiveMaximum is a number (OAS 3.1)\n const exclusiveMax = typeof schema.exclusiveMaximum === 'number';\n lines.push(\n `- Maximum: ${schema.maximum}${exclusiveMax ? ' (exclusive)' : ''}`,\n );\n if (exclusiveMax) {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n } else if (typeof schema.exclusiveMaximum === 'number') {\n lines.push(\n `- Must be strictly less than: ${schema.exclusiveMaximum}`,\n );\n }\n if (schema.multipleOf !== undefined)\n lines.push(`- Must be a multiple of: ${schema.multipleOf}`);\n break;\n case 'boolean':\n lines.push(`**Type:** \\`boolean\\`${nullableSuffix}`);\n lines.push(...description);\n break;\n case 'object':\n lines.push(`**Type:** \\`object\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#object(schema));\n break;\n case 'array':\n lines.push(`**Type:** \\`array\\`${nullableSuffix}`);\n lines.push(...description);\n lines.push(...this.#array(schema));\n break;\n case 'null':\n lines.push(`**Type:** \\`null\\``);\n lines.push(...description);\n break;\n default:\n lines.push(`**Type:** \\`${type}\\`${nullableSuffix}`);\n lines.push(...description);\n }\n if (schema.default !== undefined) {\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n }\n return lines.filter((l) => l); // Filter out empty description lines\n }\n\n /**\n * Handle schemas by resolving references and delegating to appropriate handler\n */\n public handle(schemaOrRef: SchemaObject | ReferenceObject): string[] {\n if (isRef(schemaOrRef)) {\n return this.#ref(schemaOrRef.$ref);\n }\n\n const schema = schemaOrRef;\n\n // Handle composition keywords first\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.#allOf(schema.allOf);\n }\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.#anyOf(schema.anyOf);\n }\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.#oneOf(schema.oneOf);\n }\n\n // Handle enums\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.#enum(schema);\n }\n\n // Determine type(s) and nullability\n let types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n let nullable = false; // Default to false\n\n if (types.includes('null')) {\n nullable = true;\n types = types.filter((t) => t !== 'null');\n }\n\n // Infer type if not explicitly set\n if (types.length === 0) {\n if (schema.properties || schema.additionalProperties) {\n types = ['object'];\n } else if (schema.items) {\n types = ['array'];\n }\n // Add other inferences if needed (e.g., based on format)\n }\n\n // If still no type, treat as unknown or any\n if (types.length === 0) {\n const lines = ['**Type:** `unknown`'];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n // Handle single type (potentially nullable)\n if (types.length === 1) {\n return this.#normal(types[0], schema, nullable);\n }\n\n // Handle union of multiple non-null types (potentially nullable overall)\n const typeString = types.join(' | ');\n const nullableSuffix = nullable ? ' (nullable)' : '';\n const lines = [`**Type:** \\`${typeString}\\`${nullableSuffix}`];\n if (schema.description) lines.push(schema.description);\n if (schema.default !== undefined)\n lines.push(`**Default:** \\`${JSON.stringify(schema.default)}\\``);\n return lines;\n }\n\n /**\n * Process a request body and return markdown documentation\n */\n requestBody(requestBody?: RequestBodyObject): string[] {\n if (!requestBody) return [];\n\n const lines: string[] = [];\n lines.push(`##### Request Body`);\n\n if (requestBody.description) {\n lines.push(requestBody.description);\n }\n if (requestBody.required) {\n lines.push(`*This request body is required.*`);\n }\n\n if (requestBody.content) {\n for (const [contentType, mediaType] of Object.entries(\n requestBody.content,\n )) {\n lines.push(`**Content Type:** \\`${contentType}\\``);\n\n if (mediaType.schema) {\n // Use the main handle method here\n const schemaDocs = this.handle(mediaType.schema);\n lines.push(...schemaDocs); // Add schema docs directly\n }\n }\n }\n\n return lines;\n }\n}\n", "import type {\n ComponentsObject,\n OpenAPIObject,\n OperationObject,\n ParameterLocation,\n ParameterObject,\n PathsObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport type { Method } from '@sdk-it/core/paths.js';\nimport { followRef, isRef } from '@sdk-it/core/ref.js';\n\nimport {\n type PaginationGuess,\n guessPagination,\n} from './pagination/pagination.js';\n\nexport function augmentSpec(config: GenerateSdkConfig) {\n config.spec.paths ??= {};\n const paths: PathsObject = {};\n for (const [path, pathItem] of Object.entries(config.spec.paths)) {\n const { parameters = [], ...methods } = pathItem;\n\n // Convert Express-style routes (:param) to OpenAPI-style routes ({param})\n const fixedPath = path.replace(/:([^/]+)/g, '{$1}');\n for (const [method, operation] of Object.entries(methods) as [\n Method,\n OperationObject,\n ][]) {\n const formatOperationId = config.operationId ?? defaults.operationId;\n const formatTag = config.tag ?? defaults.tag;\n const operationId = formatOperationId(operation, fixedPath, method);\n const operationTag = formatTag(operation, fixedPath);\n const requestBody = isRef(operation.requestBody)\n ? followRef<RequestBodyObject>(config.spec, operation.requestBody.$ref)\n : operation.requestBody;\n const tunedOperation: TunedOperationObject = {\n ...operation,\n parameters: [...parameters, ...(operation.parameters ?? [])].map(\n (it) =>\n isRef(it) ? followRef<ParameterObject>(config.spec, it.$ref) : it,\n ),\n tags: [operationTag],\n operationId: operationId,\n responses: resolveResponses(config.spec, operation),\n requestBody: requestBody,\n };\n\n tunedOperation['x-pagination'] = toPagination(\n config.spec,\n tunedOperation,\n );\n\n Object.assign(paths, {\n [fixedPath]: {\n ...paths[fixedPath],\n [method]: tunedOperation,\n },\n });\n }\n }\n return { ...config.spec, paths };\n}\n\nexport type OperationPagination = PaginationGuess & {\n items: string;\n};\n\nfunction toPagination(\n spec: OpenAPIObject,\n tunedOperation: TunedOperationObject,\n) {\n if (tunedOperation['x-pagination']) {\n return tunedOperation['x-pagination'];\n }\n const schema = getResponseContentSchema(\n spec,\n tunedOperation.responses['200'],\n 'application/json',\n );\n const pagination = guessPagination(\n tunedOperation,\n tunedOperation.requestBody\n ? getRequestContentSchema(\n spec,\n tunedOperation.requestBody,\n 'application/json',\n )\n : undefined,\n schema,\n );\n if (pagination && pagination.type !== 'none' && schema) {\n // console.dir({\n // [`${method.toUpperCase()} ${fixedPath}`]: {\n // ...pagination,\n // },\n // });\n return pagination;\n }\n return undefined;\n}\n\nfunction getResponseContentSchema(\n spec: OpenAPIObject,\n response: ResponseObject,\n type: string,\n) {\n if (!response) {\n return undefined;\n }\n const content = response.content;\n if (!content) {\n return undefined;\n }\n for (const contentType in content) {\n if (contentType.toLowerCase() === type.toLowerCase()) {\n return isRef(content[contentType].schema)\n ? followRef<SchemaObject>(spec, content[contentType].schema.$ref)\n : content[contentType].schema;\n }\n }\n return undefined;\n}\n\nfunction getRequestContentSchema(\n spec: OpenAPIObject,\n requestBody: RequestBodyObject,\n type: string,\n) {\n const content = requestBody.content;\n if (!content) {\n return undefined;\n }\n for (const contentType in content) {\n if (contentType.toLowerCase() === type.toLowerCase()) {\n return isRef(content[contentType].schema)\n ? followRef<SchemaObject>(spec, content[contentType].schema.$ref)\n : content[contentType].schema;\n }\n }\n return undefined;\n}\n\nexport const defaults: Partial<GenerateSdkConfig> &\n Required<Pick<GenerateSdkConfig, 'operationId' | 'tag'>> = {\n operationId: (operation, path, method) => {\n if (operation.operationId) {\n return camelcase(operation.operationId);\n }\n const metadata = operation['x-oaiMeta'];\n if (metadata && metadata.name) {\n return camelcase(metadata.name);\n }\n return camelcase(\n [method, ...path.replace(/[\\\\/\\\\{\\\\}]/g, ' ').split(' ')]\n .filter(Boolean)\n .join(' ')\n .trim(),\n );\n },\n tag: (operation, path) => {\n return operation.tags?.[0]\n ? sanitizeTag(operation.tags?.[0])\n : determineGenericTag(path, operation);\n },\n};\n\nexport type TunedOperationObject = Omit<\n OperationObject,\n 'operationId' | 'parameters' | 'responses'\n> & {\n operationId: string;\n parameters: ParameterObject[];\n responses: Record<string, ResponseObject>;\n requestBody: RequestBodyObject | undefined;\n};\n\nexport interface OperationEntry {\n name?: string;\n method: string;\n path: string;\n groupName: string;\n tag: string;\n}\nexport type Operation = {\n entry: OperationEntry;\n operation: TunedOperationObject;\n};\n\nfunction resolveResponses(spec: OpenAPIObject, operation: OperationObject) {\n const responses = operation.responses ?? {};\n const resolved: Record<string, ResponseObject> = {};\n for (const status in responses) {\n const response = isRef(responses[status] as ReferenceObject)\n ? followRef<ResponseObject>(spec, responses[status].$ref)\n : (responses[status] as ResponseObject);\n resolved[status] = response;\n }\n return resolved;\n}\n\nexport function forEachOperation<T>(\n config: GenerateSdkConfig,\n callback: (entry: OperationEntry, operation: TunedOperationObject) => T,\n) {\n const result: T[] = [];\n for (const [path, pathItem] of Object.entries(config.spec.paths ?? {})) {\n const { parameters = [], ...methods } = pathItem;\n\n for (const [method, operation] of Object.entries(methods) as [\n string,\n OperationObject,\n ][]) {\n const metadata = operation['x-oaiMeta'] ?? {};\n const operationTag = operation.tags?.[0] as string;\n\n result.push(\n callback(\n {\n name: metadata.name,\n method,\n path: path,\n groupName: operationTag,\n tag: operationTag,\n },\n operation as TunedOperationObject,\n ),\n );\n }\n }\n return result;\n}\n\nexport interface GenerateSdkConfig {\n spec: OpenAPIObject;\n operationId?: (\n operation: OperationObject,\n path: string,\n method: string,\n ) => string;\n tag?: (operation: OperationObject, path: string) => string;\n}\n\n/**\n * Set of reserved TypeScript keywords and common verbs potentially used as tags.\n */\n\nconst reservedKeywords = new Set([\n 'await', // Reserved in async functions\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'enum',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'implements', // Strict mode\n 'import',\n 'in',\n 'instanceof',\n 'interface', // Strict mode\n 'let', // Strict mode\n 'new',\n 'null',\n 'package', // Strict mode\n 'private', // Strict mode\n 'protected', // Strict mode\n 'public', // Strict mode\n 'return',\n 'static', // Strict mode\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield', // Strict mode / Generator functions\n // 'arguments' is not technically a reserved word, but it's a special identifier within functions\n // and assigning to it or declaring it can cause issues or unexpected behavior.\n 'arguments',\n]);\n\n/**\n * Sanitizes a potential tag name (assumed to be already camelCased)\n * to avoid conflicts with reserved keywords or invalid starting characters (numbers).\n * Appends an underscore if the tag matches a reserved keyword.\n * Prepends an underscore if the tag starts with a number.\n * @param camelCasedTag The potential tag name, already camelCased.\n * @returns The sanitized tag name.\n */\nfunction sanitizeTag(camelCasedTag: string): string {\n // Prepend underscore if starts with a number\n if (/^\\d/.test(camelCasedTag)) {\n return `_${camelCasedTag}`;\n }\n // Append underscore if it's a reserved keyword\n return reservedKeywords.has(camelcase(camelCasedTag))\n ? `${camelCasedTag}_`\n : camelCasedTag;\n}\n\n/**\n * Attempts to determine a generic tag for an OpenAPI operation based on path and operationId.\n * Rules and fallbacks are documented within the code.\n * @param pathString The path string.\n * @param operation The OpenAPI Operation Object.\n * @returns A sanitized, camelCased tag name string.\n */\nexport function determineGenericTag(\n pathString: string,\n operation: OperationObject,\n): string {\n const operationId = operation.operationId || '';\n const VERSION_REGEX = /^[vV]\\d+$/;\n const commonVerbs = new Set([\n // Verbs to potentially strip from operationId prefix\n 'get',\n 'list',\n 'create',\n 'update',\n 'delete',\n 'post',\n 'put',\n 'patch',\n 'do',\n 'send',\n 'add',\n 'remove',\n 'set',\n 'find',\n 'search',\n 'check',\n 'make',\n ]);\n\n const segments = pathString.split('/').filter(Boolean);\n\n const potentialCandidates = segments.filter(\n (segment) =>\n segment &&\n !segment.startsWith('{') &&\n !segment.endsWith('}') &&\n !VERSION_REGEX.test(segment),\n );\n\n // --- Heuristic 1: Last non-'@' path segment ---\n for (let i = potentialCandidates.length - 1; i >= 0; i--) {\n const segment = potentialCandidates[i];\n if (!segment.startsWith('@')) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(segment));\n }\n }\n\n const canFallbackToPathSegment = potentialCandidates.length > 0;\n\n // --- Heuristic 2: OperationId parsing ---\n if (operationId) {\n const lowerOpId = operationId.toLowerCase();\n const parts = operationId\n .replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n .replace(/([a-zA-Z])(\\d)/g, '$1_$2')\n .replace(/(\\d)([a-zA-Z])/g, '$1_$2')\n .toLowerCase()\n .split(/[_-\\s]+/);\n\n const validParts = parts.filter(Boolean);\n\n // Quick skip: If opId is just a verb and we can use Heuristic 3, prefer that.\n if (\n commonVerbs.has(lowerOpId) &&\n validParts.length === 1 &&\n canFallbackToPathSegment\n ) {\n // Proceed directly to Heuristic 3\n }\n // Only process if there are valid parts and the quick skip didn't happen\n else if (validParts.length > 0) {\n const firstPart = validParts[0];\n const isFirstPartVerb = commonVerbs.has(firstPart);\n\n // Case 2a: Starts with verb, has following parts\n if (isFirstPartVerb && validParts.length > 1) {\n const verbPrefixLength = firstPart.length;\n let nextPartStartIndex = -1;\n if (operationId.length > verbPrefixLength) {\n // Simplified check for next part start\n const charAfterPrefix = operationId[verbPrefixLength];\n if (charAfterPrefix >= 'A' && charAfterPrefix <= 'Z') {\n nextPartStartIndex = verbPrefixLength;\n } else if (charAfterPrefix >= '0' && charAfterPrefix <= '9') {\n nextPartStartIndex = verbPrefixLength;\n } else if (['_', '-'].includes(charAfterPrefix)) {\n nextPartStartIndex = verbPrefixLength + 1;\n } else {\n const match = operationId\n .substring(verbPrefixLength)\n .match(/[A-Z0-9]/);\n if (match && match.index !== undefined) {\n nextPartStartIndex = verbPrefixLength + match.index;\n }\n if (\n nextPartStartIndex === -1 &&\n operationId.length > verbPrefixLength\n ) {\n nextPartStartIndex = verbPrefixLength; // Default guess\n }\n }\n }\n\n if (\n nextPartStartIndex !== -1 &&\n nextPartStartIndex < operationId.length\n ) {\n const remainingOriginalSubstring =\n operationId.substring(nextPartStartIndex);\n const potentialTag = camelcase(remainingOriginalSubstring);\n if (potentialTag) {\n // Sanitize just before returning\n return sanitizeTag(potentialTag);\n }\n }\n\n // Fallback: join remaining lowercased parts\n const potentialTagJoined = camelcase(validParts.slice(1).join('_'));\n if (potentialTagJoined) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagJoined);\n }\n }\n\n // Case 2b: Doesn't start with verb, or only one part (might be verb)\n const potentialTagFull = camelcase(operationId);\n if (potentialTagFull) {\n const isResultSingleVerb = validParts.length === 1 && isFirstPartVerb;\n\n // Avoid returning only a verb if Heuristic 3 is possible\n if (!(isResultSingleVerb && canFallbackToPathSegment)) {\n if (potentialTagFull.length > 0) {\n // Sanitize just before returning\n return sanitizeTag(potentialTagFull);\n }\n }\n }\n\n // Case 2c: Further fallbacks within OpId if above failed/skipped\n const firstPartCamel = camelcase(firstPart);\n if (firstPartCamel) {\n const isFirstPartCamelVerb = commonVerbs.has(firstPartCamel);\n if (\n !isFirstPartCamelVerb ||\n validParts.length === 1 ||\n !canFallbackToPathSegment\n ) {\n // Sanitize just before returning\n return sanitizeTag(firstPartCamel);\n }\n }\n if (\n isFirstPartVerb &&\n validParts.length > 1 &&\n validParts[1] &&\n canFallbackToPathSegment\n ) {\n const secondPartCamel = camelcase(validParts[1]);\n if (secondPartCamel) {\n // Sanitize just before returning\n return sanitizeTag(secondPartCamel);\n }\n }\n } // End if(validParts.length > 0) after quick skip check\n } // End if(operationId)\n\n // --- Heuristic 3: First path segment (stripping '@') ---\n if (potentialCandidates.length > 0) {\n let firstCandidate = potentialCandidates[0];\n if (firstCandidate.startsWith('@')) {\n firstCandidate = firstCandidate.substring(1);\n }\n if (firstCandidate) {\n // Sanitize just before returning\n return sanitizeTag(camelcase(firstCandidate));\n }\n }\n\n // --- Heuristic 4: Default ---\n console.warn(\n `Could not determine a suitable tag for path: ${pathString}, operationId: ${operationId}. Using 'unknown'.`,\n );\n return 'unknown'; // 'unknown' is safe\n}\n\nexport function parseJsonContentType(contentType: string | null | undefined) {\n if (!contentType) {\n return null;\n }\n\n // 1. Trim whitespace\n let mainType = contentType.trim();\n\n // 2. Remove parameters (anything after the first ';')\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n mainType = mainType.substring(0, semicolonIndex).trim(); // Trim potential space before ';'\n }\n\n // 3. Convert to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n if (mainType.endsWith('/json')) {\n return mainType.split('/')[1];\n } else if (mainType.endsWith('+json')) {\n return mainType.split('+')[1];\n }\n return null;\n}\n\n/**\n * Checks if a given content type string represents Server-Sent Events (SSE).\n * Handles case-insensitivity, parameters (like charset), and leading/trailing whitespace.\n *\n * @param contentType The content type string to check (e.g., from a Content-Type header).\n * @returns True if the content type is 'text/event-stream', false otherwise.\n */\nexport function isSseContentType(\n contentType: string | null | undefined,\n): boolean {\n if (!contentType) {\n return false; // Handle null, undefined, or empty string\n }\n\n // 1. Trim whitespace from the input string\n let mainType = contentType.trim();\n\n // 2. Find the position of the first semicolon (if any) to remove parameters\n const semicolonIndex = mainType.indexOf(';');\n if (semicolonIndex !== -1) {\n // Extract the part before the semicolon and trim potential space\n mainType = mainType.substring(0, semicolonIndex).trim();\n }\n\n // 3. Convert the main type part to lowercase for case-insensitive comparison\n mainType = mainType.toLowerCase();\n\n // 4. Compare against the standard SSE MIME type\n return mainType === 'text/event-stream';\n}\n\nexport function isStreamingContentType(\n contentType: string | null | undefined,\n): boolean {\n return contentType === 'application/octet-stream';\n}\n\nexport function isSuccessStatusCode(statusCode: number | string): boolean {\n statusCode = Number(statusCode);\n return statusCode >= 200 && statusCode < 300;\n}\n\nexport function patchParameters(\n spec: OpenAPIObject,\n objectSchema: SchemaObject,\n operation: TunedOperationObject,\n) {\n const securitySchemes = spec.components?.securitySchemes ?? {};\n const securityOptions = securityToOptions(\n spec,\n operation.security ?? [],\n securitySchemes,\n );\n\n objectSchema.properties ??= {};\n objectSchema.required ??= [];\n for (const param of operation.parameters) {\n if (param.required) {\n objectSchema.required.push(param.name);\n }\n objectSchema.properties[param.name] = isRef(param.schema)\n ? followRef<SchemaObject>(spec, param.schema.$ref)\n : (param.schema ?? { type: 'string' });\n }\n for (const param of securityOptions) {\n objectSchema.required = (objectSchema.required ?? []).filter(\n (name) => name !== param.name,\n );\n objectSchema.properties[param.name] = isRef(param.schema)\n ? followRef<SchemaObject>(spec, param.schema.$ref)\n : (param.schema ?? { type: 'string' });\n }\n}\n\nexport function securityToOptions(\n spec: OpenAPIObject,\n security: SecurityRequirementObject[],\n securitySchemes: ComponentsObject['securitySchemes'],\n staticIn?: ParameterLocation,\n) {\n securitySchemes ??= {};\n const parameters: ParameterObject[] = [];\n for (const it of security) {\n const [name] = Object.keys(it);\n if (!name) {\n // this means the operation doesn't necessarily require security\n continue;\n }\n const schema = isRef(securitySchemes[name])\n ? followRef(spec, securitySchemes[name].$ref)\n : securitySchemes[name];\n\n if (schema.type === 'http') {\n parameters.push({\n in: staticIn ?? 'header',\n name: 'authorization',\n schema: { type: 'string' },\n });\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n parameters.push({\n in: staticIn ?? (schema.in as ParameterLocation),\n name: schema.name,\n schema: { type: 'string' },\n });\n continue;\n }\n }\n return parameters;\n}\n", "import type { SchemaObject, SchemasObject } from 'openapi3-ts/oas31';\n\nimport { isRef } from '@sdk-it/core/ref.js';\nimport { isEmpty } from '@sdk-it/core/utils.js';\n\nimport type { TunedOperationObject } from '../operation';\nimport { getHasMoreName, getItemsName } from './pagination-result.js';\n\ninterface PaginationResultBase {\n type: 'offset' | 'page' | 'cursor' | 'none';\n}\n\nexport interface OffsetPaginationResult extends PaginationResultBase {\n type: 'offset';\n offsetParamName: string;\n offsetKeyword: string; // The actual part of param name that matched\n limitParamName: string;\n limitKeyword: string; // The actual part of param name that matched\n}\n\nexport interface PagePaginationResult extends PaginationResultBase {\n type: 'page';\n pageNumberParamName: string;\n pageNumberKeyword: string;\n pageSizeParamName: string;\n pageSizeKeyword: string;\n}\n\nexport interface CursorPaginationResult extends PaginationResultBase {\n type: 'cursor';\n cursorParamName: string;\n cursorKeyword: string;\n limitParamName: string;\n limitKeyword: string;\n}\n\nexport interface NoPaginationResult extends PaginationResultBase {\n type: 'none';\n reason: string;\n}\n\nexport type PaginationGuess =\n | ((\n | OffsetPaginationResult\n | PagePaginationResult\n | CursorPaginationResult\n ) & { items: string; hasMore: string })\n | NoPaginationResult;\n\n// --- Keyword Regex Definitions ---\n\nexport const OFFSET_PARAM_REGEXES: RegExp[] = [\n /\\boffset\\b/i,\n /\\bskip\\b/i,\n /\\bstart(?:ing_at|_index)?\\b/i, // e.g., start, starting_at, start_index\n /\\bfrom\\b/i,\n];\n\nexport const GENERIC_LIMIT_PARAM_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\b(?:page_?)?size\\b/i, // e.g., size, page_size, pagesize\n /\\bmax_results\\b/i,\n /\\bnum_results\\b/i,\n /\\bshow\\b/i, // Can sometimes mean limit\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\btake\\b/i,\n];\n\nexport const PAGE_NUMBER_REGEXES: RegExp[] = [\n /^page$/i, // Exact match for \"page\"\n /^p$/i, // Exact match for \"p\" (common shorthand)\n /\\bpage_?(?:number|num|idx|index)\\b/i, // e.g., page_number, pageNumber, page_num, page_idx\n];\n\n// Regexes for parameters indicating page size (when used with page number)\nexport const PAGE_SIZE_REGEXES: RegExp[] = [\n /\\bpage_?size\\b/i, // e.g., page_size, pagesize\n /^size$/i, // Exact \"size\"\n // /\\bsize\\b/i, // Broader \"size\" - can be ambiguous, prefer more specific ones first\n /\\blimit\\b/i, // Limit is often used for page size\n /\\bcount\\b/i, // Count can also be used for page size\n /\\bper_?page\\b/i, // e.g., per_page, perpage\n /\\bper-page\\b/i,\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items, numitems\n /\\bresults_?per_?page\\b/i,\n];\n\n// Regexes for parameters indicating a cursor\nexport const CURSOR_REGEXES: RegExp[] = [\n /\\bcursor\\b/i,\n /\\bafter(?:_?cursor)?\\b/i, // e.g., after, after_cursor\n /\\bbefore(?:_?cursor)?\\b/i, // e.g., before, before_cursor\n /\\b(next|prev|previous)_?(?:page_?)?token\\b/i, // e.g., next_page_token, nextPageToken, prev_token\n /\\b(next|prev|previous)_?cursor\\b/i, // e.g., next_cursor, previousCursor\n /\\bcontinuation(?:_?token)?\\b/i, // e.g., continuation, continuation_token\n /\\bpage(?:_?(token|id))?\\b/i, // e.g., after, after_cursor\n\n /\\bstart_?(?:key|cursor|token|after)\\b/i, // e.g., start_key, startCursor, startToken, startAfter\n];\n\n// Regexes for parameters indicating a limit when used with cursors\nexport const CURSOR_LIMIT_REGEXES: RegExp[] = [\n /\\blimit\\b/i,\n /\\bcount\\b/i,\n /\\bsize\\b/i, // General size\n /\\bfirst\\b/i, // Common in Relay-style cursor pagination (forward pagination)\n /\\blast\\b/i, // Common in Relay-style cursor pagination (backward pagination)\n /\\bpage_?size\\b/i, // Sometimes page_size is used with cursors\n /\\bnum_?(?:items|records|results)\\b/i, // e.g., num_items\n /\\bmax_?items\\b/i,\n /\\btake\\b/i,\n];\n\n// --- Helper Function ---\nfunction findParamAndKeyword(\n queryParams: { name: string }[],\n regexes: RegExp[],\n excludeParamName?: string,\n) {\n for (const param of queryParams) {\n if (param.name === excludeParamName) {\n continue;\n }\n for (const regex of regexes) {\n const match = param.name.match(regex);\n if (match) {\n return { param, keyword: match[0] }; // match[0] is the actual matched substring\n }\n }\n }\n return null;\n}\n\nfunction isOffsetPagination(\n operation: TunedOperationObject,\n parameters: { name: string }[],\n): OffsetPaginationResult | null {\n const offsetMatch = findParamAndKeyword(parameters, OFFSET_PARAM_REGEXES);\n if (!offsetMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n parameters,\n GENERIC_LIMIT_PARAM_REGEXES,\n offsetMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'offset',\n offsetParamName: offsetMatch.param.name,\n offsetKeyword: offsetMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\nfunction isPagePagination(\n operation: TunedOperationObject,\n): PagePaginationResult | null {\n const queryParams = operation.parameters\n .filter((p) => p.in === 'query')\n .filter(\n (it) => it.schema && !isRef(it.schema) && it.schema.type === 'integer',\n );\n\n if (queryParams.length < 2) return null;\n\n const pageNoMatch = findParamAndKeyword(queryParams, PAGE_NUMBER_REGEXES);\n if (!pageNoMatch) return null;\n\n const pageSizeMatch = findParamAndKeyword(\n queryParams,\n PAGE_SIZE_REGEXES,\n pageNoMatch.param.name,\n );\n if (!pageSizeMatch) return null;\n\n return {\n type: 'page',\n pageNumberParamName: pageNoMatch.param.name,\n pageNumberKeyword: pageNoMatch.keyword,\n pageSizeParamName: pageSizeMatch.param.name,\n pageSizeKeyword: pageSizeMatch.keyword,\n };\n}\n\nfunction isCursorPagination(\n operation: TunedOperationObject,\n): CursorPaginationResult | null {\n const queryParams = operation.parameters.filter((p) => p.in === 'query');\n if (queryParams.length < 2) return null; // Need at least a cursor and a limit-like param\n\n const cursorMatch = findParamAndKeyword(queryParams, CURSOR_REGEXES);\n if (!cursorMatch) return null;\n\n const limitMatch = findParamAndKeyword(\n queryParams,\n CURSOR_LIMIT_REGEXES,\n cursorMatch.param.name,\n );\n if (!limitMatch) return null;\n\n return {\n type: 'cursor',\n cursorParamName: cursorMatch.param.name,\n cursorKeyword: cursorMatch.keyword,\n limitParamName: limitMatch.param.name,\n limitKeyword: limitMatch.keyword,\n };\n}\n\n/**\n * Guesses the pagination strategy of an OpenAPI operation based on its query parameters.\n * It checks for offset, page-based, and cursor-based pagination in that order.\n *\n * @param operation The OpenAPI operation object.\n * @returns A PaginationGuess object indicating the detected type and relevant parameters.\n */\nexport function guessPagination(\n operation: TunedOperationObject,\n body?: SchemaObject,\n response?: SchemaObject,\n): PaginationGuess {\n const bodyParameters =\n body && body.properties\n ? Object.keys(body.properties).map((it) => ({ name: it }))\n : [];\n const parameters = operation.parameters;\n if (isEmpty(operation.parameters) && isEmpty(bodyParameters)) {\n return { type: 'none', reason: 'no parameters' };\n }\n if (!response) {\n return { type: 'none', reason: 'no response' };\n }\n if (!response.properties) {\n return { type: 'none', reason: 'empty response' };\n }\n const properties = response.properties as SchemasObject;\n\n const itemsKey = getItemsName(properties);\n if (!itemsKey) {\n return { type: 'none', reason: 'no items key' };\n }\n const hasMoreKey = getHasMoreName(excludeKey(properties, itemsKey));\n\n if (!hasMoreKey) {\n return { type: 'none', reason: 'no hasMore key' };\n }\n const pagination =\n isOffsetPagination(operation, [...parameters, ...bodyParameters]) ||\n isPagePagination(operation) ||\n isCursorPagination(operation);\n return pagination\n ? { ...pagination, items: itemsKey, hasMore: hasMoreKey }\n : { type: 'none', reason: 'no pagination' };\n}\n\nfunction excludeKey<T extends Record<string, any>>(\n obj: T,\n key: string,\n): Omit<T, typeof key> {\n const { [key]: _, ...rest } = obj;\n return rest;\n}\n", "import type { SchemaObject, SchemasObject } from 'openapi3-ts/oas31';\nimport pluralize from 'pluralize';\n\nconst PRIMARY_TOP_TIER_KEYWORDS: string[] = [\n 'data',\n 'items',\n 'results',\n 'value',\n];\nconst PRIMARY_OTHER_KEYWORDS: string[] = [\n 'records',\n 'content',\n 'list',\n 'payload',\n 'entities',\n 'collection',\n 'users',\n 'products',\n 'orders',\n 'bookings',\n 'articles',\n 'posts',\n 'documents',\n 'events',\n];\nconst SECONDARY_KEYWORDS: string[] = ['entries', 'rows', 'elements'];\n\nconst PLURAL_DEPRIORITIZE_LIST: string[] = [\n 'status',\n 'success',\n 'address',\n 'details',\n 'properties',\n 'params',\n 'headers',\n 'cookies',\n 'series',\n 'links',\n 'meta',\n 'metadata',\n 'statistics',\n 'settings',\n 'options',\n 'permissions',\n 'credentials',\n 'diagnostics',\n 'warnings',\n 'errors',\n 'actions',\n 'attributes',\n 'categories',\n 'features',\n 'includes',\n 'tags',\n];\n\n// For exact matches (normalized: lowercase, no underscores/hyphens)\nconst HAS_MORE_PRIMARY_POSITIVE_EXACT: string[] = [\n 'hasmore',\n 'hasnext',\n 'hasnextpage',\n 'moreitems',\n 'moreitemsavailable',\n 'nextpage',\n 'nextpageexists',\n 'nextpageavailable',\n 'hasadditionalresults',\n 'moreresultsavailable',\n 'canloadmore',\n 'hasadditional',\n 'additionalitems',\n 'fetchmore',\n];\n\nconst HAS_MORE_SECONDARY_POSITIVE_EXACT: string[] = ['more', 'next'];\n\nconst HAS_MORE_PRIMARY_INVERTED_EXACT: string[] = [\n 'islast',\n 'lastpage',\n 'endofresults',\n 'endoflist',\n 'nomoreitems',\n 'nomoredata',\n 'allitemsloaded',\n 'iscomplete',\n 'completed',\n];\n\n// For regex-based sub-phrase matching (tested against original propName, case-insensitive)\n// These regexes look for meaningful phrases, often using word boundaries (\\b)\n// and allowing for optional underscores.\nconst HAS_MORE_POSITIVE_REGEX_PATTERNS: string[] = [\n '\\\\bhas_?more\\\\b',\n '\\\\bhas_?next\\\\b', // e.g., itemsHasNext, items_has_next\n '\\\\bmore_?items\\\\b',\n '\\\\bnext_?page\\\\b', // e.g., userNextPageFlag\n '\\\\badditional\\\\b', // e.g., hasAdditionalData, additional_results_exist\n '\\\\bcontinuation\\\\b', // e.g., continuationAvailable, has_continuation_token\n '\\\\bmore_?results\\\\b',\n '\\\\bpage_?available\\\\b',\n '\\\\bnext(?:_?(page))?\\\\b',\n];\nconst COMPILED_HAS_MORE_POSITIVE_REGEXES: RegExp[] =\n HAS_MORE_POSITIVE_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\nconst HAS_MORE_INVERTED_REGEX_PATTERNS: string[] = [\n '\\\\bis_?last\\\\b', // e.g., pageIsLast\n '\\\\blast_?page\\\\b', // e.g., resultsAreLastPage\n '\\\\bend_?of_?(data|results|list|items|stream)\\\\b',\n '\\\\bno_?more_?(items|data|results)?\\\\b',\n '\\\\ball_?(items_?)?loaded\\\\b',\n '\\\\bis_?complete\\\\b',\n];\nconst COMPILED_HAS_MORE_INVERTED_REGEXES: RegExp[] =\n HAS_MORE_INVERTED_REGEX_PATTERNS.map((p) => new RegExp(p, 'i'));\n\n/**\n * Tries to guess the name of the property that holds the main list of items\n * within an object schema using a series of heuristics.\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely property containing the items array,\n * or null if no array properties are found in the schema.\n */\nexport function getItemsName(\n properties: Record<string, SchemaObject>,\n): string | null {\n const arrayPropertyNames: string[] = [];\n for (const propName in properties) {\n if (propName in properties) {\n const propSchema = properties[propName] as SchemaObject;\n if (propSchema && propSchema.type === 'array') {\n arrayPropertyNames.push(propName);\n }\n }\n }\n\n // Heuristic 0: No array properties at all.\n if (arrayPropertyNames.length === 0) {\n return null;\n }\n\n // Heuristic 1: Exactly one array property. This is the strongest signal.\n if (arrayPropertyNames.length === 1) {\n return arrayPropertyNames[0];\n }\n\n // Multiple array properties exist. Apply ranked heuristics:\n let bestCandidate: string | null = null;\n let candidateRank = Infinity; // Lower is better\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of arrayPropertyNames) {\n const lowerPropName = propName.toLowerCase();\n\n // Heuristic 2: Top-tier primary keywords (e.g., \"data\", \"items\")\n if (PRIMARY_TOP_TIER_KEYWORDS.includes(lowerPropName)) {\n updateCandidate(propName, 2);\n continue; // Move to next property, this is a strong match for this prop\n }\n\n // Heuristic 3: Other primary keywords\n if (candidateRank > 3 && PRIMARY_OTHER_KEYWORDS.includes(lowerPropName)) {\n updateCandidate(propName, 3);\n continue;\n }\n\n // Heuristic 4: Secondary keywords\n if (candidateRank > 4 && SECONDARY_KEYWORDS.includes(lowerPropName)) {\n updateCandidate(propName, 4);\n continue;\n }\n\n // Heuristic 5: Pluralized name, not on the deprioritize list\n if (\n candidateRank > 5 &&\n pluralize.isPlural(propName) &&\n !PLURAL_DEPRIORITIZE_LIST.includes(lowerPropName)\n ) {\n updateCandidate(propName, 5);\n continue;\n }\n\n // Heuristic 6: Pluralized name, IS on the deprioritize list (less preferred plural)\n if (\n candidateRank > 6 &&\n pluralize.isPlural(propName) &&\n PLURAL_DEPRIORITIZE_LIST.includes(lowerPropName)\n ) {\n updateCandidate(propName, 6);\n continue;\n }\n }\n\n // If any of the above heuristics found a candidate, return it.\n if (bestCandidate) {\n return bestCandidate;\n }\n\n // Heuristic 7: Fallback - If no keywords or clear plurals,\n // and multiple arrays exist, return the first array property encountered.\n // This ensures we always return a name if arrays are present.\n return arrayPropertyNames[0];\n}\n\nfunction guess(properties: Record<string, SchemaObject>) {\n const booleanPropertyNames: string[] = [];\n for (const propName in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, propName)) {\n const propSchema = properties[propName] as SchemaObject;\n if (\n (propSchema && propSchema.type === 'boolean') ||\n propSchema.type === 'integer'\n ) {\n booleanPropertyNames.push(propName);\n }\n }\n }\n\n if (booleanPropertyNames.length === 0) {\n return null;\n }\n\n if (booleanPropertyNames.length === 1) {\n return booleanPropertyNames[0];\n }\n\n let bestCandidate: string | null = null;\n let candidateRank = Infinity;\n\n const updateCandidate = (propName: string, rank: number) => {\n if (rank < candidateRank) {\n bestCandidate = propName;\n candidateRank = rank;\n }\n };\n\n for (const propName of booleanPropertyNames) {\n const normalizedForExactMatch = propName.toLowerCase().replace(/[-_]/g, '');\n let currentPropRank = Infinity;\n\n // Rank 1: Primary Exact Positive Match\n if (HAS_MORE_PRIMARY_POSITIVE_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 1;\n }\n // Rank 2: Secondary Exact Positive Match\n else if (\n HAS_MORE_SECONDARY_POSITIVE_EXACT.includes(normalizedForExactMatch)\n ) {\n currentPropRank = 2;\n }\n // Rank 3: Positive Regex Match (sub-phrase)\n else {\n let foundPositiveRegex = false;\n for (const regex of COMPILED_HAS_MORE_POSITIVE_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 3;\n foundPositiveRegex = true;\n break;\n }\n }\n\n // Only proceed to inverted matches if no positive match of any kind (Rank 1, 2, or 3) was found\n if (!foundPositiveRegex) {\n // Rank 4: Primary Exact Inverted Match\n if (HAS_MORE_PRIMARY_INVERTED_EXACT.includes(normalizedForExactMatch)) {\n currentPropRank = 4;\n }\n // Rank 5: Inverted Regex Match (sub-phrase)\n else {\n for (const regex of COMPILED_HAS_MORE_INVERTED_REGEXES) {\n if (regex.test(propName)) {\n // Test against original propName\n currentPropRank = 5;\n break;\n }\n }\n }\n }\n }\n\n updateCandidate(propName, currentPropRank);\n }\n return bestCandidate;\n}\n\n/**\n * Tries to guess the name of a boolean property that indicates if there are more items\n * to fetch (e.g., for pagination).\n *\n * @param schema The OpenAPI SchemaObject, expected to be of type 'object'.\n * @returns The name of the most likely boolean property indicating \"has more\",\n * or null if no suitable boolean property is found.\n */\nexport function getHasMoreName(properties: SchemasObject): string | null {\n const rootGuess = guess(properties);\n if (rootGuess) {\n return rootGuess;\n }\n for (const propName in properties) {\n const propSchema = properties[propName];\n if (propSchema.type === 'object' && propSchema.properties) {\n const nested = getHasMoreName(propSchema.properties as SchemasObject);\n if (nested) {\n return propName + '.' + nested;\n }\n }\n }\n return null;\n}\n", "import { toLitObject } from '@sdk-it/core';\n\nimport type { Spec } from './sdk.ts';\nimport type { Style } from './style.ts';\n\nexport default (spec: Omit<Spec, 'operations'>, style: Style) => {\n const optionsEntries = Object.entries(spec.options).map(\n ([key, value]) => [`'${key}'`, value] as const,\n );\n const defaultHeaders = `{${optionsEntries\n .filter(([, value]) => value.in === 'header')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${optionsEntries\n .filter(([, value]) => value.in === 'input')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const specOptions: Record<string, { schema: string }> = {\n ...Object.fromEntries(\n optionsEntries.map(([key, value]) => [value.optionName ?? key, value]),\n ),\n fetch: {\n schema: 'fetchType',\n },\n baseUrl: {\n schema: spec.servers.length\n ? `z.enum(servers).default(servers[0])`\n : 'z.string()',\n },\n };\n\n return `import z from 'zod';\nimport type { HeadersInit, RequestConfig } from './http/${spec.makeImport('request')}';\nimport { fetchType, parse } from './http/${spec.makeImport('dispatcher')}';\nimport schemas from './api/${spec.makeImport('schemas')}';\nimport {\n createBaseUrlInterceptor,\n createHeadersInterceptor,\n} from './http/${spec.makeImport('interceptors')}';\n\nimport { parseInput, type ParseError } from './http/${spec.makeImport('parser')}';\n\n${spec.servers.length ? `export const servers = ${JSON.stringify(spec.servers, null, 2)} as const` : ''}\nconst optionsSchema = z.object(${toLitObject(specOptions, (x) => x.schema)});\n${spec.servers.length ? `export type Servers = typeof servers[number];` : ''}\n\ntype ${spec.name}Options = z.infer<typeof optionsSchema>;\n\nexport class ${spec.name} {\n public options: ${spec.name}Options\n constructor(options: ${spec.name}Options) {\n this.options = optionsSchema.parse(options);\n }\n\n async request<const E extends keyof typeof schemas>(\n endpoint: E,\n input: z.infer<(typeof schemas)[E]['schema']>,\n options?: { signal?: AbortSignal, headers?: HeadersInit },\n ) ${style.errorAsValue ? `: Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>| [never, ParseError<(typeof schemas)[E]['schema']>]>` : `: Promise<Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>>`} {\n const route = schemas[endpoint];\n const withDefaultInputs = Object.assign({}, this.#defaultInputs, input);\n const [parsedInput, parseError] = parseInput(route.schema, withDefaultInputs);\n if (parseError) {\n ${style.errorAsValue ? 'return [null as never, parseError as never] as const;' : 'throw parseError;'}\n }\n const result = await route.dispatch(parsedInput as never, {\n fetch: this.options.fetch,\n interceptors: [\n createHeadersInterceptor(() => this.defaultHeaders, options?.headers ?? {}),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ],\n signal: options?.signal,\n });\n return result as Awaited<ReturnType<(typeof schemas)[E]['dispatch']>>;\n }\n\n async prepare<const E extends keyof typeof schemas>(\n endpoint: E,\n input: z.infer<(typeof schemas)[E]['schema']>,\n options?: { headers?: HeadersInit },\n ): ${\n style.errorAsValue\n ? `Promise<\n readonly [\n RequestConfig & {\n parse: (response: Response) => ReturnType<typeof parse>;\n },\n ParseError<(typeof schemas)[E]['schema']> | null,\n ]\n >`\n : `Promise<RequestConfig & {\n parse: (response: Response) => ReturnType<typeof parse>;\n }>`\n } {\n const route = schemas[endpoint];\n\n const interceptors = [\n createHeadersInterceptor(\n () => this.defaultHeaders,\n options?.headers ?? {},\n ),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ];\n const [parsedInput, parseError] = parseInput(route.schema, input);\n if (parseError) {\n ${style.errorAsValue ? 'return [null as never, parseError as never] as const;' : 'throw parseError;'}\n }\n\n let config = route.toRequest(parsedInput as never);\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n const prepared = { ...config, parse: (response: Response) => parse(route.output, response) as never };\n return ${style.errorAsValue ? '[prepared, null as never] as const;' : 'prepared as any'}\n }\n\n get defaultHeaders() {\n return ${defaultHeaders}\n }\n\n get #defaultInputs() {\n return ${defaultInputs}\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n const validated = optionsSchema.partial().parse(options);\n\n for (const key of Object.keys(validated) as (keyof ${spec.name}Options)[]) {\n if (validated[key] !== undefined) {\n (this.options[key] as typeof validated[typeof key]) = validated[key]!;\n }\n }\n }\n}`;\n};\n", "import { merge, template } from 'lodash-es';\nimport { join } from 'node:path';\nimport type {\n OpenAPIObject,\n ParameterLocation,\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef } from '@sdk-it/core';\nimport {\n type GenerateSdkConfig,\n forEachOperation,\n} from '@sdk-it/spec/operation.js';\n\nimport { ZodEmitter } from './emitters/zod.ts';\nimport {\n type Operation,\n type OperationInput,\n type Spec,\n toEndpoint,\n} from './sdk.ts';\nimport type { Style } from './style.ts';\nimport endpointsTxt from './styles/github/endpoints.txt';\nimport {\n importsToString,\n mergeImports,\n securityToOptions,\n useImports,\n} from './utils.ts';\n\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly: boolean;\n}\nexport interface Import {\n isTypeOnly: boolean;\n moduleSpecifier: string;\n defaultImport: string | undefined;\n namedImports: NamedImport[];\n namespaceImport: string | undefined;\n}\n\nexport function generateCode(\n config: GenerateSdkConfig & {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n style: Style;\n makeImport: (module: string) => string;\n },\n) {\n const commonZod = new Map<string, string>();\n const commonZodImports: Import[] = [];\n const zodDeserialzer = new ZodEmitter(config.spec, (model, schema) => {\n commonZod.set(model, schema);\n commonZodImports.push({\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `./${config.makeImport(model)}`,\n namedImports: [{ isTypeOnly: true, name: model }],\n namespaceImport: undefined,\n });\n });\n\n const groups: Spec['operations'] = {};\n const outputs: Record<string, string> = {};\n const endpoints: Record<string, ReturnType<typeof toEndpoint>[]> = {};\n\n forEachOperation(config, (entry, operation) => {\n console.log(`Processing ${entry.method} ${entry.path}`);\n groups[entry.groupName] ??= [];\n endpoints[entry.groupName] ??= [];\n const inputs: Operation['inputs'] = {};\n\n const additionalProperties: Record<string, ParameterObject> = {};\n for (const param of operation.parameters) {\n if (!param.schema) {\n param.schema = {\n type: 'string',\n };\n }\n inputs[param.name] = {\n in: param.in,\n schema: '',\n };\n additionalProperties[param.name] = param;\n }\n\n const securitySchemes = config.spec.components?.securitySchemes ?? {};\n const securityOptions = securityToOptions(\n config.spec,\n operation.security ?? [],\n securitySchemes,\n );\n\n Object.assign(inputs, securityOptions);\n\n // the spec might have explict security param for security set\n // which we need to overwrite it by ours. (avoid having it mandatory)\n Object.entries(securityOptions).forEach(([name, value]) => {\n additionalProperties[name] = {\n name: name,\n required: false,\n schema: {\n type: 'string',\n },\n in: value.in as ParameterLocation,\n } satisfies ParameterObject;\n });\n\n const schemas: Record<string, string> = {};\n const shortContenTypeMap: Record<string, string> = {\n 'application/json': 'json',\n 'application/*+json': 'json', // type specific of json like application/vnd.api+json (from the generation pov it shouldn't matter)\n 'text/json': 'json', // non standard - later standardized to application/json\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'multipart/form-data': 'formdata',\n 'application/xml': 'xml',\n 'text/plain': 'text',\n };\n let outgoingContentType: string | undefined;\n\n if (!isEmpty(operation.requestBody)) {\n for (const type in operation.requestBody.content) {\n const ctSchema = isRef(operation.requestBody.content[type].schema)\n ? followRef(\n config.spec,\n operation.requestBody.content[type].schema.$ref,\n )\n : operation.requestBody.content[type].schema;\n if (!ctSchema) {\n console.warn(\n `Schema not found for ${type} in ${entry.method} ${entry.path}`,\n );\n continue;\n }\n\n let objectSchema = ctSchema;\n if (objectSchema.type !== 'object') {\n objectSchema = {\n type: 'object',\n required: [operation.requestBody.required ? '$body' : ''],\n properties: {\n $body: ctSchema,\n },\n };\n }\n const schema = merge({}, objectSchema, {\n required: Object.values(additionalProperties)\n .filter((p) => p.required)\n .map((p) => p.name),\n properties: Object.entries(additionalProperties).reduce<\n Record<string, unknown>\n >(\n (acc, [, p]) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n ),\n });\n\n Object.assign(inputs, bodyInputs(config, objectSchema));\n schemas[shortContenTypeMap[type]] = zodDeserialzer.handle(schema, true);\n }\n\n if (operation.requestBody.content['application/json']) {\n outgoingContentType = 'json';\n } else if (\n operation.requestBody.content['application/x-www-form-urlencoded']\n ) {\n outgoingContentType = 'urlencoded';\n } else if (operation.requestBody.content['multipart/form-data']) {\n outgoingContentType = 'formdata';\n } else {\n outgoingContentType = 'json';\n }\n } else {\n const properties = Object.entries(additionalProperties).reduce<\n Record<string, any>\n >(\n (acc, [, p]) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n );\n schemas[shortContenTypeMap['application/json']] = zodDeserialzer.handle(\n {\n type: 'object',\n required: Object.values(additionalProperties)\n .filter((p) => p.required)\n .map((p) => p.name),\n properties,\n },\n true,\n );\n }\n\n const endpoint = toEndpoint(\n entry.groupName,\n config.spec,\n operation,\n {\n outgoingContentType,\n name: operation.operationId,\n type: 'http',\n trigger: entry,\n schemas,\n inputs,\n },\n { makeImport: config.makeImport, style: config.style },\n );\n\n const output = [\n `import z from 'zod';`,\n `import type * as http from '${config.makeImport('../http/index')}';`,\n ];\n const responses = endpoint.responses.flatMap((it) => it.responses);\n const responsesImports = endpoint.responses.flatMap((it) =>\n Object.values(it.imports),\n );\n if (responses.length) {\n output.push(\n ...responses.map(\n (it) =>\n `${it.description ? `\\n/** \\n * ${it.description}\\n */\\n` : ''} export type ${it.name} = ${it.schema};`,\n ),\n );\n } else {\n output.push(\n `export type ${pascalcase(operation.operationId + ' output')} = void;`,\n );\n }\n\n output.unshift(...useImports(output.join(''), ...responsesImports));\n\n outputs[`${spinalcase(operation.operationId)}.ts`] = output.join('\\n');\n\n endpoints[entry.groupName].push(endpoint);\n\n groups[entry.groupName].push({\n name: operation.operationId,\n type: 'http',\n inputs,\n outgoingContentType,\n schemas,\n trigger: entry,\n });\n });\n const commonSchemas = Object.values(endpoints).reduce<Record<string, string>>(\n (acc, endpoint) => ({\n ...acc,\n ...endpoint.reduce<Record<string, string>>(\n (acc, { responses }) => ({\n ...acc,\n ...responses.reduce<Record<string, string>>(\n (acc, it) => ({ ...acc, ...it.schemas }),\n {},\n ),\n }),\n {},\n ),\n }),\n {},\n );\n\n const allSchemas = Object.keys(endpoints).map((it) => ({\n import: `import ${camelcase(it)} from './${config.makeImport(spinalcase(it))}';`,\n use: ` ...${camelcase(it)}`,\n }));\n\n const imports = [\n 'import z from \"zod\";',\n `import type { ParseError } from '${config.makeImport('../http/parser')}';`,\n `import type { ServerError } from '${config.makeImport('../http/response')}';`,\n ];\n return {\n groups,\n commonSchemas,\n commonZod,\n outputs,\n endpoints: {\n [join('api', 'endpoints.ts')]: `\n\n\nimport type z from 'zod';\nimport type { ParseError } from '${config.makeImport('../http/parser')}';\nimport type { ProblematicResponse, SuccessfulResponse } from '${config.makeImport(\n '../http/response',\n )}';\n\nimport schemas from '${config.makeImport('./schemas')}';\nimport type { Unionize } from '${config.makeImport('../http/dispatcher')}';\n ${template(endpointsTxt)({ outputType: config.style?.outputType })}`,\n [`${join('api', 'schemas.ts')}`]:\n `${allSchemas.map((it) => it.import).join('\\n')}\nimport { KIND } from \"${config.makeImport('../http/index')}\";\nexport default {\\n${allSchemas.map((it) => it.use).join(',\\n')}\\n};\n\n`.trim(),\n ...Object.fromEntries(\n Object.entries(endpoints)\n .map(([name, endpoint]) => {\n const imps = importsToString(\n ...mergeImports(\n ...endpoint.flatMap((it) =>\n it.responses.flatMap((it) =>\n Object.values(it.endpointImports),\n ),\n ),\n ),\n );\n return [\n [\n join('api', `${spinalcase(name)}.ts`),\n `${[\n ...imps,\n `import z from 'zod';`,\n `import * as http from '${config.makeImport('../http/response')}';`,\n `import { toRequest, json, urlencoded, empty, formdata, createUrl, type HeadersInit } from '${config.makeImport('../http/request')}';`,\n `import { chunked, buffered } from \"${config.makeImport('../http/parse-response')}\";`,\n `import * as ${camelcase(name)} from '../inputs/${config.makeImport(spinalcase(name))}';`,\n `import { createBaseUrlInterceptor, createHeadersInterceptor, type Interceptor } from '${config.makeImport('../http/interceptors')}';`,\n `import { Dispatcher, fetchType, type InstanceType } from '${config.makeImport('../http/dispatcher')}';`,\n `import { Pagination, OffsetPagination, CursorPagination } from \"${config.makeImport('../pagination/index')}\";`,\n ].join(\n '\\n',\n )}\\nexport default {\\n${endpoint.flatMap((it) => it.schemas).join(',\\n')}\\n}`,\n ],\n ];\n })\n .flat(),\n ),\n },\n };\n}\n\nfunction toProps(\n spec: OpenAPIObject,\n schemaOrRef: SchemaObject | ReferenceObject,\n aggregator: string[] = [],\n) {\n if (isRef(schemaOrRef)) {\n const schema = followRef(spec, schemaOrRef.$ref);\n return toProps(spec, schema, aggregator);\n } else if (schemaOrRef.type === 'object') {\n for (const [name] of Object.entries(schemaOrRef.properties ?? {})) {\n aggregator.push(name);\n }\n return void 0;\n } else if (\n (schemaOrRef.type === 'array' || schemaOrRef.type?.includes('array')) &&\n schemaOrRef.items\n ) {\n toProps(spec, schemaOrRef.items, aggregator);\n return void 0;\n } else if (schemaOrRef.allOf) {\n for (const it of schemaOrRef.allOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n } else if (schemaOrRef.oneOf) {\n for (const it of schemaOrRef.oneOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n } else if (schemaOrRef.anyOf) {\n for (const it of schemaOrRef.anyOf) {\n toProps(spec, it, aggregator);\n }\n return void 0;\n }\n console.warn('Unknown schema in body', schemaOrRef);\n return void 0;\n}\n\nfunction bodyInputs(\n config: GenerateSdkConfig,\n ctSchema: SchemaObject | ReferenceObject,\n) {\n const props: string[] = [];\n toProps(config.spec, ctSchema, props);\n return props.reduce<Record<string, OperationInput>>(\n (acc, prop) => ({\n ...acc,\n [prop]: {\n in: 'body',\n schema: '',\n },\n }),\n {},\n );\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, content: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n * adapted for OpenAPI 3.1 (fully aligned with JSON Schema 2020-12).\n */\nexport class ZodEmitter {\n generatedRefs = new Set<string>();\n #spec: OpenAPIObject;\n #onRef?: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef?: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n /**\n * Handle objects (properties, additionalProperties).\n */\n object(schema: SchemaObject): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n return `'${key}': ${this.handle(propSchema, isRequired)}`;\n });\n\n let additionalProps = '';\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n // e.g. z.record() if it\u2019s an object schema\n const addPropZod = this.handle(schema.additionalProperties, true);\n additionalProps = `.catchall(${addPropZod})`;\n } else if (schema.additionalProperties === true) {\n // free-form additional props\n additionalProps = `.catchall(z.unknown())`;\n }\n }\n\n return `z.object({${propEntries.join(', ')}})${additionalProps}`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple (array of schemas)).\n * In JSON Schema 2020-12, `items` can be an array \u2192 tuple style.\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => z.array(z.unknown())\n return `z.array(z.unknown())${appendOptional(required)}`;\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n // Build a Zod tuple\n const tupleItems = items.map((sub) => this.handle(sub, true));\n const base = `z.tuple([${tupleItems.join(', ')}])`;\n // // If we have additionalItems: false => that\u2019s a fixed length\n // // If additionalItems is a schema => rest(...)\n // if (schema.additionalItems) {\n // if (typeof schema.additionalItems === 'object') {\n // const restSchema = jsonSchemaToZod(spec, schema.additionalItems, true);\n // base += `.rest(${restSchema})`;\n // }\n // // If `additionalItems: false`, no rest is allowed => do nothing\n // }\n return `${base}${appendOptional(required)}`;\n }\n\n // If items is a single schema => standard z.array(...)\n const itemsSchema = this.handle(items, true);\n return `z.array(${itemsSchema})${appendOptional(required)}`;\n }\n\n #suffixes = (defaultValue: unknown, required: boolean, nullable: boolean) => {\n return `${nullable ? '.nullable()' : ''}${appendDefault(defaultValue)}${appendOptional(required)}`;\n };\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to Zod.\n * We'll also handle .optional() if needed.\n */\n normal(\n type: string,\n schema: SchemaObject,\n required = false,\n nullable = false,\n ): string {\n switch (type) {\n case 'string':\n return `${this.string(schema)}${this.#suffixes(JSON.stringify(schema.default), required, nullable)}`;\n case 'number':\n case 'integer': {\n const { base, defaultValue } = this.number(schema);\n return `${base}${this.#suffixes(defaultValue, required, nullable)}`;\n }\n case 'boolean':\n return `z.boolean()${this.#suffixes(schema.default, required, nullable)}`;\n case 'object':\n return `${this.object(schema)}${this.#suffixes(JSON.stringify(schema.default), required, nullable)}`;\n // required always\n case 'array':\n return this.array(schema, required);\n case 'null':\n // If \"type\": \"null\" alone, this is basically z.null()\n return `z.null()${appendOptional(required)}`;\n default:\n // Unknown type -> fallback\n return `z.unknown()${appendOptional(required)}`;\n }\n }\n\n ref($ref: string, required: boolean) {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.generatedRefs.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef<SchemaObject>(this.#spec, $ref), required),\n );\n\n return schemaName;\n }\n allOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const allOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (allOfSchemas.length === 0) {\n return `z.unknown()`;\n }\n if (allOfSchemas.length === 1) {\n return `${allOfSchemas[0]}${appendOptional(required)}`;\n }\n return `${this.#toIntersection(allOfSchemas)}${appendOptional(required)}`;\n }\n\n #toIntersection(schemas: string[]): string {\n const [left, ...right] = schemas;\n if (!right.length) {\n return left;\n }\n return `z.intersection(${left}, ${this.#toIntersection(right)})`;\n }\n\n anyOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const anyOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (anyOfSchemas.length === 1) {\n return `${anyOfSchemas[0]}${appendOptional(required)}`;\n }\n return `z.union([${anyOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n oneOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const oneOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (oneOfSchemas.length === 1) {\n return `${oneOfSchemas[0]}${appendOptional(required)}`;\n }\n return `z.union([${oneOfSchemas.join(', ')}])${appendOptional(required)}`;\n }\n\n enum(type: string, values: any[]) {\n if (values.length === 1) {\n return `z.literal(${values.join(', ')})`;\n }\n if (type === 'integer') {\n // Zod doesn\u2019t have a direct enum for numbers, so we use union of literals\n return `z.union([${values.map((val) => `z.literal(${val})`).join(', ')}])`;\n }\n\n return `z.enum([${values.join(', ')}])`;\n }\n\n /**\n * Handle a `string` schema with possible format keywords (JSON Schema).\n */\n string(schema: SchemaObject): string {\n let base = 'z.string()';\n\n // 3.1 replaces `example` in the schema with `examples` (array).\n // We do not strictly need them for the Zod type, so they\u2019re optional\n // for validation. However, we could keep them as metadata if you want.\n\n if (schema.contentEncoding === 'binary') {\n base = 'z.instanceof(Blob)';\n return base;\n }\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n // parse to JS Date\n base = 'z.coerce.date()';\n break;\n case 'date':\n base =\n 'z.coerce.date() /* or z.string() if you want raw date strings */';\n break;\n case 'time':\n base =\n 'z.string() /* optionally add .regex(...) for HH:MM:SS format */';\n break;\n case 'email':\n base = 'z.string().email()';\n break;\n case 'uuid':\n base = 'z.string().uuid()';\n break;\n case 'url':\n case 'uri':\n base = 'z.string().url()';\n break;\n case 'ipv4':\n base = 'z.string().ip({version: \"v4\"})';\n break;\n case 'ipv6':\n base = 'z.string().ip({version: \"v6\"})';\n break;\n case 'phone':\n base = 'z.string() /* or add .regex(...) for phone formats */';\n break;\n case 'byte':\n case 'binary':\n base = 'z.instanceof(Blob)';\n break;\n case 'int64':\n // JS numbers can't reliably store int64, consider z.bigint() or keep as string\n base = 'z.string() /* or z.bigint() if your app can handle it */';\n break;\n default:\n // No special format\n break;\n }\n\n return base;\n }\n\n /**\n * Handle number/integer constraints from OpenAPI/JSON Schema.\n * In 3.1, exclusiveMinimum/Maximum hold the actual numeric threshold,\n * rather than a boolean toggling `minimum`/`maximum`.\n */\n number(schema: SchemaObject) {\n let defaultValue = schema.default;\n let base = 'z.number()';\n if (schema.format === 'int64') {\n base = 'z.bigint()';\n if (schema.default !== undefined) {\n defaultValue = `BigInt(${schema.default})`;\n }\n }\n\n if (schema.format === 'int32') {\n // 32-bit integer\n base += '.int()';\n }\n\n // If we see exclusiveMinimum as a number in 3.1:\n if (typeof schema.exclusiveMinimum === 'number') {\n // Zod doesn\u2019t have a direct \"exclusiveMinimum\" method, so we can do .gt()\n // If exclusiveMinimum=7 => .gt(7)\n base += `.gt(${schema.exclusiveMinimum})`;\n }\n // Similarly for exclusiveMaximum\n if (typeof schema.exclusiveMaximum === 'number') {\n // If exclusiveMaximum=10 => .lt(10)\n base += `.lt(${schema.exclusiveMaximum})`;\n }\n\n // If standard minimum/maximum\n if (typeof schema.minimum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.min(BigInt(${schema.minimum}))`\n : `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.max(BigInt(${schema.maximum}))`\n : `.max(${schema.maximum})`;\n }\n\n // multipleOf\n if (typeof schema.multipleOf === 'number') {\n // There's no direct multipleOf in Zod. Some folks do a custom refine.\n // For example:\n base += `.refine((val) => Number.isInteger(val / ${schema.multipleOf}), \"Must be a multiple of ${schema.multipleOf}\")`;\n }\n\n return { base, defaultValue };\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return `${this.ref(schema.$ref, true)}${appendOptional(required)}`;\n }\n\n // Handle allOf \u2192 intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf ?? [], required);\n }\n\n // anyOf \u2192 union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf ?? [], required);\n }\n\n // oneOf \u2192 union\n if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length) {\n return this.oneOf(schema.oneOf ?? [], required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n const enumVals = schema.enum.map((val) => JSON.stringify(val));\n const defaultValue = enumVals.includes(JSON.stringify(schema.default))\n ? JSON.stringify(schema.default)\n : undefined;\n return `${this.enum(schema.type as string, enumVals)}${this.#suffixes(defaultValue, required, false)}`;\n }\n\n // 3.1 can have type: string or type: string[] (e.g. [\"string\",\"null\"])\n // Let's parse that carefully.\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to unknown\n if (!types.length) {\n return `z.unknown()${appendOptional(required)}`;\n }\n\n // If it's a union type (like [\"string\", \"null\"]), we'll build a Zod union\n // or apply .nullable() if it's just \"type + null\".\n\n // backward compatibility with openapi 3.0\n if ('nullable' in schema && schema.nullable) {\n types.push('null');\n } else if (schema.default === null) {\n types.push('null');\n }\n\n if (types.length > 1) {\n // If it\u2019s exactly one real type plus \"null\", we can do e.g. `z.string().nullable()`\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n return this.normal(realTypes[0], schema, required, true);\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) => this.normal(t, schema, false));\n return `z.union([${subSchemas.join(', ')}])${appendOptional(required)}`;\n }\n return this.normal(types[0], schema, required, false);\n }\n}\n\n/**\n * Append .optional() if not required\n */\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n\n// Todo: convert openapi 3.0 to 3.1 before proccesing\n", "import { get } from 'lodash-es';\nimport type { OpenAPIObject, ResponseObject } from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { isRef, toLitObject } from '@sdk-it/core';\nimport type {\n OperationPagination,\n TunedOperationObject,\n} from '@sdk-it/spec/operation.js';\n\nimport { TypeScriptEmitter } from './emitters/interface.ts';\nimport type { Style } from './style.ts';\nimport { type Import, type MakeImportFn } from './utils.ts';\n\nexport type Parser = 'chunked' | 'buffered';\n\nexport interface SdkConfig {\n /**\n * The name of the sdk client\n */\n name: string;\n packageName?: string;\n options?: Record<string, any>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport type Options = Record<\n string,\n {\n in: string;\n schema: string;\n optionName?: string;\n }\n>;\nexport interface Spec {\n name: string;\n options: Options;\n servers: string[];\n operations: Record<string, Operation[]>;\n makeImport: MakeImportFn;\n}\n\nexport interface OperationInput {\n in: string;\n schema: string;\n}\nexport interface Operation {\n name: string;\n type: string;\n trigger: Record<string, any>;\n schemas: Record<string, string>;\n inputs: Record<string, OperationInput>;\n outgoingContentType?: string;\n}\n\nexport function generateInputs(\n operationsSet: Spec['operations'],\n commonZod: Map<string, string>,\n makeImport: MakeImportFn,\n) {\n const commonImports = commonZod.keys().toArray();\n const inputs: Record<string, string> = {};\n for (const [name, operations] of Object.entries(operationsSet)) {\n const output: string[] = [];\n const imports = new Set(['import { z } from \"zod\";']);\n\n for (const operation of operations) {\n const schemaName = camelcase(`${operation.name} schema`);\n\n const schema = `export const ${schemaName} = ${\n Object.keys(operation.schemas).length === 1\n ? Object.values(operation.schemas)[0]\n : toLitObject(operation.schemas)\n };`;\n\n const inputContent = schema;\n\n for (const schema of commonImports) {\n if (inputContent.includes(schema)) {\n imports.add(\n `import { ${schema} } from './schemas/${makeImport(spinalcase(schema))}';`,\n );\n }\n }\n output.push(inputContent);\n }\n inputs[`inputs/${spinalcase(name)}.ts`] =\n [...imports, ...output].join('\\n') + '\\n';\n }\n\n const schemas = commonZod\n .entries()\n .reduce<string[][]>((acc, [name, schema]) => {\n const output = [`import { z } from 'zod';`];\n const content = `export const ${name} = ${schema};`;\n for (const schema of commonImports) {\n const preciseMatch = new RegExp(`\\\\b${schema}\\\\b`);\n if (preciseMatch.test(content) && schema !== name) {\n output.push(\n `import { ${schema} } from './${makeImport(spinalcase(schema))}';`,\n );\n }\n }\n\n output.push(content);\n return [\n [`inputs/schemas/${spinalcase(name)}.ts`, output.join('\\n')],\n ...acc,\n ];\n }, []);\n\n return {\n ...Object.fromEntries(schemas),\n ...inputs,\n };\n}\n\nexport function toEndpoint(\n groupName: string,\n spec: OpenAPIObject,\n specOperation: TunedOperationObject,\n operation: Operation,\n utils: {\n makeImport: MakeImportFn;\n style?: Style;\n },\n) {\n const schemaName = camelcase(`${operation.name} schema`);\n const schemaRef = `${camelcase(groupName)}.${schemaName}`;\n\n const inputHeaders: string[] = [];\n const inputQuery: string[] = [];\n const inputBody: string[] = [];\n const inputParams: string[] = [];\n const schemas: string[] = [];\n const responses: ReturnType<typeof handleResponse>[] = [];\n for (const [name, prop] of Object.entries(operation.inputs)) {\n if (prop.in === 'headers' || prop.in === 'header') {\n inputHeaders.push(`\"${name}\"`);\n } else if (prop.in === 'query') {\n inputQuery.push(`\"${name}\"`);\n } else if (prop.in === 'body') {\n inputBody.push(`\"${name}\"`);\n } else if (prop.in === 'path') {\n inputParams.push(`\"${name}\"`);\n } else if (prop.in === 'internal') {\n // ignore internal sources\n continue;\n } else {\n throw new Error(\n `Unknown source ${prop.in} in ${name} ${JSON.stringify(\n prop,\n )} in ${operation.name}`,\n );\n }\n }\n\n specOperation.responses ??= {};\n const outputs: string[] = [];\n\n const statusesCount =\n Object.keys(specOperation.responses).filter((status) => {\n const statusCode = +status;\n return statusCode >= 200 && statusCode < 300;\n }).length > 1;\n const responseWithAtLeast200 = statusesCount\n ? specOperation.responses\n : Object.assign(\n {\n '200': {\n description: 'OK',\n content: {\n 'application/json': {\n schema: { type: 'object' },\n },\n },\n },\n },\n specOperation.responses,\n );\n for (const status in responseWithAtLeast200) {\n const handled = handleResponse(\n spec,\n operation.name,\n status,\n responseWithAtLeast200[status],\n utils,\n true,\n // statusesCount,\n );\n responses.push(handled);\n outputs.push(...handled.outputs);\n }\n\n const addTypeParser = Object.keys(operation.schemas).length > 1;\n for (const type in operation.schemas ?? {}) {\n let typePrefix = '';\n if (addTypeParser && type !== 'json') {\n typePrefix = `${type} `;\n }\n\n const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;\n schemas.push(\n `\"${endpoint}\": {\n schema: ${schemaRef}${addTypeParser ? `.${type}` : ''},\n output:[${outputs.join(',')}],\n toRequest(input: z.infer<typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}>) {\n return toRequest('${endpoint}', ${operation.outgoingContentType || 'empty'}(input, {\n inputHeaders: [${inputHeaders}],\n inputQuery: [${inputQuery}],\n inputBody: [${inputBody}],\n inputParams: [${inputParams}],\n }));},\n async dispatch(input: z.infer<typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}>,options: {\n signal?: AbortSignal;\n interceptors: Interceptor[];\n fetch: z.infer<typeof fetchType>;\n })${specOperation['x-pagination'] ? paginationOperation(specOperation, utils.style) : normalOperation(utils.style)}`,\n );\n }\n return { responses, schemas };\n}\n\nfunction normalOperation(style?: Style) {\n return `{\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(this.toRequest(input), this.output);\n return ${style?.outputType === 'status' ? 'result' : style?.errorAsValue ? `result` : 'result.data;'}\n },\n }`;\n}\n\nfunction paginationOperation(operation: TunedOperationObject, style?: Style) {\n const pagination = operation['x-pagination'] as OperationPagination;\n const data = `${style?.errorAsValue ? `result[0]${style.outputType === 'status' ? '' : ''}` : `${style?.outputType === 'default' ? 'result.data' : 'result.data'}`}`;\n\n if (pagination.type === 'offset') {\n const sameInputNames =\n pagination.limitParamName === 'limit' &&\n pagination.offsetParamName === 'offset';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, limit: input.${pagination.limitParamName}, offset: input.${pagination.offsetParamName}}`;\n\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.offsetParamName}: nextPageParams.offset, ${pagination.limitParamName}: nextPageParams.limit`;\n const logic = `const pagination = new OffsetPagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n );\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n await pagination.getNextPage();\n return ${style?.outputType === 'status' ? 'new http.Ok(pagination);' : 'pagination'}\n `;\n return style?.errorAsValue\n ? `{try {${logic}} catch (error) {return [null as never, error] as const;}}}`\n : `{${logic}}}`;\n }\n if (pagination.type === 'cursor') {\n const sameInputNames = pagination.cursorParamName === 'cursor';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, cursor: input.${pagination.cursorParamName}}`;\n\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.cursorParamName}: nextPageParams.cursor`;\n const logic = `\n const pagination = new CursorPagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n );\n ${style?.errorAsValue ? `if (result[1]) {throw result[1];}` : ''}\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n await pagination.getNextPage();\n return ${style?.outputType === 'status' ? 'new http.Ok(pagination);' : 'pagination'}\n `;\n return style?.errorAsValue\n ? `{try {${logic}} catch (error) {return [null as never, error] as const;}}}`\n : `{${logic}}}`;\n }\n if (pagination.type === 'page') {\n const sameInputNames =\n pagination.pageNumberParamName === 'page' &&\n pagination.pageSizeParamName === 'pageSize';\n const initialParams = sameInputNames\n ? 'input'\n : `{...input, page: input.${pagination.pageNumberParamName}, pageSize: input.${pagination.pageSizeParamName}}`;\n const nextPageParams = sameInputNames\n ? '...nextPageParams'\n : `${pagination.pageNumberParamName}: nextPageParams.page, ${pagination.pageSizeParamName}: nextPageParams.pageSize`;\n\n const logic = `\n const pagination = new Pagination(${initialParams}, async (nextPageParams) => {\n const dispatcher = new Dispatcher(options.interceptors, options.fetch);\n const result = await dispatcher.send(\n this.toRequest({...input, ${nextPageParams}}),\n this.output,\n );\n ${style?.errorAsValue ? `if (result[1]) {throw result[1];}` : ''}\n return {\n data: ${data}.${pagination.items},\n meta: {\n hasMore: Boolean(${data}.${pagination.hasMore}),\n },\n };\n });\n await pagination.getNextPage();\n return ${style?.outputType === 'status' ? 'new http.Ok(pagination);' : 'pagination'}\n `;\n return style?.errorAsValue\n ? `{try {${logic}} catch (error) {return [null as never, error] as const;}}}`\n : `{${logic}}}`;\n }\n return normalOperation(style);\n}\n\nconst statusCodeToResponseMap: Record<string, string> = {\n '200': 'Ok',\n '201': 'Created',\n '202': 'Accepted',\n '204': 'NoContent',\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '413': 'PayloadTooLarge',\n '410': 'Gone',\n '422': 'UnprocessableEntity',\n '429': 'TooManyRequests',\n '500': 'InternalServerError',\n '501': 'NotImplemented',\n '502': 'BadGateway',\n '503': 'ServiceUnavailable',\n '504': 'GatewayTimeout',\n};\nfunction handleResponse(\n spec: OpenAPIObject,\n operationName: string,\n status: string,\n response: ResponseObject,\n utils: { makeImport: MakeImportFn },\n numbered: boolean,\n) {\n const schemas: Record<string, string> = {};\n const imports: Record<string, Import> = {};\n const endpointImports: Record<string, Import> = {\n ParseError: {\n defaultImport: undefined,\n isTypeOnly: false,\n moduleSpecifier: utils.makeImport(`../http/parser`),\n namedImports: [{ isTypeOnly: false, name: 'ParseError' }],\n namespaceImport: undefined,\n },\n };\n const responses: { name: string; schema: string; description?: string }[] =\n [];\n const outputs: string[] = [];\n const typeScriptDeserialzer = new TypeScriptEmitter(\n spec,\n (schemaName, zod) => {\n schemas[schemaName] = zod;\n imports[schemaName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../models/${utils.makeImport(schemaName)}`,\n namedImports: [{ isTypeOnly: true, name: schemaName }],\n namespaceImport: undefined,\n };\n },\n );\n const statusCode = +status;\n const parser: Parser = (response.headers ?? {})['Transfer-Encoding']\n ? 'chunked'\n : 'buffered';\n const statusName = `http.${statusCodeToResponseMap[status] || 'APIResponse'}`;\n const interfaceName = pascalcase(\n operationName + ` output${numbered ? status : ''}`,\n );\n\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n if (status.endsWith('XX')) {\n outputs.push(`http.APIError<${interfaceName}>`);\n } else {\n outputs.push(\n parser !== 'buffered'\n ? `{type: ${statusName}<${interfaceName}>, parser: ${parser}}`\n : `${statusName}<${interfaceName}>`,\n );\n }\n }\n const responseContent = get(response, ['content']);\n const isJson = responseContent && responseContent['application/json'];\n let responseSchema = parser === 'chunked' ? 'ReadableStream' : 'void';\n if (isJson) {\n const schema = responseContent['application/json'].schema!;\n const isObject = !isRef(schema) && schema.type === 'object';\n if (isObject && schema.properties) {\n schema.properties['[http.KIND]'] = {\n 'x-internal': true,\n const: `typeof ${statusName}.kind`,\n type: 'string',\n };\n schema.required ??= [];\n schema.required.push('[http.KIND]');\n }\n responseSchema = typeScriptDeserialzer.handle(schema, true);\n }\n\n responses.push({\n name: interfaceName,\n schema: responseSchema,\n description: response.description,\n });\n const statusGroup = +status.slice(0, 1);\n if (statusCode >= 400 || statusGroup >= 4) {\n endpointImports[statusCodeToResponseMap[status] ?? 'APIError'] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [{ name: statusCodeToResponseMap[status] ?? 'APIError' }],\n };\n\n endpointImports[interfaceName] = {\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n };\n } else if (\n (statusCode >= 200 && statusCode < 300) ||\n statusCode >= 2 ||\n statusGroup <= 3\n ) {\n endpointImports[interfaceName] = {\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n namedImports: [{ isTypeOnly: true, name: interfaceName }],\n namespaceImport: undefined,\n };\n }\n return { schemas, imports, endpointImports, responses, outputs };\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef } from '@sdk-it/core';\n\ntype OnRefCallback = (ref: string, interfaceContent: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into TypeScript interfaces,\n */\nexport class TypeScriptEmitter {\n generatedRefs = new Set<string>();\n #spec: OpenAPIObject;\n #onRef: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n #stringifyKey = (value: string): string => {\n return `'${value}'`;\n };\n\n #isInternal = (schema: SchemaObject | ReferenceObject): boolean => {\n return isRef(schema) ? false : !!schema['x-internal'];\n };\n\n /**\n * Handle objects (properties)\n */\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n // Add question mark for optional properties\n return `${this.#isInternal(propSchema) ? key : this.#stringifyKey(key)}: ${tsType}`;\n });\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n const indexType = this.handle(schema.additionalProperties, true);\n propEntries.push(`[key: string]: ${indexType}`);\n } else if (schema.additionalProperties === true) {\n propEntries.push('[key: string]: any');\n }\n }\n\n return `${propEntries.length ? `{ ${propEntries.join('; ')} }` : 'unknown'}`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple)\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => any[]\n return 'any[]';\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n const tupleItems = items.map((sub) => this.handle(sub, true));\n return `[${tupleItems.join(', ')}]`;\n }\n\n // If items is a single schema => standard array\n const itemsType = this.handle(items, true);\n return `${itemsType}[]`;\n }\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to TypeScript\n */\n normal(type: string, schema: SchemaObject, required = false): string {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return appendOptional('boolean', required);\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.array(schema, required);\n case 'null':\n return 'null';\n default:\n console.warn(`Unknown type: ${type}`);\n // Unknown type -> fallback\n return appendOptional('any', required);\n }\n }\n\n ref($ref: string, required: boolean): string {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.generatedRefs.add(schemaName);\n\n this.#onRef?.(\n schemaName,\n this.handle(followRef<SchemaObject>(this.#spec, $ref), required),\n );\n\n return appendOptional(schemaName, required);\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[]): string {\n // For TypeScript we use intersection types for allOf\n const allOfTypes = schemas.map((sub) => this.handle(sub, true));\n return allOfTypes.length > 1 ? `${allOfTypes.join(' & ')}` : allOfTypes[0];\n }\n\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const anyOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n anyOfTypes.length > 1 ? `${anyOfTypes.join(' | ')}` : anyOfTypes[0],\n required,\n );\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const oneOfTypes = schemas.map((sub) => {\n return this.handle(sub, false);\n });\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n\n enum(values: any[], required: boolean): string {\n // For TypeScript enums as union of literals\n const enumValues = values\n .map((val) => (typeof val === 'string' ? `'${val}'` : `${val}`))\n .join(' | ');\n return appendOptional(enumValues, required);\n }\n\n /**\n * Handle string type with formats\n */\n string(schema: SchemaObject, required?: boolean): string {\n let type: string;\n\n if (schema.contentEncoding === 'binary') {\n return appendOptional('Blob', required);\n }\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n case 'date':\n type = 'Date';\n break;\n case 'binary':\n case 'byte':\n type = 'Blob';\n break;\n case 'int64':\n type = 'bigint';\n break;\n default:\n type = 'string';\n }\n\n return appendOptional(type, required);\n }\n\n /**\n * Handle number/integer types with formats\n */\n number(schema: SchemaObject, required?: boolean): string {\n const type = schema.format === 'int64' ? 'bigint' : 'number';\n return appendOptional(type, required);\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.ref(schema.$ref, required);\n }\n\n // Handle allOf (intersection in TypeScript)\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n\n // anyOf (union in TypeScript)\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf, required);\n }\n\n // oneOf (union in TypeScript)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf, required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n if (schema.const) {\n if (schema['x-internal']) {\n return `${schema.const}`;\n }\n return this.enum([schema.const], required);\n }\n\n // Handle types, in TypeScript we can have union types directly\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to any\n if (!types.length) {\n // unless properties are defined then assume object\n if ('properties' in schema) {\n return this.object(schema, required);\n }\n return appendOptional('any', required);\n }\n\n // Handle union types (multiple types)\n if (types.length > 1) {\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const tsType = this.normal(realTypes[0], schema, false);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, false));\n return appendOptional(typeResults.join(' | '), required);\n }\n\n // Single type\n return this.normal(types[0], schema, required);\n }\n}\n\n/**\n * Append \"| undefined\" if not required\n */\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import type {\n ComponentsObject,\n OpenAPIObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, removeDuplicates } from '@sdk-it/core';\n\nimport { type Options } from './sdk.ts';\n\nexport function securityToOptions(\n spec: OpenAPIObject,\n security: SecurityRequirementObject[],\n securitySchemes: ComponentsObject['securitySchemes'],\n staticIn?: string,\n) {\n securitySchemes ??= {};\n const options: Options = {};\n for (const it of security) {\n const [name] = Object.keys(it);\n if (!name) {\n // this means the operation doesn't necessarily require security\n continue;\n }\n const schema = isRef(securitySchemes[name])\n ? followRef(spec, securitySchemes[name].$ref)\n : securitySchemes[name];\n\n if (schema.type === 'http') {\n options['authorization'] = {\n in: staticIn ?? 'header',\n schema:\n 'z.string().optional().transform((val) => (val ? `Bearer ${val}` : undefined))',\n optionName: 'token',\n };\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n options[schema.name] = {\n in: staticIn ?? schema.in,\n schema: 'z.string().optional()',\n };\n continue;\n }\n }\n return options;\n}\n\nexport function mergeImports(...imports: Import[]) {\n const merged: Record<string, Import> = {};\n\n for (const it of imports) {\n merged[it.moduleSpecifier] = merged[it.moduleSpecifier] ?? {\n moduleSpecifier: it.moduleSpecifier,\n defaultImport: it.defaultImport,\n namespaceImport: it.namespaceImport,\n namedImports: [],\n };\n for (const named of it.namedImports) {\n if (\n !merged[it.moduleSpecifier].namedImports.some(\n (x) => x.name === named.name,\n )\n ) {\n merged[it.moduleSpecifier].namedImports.push(named);\n }\n }\n }\n\n return Object.values(merged);\n}\n\nexport interface Import {\n isTypeOnly?: boolean;\n moduleSpecifier: string;\n defaultImport?: string | undefined;\n namedImports: NamedImport[];\n namespaceImport?: string | undefined;\n}\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly?: boolean;\n}\n\nexport function importsToString(...imports: Import[]) {\n return imports.map((it) => {\n if (it.defaultImport) {\n return `import ${it.defaultImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namespaceImport) {\n return `import * as ${it.namespaceImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namedImports) {\n return `import {${removeDuplicates(it.namedImports, (it) => it.name)\n .map((n) => `${n.isTypeOnly ? 'type' : ''} ${n.name}`)\n .join(', ')}} from '${it.moduleSpecifier}'`;\n }\n throw new Error(`Invalid import ${JSON.stringify(it)}`);\n });\n}\n\nexport function exclude<T>(list: T[], exclude: T[]): T[] {\n return list.filter((it) => !exclude.includes(it));\n}\n\nexport function useImports(content: string, ...imports: Import[]) {\n const output: string[] = [];\n for (const it of mergeImports(...imports)) {\n const singleImport = it.defaultImport ?? it.namespaceImport;\n if (singleImport && content.includes(singleImport)) {\n output.push(importsToString(it).join('\\n'));\n } else if (it.namedImports.length) {\n for (const namedImport of it.namedImports) {\n if (content.includes(namedImport.name)) {\n output.push(importsToString(it).join('\\n'));\n }\n }\n }\n }\n return output;\n}\n\nexport type MakeImportFn = (moduleSpecifier: string) => string;\n", "type EndpointOutput<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n SuccessfulResponse\n>;\n\ntype EndpointError<K extends keyof typeof schemas> = Extract<\n Unionize<(typeof schemas)[K]['output']>,\n ProblematicResponse\n>;\n\nexport type Endpoints = {\n [K in keyof typeof schemas]: {\n input: z.infer<(typeof schemas)[K]['schema']>;\n output: <% if (outputType === 'default') { %>EndpointOutput<K>['data']<% } else { %>EndpointOutput<K><% } %>;\n error: EndpointError<K> | ParseError<(typeof schemas)[K]['schema']>;\n };\n};", "export type Unionize<T> = T extends [infer Single extends OutputType]\n ? InstanceType<Single>\n : T extends readonly [...infer Tuple extends OutputType[]]\n ? { [I in keyof Tuple]: InstanceType<Tuple[I]> }[number]\n : never;\n\nexport type InstanceType<T> =\n T extends Type<infer U>\n ? U\n : T extends { type: Type<infer U> }\n ? U\n : T extends Array<unknown>\n ? Unionize<T>\n : never;\n\nexport interface Type<T> {\n new (...args: any[]): T;\n}\nexport type Parser = (\n response: Response,\n) => Promise<unknown> | ReadableStream<any>;\nexport type OutputType =\n | Type<APIResponse>\n | { parser: Parser; type: Type<APIResponse> };\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\nexport async function parse<T extends OutputType[]>(\n outputs: T,\n response: Response,\n) <% if(!throwError) { %>\n: Promise<\n [\n Extract<InstanceType<T>, SuccessfulResponse>['data'],\n Extract<InstanceType<T>, ProblematicResponse>['data'],\n ]\n>\n <% } %>\n\n\n\n {\n let output: typeof APIResponse | null = null;\n let parser: Parser = buffered;\n for (const outputType of outputs) {\n if ('parser' in outputType) {\n parser = outputType.parser;\n if (isTypeOf(outputType.type, APIResponse)) {\n if (response.status === outputType.type.status) {\n output = outputType.type;\n break;\n }\n }\n } else if (isTypeOf(outputType, APIResponse)) {\n if (response.status === outputType.status) {\n output = outputType;\n break;\n }\n }\n }\n\n\n if (response.ok) {\n const apiresponse = (output || APIResponse).create(\n response.status,\n await parser(response),\n );\n <% if(throwError) { %>\n return <% if (outputType === 'default') { %>apiresponse as Extract<InstanceType<T>, SuccessfulResponse><% } else { %>apiresponse as Extract<InstanceType<T>, SuccessfulResponse>;<% } %>;\n <% } else { %>\n return [<% if (outputType === 'default') { %>apiresponse.data as Extract<InstanceType<T>, SuccessfulResponse>['data']<% } else { %>apiresponse as Extract<InstanceType<T>, SuccessfulResponse><% } %>, null] as const;\n <% } %>\n }\n<% if(throwError) { %>\n throw (output || APIError).create(\n response.status,\n await parser(response),\n );\n<% } else { %>\n const data = (output || APIError).create(\n response.status,\n await parser(response),\n );\n return [null, data] as const;\n<% } %>\n}\n\nexport function isTypeOf<T extends Type<APIResponse>>(\n instance: any,\n baseType: T,\n): instance is T {\n if (instance === baseType) {\n return true;\n }\n const prototype = Object.getPrototypeOf(instance);\n if (prototype === null) {\n return false;\n }\n return isTypeOf(prototype, baseType);\n}\n\nexport class Dispatcher {\n #interceptors: Interceptor[] = [];\n #fetch: z.infer<typeof fetchType>;\n constructor(interceptors: Interceptor[], fetch?: z.infer<typeof fetchType>) {\n this.#interceptors = interceptors;\n this.#fetch = fetch;\n }\n\n async send<T extends OutputType[]>(\n config: RequestConfig,\n outputs: T,\n signal?: AbortSignal,\n ) {\n for (const interceptor of this.#interceptors) {\n if (interceptor.before) {\n config = await interceptor.before(config);\n }\n }\n\n let response = await (this.#fetch ?? fetch)(\n new Request(config.url, config.init),\n {\n ...config.init,\n signal: signal,\n },\n );\n\n for (let i = this.#interceptors.length - 1; i >= 0; i--) {\n const interceptor = this.#interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n return await parse(outputs, response);\n }\n}\n", "export interface Interceptor {\n before?: (config: RequestConfig) => Promise<RequestConfig> | RequestConfig;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createHeadersInterceptor = (\n defaultHeaders: () => Record<string, string | undefined>,\n requestHeaders: HeadersInit,\n):Interceptor => {\n return {\n before({init, url}) {\n // Priority Levels\n // 1. Headers Input\n // 2. Request Headers\n // 3. Default Headers\n const headers = defaultHeaders();\n\n for (const [key, value] of new Headers(requestHeaders)) {\n // Only set the header if it doesn't already exist and has a value\n // even though these headers are passed at operation level\n // still they are lower priority compared to the headers input\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !init.headers.has(key)) {\n init.headers.set(key, value);\n }\n }\n\n return {init, url};\n },\n };\n};\n\nexport const createBaseUrlInterceptor = (\n getBaseUrl: () => string,\n): Interceptor => {\n return {\n before({ init, url }) {\n const baseUrl = getBaseUrl();\n if (url.protocol === 'local:') {\n return {\n init,\n url: new URL(url.href.replace('local://', baseUrl))\n };\n }\n return { init, url };\n },\n };\n};\n\nexport const logInterceptor: Interceptor = {\n before({ url, init }) {\n console.log('Request:', { url, init });\n return { url, init };\n },\n after(response) {\n console.log('Response:', response);\n return response;\n },\n};\n\n/**\n * Creates an interceptor that logs detailed information about requests and responses.\n * @param options Configuration options for the logger\n * @returns An interceptor object with before and after handlers\n */\nexport const createDetailedLogInterceptor = (options?: {\n logLevel?: 'debug' | 'info' | 'warn' | 'error';\n includeRequestBody?: boolean;\n includeResponseBody?: boolean;\n}) => {\n const logLevel = options?.logLevel || 'info';\n const includeRequestBody = options?.includeRequestBody || false;\n const includeResponseBody = options?.includeResponseBody || false;\n\n return {\n async before(request: Request) {\n const logData = {\n url: request.url,\n method: request.method,\n contentType: request.headers.get('Content-Type'),\n headers: Object.fromEntries([...request.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDE80 Outgoing Request:', logData);\n\n if (includeRequestBody) {\n try {\n // Clone the request to avoid consuming the body stream\n const clonedRequest = request.clone();\n if (clonedRequest.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedRequest.json().catch(() => null);\n console[logLevel]('Request Body:', body);\n } else {\n const body = await clonedRequest.text().catch(() => null);\n console[logLevel]('Request Body:', body);\n }\n } catch (error) {\n console.error('Could not log request body:', error);\n }\n }\n\n return request;\n },\n\n async after(response: Response) {\n const logData = {\n status: response.status,\n statusText: response.statusText,\n url: response.url,\n headers: Object.fromEntries([...response.headers.entries()]),\n };\n\n console[logLevel]('\uD83D\uDCE5 Incoming Response:', logData);\n\n if (includeResponseBody && response.body) {\n try {\n // Clone the response to avoid consuming the body stream\n const clonedResponse = response.clone();\n if (clonedResponse.headers.get('Content-Type')?.includes('application/json')) {\n const body = await clonedResponse.json().catch(() => null);\n console[logLevel]('Response Body:', body);\n } else {\n const body = await clonedResponse.text().catch(() => null);\n if (body) {\n console[logLevel]('Response Body:', body.substring(0, 500) + (body.length > 500 ? '...' : ''));\n } else {\n console[logLevel]('No response body');\n }\n }\n } catch (error) {\n console.error('Could not log response body:', error);\n }\n }\n\n return response;\n },\n };\n};\n", "import { parse } from \"fast-content-type-parse\";\n\nasync function handleChunkedResponse(response: Response, contentType: string) {\n\tconst { type } = parse(contentType);\n\n\tswitch (type) {\n\t\tcase \"application/json\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn JSON.parse(buffer);\n\t\t}\n\t\tcase \"text/html\":\n\t\tcase \"text/plain\": {\n\t\t\tlet buffer = \"\";\n\t\t\tconst reader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\twhile (true) {\n\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value);\n\t\t\t}\n\t\t\treturn buffer;\n\t\t}\n\t\tdefault:\n\t\t\treturn response.body;\n\t}\n}\n\nexport function chunked(response: Response) {\n\treturn response.body!;\n}\n\nexport async function buffered(response: Response) {\n\tconst contentType = response.headers.get(\"Content-Type\");\n\tif (!contentType) {\n\t\tthrow new Error(\"Content-Type header is missing\");\n\t}\n\n\tif (response.status === 204) {\n\t\treturn null;\n\t}\n\n\tconst { type } = parse(contentType);\n\tswitch (type) {\n\t\tcase \"application/json\":\n\t\t\treturn response.json();\n\t\tcase \"text/plain\":\n\t\t\treturn response.text();\n\t\tcase \"text/html\":\n\t\t\treturn response.text();\n\t\tcase \"text/xml\":\n\t\tcase \"application/xml\":\n\t\t\treturn response.text();\n\t\tcase \"application/x-www-form-urlencoded\": {\n\t\t\tconst text = await response.text();\n\t\t\treturn Object.fromEntries(new URLSearchParams(text));\n\t\t}\n\t\tcase \"multipart/form-data\":\n\t\t\treturn response.formData();\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported content type: ${contentType}`);\n\t}\n}\n", "import { z } from 'zod';\n\nexport class ParseError<T extends z.ZodType<any, any, any>> {\n public data: z.typeToFlattenedError<T, z.ZodIssue>;\n constructor(data: z.typeToFlattenedError<T, z.ZodIssue>) {\n this.data = data;\n }\n}\n\nexport function parseInput<T extends z.ZodType<any, any, any>>(\n schema: T,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = result.error.flatten((issue) => issue);\n return [null, new ParseError(error)];\n }\n return [result.data as z.infer<T>, null];\n}\n", "type Init = Omit<RequestInit, 'headers'> & { headers: Headers; };\nexport type RequestConfig = { init: Init; url: URL };\nexport type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart' | 'formdata';\nexport type HeadersInit = [string, string][] | Record<string, string>;\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(\n input: Input,\n props: Props,\n ) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n if (\n this.props.inputBody.length === 1 &&\n this.props.inputBody[0] === '$body'\n ) {\n return JSON.stringify(this.input.$body);\n }\n\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Accept: 'application/json',\n };\n }\n}\n\nclass EmptySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {\n Accept: 'application/json',\n };\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function empty(input: Input, props: Props) {\n return new EmptySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): RequestConfig {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n return {\n url: createUrl(pathVariable, input.query),\n init: {\n method: method,\n headers: new Headers(input.headers),\n body: method === 'GET' ? undefined : input.body,\n },\n }\n}\n", "export const KIND = Symbol('APIDATA');\n\nexport class APIResponse<Body = unknown, Status extends number = number> {\n static readonly status: number;\n static readonly kind: symbol = Symbol.for(\"APIResponse\");\n status: Status;\n data: Body;\n\n constructor(status: Status, data: Body) {\n this.status = status;\n this.data = data;\n }\n\n static create<Body = unknown>(status: number, data: Body) {\n return new this(status, data);\n }\n\n}\n\nexport class APIError<Body, Status extends number = number> extends APIResponse<\n Body,\n Status\n> {\n static override create<T>(status: number, data: T) {\n return new this(status, data);\n }\n}\n\n\n// 2xx Success\nexport class Ok<T> extends APIResponse<T, 200> {\n static override readonly kind = Symbol.for(\"Ok\");\n static override readonly status = 200 as const;\n constructor(data: T) {\n super(Ok.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]:typeof Ok['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\n\nexport class Created<T> extends APIResponse<T, 201> {\n static override readonly kind = Symbol.for(\"Created\");\n static override status = 201 as const;\n constructor(data: T) {\n super(Created.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Created['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Accepted<T> extends APIResponse<T, 202> {\n static override readonly kind = Symbol.for(\"Accepted\");\n static override status = 202 as const;\n constructor(data: T) {\n super(Accepted.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Accepted['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NoContent extends APIResponse<never, 204> {\n static override readonly kind = Symbol.for(\"NoContent\");\n static override status = 204 as const;\n constructor() {\n super(NoContent.status, null as never);\n }\n static override create(status: number, data: never): NoContent {\n return new this();\n }\n\n static is<T extends {[KIND]: typeof NoContent['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\n// 4xx Client Errors\nexport class BadRequest<T> extends APIError<T, 400> {\n static override readonly kind = Symbol.for(\"BadRequest\");\n static override status = 400 as const;\n constructor(data: T) {\n super(BadRequest.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof BadRequest['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Unauthorized<T = { message: string }> extends APIError<T, 401> {\n static override readonly kind = Symbol.for(\"Unauthorized\");\n static override status = 401 as const;\n constructor(data: T) {\n super(Unauthorized.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Unauthorized['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class PaymentRequired<T = { message: string }> extends APIError<T, 402> {\n static override readonly kind = Symbol.for(\"PaymentRequired\");\n static override status = 402 as const;\n constructor(data: T) {\n super(PaymentRequired.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof PaymentRequired['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Forbidden<T = { message: string }> extends APIError<T, 403> {\n static override readonly kind = Symbol.for(\"Forbidden\");\n static override status = 403 as const;\n constructor(data: T) {\n super(Forbidden.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Forbidden['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NotFound<T = { message: string }> extends APIError<T, 404> {\n static override readonly kind = Symbol.for(\"NotFound\");\n static override status = 404 as const;\n constructor(data: T) {\n super(NotFound.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof NotFound['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class MethodNotAllowed<T = { message: string }> extends APIError<\n T,\n 405\n> {\n static override readonly kind = Symbol.for(\"MethodNotAllowed\");\n static override status = 405 as const;\n constructor(data: T) {\n super(MethodNotAllowed.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof MethodNotAllowed['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NotAcceptable<T = { message: string }> extends APIError<T, 406> {\n static override readonly kind = Symbol.for(\"NotAcceptable\");\n static override status = 406 as const;\n constructor(data: T) {\n super(NotAcceptable.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof NotAcceptable['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Conflict<T = { message: string }> extends APIError<T, 409> {\n static override readonly kind = Symbol.for(\"Conflict\");\n static override status = 409 as const;\n constructor(data: T) {\n super(Conflict.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Conflict['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class Gone<T = { message: string }> extends APIError<T, 410> {\n static override readonly kind = Symbol.for(\"Gone\");\n static override status = 410 as const;\n constructor(data: T) {\n super(Gone.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof Gone['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class UnprocessableEntity<\n T = { message: string; errors?: Record<string, string[]> },\n> extends APIError<T, 422> {\n static override readonly kind = Symbol.for(\"UnprocessableEntity\");\n static override status = 422 as const;\n constructor(data: T) {\n super(UnprocessableEntity.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof UnprocessableEntity['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class TooManyRequests<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 429> {\n static override readonly kind = Symbol.for(\"TooManyRequests\");\n static override status = 429 as const;\n constructor(data: T) {\n super(TooManyRequests.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof TooManyRequests['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class PayloadTooLarge<T = { message: string }> extends APIError<T, 413> {\n static override readonly kind = Symbol.for(\"PayloadTooLarge\");\n static override status = 413 as const;\n constructor(data: T) {\n super(PayloadTooLarge.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof PayloadTooLarge['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class UnsupportedMediaType<T = { message: string }> extends APIError<\n T,\n 415\n> {\n static override readonly kind = Symbol.for(\"UnsupportedMediaType\");\n static override status = 415 as const;\n constructor(data: T) {\n super(UnsupportedMediaType.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof UnsupportedMediaType['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\n// 5xx Server Errors\nexport class InternalServerError<T = { message: string }> extends APIError<\n T,\n 500\n> {\n static override readonly kind = Symbol.for(\"InternalServerError\");\n static override status = 500 as const;\n constructor(data: T) {\n super(InternalServerError.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof InternalServerError['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class NotImplemented<T = { message: string }> extends APIError<T, 501> {\n static override readonly kind = Symbol.for(\"NotImplemented\");\n static override status = 501 as const;\n constructor(data: T) {\n super(NotImplemented.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof NotImplemented['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class BadGateway<T = { message: string }> extends APIError<T, 502> {\n static override readonly kind = Symbol.for(\"BadGateway\");\n static override status = 502 as const;\n constructor(data: T) {\n super(BadGateway.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof BadGateway['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class ServiceUnavailable<\n T = { message: string; retryAfter?: string },\n> extends APIError<T, 503> {\n static override readonly kind = Symbol.for(\"ServiceUnavailable\");\n static override status = 503 as const;\n constructor(data: T) {\n super(ServiceUnavailable.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof ServiceUnavailable['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\nexport class GatewayTimeout<T = { message: string }> extends APIError<T, 504> {\n static override readonly kind = Symbol.for(\"GatewayTimeout\");\n static override status = 504 as const;\n constructor(data: T) {\n super(GatewayTimeout.status, data);\n }\n static override create<T>(status: number, data: T) {\n Object.defineProperty(data, KIND, { value: this.kind });\n return new this(data);\n }\n\n static is<T extends {[KIND]: typeof GatewayTimeout['kind']}>(value: unknown): value is T {\n return typeof value === 'object' && value !== null && KIND in value && value[KIND] === this.kind;\n }\n}\n\nexport type ClientError =\n | BadRequest<{ message: string }>\n | Unauthorized<unknown>\n | PaymentRequired<unknown>\n | Forbidden<unknown>\n | NotFound<unknown>\n | MethodNotAllowed<unknown>\n | NotAcceptable<unknown>\n | Conflict<unknown>\n | Gone<unknown>\n | UnprocessableEntity<unknown>\n | TooManyRequests<unknown>;\n\nexport type ServerError =\n | InternalServerError<unknown>\n | NotImplemented<unknown>\n | BadGateway<unknown>\n | ServiceUnavailable<unknown>\n | GatewayTimeout<unknown>;\n\nexport type ProblematicResponse = ClientError | ServerError;\n\nexport type SuccessfulResponse =\n | Ok<unknown>\n | Created<unknown>\n | Accepted<unknown>\n | NoContent;\n", "type CursorPaginationParams = {\n cursor?: string;\n};\n\ninterface CursorMetadata extends Metadata {\n nextCursor?: string;\n}\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationResult<T, M extends CursorMetadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends CursorMetadata> = (\n input: CursorPaginationParams,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class CursorPagination<T, M extends CursorMetadata> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: CursorPaginationParams;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M>;\n\n constructor(\n initialParams: PartialNullable<CursorPaginationParams>,\n fetchFn: FetchFn<T, M>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = {\n cursor: initialParams.cursor ?? undefined,\n };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n cursor: result.meta.nextCursor,\n };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n\ntype PartialNullable<T> = {\n [K in keyof T]?: T[K] | null;\n};\n", "type OffsetPaginationParams = {\n offset: number;\n limit: number;\n};\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationResult<T, M extends Metadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<T, M extends Metadata> = (\n input: OffsetPaginationParams,\n) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class OffsetPagination<T, M extends Metadata> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: OffsetPaginationParams;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M>;\n\n constructor(\n initialParams: Partial<OffsetPaginationParams>,\n fetchFn: FetchFn<T, M>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = {\n limit: initialParams.limit ?? 0,\n offset: initialParams.offset ?? 0,\n };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n offset: this.#params.offset + this.#params.limit,\n };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n\n reset(params?: Partial<OffsetPaginationParams>) {\n this.#meta = null;\n this.#currentPage = null;\n if (params) {\n this.#params = { ...this.#params, ...params };\n } else {\n this.#params.offset = 0;\n }\n return this;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n", "type InferPage<T> = T extends Page<infer U> ? U : never;\ntype PaginationParams<P extends number | bigint, S extends number | bigint> = {\n page?: P;\n pageSize?: S;\n};\n\ninterface Metadata {\n hasMore?: boolean;\n}\n\ntype PaginationResult<T, M extends Metadata> = {\n data: T[];\n meta: M;\n};\n\ntype FetchFn<\n T,\n M extends Metadata,\n P extends number | bigint,\n S extends number | bigint,\n> = (input: Partial<PaginationParams<P, S>>) => Promise<PaginationResult<T, M>>;\n\n/**\n * @experimental\n */\nexport class Pagination<\n T,\n M extends Metadata,\n P extends number | bigint,\n S extends number | bigint,\n> {\n #meta: PaginationResult<T, M>['meta'] | null = null;\n #params: PaginationParams<P, S>;\n #currentPage: Page<T> | null = null;\n readonly #fetchFn: FetchFn<T, M, P, S>;\n\n constructor(\n initialParams: Partial<PaginationParams<P, S>>,\n fetchFn: FetchFn<T, M, P, S>,\n ) {\n this.#fetchFn = fetchFn;\n this.#params = { ...initialParams, page: initialParams.page };\n }\n\n async getNextPage() {\n const result = await this.#fetchFn(this.#params);\n this.#currentPage = new Page(result.data);\n this.#meta = result.meta;\n this.#params = {\n ...this.#params,\n page: ((this.#params.page as number) || 0 + 1) as never,\n };\n return this;\n }\n\n getCurrentPage() {\n if (!this.#currentPage) {\n throw new Error(\n 'No page data available. Please call getNextPage() first.',\n );\n }\n return this.#currentPage;\n }\n\n get hasMore() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta.hasMore;\n }\n\n async *[Symbol.asyncIterator]() {\n for await (const page of this.iter()) {\n yield page.getCurrentPage();\n }\n }\n\n async *iter() {\n if (!this.#currentPage) {\n yield await this.getNextPage();\n }\n\n while (this.hasMore) {\n yield await this.getNextPage();\n }\n }\n\n get metadata() {\n if (!this.#meta) {\n throw new Error(\n 'No meta data available. Please call getNextPage() first.',\n );\n }\n return this.#meta;\n }\n}\n\nclass Page<T> {\n data: T[];\n constructor(data: T[]) {\n this.data = data;\n }\n}\n", "import type { OpenAPIObject, SchemaObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef, pascalcase } from '@sdk-it/core';\nimport {\n type OperationEntry,\n type TunedOperationObject,\n patchParameters,\n} from '@sdk-it/spec/operation.js';\n\nimport { SnippetEmitter } from './emitters/snippet.ts';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\n\nexport class TypeScriptGenerator {\n #spec: OpenAPIObject;\n #settings: TypeScriptGeneratorOptions;\n #snippetEmitter: SnippetEmitter;\n #clientName: string;\n #packageName: string;\n constructor(spec: OpenAPIObject, settings: TypeScriptGeneratorOptions) {\n this.#spec = spec;\n this.#settings = settings;\n this.#snippetEmitter = new SnippetEmitter(spec);\n this.#clientName = settings.name?.trim()\n ? pascalcase(settings.name)\n : 'Client';\n\n this.#packageName = settings.name\n ? `@${spinalcase(this.#clientName.toLowerCase())}/sdk`\n : 'sdk';\n }\n\n succinct(\n entry: OperationEntry,\n operation: TunedOperationObject,\n values: {\n requestBody?: Record<string, unknown>;\n pathParameters?: Record<string, unknown>;\n queryParameters?: Record<string, unknown>;\n headers?: Record<string, unknown>;\n cookies?: Record<string, unknown>;\n },\n ) {\n let payload = '{}';\n if (!isEmpty(operation.requestBody)) {\n const contentTypes = Object.keys(operation.requestBody.content || {});\n if (contentTypes.length > 0) {\n const firstContent = operation.requestBody.content[contentTypes[0]];\n let schema = isRef(firstContent.schema)\n ? followRef(this.#spec, firstContent.schema.$ref)\n : firstContent.schema;\n if (schema) {\n if (schema.type !== 'object') {\n schema = {\n type: 'object',\n required: [operation.requestBody.required ? '$body' : ''],\n properties: {\n $body: schema,\n },\n };\n }\n const properties: Record<string, SchemaObject> = {};\n patchParameters(\n this.#spec,\n { type: 'object', properties },\n operation,\n );\n const examplePayload = this.#snippetEmitter.handle({\n ...schema,\n properties: Object.assign({}, properties, schema.properties),\n });\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as any,\n values.requestBody ?? {},\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = JSON.stringify(examplePayload, null, 2);\n }\n }\n } else {\n const properties: Record<string, SchemaObject> = {};\n patchParameters(this.#spec, { type: 'object', properties }, operation);\n const examplePayload = this.#snippetEmitter.handle({\n properties: properties,\n });\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as any,\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = JSON.stringify(examplePayload, null, 2);\n }\n return `const result = await ${camelcase(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload});`;\n }\n snippet(entry: OperationEntry, operation: TunedOperationObject) {\n const payload = this.succinct(entry, operation, {});\n return [\n '```typescript',\n `${this.client()}\n${payload}\n\nconsole.log(result.data);\n`,\n '```',\n ].join('\\n');\n }\n\n client() {\n return `import { ${this.#clientName} } from '${this.#packageName}';\n\nconst ${camelcase(this.#clientName)} = new ${this.#clientName}({\n baseUrl: '${this.#spec.servers?.[0]?.url ?? 'http://localhost:3000'}',\n});`;\n }\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef } from '@sdk-it/core';\n\n/**\n * Generate example values for OpenAPI schemas\n * This emitter creates sample input payloads for API documentation and code snippets\n */\nexport class SnippetEmitter {\n private spec: OpenAPIObject;\n public generatedRefs = new Set<string>();\n private cache = new Map<string, unknown>();\n\n constructor(spec: OpenAPIObject) {\n this.spec = spec;\n }\n\n public object(\n schema: SchemaObject | ReferenceObject,\n ): Record<string, unknown> {\n const schemaObj = isRef(schema)\n ? followRef<SchemaObject>(this.spec, schema.$ref)\n : schema;\n const result: Record<string, unknown> = {};\n const properties = schemaObj.properties || {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const isRequired = (schemaObj.required ?? []).includes(propName);\n const resolvedProp = isRef(propSchema)\n ? followRef<SchemaObject>(this.spec, propSchema.$ref)\n : propSchema;\n\n if (\n isRequired ||\n resolvedProp.example !== undefined ||\n resolvedProp.default !== undefined ||\n Math.random() > 0.5\n ) {\n result[propName] = this.handle(propSchema);\n }\n }\n\n if (\n schemaObj.additionalProperties &&\n typeof schemaObj.additionalProperties === 'object'\n ) {\n result['additionalPropExample'] = this.handle(\n schemaObj.additionalProperties,\n );\n }\n\n return result;\n }\n\n public array(schema: SchemaObject | ReferenceObject): unknown[] {\n const schemaObj = isRef(schema)\n ? followRef<SchemaObject>(this.spec, schema.$ref)\n : schema;\n const itemsSchema = schemaObj.items;\n if (!itemsSchema) {\n return [];\n }\n\n const count = Math.min(schemaObj.minItems ?? 1, 2);\n const result: unknown[] = [];\n\n for (let i = 0; i < count; i++) {\n result.push(this.handle(itemsSchema));\n }\n\n return result;\n }\n\n public string(schema: SchemaObject): string {\n if (schema.example !== undefined) return String(schema.example);\n if (schema.default !== undefined) return String(schema.default);\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n return new Date().toISOString();\n case 'date':\n return new Date().toISOString().split('T')[0];\n case 'time':\n return new Date().toISOString().split('T')[1];\n case 'email':\n return 'user@example.com';\n case 'uuid':\n return '123e4567-e89b-12d3-a456-426614174000';\n case 'uri':\n case 'url':\n return 'https://example.com';\n case 'ipv4':\n return '192.168.1.1';\n case 'ipv6':\n return '2001:0db8:85a3:0000:0000:8a2e:0370:7334';\n case 'hostname':\n return 'example.com';\n case 'binary':\n case 'byte':\n return '[binary data]';\n default:\n if (schema.enum && schema.enum.length > 0) {\n return String(schema.enum[0]);\n }\n return schema.pattern ? `string matching ${schema.pattern}` : 'example';\n }\n }\n\n public number(schema: SchemaObject): number {\n if (schema.example !== undefined) return Number(schema.example);\n if (schema.default !== undefined) return Number(schema.default);\n\n let value: number;\n if (typeof schema.exclusiveMinimum === 'number') {\n value = schema.exclusiveMinimum + 1;\n } else if (typeof schema.minimum === 'number') {\n value = schema.minimum;\n } else {\n value = schema.type === 'integer' ? 42 : 42.42;\n }\n\n if (\n typeof schema.exclusiveMaximum === 'number' &&\n value >= schema.exclusiveMaximum\n ) {\n value = schema.exclusiveMaximum - 1;\n } else if (typeof schema.maximum === 'number' && value > schema.maximum) {\n value = schema.maximum;\n }\n\n if (\n typeof schema.multipleOf === 'number' &&\n value % schema.multipleOf !== 0\n ) {\n value = Math.floor(value / schema.multipleOf) * schema.multipleOf;\n }\n\n return schema.type === 'integer' ? Math.floor(value) : value;\n }\n\n public boolean(schema: SchemaObject): boolean {\n if (schema.example !== undefined) return Boolean(schema.example);\n if (schema.default !== undefined) return Boolean(schema.default);\n return true;\n }\n\n public null(): null {\n return null;\n }\n\n public ref($ref: string): unknown {\n const parts = $ref.split('/');\n const refKey = parts[parts.length - 1] || '';\n\n if (this.cache.has($ref)) {\n return this.cache.get($ref) as unknown;\n }\n\n this.cache.set($ref, { _ref: refKey });\n\n const resolved = followRef<SchemaObject>(this.spec, $ref);\n const result = this.handle(resolved);\n\n this.cache.set($ref, result);\n return result;\n }\n\n public allOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n const initial: Record<string, unknown> = {};\n return schemas.reduce<Record<string, unknown>>((result, schema) => {\n const example = this.handle(schema);\n if (typeof example === 'object' && example !== null) {\n return { ...result, ...example };\n }\n return result;\n }, initial);\n }\n\n public anyOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n if (schemas.length === 0) return {};\n return this.handle(schemas[0]);\n }\n\n public oneOf(schemas: (SchemaObject | ReferenceObject)[]): unknown {\n if (schemas.length === 0) return {};\n return this.handle(schemas[0]);\n }\n\n public enum(schema: SchemaObject): unknown {\n return Array.isArray(schema.enum) && schema.enum.length > 0\n ? schema.enum[0]\n : undefined;\n }\n\n public handle(schemaOrRef: SchemaObject | ReferenceObject): unknown {\n if (isRef(schemaOrRef)) {\n return this.ref(schemaOrRef.$ref);\n }\n\n const schema = isRef(schemaOrRef)\n ? followRef<SchemaObject>(this.spec, schemaOrRef.$ref)\n : schemaOrRef;\n\n if (schema.example !== undefined) {\n return schema.example;\n }\n if (schema.default !== undefined) {\n return schema.default;\n }\n\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf);\n }\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf);\n }\n\n if (schema.enum && Array.isArray(schema.enum) && schema.enum.length > 0) {\n return this.enum(schema);\n }\n\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n if (types.length === 0) {\n if (schema.properties || schema.additionalProperties) {\n return this.object(schema);\n } else if (schema.items) {\n return this.array(schema);\n }\n return 'example';\n }\n\n const primaryType = types.find((t) => t !== 'null') || types[0];\n\n switch (primaryType) {\n case 'string':\n return this.string(schema);\n case 'number':\n case 'integer':\n return this.number(schema);\n case 'boolean':\n return this.boolean(schema);\n case 'object':\n return this.object(schema);\n case 'array':\n return this.array(schema);\n case 'null':\n return this.null();\n default:\n return 'unknown';\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,KAAC,SAAU,MAAMA,YAAW;AAE1B,UAAI,OAAO,cAAY,cAAc,OAAO,YAAY,YAAY,OAAO,WAAW,UAAU;AAE9F,eAAO,UAAUA,WAAU;AAAA,MAC7B,WAAW,OAAO,WAAW,cAAc,OAAO,KAAK;AAErD,eAAO,WAAY;AACjB,iBAAOA,WAAU;AAAA,QACnB,CAAC;AAAA,MACH,OAAO;AAEL,aAAK,YAAYA,WAAU;AAAA,MAC7B;AAAA,IACF,GAAG,SAAM,WAAY;AAGnB,UAAI,cAAc,CAAC;AACnB,UAAI,gBAAgB,CAAC;AACrB,UAAI,eAAe,CAAC;AACpB,UAAI,mBAAmB,CAAC;AACxB,UAAI,mBAAmB,CAAC;AAQxB,eAAS,aAAc,MAAM;AAC3B,YAAI,OAAO,SAAS,UAAU;AAC5B,iBAAO,IAAI,OAAO,MAAM,OAAO,KAAK,GAAG;AAAA,QACzC;AAEA,eAAO;AAAA,MACT;AAUA,eAAS,YAAa,MAAM,OAAO;AAEjC,YAAI,SAAS;AAAO,iBAAO;AAG3B,YAAI,SAAS,KAAK,YAAY;AAAG,iBAAO,MAAM,YAAY;AAG1D,YAAI,SAAS,KAAK,YAAY;AAAG,iBAAO,MAAM,YAAY;AAG1D,YAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,YAAY,GAAG;AACrC,iBAAO,MAAM,OAAO,CAAC,EAAE,YAAY,IAAI,MAAM,OAAO,CAAC,EAAE,YAAY;AAAA,QACrE;AAGA,eAAO,MAAM,YAAY;AAAA,MA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EAAE;AAClB,SAAO;AAAA,IACL;AAAA,IACA,OAAO,CAAC,QAA6B,YACnC,UAAU,MAAM,KAAK,UAAU,OAAO,MAAM,CAAC,GAAG,OAAO;AAAA,EAC3D;AACF;",
|
|
6
|
+
"names": ["pluralize", "template", "join", "spinalcase", "pascalcase", "isEmpty", "isRef", "followRef", "methods", "lines", "camelcase", "followRef", "isRef", "isRef", "isEmpty", "import_pluralize", "HAS_MORE_POSITIVE_REGEX_PATTERNS", "COMPILED_HAS_MORE_POSITIVE_REGEXES", "HAS_MORE_INVERTED_REGEX_PATTERNS", "COMPILED_HAS_MORE_INVERTED_REGEXES", "pluralize", "isRef", "isEmpty", "methods", "isRef", "followRef", "camelcase", "forEachOperation", "isRef", "followRef", "security", "camelcase", "pascalcase", "spinalcase", "followRef", "isEmpty", "isRef", "followRef", "isRef", "camelcase", "isRef", "toLitObject", "cleanRef", "followRef", "isRef", "appendOptional", "followRef", "isRef", "securityToOptions", "security", "isRef", "followRef", "it", "exclude", "camelcase", "toLitObject", "schema", "isRef", "forEachOperation", "securityToOptions", "isEmpty", "isRef", "followRef", "pascalcase", "spinalcase", "acc", "camelcase", "it", "camelcase", "spinalcase", "followRef", "isEmpty", "isRef", "pascalcase", "followRef", "isRef", "pascalcase", "spinalcase", "isEmpty", "isRef", "followRef", "camelcase", "security", "securityToOptions", "join", "pascalcase", "spinalcase", "template"]
|
|
7
7
|
}
|