@sdk-it/typescript 0.22.1 → 0.24.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.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/generate.ts", "../src/lib/client.ts", "../src/lib/emitters/interface.ts", "../src/lib/generator.ts", "../src/lib/emitters/zod.ts", "../src/lib/sdk.ts", "../src/lib/status-map.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": ["import { template } from 'lodash-es';\nimport { readdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { methods, pascalcase, toLitObject } from '@sdk-it/core';\nimport {\n type WriteContent,\n createWriterProxy,\n getFolderExports,\n writeFiles,\n} from '@sdk-it/core/file-system.js';\nimport { toReadme } from '@sdk-it/readme';\nimport {\n type OurOpenAPIObject,\n augmentSpec,\n cleanFiles,\n readWriteMetadata,\n sanitizeTag,\n} from '@sdk-it/spec';\n\nimport backend from './client.ts';\nimport { TypeScriptEmitter } from './emitters/interface.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 type { Operation } from './sdk.ts';\nimport { TypeScriptGenerator } from './typescript-snippet.ts';\nimport { type MakeImportFn, 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(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\n// FIXME: there should not be default here\n// instead export this function from the cli package with\n// defaults for programmatic usage\nexport async function generate(\n openapi: OpenAPIObject,\n settings: TypeScriptGeneratorOptions,\n) {\n const spec = augmentSpec(\n { spec: openapi, responses: { flattenErrorResponses: true } },\n false,\n );\n \n const generator = new TypeScriptGenerator(spec, settings);\n const style = Object.assign(\n {},\n {\n errorAsValue: false,\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 const { writer, files: writtenFiles } = createWriterProxy(\n settings.writer ?? writeFiles,\n output,\n );\n settings.writer = writer;\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 { endpoints, groups, commonZod } = generateCode({\n spec,\n style,\n makeImport,\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 const inputs = toInputs(groups, commonZod, makeImport);\n const models = serializeModels(spec);\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(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 ...inputs,\n ...endpoints,\n });\n\n await settings.writer(output, models);\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 readWriteMetadata(output, Array.from(writtenFiles));\n if (settings.cleanup !== false && writtenFiles.size > 0) {\n await cleanFiles(metadata.content, output, [\n '/tsconfig*.json',\n '/package.json',\n '/metadata.json',\n '/**/index.ts',\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 getFolderExports(\n join(output, 'models'),\n settings.readFolder,\n settings.useTsExtension,\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 'models/index.ts': modelsIndex,\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\nfunction serializeModels(spec: OurOpenAPIObject) {\n const filesMap: Record<string, string[]> = {};\n const files: Record<string, string> = {};\n for (const [name, schema] of Object.entries(spec.components.schemas)) {\n // if (isRef(schema)) {\n // continue;\n // }\n const isResponseBody = (schema as any)['x-responsebody'];\n const isRequestBody = (schema as any)['x-requestbody'];\n const responseGroup = (schema as any)['x-response-group'];\n const stream = (schema as any)['x-stream'];\n // if (isRequestBody) {\n // // we do not generate interfaces for request bodies. we use zod for that.\n // continue;\n // }\n const folder = isResponseBody ? 'outputs' : 'models';\n let typeContent = 'ReadableStream';\n if (!stream) {\n const serializer = new TypeScriptEmitter(spec);\n typeContent = serializer.handle(schema, true);\n }\n\n const fileContent = [\n `\\n${schema.description ? `\\n/** \\n * ${schema.description}\\n */\\n` : ''}`,\n `export type ${pascalcase(sanitizeTag(name))} = ${typeContent};`,\n ];\n const fileName = responseGroup\n ? join(folder, `${spinalcase(responseGroup)}.ts`)\n : join(folder, `${spinalcase(name)}.ts`);\n filesMap[fileName] ??= [];\n filesMap[fileName].push(fileContent.join('\\n'));\n }\n\n for (const [group, contents] of Object.entries(filesMap)) {\n let fileContent = contents.join('\\n');\n if (fileContent.includes('models.')) {\n fileContent = `import type * as models from '../index.ts';\\n${fileContent}`;\n }\n files[group] = fileContent;\n }\n return files;\n}\n\nexport function toInputs(\n operationsSet: Record<string, Operation[]>,\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 for (const it of commonImports) {\n if (schema.includes(it)) {\n imports.add(\n `import { ${it} } from './schemas/${makeImport(spinalcase(it))}';`,\n );\n }\n }\n output.push(schema);\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 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", "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 type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, parseRef, pascalcase } from '@sdk-it/core';\nimport { isPrimitiveSchema, sanitizeTag } from '@sdk-it/spec';\n\nexport class TypeScriptEmitter {\n #spec: OpenAPIObject;\n\n constructor(spec: OpenAPIObject) {\n this.#spec = spec;\n }\n #stringifyKey = (value: string): string => {\n return `'${value}'`;\n };\n\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n return `${this.#stringifyKey(key)}: ${tsType}`;\n });\n\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.length > 1 ? `(${itemsType})[]` : `${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 = pascalcase(sanitizeTag(parseRef($ref).model));\n const schema = followRef(this.#spec, $ref);\n if (isPrimitiveSchema(schema)) {\n return this.handle(schema, required);\n }\n\n return `models.${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 oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const oneOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n return this.oneOf(schemas, required);\n }\n\n enum(values: unknown[], 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 return this.enum([schema.const], true);\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\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\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, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef, resolveRef } from '@sdk-it/core';\nimport { type OurOpenAPIObject, forEachOperation } from '@sdk-it/spec';\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 { importsToString, mergeImports, securityToOptions } 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(config: {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n spec: OurOpenAPIObject;\n style: Style;\n makeImport: (module: string) => string;\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 endpoints: Record<string, ReturnType<typeof toEndpoint>[]> = {};\n\n forEachOperation(config.spec, (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 = 'empty';\n\n for (const type in operation.requestBody.content) {\n let objectSchema = resolveRef(\n config.spec,\n operation.requestBody.content[type].schema,\n );\n\n if (type === 'application/empty') {\n // if empty body and not params then we need to set it to object with additional properties\n // to avoid unknown input ts errors.\n objectSchema = {\n type: 'object',\n // properties: objectSchema['x-properties'],\n additionalProperties: isEmpty(objectSchema['x-properties']),\n };\n // if (isEmpty(additionalProperties)) {\n // }\n } else {\n if (objectSchema.type !== 'object') {\n objectSchema = {\n type: 'object',\n required: [operation.requestBody.required ? '$body' : ''],\n properties: {\n $body: objectSchema,\n // ...objectSchema['x-properties'],\n },\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 >((acc, [, p]) => ({ ...acc, [p.name]: p.schema }), {}),\n });\n\n Object.assign(inputs, bodyInputs(config.spec, 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 }\n\n const endpoint = toEndpoint(\n entry.groupName,\n config.spec,\n operation,\n {\n outgoingContentType,\n name: operation.operationId,\n method: entry.method,\n path: entry.path,\n schemas,\n inputs: inputs,\n },\n { makeImport: config.makeImport, style: config.style },\n );\n\n endpoints[entry.groupName].push(endpoint);\n\n groups[entry.groupName].push({\n name: operation.operationId,\n inputs: inputs,\n outgoingContentType,\n schemas,\n method: entry.method,\n path: entry.path,\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 return {\n groups,\n commonZod,\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 * as outputs from '${config.makeImport('../outputs/index')}';`,\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 spec: OurOpenAPIObject,\n ctSchema: SchemaObject | ReferenceObject,\n) {\n const props: string[] = [];\n toProps(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 { followRef, isRef, parseRef, pascalcase } from '@sdk-it/core';\nimport { isPrimitiveSchema, sanitizeTag } from '@sdk-it/spec';\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 #array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\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})${this.#suffixes(JSON.stringify(schema.default), required, false)}`;\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 = pascalcase(sanitizeTag(parseRef($ref).model));\n const schema = followRef(this.#spec, $ref);\n\n if (isPrimitiveSchema(schema)) {\n const result = this.handle(schema, required);\n this.#onRef?.(schemaName, result);\n return result;\n }\n\n if (this.#generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.#generatedRefs.add(schemaName);\n this.#onRef?.(schemaName, this.handle(schema, required));\n\n return schemaName;\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 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 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\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\n\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n", "import type { OpenAPIObject, ResponseObject } from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport { isEmpty, pascalcase } from '@sdk-it/core';\nimport {\n type OperationPagination,\n type TunedOperationObject,\n isErrorStatusCode,\n isStreamingContentType,\n isSuccessStatusCode,\n isTextContentType,\n parseJsonContentType,\n sanitizeTag,\n} from '@sdk-it/spec';\n\nimport { TypeScriptEmitter } from './emitters/interface.ts';\nimport statusMap from './status-map.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, unknown>;\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 method: string;\n path: string;\n schemas: Record<string, string>;\n inputs: Record<string, OperationInput>;\n outgoingContentType?: string;\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 for (const status in specOperation.responses) {\n const handled = handleResponse(\n spec,\n operation.name,\n status,\n specOperation.responses[status],\n utils,\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.method.toUpperCase()} ${operation.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 const returnValue = `${style?.errorAsValue ? `[${style?.outputType === 'status' ? 'new http.Ok(pagination)' : 'pagination'}, null]` : `${style?.outputType === 'status' ? 'new http.Ok(pagination);' : 'pagination'}`}`;\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 ${returnValue}\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 ${returnValue}\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 ${returnValue}\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\nfunction handleResponse(\n spec: OpenAPIObject,\n operationName: string,\n status: string,\n response: ResponseObject,\n utils: { makeImport: MakeImportFn },\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(spec);\n const statusCode = +status;\n const statusName = `http.${statusMap[status] || 'APIResponse'}`;\n const interfaceName = pascalcase(sanitizeTag(response['x-response-name']));\n\n let parser: Parser = 'buffered';\n if (isEmpty(response.content)) {\n responses.push({\n name: interfaceName,\n schema: 'void',\n description: response.description,\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 } else {\n const contentTypeResult = fromContentType(\n spec,\n typeScriptDeserialzer,\n response,\n );\n if (!contentTypeResult) {\n throw new Error(\n `No recognizable content type for response ${status} in operation ${operationName}`,\n );\n }\n parser = contentTypeResult.parser;\n const responseSchema = contentTypeResult.responseSchema;\n responses.push({\n name: interfaceName,\n schema: responseSchema,\n description: response.description,\n });\n if (isErrorStatusCode(statusCode)) {\n endpointImports[statusMap[status] ?? 'APIError'] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [{ name: statusMap[status] ?? 'APIError' }],\n };\n // endpointImports[interfaceName] = {\n // isTypeOnly: true,\n // moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n // namedImports: [{ isTypeOnly: true, name: interfaceName }],\n // };\n } else if (isSuccessStatusCode(statusCode)) {\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 }\n\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n if (status.endsWith('XX')) {\n outputs.push(`http.APIError<outputs.${interfaceName}>`);\n } else {\n outputs.push(\n parser !== 'buffered'\n ? `{type: ${statusName}<outputs.${interfaceName}>, parser: ${parser}}`\n : `${statusName}<outputs.${interfaceName}>`,\n );\n }\n }\n\n return { schemas, imports, endpointImports, responses, outputs };\n}\n\nfunction fromContentType(\n spec: OpenAPIObject,\n typeScriptDeserialzer: TypeScriptEmitter,\n response: ResponseObject,\n) {\n if ((response.headers ?? {})['Transfer-Encoding']) {\n return streamedOutput();\n }\n for (const type in response.content) {\n if (isStreamingContentType(type)) {\n return streamedOutput();\n }\n if (parseJsonContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n if (isTextContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n }\n return streamedOutput();\n}\n\nfunction streamedOutput() {\n return {\n parser: 'chunked' as const,\n responseSchema: 'ReadableStream',\n };\n}\n", "export default {\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 '412': 'PreconditionFailed',\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} as Record<string, string>;\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 PreconditionFailed<T = { message: string }> extends APIError<T, 412> {\n static override readonly kind = Symbol.for('PreconditionFailed');\n static override status = 412 as const;\n constructor(data: T) {\n super(PreconditionFailed.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 PreconditionFailed)['kind'] }>(\n value: unknown,\n ): value is T {\n return (\n typeof value === 'object' &&\n value !== null &&\n KIND in value &&\n value[KIND] === this.kind\n );\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<unknown>\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 | PreconditionFailed<unknown>\n | PayloadTooLarge<unknown>\n | UnsupportedMediaType<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;", "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 { ResponseObject, SchemaObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { isEmpty, pascalcase, resolveRef } from '@sdk-it/core';\nimport {\n type OperationEntry,\n type OperationPagination,\n type OurOpenAPIObject,\n type TunedOperationObject,\n patchParameters,\n securityToOptions,\n} from '@sdk-it/spec';\n\nimport { SnippetEmitter } from './emitters/snippet.ts';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\n\nexport class TypeScriptGenerator {\n #spec: OurOpenAPIObject;\n #settings: TypeScriptGeneratorOptions;\n #snippetEmitter: SnippetEmitter;\n #clientName: string;\n #packageName: string;\n constructor(spec: OurOpenAPIObject, 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 const schema = resolveRef(\n this.#spec,\n operation.requestBody.content[contentTypes[0]].schema,\n );\n\n const examplePayload = this.#snippetEmitter.handle({\n ...schema,\n properties: Object.assign({}, schema.properties, schema.properties),\n });\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as Record<string, unknown>,\n values.requestBody ?? {},\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = examplePayload as any;\n } else {\n const requestBody: SchemaObject = { type: 'object', properties: {} };\n patchParameters(\n this.#spec,\n requestBody,\n operation.parameters,\n operation.security ?? [],\n );\n const examplePayload = this.#snippetEmitter.handle(requestBody);\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as Record<string, unknown>,\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = examplePayload as any;\n }\n payload = JSON.stringify(\n payload,\n (key, value) => {\n if (value?.startsWith && value.startsWith('new')) {\n return `__REPLACE_${Math.random().toString(36).substring(2, 11)}__${value}__REPLACE_END__`;\n }\n return value;\n },\n 2,\n ).replace(/\"__REPLACE_[^\"]*__([^\"]*?)__REPLACE_END__\"/g, '$1');\n\n let successResponse: ResponseObject | undefined;\n for (const status in operation.responses) {\n if (status.startsWith('2')) {\n successResponse = operation.responses[status] as ResponseObject;\n break;\n }\n }\n\n if (successResponse) {\n if (successResponse.headers?.['Transfer-Encoding']) {\n return this.#httpStreaming(entry, payload);\n }\n if (\n successResponse.content &&\n successResponse.content['application/octet-stream']\n ) {\n return this.#streamDownload(entry, payload);\n }\n }\n\n if (!isEmpty(operation['x-pagination'])) {\n return this.#pagination(operation, entry, payload);\n }\n return this.#normal(entry, payload);\n }\n\n #pagination(\n opeartion: TunedOperationObject,\n entry: OperationEntry,\n payload: string,\n ) {\n const pagination: OperationPagination = opeartion['x-pagination'];\n switch (pagination.type) {\n case 'page':\n return {\n content: `const result = ${this.#ddd(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\tconsole.log(page);\\n}`,\n };\n case 'offset':\n return {\n content: `const result = ${this.#ddd(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\tconsole.log(page);\\n}`,\n };\n case 'cursor':\n return {\n content: `const result = ${this.#ddd(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\tconsole.log(page);\\n}`,\n };\n }\n return this.#normal(entry, payload);\n }\n\n #normal(entry: OperationEntry, payload: string) {\n return {\n content: `const result = ${this.#ddd(entry, payload)};`,\n footer: 'console.log(result.data)',\n };\n }\n\n #streamDownload(entry: OperationEntry, payload: string) {\n return {\n content: `const stream = ${this.#ddd(entry, payload)}`,\n footer: `await writeFile('./report.pdf', stream);`,\n };\n }\n\n #httpStreaming(entry: OperationEntry, payload: string) {\n return {\n content: `const stream = ${this.#ddd(entry, payload)}`,\n footer: `for await (const chunk of stream) {\\n\\tconsole.log(chunk);\\n}`,\n };\n }\n\n #ddd(entry: OperationEntry, payload: string) {\n return `await ${camelcase(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload});`;\n }\n\n snippet(\n entry: OperationEntry,\n operation: TunedOperationObject,\n config: Record<string, unknown> = {},\n ) {\n const payload = this.succinct(entry, operation, config);\n const content: string[] = [\n this.client(),\n '',\n payload.content,\n '',\n payload.footer,\n ];\n if (config.frame !== false) {\n content.unshift('```typescript');\n content.push('```');\n }\n return content.join('\\n');\n }\n\n #authentication() {\n return securityToOptions(\n this.#spec,\n this.#spec.security ?? [],\n this.#spec.components?.securitySchemes ?? {},\n );\n }\n\n client() {\n const inputs = [\n `baseUrl: '${this.#spec.servers?.[0]?.url ?? 'http://localhost:3000'}'`,\n ];\n const authOptions = this.#authentication();\n if (!isEmpty(authOptions)) {\n const [firstAuth] = authOptions;\n inputs.push(`${firstAuth.name}: ${firstAuth.example}`);\n }\n return `import { ${this.#clientName} } from '${this.#packageName}';\n\nconst ${camelcase(this.#clientName)} = new ${this.#clientName}({ \\n\\t${inputs.join(',\\n\\t')}\\n});`;\n }\n}\n\nexport function generateSnippet(\n spec: OurOpenAPIObject,\n settings: TypeScriptGeneratorOptions,\n entry: OperationEntry,\n operation: TunedOperationObject,\n config: Record<string, unknown> = {},\n): string {\n const generator = new TypeScriptGenerator(spec, settings);\n return generator.snippet(entry, operation, config);\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 `new Blob(['example'], { type: 'text/plain' })`;\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,SAAS,YAAAA,iBAAgB;AACzB,SAAS,eAA0B;AACnC,SAAS,QAAAC,aAAY;AACrB,SAAS,qBAAqB;AAE9B,SAAS,aAAAC,YAAW,cAAAC,mBAAkB;AAEtC,SAAS,SAAS,cAAAC,aAAY,eAAAC,oBAAmB;AACjD;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AACzB;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,OACK;;;ACrBP,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,EAC3C;AAAA,IACC,CAAC,CAAC,KAAK,KAAK,MACV,GAAG,GAAG,kBAAkB,MAAM,aAAa,IAAI,MAAM,UAAU,MAAM,GAAG;AAAA,EAC5E,EACC,KAAK,KAAK,CAAC;AACd,QAAM,gBAAgB,IAAI,eACvB,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,MAAM,OAAO,OAAO,EAC1C;AAAA,IACC,CAAC,CAAC,KAAK,KAAK,MACV,GAAG,GAAG,kBAAkB,MAAM,aAAa,IAAI,MAAM,UAAU,MAAM,GAAG;AAAA,EAC5E,EACC,KAAK,KAAK,CAAC;AACd,QAAM,cAAkD;AAAA,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AW,MAAM;AACjD,eAAO;AAAA,UACL,YAAYA,OAAM,cAAc,WAAWL,YAAWK,OAAM,CAAC,CAAC;AAAA,QAChE;AAAA,MACF;AAAA,IACF;AACA,WAAO,KAAK,OAAO;AACnB,WAAO;AAAA,MACL,CAAC,kBAAkBL,YAAW,IAAI,CAAC,OAAO,OAAO,KAAK,IAAI,CAAC;AAAA,MAC3D,GAAG;AAAA,IACL;AAAA,EACF,GAAG,CAAC,CAAC;AAEP,SAAO;AAAA,IACL,GAAG,OAAO,YAAY,OAAO;AAAA,IAC7B,GAAG;AAAA,EACL;AACF;",
6
- "names": ["template", "join", "camelcase", "spinalcase", "pascalcase", "toLitObject", "sanitizeTag", "camelcase", "followRef", "isEmpty", "isRef", "followRef", "isRef", "parseRef", "pascalcase", "isPrimitiveSchema", "sanitizeTag", "appendOptional", "pascalcase", "sanitizeTag", "followRef", "isRef", "security", "isRef", "followRef", "it", "pascalcase", "sanitizeTag", "isEmpty", "camelcase", "it", "isRef", "followRef", "camelcase", "spinalcase", "isEmpty", "pascalcase", "resolveRef", "securityToOptions", "followRef", "isRef", "pascalcase", "spinalcase", "isEmpty", "resolveRef", "camelcase", "securityToOptions", "security", "join", "pascalcase", "spinalcase", "template", "sanitizeTag", "camelcase", "toLitObject", "schema"]
3
+ "sources": ["../src/lib/generate.ts", "../src/lib/client.ts", "../src/lib/emitters/zod.ts", "../src/lib/emitters/interface.ts", "../src/lib/generator.ts", "../src/lib/import-utilities.ts", "../src/lib/sdk.ts", "../src/lib/status-map.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": ["import { template } from 'lodash-es';\nimport { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { methods, pascalcase, toLitObject } from '@sdk-it/core';\nimport {\n type WriteContent,\n createWriterProxy,\n getFolderExports,\n writeFiles,\n} from '@sdk-it/core/file-system.js';\nimport { toReadme } from '@sdk-it/readme';\nimport {\n type OurOpenAPIObject,\n augmentSpec,\n cleanFiles,\n readWriteMetadata,\n sanitizeTag,\n securityToOptions,\n} from '@sdk-it/spec';\n\nimport backend from './client.ts';\nimport { TypeScriptEmitter } from './emitters/interface.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 MakeImportFn } from './import-utilities.ts';\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 type { Operation } from './sdk.ts';\nimport { TypeScriptGenerator } from './typescript-snippet.ts';\n\nfunction security(spec: OurOpenAPIObject) {\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\n// FIXME: there should not be default here\n// instead export this function from the cli package with\n// defaults for programmatic usage\nexport async function generate(\n openapi: OpenAPIObject,\n settings: TypeScriptGeneratorOptions,\n) {\n const spec = augmentSpec(\n {\n spec: openapi,\n responses: { flattenErrorResponses: true },\n pagination: settings.pagination,\n },\n false,\n );\n\n const generator = new TypeScriptGenerator(spec, settings);\n const style = Object.assign(\n {},\n {\n errorAsValue: false,\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 settings.readme ??= true;\n const { writer, files: writtenFiles } = createWriterProxy(\n settings.writer ?? writeFiles,\n output,\n );\n settings.writer = writer;\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 { endpoints, groups, commonZod } = generateCode({\n spec,\n style,\n makeImport,\n });\n\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 const inputs = toInputs(groups, commonZod, makeImport);\n const models = serializeModels(spec);\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(output, {\n 'client.ts': backend(\n {\n name: clientName,\n servers: (spec.servers ?? []).map((server) => server.url) || [],\n options: security(spec),\n makeImport,\n },\n style,\n ),\n ...inputs,\n ...endpoints,\n });\n\n await settings.writer(output, models);\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 readWriteMetadata(output, Array.from(writtenFiles));\n if (settings.cleanup !== false && writtenFiles.size > 0) {\n await cleanFiles(metadata.content, output, [\n '/tsconfig*.json',\n '/package.json',\n '/metadata.json',\n '/**/index.ts',\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 getFolderExports(\n join(output, 'models'),\n settings.readFolder,\n settings.useTsExtension,\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 'models/index.ts': modelsIndex,\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'] = toReadme(spec, {\n generateSnippet: (...args) => generator.snippet(...args),\n });\n }\n await settings.writer(settings.output, configFiles);\n }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n}\n\nfunction serializeModels(spec: OurOpenAPIObject) {\n const filesMap: Record<string, string[]> = {};\n const files: Record<string, string> = {};\n for (const [name, schema] of Object.entries(spec.components.schemas)) {\n // if (isRef(schema)) {\n // continue;\n // }\n const isResponseBody = (schema as any)['x-responsebody'];\n const isRequestBody = (schema as any)['x-requestbody'];\n const responseGroup = (schema as any)['x-response-group'];\n const stream = (schema as any)['x-stream'];\n if (isRequestBody) {\n // we do not generate interfaces for request bodies. we use zod for that.\n // bewary that the sometimes request body content schema is used as model somewhere else.\n // so we need to till the augmenter to create completeley separate model for request body suffixed by `Input`\n continue;\n }\n const folder = isResponseBody ? 'outputs' : 'models';\n let typeContent = 'ReadableStream';\n if (!stream) {\n const serializer = new TypeScriptEmitter(spec);\n typeContent = serializer.handle(schema, true);\n }\n\n const fileContent = [\n `\\n${schema.description ? `\\n/** \\n * ${schema.description}\\n */\\n` : ''}`,\n `export type ${pascalcase(sanitizeTag(name))} = ${typeContent};`,\n ];\n const fileName = responseGroup\n ? join(folder, `${spinalcase(responseGroup)}.ts`)\n : join(folder, `${spinalcase(name)}.ts`);\n filesMap[fileName] ??= [];\n filesMap[fileName].push(fileContent.join('\\n'));\n }\n\n for (const [group, contents] of Object.entries(filesMap)) {\n let fileContent = contents.join('\\n');\n if (fileContent.includes('models.')) {\n fileContent = `import type * as models from '../index.ts';\\n${fileContent}`;\n }\n files[group] = fileContent;\n }\n return files;\n}\n\nexport function toInputs(\n operationsSet: Record<string, Operation[]>,\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 for (const it of commonImports) {\n if (schema.includes(it)) {\n imports.add(\n `import { ${it} } from './schemas/${makeImport(spinalcase(it))}';`,\n );\n }\n }\n output.push(schema);\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 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", "import { toLitObject } from '@sdk-it/core';\n\nimport { toZod } from './emitters/zod.ts';\nimport type { Spec } from './sdk.ts';\nimport type { Style } from './style.ts';\n\nexport default (spec: Omit<Spec, 'operations'>, style: Style) => {\n const defaultHeaders = `{${spec.options\n .filter((value) => value.in === 'header')\n .map(\n (value) =>\n `'${value.name}': this.options['${value['x-optionName'] ?? value.name}']`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${spec.options\n .filter((value) => value.in === 'input')\n .map(\n (value) =>\n `'${value.name}': this.options['${value['x-optionName'] ?? value.name}']`,\n )\n .join(',\\n')}}`;\n const specOptions: Record<string, { schema: string }> = {\n ...Object.fromEntries(\n spec.options.map((value) => [\n `'${value['x-optionName'] ?? value.name}'`,\n { schema: toZod(value.schema, value.required) },\n ]),\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 type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, parseRef, pascalcase } from '@sdk-it/core';\nimport { isPrimitiveSchema, sanitizeTag } from '@sdk-it/spec';\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 #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 #array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\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})${this.#suffixes(JSON.stringify(schema.default), required, false)}`;\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 = pascalcase(sanitizeTag(parseRef($ref).model));\n const schema = followRef(this.#spec, $ref);\n\n if (isPrimitiveSchema(schema)) {\n const result = this.handle(schema, required);\n this.#onRef?.(schemaName, result);\n return result;\n }\n\n if (this.#generatedRefs.has(schemaName)) {\n return schemaName;\n }\n this.#generatedRefs.add(schemaName);\n this.#onRef?.(schemaName, this.handle(schema, required));\n\n return schemaName;\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 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 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\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\n\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined || typeof defaultValue !== 'undefined'\n ? `.default(${defaultValue})`\n : '';\n}\n\nexport function toZod(schema: SchemaObject, required?: boolean): string {\n const emitter = new ZodEmitter({} as OpenAPIObject);\n const schemaStr = emitter.handle(schema, required ?? false);\n if (schema['x-prefix']) {\n const prefix = schema['x-prefix'];\n if (required === false) {\n return (\n schemaStr +\n `.transform((val) => (val ? \\`${prefix}\\${val}\\` : undefined))`\n );\n } else {\n return schemaStr + `.transform((val) => \\`${prefix}\\${val}\\`)`;\n }\n }\n return schemaStr;\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { followRef, isRef, parseRef, pascalcase } from '@sdk-it/core';\nimport { isPrimitiveSchema, sanitizeTag } from '@sdk-it/spec';\n\nexport class TypeScriptEmitter {\n #spec: OpenAPIObject;\n\n constructor(spec: OpenAPIObject) {\n this.#spec = spec;\n }\n #stringifyKey = (value: string): string => {\n return `'${value}'`;\n };\n\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n return `${this.#stringifyKey(key)}: ${tsType}`;\n });\n\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.length > 1 ? `(${itemsType})[]` : `${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 = pascalcase(sanitizeTag(parseRef($ref).model));\n const schema = followRef(this.#spec, $ref);\n if (isPrimitiveSchema(schema)) {\n return this.handle(schema, required);\n }\n\n return `models.${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 oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const oneOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n return this.oneOf(schemas, required);\n }\n\n enum(values: unknown[], 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 return this.enum([schema.const], true);\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\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import { merge, template } from 'lodash-es';\nimport { join } from 'node:path';\nimport type {\n OpenAPIObject,\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { followRef, isEmpty, isRef, resolveRef } from '@sdk-it/core';\nimport { type OurOpenAPIObject, forEachOperation } from '@sdk-it/spec';\n\nimport { ZodEmitter } from './emitters/zod.ts';\nimport { importsToString, mergeImports } from './import-utilities.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';\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(config: {\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n spec: OurOpenAPIObject;\n style: Style;\n makeImport: (module: string) => string;\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 endpoints: Record<string, ReturnType<typeof toEndpoint>[]> = {};\n\n forEachOperation(config.spec, (entry, operation) => {\n console.log(`Processing ${entry.method} ${entry.path}`);\n groups[entry.groupName] ??= [];\n endpoints[entry.groupName] ??= [];\n const inputs: Operation['inputs'] = {};\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 = 'empty';\n\n for (const type in operation.requestBody.content) {\n let objectSchema = resolveRef(\n config.spec,\n operation.requestBody.content[type].schema,\n );\n const xProperties: Record<string, SchemaObject> =\n objectSchema['x-properties'] ?? {};\n const xRequired: string[] = objectSchema['x-required'] ?? [];\n\n if (type === 'application/empty') {\n // if empty body and not params then we need to set it to object with additional properties\n // to avoid unknown input ts errors.\n objectSchema = {\n type: 'object',\n additionalProperties: isEmpty(xProperties),\n };\n } else {\n if (objectSchema.type !== 'object') {\n objectSchema = {\n type: 'object',\n required: [operation.requestBody.required ? '$body' : ''],\n properties: {\n $body: objectSchema,\n },\n };\n }\n }\n const additionalProperties: Record<string, ParameterObject> = {};\n for (const [name, prop] of Object.entries(xProperties)) {\n additionalProperties[name] = {\n name: name,\n required: xRequired?.includes(name),\n schema: prop,\n in: prop['x-in'],\n };\n inputs[name] = {\n in: prop['x-in'],\n schema: '',\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 (acc, [, p]) => ({ ...acc, [p.name]: p.schema }),\n {},\n ),\n });\n\n Object.assign(inputs, bodyInputs(config.spec, 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 }\n\n const endpoint = toEndpoint(\n entry.groupName,\n config.spec,\n operation,\n {\n outgoingContentType,\n name: operation.operationId,\n method: entry.method,\n path: entry.path,\n schemas,\n inputs: inputs,\n },\n { makeImport: config.makeImport, style: config.style },\n );\n\n endpoints[entry.groupName].push(endpoint);\n\n groups[entry.groupName].push({\n name: operation.operationId,\n inputs: inputs,\n outgoingContentType,\n schemas,\n method: entry.method,\n path: entry.path,\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 return {\n groups,\n commonZod,\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 * as outputs from '${config.makeImport('../outputs/index')}';`,\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 spec: OurOpenAPIObject,\n ctSchema: SchemaObject | ReferenceObject,\n) {\n const props: string[] = [];\n toProps(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 { removeDuplicates } from '@sdk-it/core';\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 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", "import type { OpenAPIObject, ResponseObject } from 'openapi3-ts/oas31';\nimport { camelcase } from 'stringcase';\n\nimport { isEmpty, pascalcase } from '@sdk-it/core';\nimport {\n type OperationPagination,\n type OurParameter,\n type TunedOperationObject,\n isErrorStatusCode,\n isStreamingContentType,\n isSuccessStatusCode,\n isTextContentType,\n parseJsonContentType,\n sanitizeTag,\n} from '@sdk-it/spec';\n\nimport { TypeScriptEmitter } from './emitters/interface.ts';\nimport { type Import, type MakeImportFn } from './import-utilities.ts';\nimport statusMap from './status-map.ts';\nimport type { Style } from './style.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, unknown>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport interface Spec {\n name: string;\n options: OurParameter[];\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 method: string;\n path: string;\n schemas: Record<string, string>;\n inputs: Record<string, OperationInput>;\n outgoingContentType?: string;\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 for (const status in specOperation.responses) {\n const handled = handleResponse(\n spec,\n operation.name,\n status,\n specOperation.responses[status],\n utils,\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.method.toUpperCase()} ${operation.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 const returnValue = `${style?.errorAsValue ? `[${style?.outputType === 'status' ? 'new http.Ok(pagination)' : 'pagination'}, null]` : `${style?.outputType === 'status' ? 'new http.Ok(pagination);' : 'pagination'}`}`;\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 ${returnValue}\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 ${returnValue}\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 ${returnValue}\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\nfunction handleResponse(\n spec: OpenAPIObject,\n operationName: string,\n status: string,\n response: ResponseObject,\n utils: { makeImport: MakeImportFn },\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(spec);\n const statusCode = +status;\n const statusName = `http.${statusMap[status] || 'APIResponse'}`;\n const interfaceName = pascalcase(sanitizeTag(response['x-response-name']));\n\n let parser: Parser = 'buffered';\n if (isEmpty(response.content)) {\n responses.push({\n name: interfaceName,\n schema: 'void',\n description: response.description,\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 } else {\n const contentTypeResult = fromContentType(\n spec,\n typeScriptDeserialzer,\n response,\n );\n if (!contentTypeResult) {\n throw new Error(\n `No recognizable content type for response ${status} in operation ${operationName}`,\n );\n }\n parser = contentTypeResult.parser;\n const responseSchema = contentTypeResult.responseSchema;\n responses.push({\n name: interfaceName,\n schema: responseSchema,\n description: response.description,\n });\n if (isErrorStatusCode(statusCode)) {\n endpointImports[statusMap[status] ?? 'APIError'] = {\n moduleSpecifier: utils.makeImport('../http/response'),\n namedImports: [{ name: statusMap[status] ?? 'APIError' }],\n };\n // endpointImports[interfaceName] = {\n // isTypeOnly: true,\n // moduleSpecifier: `../outputs/${utils.makeImport(spinalcase(operationName))}`,\n // namedImports: [{ isTypeOnly: true, name: interfaceName }],\n // };\n } else if (isSuccessStatusCode(statusCode)) {\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 }\n\n if (statusCode === 204) {\n outputs.push(statusName);\n } else {\n if (status.endsWith('XX')) {\n outputs.push(`http.APIError<outputs.${interfaceName}>`);\n } else {\n outputs.push(\n parser !== 'buffered'\n ? `{type: ${statusName}<outputs.${interfaceName}>, parser: ${parser}}`\n : `${statusName}<outputs.${interfaceName}>`,\n );\n }\n }\n\n return { schemas, imports, endpointImports, responses, outputs };\n}\n\nfunction fromContentType(\n spec: OpenAPIObject,\n typeScriptDeserialzer: TypeScriptEmitter,\n response: ResponseObject,\n) {\n if ((response.headers ?? {})['Transfer-Encoding']) {\n return streamedOutput();\n }\n for (const type in response.content) {\n if (isStreamingContentType(type)) {\n return streamedOutput();\n }\n if (parseJsonContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n if (isTextContentType(type)) {\n return {\n parser: 'buffered' as const,\n responseSchema: response.content[type].schema\n ? typeScriptDeserialzer.handle(response.content[type].schema, true)\n : 'void',\n };\n }\n }\n return streamedOutput();\n}\n\nfunction streamedOutput() {\n return {\n parser: 'chunked' as const,\n responseSchema: 'ReadableStream',\n };\n}\n", "export default {\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 '412': 'PreconditionFailed',\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} as Record<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 PreconditionFailed<T = { message: string }> extends APIError<T, 412> {\n static override readonly kind = Symbol.for('PreconditionFailed');\n static override status = 412 as const;\n constructor(data: T) {\n super(PreconditionFailed.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 PreconditionFailed)['kind'] }>(\n value: unknown,\n ): value is T {\n return (\n typeof value === 'object' &&\n value !== null &&\n KIND in value &&\n value[KIND] === this.kind\n );\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<unknown>\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 | PreconditionFailed<unknown>\n | PayloadTooLarge<unknown>\n | UnsupportedMediaType<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;", "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 { ResponseObject, SchemaObject } from 'openapi3-ts/oas31';\nimport { camelcase, spinalcase } from 'stringcase';\n\nimport { isEmpty, pascalcase, resolveRef } from '@sdk-it/core';\nimport {\n type OperationEntry,\n type OperationPagination,\n type OurOpenAPIObject,\n type TunedOperationObject,\n patchParameters,\n securityToOptions,\n} from '@sdk-it/spec';\n\nimport { SnippetEmitter } from './emitters/snippet.ts';\nimport type { TypeScriptGeneratorOptions } from './options.ts';\n\nexport class TypeScriptGenerator {\n #spec: OurOpenAPIObject;\n #settings: TypeScriptGeneratorOptions;\n #snippetEmitter: SnippetEmitter;\n #clientName: string;\n #packageName: string;\n constructor(spec: OurOpenAPIObject, 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 const schema = resolveRef(\n this.#spec,\n operation.requestBody.content[contentTypes[0]].schema,\n );\n\n const examplePayload = this.#snippetEmitter.handle({\n ...schema,\n properties: Object.assign({}, schema.properties, schema.properties),\n });\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as Record<string, unknown>,\n values.requestBody ?? {},\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = examplePayload as any;\n } else {\n const requestBody: SchemaObject = { type: 'object', properties: {} };\n patchParameters(\n this.#spec,\n requestBody,\n operation.parameters,\n operation.security ?? [],\n );\n const examplePayload = this.#snippetEmitter.handle(requestBody);\n // merge explicit values into the example payload\n Object.assign(\n examplePayload as Record<string, unknown>,\n values.pathParameters ?? {},\n values.queryParameters ?? {},\n values.headers ?? {},\n values.cookies ?? {},\n );\n payload = examplePayload as any;\n }\n payload = JSON.stringify(\n payload,\n (key, value) => {\n if (value?.startsWith && value.startsWith('new')) {\n return `__REPLACE_${Math.random().toString(36).substring(2, 11)}__${value}__REPLACE_END__`;\n }\n return value;\n },\n 2,\n ).replace(/\"__REPLACE_[^\"]*__([^\"]*?)__REPLACE_END__\"/g, '$1');\n\n let successResponse: ResponseObject | undefined;\n for (const status in operation.responses) {\n if (status.startsWith('2')) {\n successResponse = operation.responses[status] as ResponseObject;\n break;\n }\n }\n\n if (successResponse) {\n if (successResponse.headers?.['Transfer-Encoding']) {\n return this.#httpStreaming(entry, payload);\n }\n if (\n successResponse.content &&\n successResponse.content['application/octet-stream']\n ) {\n return this.#streamDownload(entry, payload);\n }\n }\n\n if (!isEmpty(operation['x-pagination'])) {\n return this.#pagination(operation, entry, payload);\n }\n return this.#normal(entry, payload);\n }\n\n #pagination(\n opeartion: TunedOperationObject,\n entry: OperationEntry,\n payload: string,\n ) {\n const pagination: OperationPagination = opeartion['x-pagination'];\n switch (pagination.type) {\n case 'page':\n return {\n content: `const result = ${this.#ddd(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\tconsole.log(page);\\n}`,\n };\n case 'offset':\n return {\n content: `const result = ${this.#ddd(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\tconsole.log(page);\\n}`,\n };\n case 'cursor':\n return {\n content: `const result = ${this.#ddd(entry, payload)}`,\n footer: `for await (const page of result) {\\n\\tconsole.log(page);\\n}`,\n };\n }\n return this.#normal(entry, payload);\n }\n\n #normal(entry: OperationEntry, payload: string) {\n return {\n content: `const result = ${this.#ddd(entry, payload)};`,\n footer: 'console.log(result.data)',\n };\n }\n\n #streamDownload(entry: OperationEntry, payload: string) {\n return {\n content: `const stream = ${this.#ddd(entry, payload)}`,\n footer: `await writeFile('./report.pdf', stream);`,\n };\n }\n\n #httpStreaming(entry: OperationEntry, payload: string) {\n return {\n content: `const stream = ${this.#ddd(entry, payload)}`,\n footer: `for await (const chunk of stream) {\\n\\tconsole.log(chunk);\\n}`,\n };\n }\n\n #ddd(entry: OperationEntry, payload: string) {\n return `await ${camelcase(this.#clientName)}.request('${entry.method.toUpperCase()} ${entry.path}', ${payload});`;\n }\n\n snippet(\n entry: OperationEntry,\n operation: TunedOperationObject,\n config: Record<string, unknown> = {},\n ) {\n const payload = this.succinct(entry, operation, config);\n const content: string[] = [\n this.client(),\n '',\n payload.content,\n '',\n payload.footer,\n ];\n if (config.frame !== false) {\n content.unshift('```typescript');\n content.push('```');\n }\n return content.join('\\n');\n }\n\n #authentication() {\n return securityToOptions(\n this.#spec,\n this.#spec.security ?? [],\n this.#spec.components?.securitySchemes ?? {},\n );\n }\n\n client() {\n const inputs = [\n `baseUrl: '${this.#spec.servers?.[0]?.url ?? 'http://localhost:3000'}'`,\n ];\n const authOptions = this.#authentication();\n if (!isEmpty(authOptions)) {\n const [firstAuth] = authOptions;\n inputs.push(\n `'${firstAuth['x-optionName'] ?? firstAuth.name}': ${firstAuth.example}`,\n );\n }\n return `import { ${this.#clientName} } from '${this.#packageName}';\n\nconst ${camelcase(this.#clientName)} = new ${this.#clientName}({ \\n\\t${inputs.join(',\\n\\t')}\\n});`;\n }\n}\n\nexport function generateSnippet(\n spec: OurOpenAPIObject,\n settings: TypeScriptGeneratorOptions,\n entry: OperationEntry,\n operation: TunedOperationObject,\n config: Record<string, unknown> = {},\n): string {\n const generator = new TypeScriptGenerator(spec, settings);\n return generator.snippet(entry, operation, config);\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 `new Blob(['example'], { type: 'text/plain' })`;\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,SAAS,YAAAA,iBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,QAAAC,aAAY;AACrB,SAAS,qBAAqB;AAE9B,SAAS,aAAAC,YAAW,cAAAC,mBAAkB;AAEtC,SAAS,SAAS,cAAAC,aAAY,eAAAC,oBAAmB;AACjD;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AACzB;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,qBAAAC;AAAA,OACK;;;ACtBP,SAAS,mBAAmB;;;ACM5B,SAAS,WAAW,OAAO,UAAU,kBAAkB;AACvD,SAAS,mBAAmB,mBAAmB;AAQxC,IAAM,aAAN,MAAiB;AAAA,EACtB,iBAAiB,oBAAI,IAAY;AAAA,EACjC;AAAA,EACA;AAAA,EAEA,YAAY,MAAqB,OAAuB;AACtD,SAAK,QAAQ;AACb,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,QAAQ,QAA8B;AACpC,UAAM,aAAa,OAAO,cAAc,CAAC;AAGzC,UAAM,cAAc,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,KAAK,UAAU,MAAM;AACxE,YAAM,cAAc,OAAO,YAAY,CAAC,GAAG,SAAS,GAAG;AACvD,aAAO,IAAI,GAAG,MAAM,KAAK,OAAO,YAAY,UAAU,CAAC;AAAA,IACzD,CAAC;AAED,QAAI,kBAAkB;AACtB,QAAI,OAAO,sBAAsB;AAC/B,UAAI,OAAO,OAAO,yBAAyB,UAAU;AAEnD,cAAM,aAAa,KAAK,OAAO,OAAO,sBAAsB,IAAI;AAChE,0BAAkB,aAAa,UAAU;AAAA,MAC3C,WAAW,OAAO,yBAAyB,MAAM;AAE/C,0BAAkB;AAAA,MACpB;AAAA,IACF;AAEA,WAAO,aAAa,YAAY,KAAK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I,IAAI;AAAA,EACzC;AAEA,QAAM,UAAU,UACb,QAAQ,EACR,OAAmB,CAAC,KAAK,CAAC,MAAM,MAAM,MAAM;AAC3C,UAAM,SAAS,CAAC,0BAA0B;AAC1C,UAAM,UAAU,gBAAgB,IAAI,MAAM,MAAM;AAChD,eAAWK,WAAU,eAAe;AAClC,YAAM,eAAe,IAAI,OAAO,MAAMA,OAAM,KAAK;AACjD,UAAI,aAAa,KAAK,OAAO,KAAKA,YAAW,MAAM;AACjD,eAAO;AAAA,UACL,YAAYA,OAAM,cAAc,WAAWL,YAAWK,OAAM,CAAC,CAAC;AAAA,QAChE;AAAA,MACF;AAAA,IACF;AACA,WAAO,KAAK,OAAO;AACnB,WAAO;AAAA,MACL,CAAC,kBAAkBL,YAAW,IAAI,CAAC,OAAO,OAAO,KAAK,IAAI,CAAC;AAAA,MAC3D,GAAG;AAAA,IACL;AAAA,EACF,GAAG,CAAC,CAAC;AAEP,SAAO;AAAA,IACL,GAAG,OAAO,YAAY,OAAO;AAAA,IAC7B,GAAG;AAAA,EACL;AACF;",
6
+ "names": ["template", "join", "camelcase", "spinalcase", "pascalcase", "toLitObject", "sanitizeTag", "securityToOptions", "followRef", "isRef", "parseRef", "pascalcase", "isPrimitiveSchema", "sanitizeTag", "appendOptional", "camelcase", "followRef", "isEmpty", "isRef", "it", "pascalcase", "sanitizeTag", "pascalcase", "sanitizeTag", "isEmpty", "camelcase", "it", "isRef", "followRef", "camelcase", "spinalcase", "isEmpty", "pascalcase", "resolveRef", "followRef", "isRef", "pascalcase", "spinalcase", "isEmpty", "resolveRef", "camelcase", "security", "securityToOptions", "join", "pascalcase", "spinalcase", "template", "sanitizeTag", "camelcase", "toLitObject", "schema"]
7
7
  }