From eece76db202e2884c1f3a661850dc5c804837d45 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 00:20:30 +0000 Subject: [PATCH 1/9] perf: cache compiled Eta templates Eta.render() recompiled the template on every call (once per route, model and include), which dominated generation time. Compile each template source once and reuse the function. ~2.4x faster on a 1500 schemas / 3000 operations spec (4.7s -> 2.0s), byte-identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- src/templates-worker.ts | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/templates-worker.ts b/src/templates-worker.ts index 9545f52..f58f780 100644 --- a/src/templates-worker.ts +++ b/src/templates-worker.ts @@ -237,6 +237,9 @@ class TemplatesWorker { /** * Renders a template (synchronously) with the base template data (`utils`, `config`) and `configuration`. */ + /** compiled templates, keyed by the template source */ + compiledTemplates = new Map>(); + renderTemplate = ( template: string | undefined | null, configuration: object = {}, @@ -245,20 +248,25 @@ class TemplatesWorker { if (!template) { return ''; } - return Eta.render( - template, + const etaConfig = Eta.getConfig({ + async: false, + ...options, + includeFile: (path: string, configuration?: object, options?: TemplateRenderOptions) => { + return this.renderTemplate(this.getTemplateContent(path), configuration, options); + }, + }); + let templateFn = this.compiledTemplates.get(template); + if (!templateFn) { + templateFn = Eta.compile(template, etaConfig); + this.compiledTemplates.set(template, templateFn); + } + return templateFn( { ...this.getRenderTemplateData(), ...configuration, }, - { - async: false, - ...options, - includeFile: (path: string, configuration?: object, options?: TemplateRenderOptions) => { - return this.renderTemplate(this.getTemplateContent(path), configuration, options); - }, - } - ); + etaConfig + ) as string; }; } From 26d47c9824dae192aa7ec273f67674a77baa54e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 00:36:57 +0000 Subject: [PATCH 2/9] perf: load typescript lazily, cache included templates, add benchmark - typescript is imported only when toJS is used (was ~400ms at startup) - included template files are read once per template paths - fix: explicit type for the compiled template cache (d.ts build failed) - npm run bench: benchmark of the built package on small / medium / large specs - tests for the caches, lazy typescript and cache isolation between generations CLI on a small spec: ~800ms -> ~400ms; 1500 schemas / 3000 operations: ~3.4s -> ~2.1s. Output unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- CHANGELOG.md | 8 ++ README.md | 1 + bench/generate-spec.mjs | 62 ++++++++++++ bench/index.mjs | 101 +++++++++++++++++++ package.json | 1 + src/code-gen-process.ts | 3 +- src/configuration.ts | 8 +- src/templates-worker.ts | 21 +++- src/translators/javascript.ts | 10 +- tests/core/performance-caches.test.ts | 135 ++++++++++++++++++++++++++ 10 files changed, 341 insertions(+), 9 deletions(-) create mode 100644 bench/generate-spec.mjs create mode 100644 bench/index.mjs create mode 100644 tests/core/performance-caches.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index aa2c166..96b0105 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,14 @@ - `primitiveTypeConstructs` without `$default` could produce `[object Object]` types. - `$ref` names containing "undefined" could resolve to the wrong schema for operations without `operationId`. +### ⚑ Performance + +- Compiled Eta templates are cached (they were recompiled for every route, model and include) and + included template files are read once. +- `typescript` is only loaded when `toJS` is used (~400ms less startup). +- CLI run on a small spec: ~800ms β†’ ~400ms; 1500 schemas / 3000 operations: ~3.4s β†’ ~2.1s + (`npm run bench`). The generated output is unchanged. + ### 🏎 Dependencies - Replaced `unprompts` with `cac` (drops `unbuild`/`esbuild` from runtime dependencies), `node-fetch-h2` with diff --git a/README.md b/README.md index 6834e86..b8d3657 100644 --- a/README.md +++ b/README.md @@ -774,6 +774,7 @@ npm install | `npm run fmt` | Format with oxfmt (`fmt:check` to check) | | `npm run typecheck` | `tsc --noEmit` | | `npm start` | Run the playground `play/test.ts` | +| `npm run bench` | Build, then benchmark generation on small / large specs | | `npm run test:cli` | Run the built CLI (`node dist/cli.mjs`) | | `npm run test:cli1` | Run the CLI from source (`tsx src/cli.ts`) | diff --git a/bench/generate-spec.mjs b/bench/generate-spec.mjs new file mode 100644 index 0000000..94e5927 --- /dev/null +++ b/bench/generate-spec.mjs @@ -0,0 +1,62 @@ +/** + * Synthetic OpenAPI 3 document: `schemas` object models (with enums, arrays, $refs, oneOf, nullable) + * and `operations` operations spread over 50 paths prefixes and 30 tags. + */ +export const generateSpec = ({ schemas = 1500, operations = 3000 } = {}) => { + const componentsSchemas = {}; + for (let i = 0; i < schemas; i++) { + componentsSchemas[`Model${i}`] = { + type: 'object', + required: ['id', 'name'], + properties: { + id: { type: 'integer', format: 'int64' }, + name: { type: 'string', description: `name ${i}` }, + status: { type: 'string', enum: ['a', 'b', 'c'] }, + tags: { type: 'array', items: { type: 'string' } }, + nested: + i > 0 + ? { $ref: `#/components/schemas/Model${i - 1}` } + : { type: 'object', additionalProperties: true }, + createdAt: { type: 'string', format: 'date-time', nullable: true }, + ...(i % 5 === 0 + ? { + poly: { + oneOf: [ + { $ref: `#/components/schemas/Model${Math.max(0, i - 2)}` }, + { type: 'string' }, + ], + }, + } + : {}), + }, + }; + } + + const paths = {}; + for (let j = 0; j < operations / 2; j++) { + const ref = { $ref: `#/components/schemas/Model${j % schemas}` }; + const id = { name: 'id', in: 'path', required: true, schema: { type: 'integer' } }; + paths[`/res${j % 50}/items${j}/{id}`] = { + get: { + tags: [`tag${j % 30}`], + operationId: `get${j}`, + parameters: [id, { name: 'q', in: 'query', schema: { type: 'string' } }], + responses: { 200: { description: 'ok', content: { 'application/json': { schema: ref } } } }, + }, + post: { + tags: [`tag${j % 30}`], + operationId: `post${j}`, + parameters: [id], + requestBody: { required: true, content: { 'application/json': { schema: ref } } }, + responses: { 201: { description: 'ok', content: { 'application/json': { schema: ref } } } }, + }, + }; + } + + return { + openapi: '3.0.3', + info: { title: 'bench', version: '1.0.0' }, + paths, + components: { schemas: componentsSchemas }, + }; +}; diff --git a/bench/index.mjs b/bench/index.mjs new file mode 100644 index 0000000..ec0eef4 --- /dev/null +++ b/bench/index.mjs @@ -0,0 +1,101 @@ +/** + * Generation benchmark of the built library (`npm run bench` builds first). + * + * node bench/index.mjs [--runs 5] [--filter small] + * + * Prints the median / min time of each scenario and the import time of the package. + */ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { generateSpec } from './generate-spec.mjs'; + +const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const entry = pathToFileURL(path.join(rootDir, 'dist/index.mjs')).href; + +const args = process.argv.slice(2); +const argValue = (name, fallback) => { + const index = args.indexOf(`--${name}`); + return index === -1 ? fallback : args[index + 1]; +}; +const runs = Number(argValue('runs', 5)); +const filter = argValue('filter', ''); + +const petstore = JSON.parse( + fs.readFileSync(path.join(rootDir, 'tests/fixtures/petstore.json'), 'utf8') +); +const medium = generateSpec({ schemas: 300, operations: 600 }); +const large = generateSpec({ schemas: 1500, operations: 3000 }); + +const scenarios = [ + { name: 'petstore (small)', spec: petstore }, + { name: 'petstore modular', spec: petstore, options: { modular: true } }, + { name: 'petstore toJS', spec: petstore, options: { toJS: true } }, + { name: 'medium 300 schemas / 600 ops', spec: medium }, + { name: 'large 1500 schemas / 3000 ops', spec: large }, + { name: 'large modular', spec: large, options: { modular: true } }, + { + name: 'large extract* + route types', + spec: large, + options: { extractRequestParams: true, extractEnums: true, generateRouteTypes: true }, + }, +].filter((scenario) => scenario.name.includes(filter)); + +const importTime = () => { + const code = `const t = performance.now(); await import(${JSON.stringify(entry)}); process.stdout.write(String(performance.now() - t));`; + const times = Array.from({ length: runs }, () => { + const { stdout } = spawnSync(process.execPath, ['--input-type=module', '-e', code], { + encoding: 'utf8', + }); + return Number(stdout); + }); + return times; +}; + +const stats = (times) => { + const sorted = [...times].sort((a, b) => a - b); + return { median: sorted[Math.floor(sorted.length / 2)], min: sorted[0] }; +}; + +const format = (ms) => `${ms.toFixed(0).padStart(6)} ms`; + +const main = async () => { + const { generateApi } = await import(entry); + const rows = []; + + const imports = stats(importTime()); + rows.push({ name: 'import package (cold, new process)', ...imports, output: '' }); + + for (const scenario of scenarios) { + const times = []; + let outputSize = 0; + // one warm-up run (JIT), not measured + await generateApi({ spec: scenario.spec, output: false, silent: true, ...scenario.options }); + for (let i = 0; i < runs; i++) { + const start = performance.now(); + const result = await generateApi({ + spec: structuredClone(scenario.spec), + output: false, + silent: true, + ...scenario.options, + }); + times.push(performance.now() - start); + outputSize = result.files.reduce((size, file) => size + file.fileContent.length, 0); + } + rows.push({ + name: scenario.name, + ...stats(times), + output: `${(outputSize / 1024).toFixed(0)} KB`, + }); + } + + console.log(`node ${process.version}, ${runs} runs per scenario\n`); + console.log(`${'scenario'.padEnd(38)}${'median'.padStart(9)}${'min'.padStart(10)} output`); + for (const row of rows) { + console.log(`${row.name.padEnd(38)}${format(row.median)} ${format(row.min)} ${row.output}`); + } +}; + +await main(); diff --git a/package.json b/package.json index 1b2f9a1..a3e6796 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "start": "tsx play/test.ts", "test": "vitest", "test:coverage": "vitest run --coverage", + "bench": "npm run build && node bench/index.mjs", "changelog": "npx changeloggithub@latest --all true && git add CHANGELOG.md && git commit -m 'chore: update CHANGELOG.md'", "prepublishOnly": "npm run build", "release": "bumpp -r && npm publish" diff --git a/src/code-gen-process.ts b/src/code-gen-process.ts index 67bb321..d52525e 100644 --- a/src/code-gen-process.ts +++ b/src/code-gen-process.ts @@ -20,7 +20,6 @@ import { values, } from 'lodash-es'; import pc from 'picocolors'; -import ts from 'typescript'; import { CodeFormatter } from './code-formatter'; import { CodeGenConfig } from './configuration.js'; @@ -558,7 +557,7 @@ class CodeGenProcess { content: string ): Promise => { const fileName = this.fileSystem.cropExtension(fileNameFull); - const fileExtension = ts.Extension.Ts; + const fileExtension = '.ts'; if (configuration.translateToJavaScript) { this.logger.debug('Using js translator for', fileName); diff --git a/src/configuration.ts b/src/configuration.ts index bb3c676..cd931b1 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import { cloneDeep, compact, join, map, merge, uniq } from 'lodash-es'; -import ts from 'typescript'; +import type ts from 'typescript'; import { ComponentTypeNameResolver } from './component-type-name-resolver'; import * as CONSTANTS from './constants'; @@ -217,10 +217,12 @@ class CodeGenConfig { }; compilerTsConfig: ts.CompilerOptions = { - module: ts.ModuleKind.ESNext, + // `ts.ModuleKind.ESNext` (literal: `typescript` is only loaded when `toJS` is used) + module: 99, noImplicitReturns: true, alwaysStrict: true, - target: ts.ScriptTarget.ESNext, + // `ts.ScriptTarget.ESNext` + target: 99, declaration: true, noImplicitAny: false, sourceMap: false, diff --git a/src/templates-worker.ts b/src/templates-worker.ts index f58f780..cb7fc9f 100644 --- a/src/templates-worker.ts +++ b/src/templates-worker.ts @@ -36,6 +36,9 @@ export interface TemplatesWorkerDeps { /** `require` for an ESM-only package (works from sources and from `dist`) */ const packageRequire = createRequire(import.meta.url); +/** `Eta.compile()` result (eta does not export its `TemplateFunction` type) */ +type CompiledTemplate = (data: object, config: EtaConfig) => string; + class TemplatesWorker { config: CodeGenConfig; @@ -195,7 +198,23 @@ class TemplatesWorker { * Reads a template included from another template (`includeFile("@base/route-docs", data)`). * `@base`, `@default`, `@modular`, `@original` and `@custom` prefixes are replaced with the template paths. */ + /** contents of included templates, keyed by the template paths + the include path */ + templateContents = new Map(); + getTemplateContent = (path: string) => { + // `config.update()` merges `templatePaths` in place, so key by the values, not the object + const key = `${Object.values(this.config.templatePaths).join('\0')}\0${path}`; + let content = this.templateContents.get(key); + + if (content === undefined) { + content = this.readTemplateContent(path); + this.templateContents.set(key, content); + } + + return content; + }; + + readTemplateContent = (path: string): string => { const templatePaths: Record = this.config.templatePaths; const foundTemplatePathKey = Object.keys(templatePaths).find((key) => startsWith(path, `@${key}`) @@ -238,7 +257,7 @@ class TemplatesWorker { * Renders a template (synchronously) with the base template data (`utils`, `config`) and `configuration`. */ /** compiled templates, keyed by the template source */ - compiledTemplates = new Map>(); + compiledTemplates = new Map(); renderTemplate = ( template: string | undefined | null, diff --git a/src/translators/javascript.ts b/src/translators/javascript.ts index 27ae10a..d892134 100644 --- a/src/translators/javascript.ts +++ b/src/translators/javascript.ts @@ -1,4 +1,4 @@ -import ts from 'typescript'; +import type ts from 'typescript'; import type { TranslatorIO } from '../types/config'; import { Translator } from './translator'; @@ -7,7 +7,10 @@ class JavascriptTranslator extends Translator { /** * @returns emitted files: Record */ - compileTSCode = (input: TranslatorIO) => { + /** `typescript` is heavy (~400ms to import), so it is loaded only when `toJS` is used */ + loadTypescript = async (): Promise => (await import('typescript')).default; + + compileTSCode = (ts: typeof import('typescript'), input: TranslatorIO) => { const fileNameFull = `${input.fileName}${input.fileExtension}`; const output: Record = {}; const host = ts.createCompilerHost(this.config.compilerTsConfig, true); @@ -42,7 +45,8 @@ class JavascriptTranslator extends Translator { }; translate = async (input: TranslatorIO): Promise => { - const compiled = this.compileTSCode(input); + const ts = await this.loadTypescript(); + const compiled = this.compileTSCode(ts, input); const jsFileName = `${input.fileName}${ts.Extension.Js}`; const dtsFileName = `${input.fileName}${ts.Extension.Dts}`; diff --git a/tests/core/performance-caches.test.ts b/tests/core/performance-caches.test.ts new file mode 100644 index 0000000..bff9a9d --- /dev/null +++ b/tests/core/performance-caches.test.ts @@ -0,0 +1,135 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import ts from 'typescript'; +import { describe, expect, it, vi } from 'vitest'; + +import { CodeGenConfig } from '../../src/configuration'; +import { TemplatesWorker } from '../../src/templates-worker'; +import { generate, typeCheck } from '../helpers/generate'; + +const SRC_DIR = path.resolve(__dirname, '../../src'); + +const listSourceFiles = (dir: string): string[] => + fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return listSourceFiles(full); + return entry.name.endsWith('.ts') && !entry.name.endsWith('.test.ts') ? [full] : []; + }); + +const spec = { + openapi: '3.0.3', + info: { title: 't', version: '1' }, + paths: Object.fromEntries( + Array.from({ length: 20 }, (_, i) => [ + `/items${i}/{id}`, + { + get: { + operationId: `getItem${i}`, + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + responses: { + 200: { + description: 'ok', + content: { 'application/json': { schema: { $ref: '#/components/schemas/Item' } } }, + }, + }, + }, + }, + ]) + ), + components: { + schemas: { Item: { type: 'object', properties: { id: { type: 'string' } } } }, + }, +}; + +const createWorker = (getFileContent: (path: string) => string) => { + const config = new CodeGenConfig({}); + const worker = new TemplatesWorker({ + config, + logger: { log: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as any, + fileSystem: { pathIsExist: () => true, getFileContent } as any, + getRenderTemplateData: () => ({}) as any, + }); + config.update({ templatePaths: worker.getTemplatePaths(config) }); + return { config, worker }; +}; + +describe('compiled template cache', () => { + it('compiles each template source once, however many times it is rendered', () => { + const { worker } = createWorker(() => ''); + for (let i = 0; i < 50; i++) { + expect(worker.renderTemplate('<%~ it.value %>!', { value: i })).toBe(`${i}!`); + } + expect(worker.renderTemplate('other <%~ it.value %>', { value: 1 })).toBe('other 1'); + expect(worker.compiledTemplates.size).toBe(2); + }); + + it('includeFile still receives its own data', () => { + const { worker } = createWorker((file) => + file.includes('partial') ? 'partial:<%~ it.x %>' : '' + ); + const out = worker.renderTemplate( + '<% for (const x of it.xs) { %><%~ includeFile("@base/partial", { x }) %>;<% } %>', + { xs: [1, 2, 3] } + ); + expect(out).toBe('partial:1;partial:2;partial:3;'); + }); +}); + +describe('included template contents cache', () => { + it('reads an included template from disk once', () => { + const getFileContent = vi.fn(() => 'content'); + const { worker } = createWorker(getFileContent); + for (let i = 0; i < 10; i++) { + expect(worker.getTemplateContent('@base/data-contracts')).toBe('content'); + } + expect(getFileContent).toHaveBeenCalledTimes(1); + }); + + it('is invalidated when templatePaths change', () => { + const getFileContent = vi.fn((file: string) => file); + const { config, worker } = createWorker(getFileContent); + const first = worker.getTemplateContent('@base/data-contracts'); + config.update({ templatePaths: { ...config.templatePaths, base: '/other/base' } }); + const second = worker.getTemplateContent('@base/data-contracts'); + expect(second).not.toBe(first); + expect(second).toContain('/other/base'); + expect(getFileContent).toHaveBeenCalledTimes(2); + }); +}); + +describe('typescript is loaded lazily', () => { + it('is only imported as a type in src (runtime import only in the JS translator)', () => { + const valueImports = listSourceFiles(SRC_DIR).filter((file) => + /^import\s+(?!type\b)[^;]*from\s+['"]typescript['"]/m.test(fs.readFileSync(file, 'utf8')) + ); + expect(valueImports).toEqual([]); + expect(fs.readFileSync(path.join(SRC_DIR, 'translators/javascript.ts'), 'utf8')).toContain( + "import('typescript')" + ); + }); + + it('keeps the compiler options equal to the typescript enum values', () => { + const config = new CodeGenConfig({}); + expect(config.compilerTsConfig.module).toBe(ts.ModuleKind.ESNext); + expect(config.compilerTsConfig.target).toBe(ts.ScriptTarget.ESNext); + }); + + it('toJS still works', async () => { + const { files } = await generate(spec, { toJS: true }); + expect(Object.keys(files).sort()).toEqual(['api.d.ts', 'api.js']); + expect(files['api.js']).toContain('getItem19'); + expect(typeCheck({ 'api.d.ts': files['api.d.ts'] })).toEqual([]); + }); +}); + +describe('caches do not leak between generations', () => { + it('generates the same output twice and with different options', async () => { + const a = await generate(spec); + const b = await generate(spec); + const modular = await generate(spec, { modular: true }); + expect(b.files).toEqual(a.files); + expect(Object.keys(modular.files).length).toBeGreaterThan(1); + expect(typeCheck(modular.files)).toEqual([]); + }); +}); From e2a070ba1ae30d32652b02a9f8de45dc76af59c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 00:55:45 +0000 Subject: [PATCH 3/9] perf: replace lodash-es with es-toolkit, stop deep-merging documents into the config - es-toolkit/compat for lodash semantics (utils._ in templates keeps the same functions), core es-toolkit cloneDeep for whole documents - config.update replaces spec / swaggerSchema / originalSchema by reference instead of deep-merging them, and the no-op onInit update is skipped (each copied the whole schema) - validate that paths / components / definitions are objects: the error for an invalid document relied on a lodash merge quirk - tests: update semantics, onInit, input spec not mutated, document validation ~15% faster generation of a 1500 schemas / 3000 operations spec in-process, ~20% on a 300 / 600 one; byte-identical output on 27 spec / option combinations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- CHANGELOG.md | 11 ++-- README.md | 3 +- docs/next.config.ts | 2 +- package-lock.json | 38 +++++-------- package.json | 3 +- src/code-gen-process.ts | 8 ++- src/configuration.ts | 13 ++++- src/schema-components-map.ts | 2 +- .../base-schema-parsers/array.ts | 2 +- .../base-schema-parsers/complex.ts | 2 +- .../base-schema-parsers/discriminator.ts | 13 +---- src/schema-parser/base-schema-parsers/enum.ts | 2 +- .../base-schema-parsers/object.ts | 2 +- .../base-schema-parsers/primitive.ts | 2 +- .../complex-schema-parsers/all-of.ts | 2 +- .../complex-schema-parsers/any-of.ts | 2 +- .../complex-schema-parsers/one-of.ts | 2 +- src/schema-parser/schema-formatters.ts | 2 +- src/schema-parser/schema-parser-fabric.ts | 2 +- src/schema-parser/schema-parser.ts | 2 +- src/schema-parser/schema-utils.ts | 2 +- src/schema-routes/schema-routes.ts | 2 +- src/schema-walker.ts | 3 +- src/swagger-schema-resolver.ts | 12 ++++- src/templates-worker.ts | 2 +- src/type-name-formatter.ts | 2 +- src/types/config.ts | 2 +- src/util/file-system.ts | 2 +- src/util/internal-case.ts | 2 +- src/util/logger.ts | 2 +- src/util/name-resolver.ts | 2 +- src/util/object-assign.ts | 2 +- src/util/pascal-case.ts | 2 +- src/util/request.ts | 2 +- src/util/type-guards.ts | 2 +- tests/core/performance-caches.test.ts | 53 +++++++++++++++++++ tests/core/swagger-schema-resolver.test.ts | 29 ++++++++++ 37 files changed, 165 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96b0105..1cc8fff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,13 +60,18 @@ - Compiled Eta templates are cached (they were recompiled for every route, model and include) and included template files are read once. - `typescript` is only loaded when `toJS` is used (~400ms less startup). -- CLI run on a small spec: ~800ms β†’ ~400ms; 1500 schemas / 3000 operations: ~3.4s β†’ ~2.1s - (`npm run bench`). The generated output is unchanged. +- `lodash-es` replaced by `es-toolkit` (`es-toolkit/compat` where lodash semantics matter, the faster + core `cloneDeep` for documents). `utils._` in templates keeps the same lodash-compatible functions. +- The config no longer deep-merges whole documents (`spec`, `swaggerSchema`, `originalSchema`) and + skips the no-op `onInit` update, which copied the whole schema several times. +- CLI run (new process) on a small spec: ~800ms β†’ ~400ms; 1500 schemas / 3000 operations: ~3.4s β†’ ~2.2s. + Repeated in-process generation of that spec: ~2.7s β†’ ~1.5s (`npm run bench`). The generated output is + unchanged. ### 🏎 Dependencies - Replaced `unprompts` with `cac` (drops `unbuild`/`esbuild` from runtime dependencies), `node-fetch-h2` with - `undici`, removed `make-dir`, `nanoid` and `node-emoji`, declared `picocolors`. + `undici`, removed `make-dir`, `nanoid`, `node-emoji` and `lodash-es` (now `es-toolkit`), declared `picocolors`. - `npm audit`: 0 vulnerabilities. ### 🏷 Types diff --git a/README.md b/README.md index b8d3657..068934a 100644 --- a/README.md +++ b/README.md @@ -645,7 +645,8 @@ is looked up in the custom folder, then in the built-in one. **`utils`:** `Ts`, `formatDescription`, `escapeJSDocContent`, `internalCase`, `classNameCase`, `pascalCase`, `getInlineParseContent`, `getParseContent`, `getComponentByRef`, `parseSchema`, `checkAndAddNull`, `safeAddNullToType`, `isNeedToAddNull`, `inlineExtraFormatters`, `formatters`, -`formatModelName`, `fmtToJSDocLine`, `NameResolver`, `require`, and `_`, a subset of lodash: +`formatModelName`, `fmtToJSDocLine`, `NameResolver`, `require`, and `_`, lodash-compatible helpers +(from [`es-toolkit/compat`](https://es-toolkit.dev/compatibility.html)): `compact`, `merge`, `each`, `isEmpty`, `sortByProperty`, `noop`, `isObject`, `isString`, `isUndefined`, `map`, `uniq`, `size`, `replace`, `camelCase`, `lowerCase`, `values`, `join`, `get`, `upperCase`, `sortBy`. `require('./x')` resolves from the templates folder. A package name diff --git a/docs/next.config.ts b/docs/next.config.ts index aa0bde0..2bb53de 100644 --- a/docs/next.config.ts +++ b/docs/next.config.ts @@ -11,7 +11,7 @@ const repoRoot = path.join(rootDir, '..'); const LIBRARY_RUNTIME_DEPENDENCIES = [ 'eta', 'js-yaml', - 'lodash-es', + 'es-toolkit', 'oxfmt', 'picocolors', 'swagger2openapi', diff --git a/package-lock.json b/package-lock.json index 24cb6d8..3c59c75 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,9 +10,9 @@ "license": "MIT", "dependencies": { "cac": "^6.7.14", + "es-toolkit": "^1.52.0", "eta": "^2.2.0", "js-yaml": "^4.2.0", - "lodash-es": "^4.18.1", "oxfmt": "^0.56.0", "picocolors": "^1.1.1", "swagger2openapi": "^7.0.8", @@ -25,7 +25,6 @@ }, "devDependencies": { "@types/js-yaml": "^4.0.9", - "@types/lodash-es": "^4.17.12", "@types/node": "^20.19.0", "@types/swagger2openapi": "^7.0.4", "@vitest/coverage-v8": "^4.1.11", @@ -2069,23 +2068,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/lodash": { - "version": "4.17.25", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.25.tgz", - "integrity": "sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/lodash-es": { - "version": "4.17.12", - "resolved": "https://registry.npmjs.org/@types/lodash-es/-/lodash-es-4.17.12.tgz", - "integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/lodash": "*" - } - }, "node_modules/@types/node": { "version": "20.19.43", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", @@ -3154,6 +3136,18 @@ "node": ">= 0.4" } }, + "node_modules/es-toolkit": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", + "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, "node_modules/es6-promise": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", @@ -3986,12 +3980,6 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "license": "MIT" }, - "node_modules/lodash-es": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", - "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", - "license": "MIT" - }, "node_modules/lodash.memoize": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", diff --git a/package.json b/package.json index a3e6796..172ddaa 100644 --- a/package.json +++ b/package.json @@ -51,9 +51,9 @@ }, "dependencies": { "cac": "^6.7.14", + "es-toolkit": "^1.52.0", "eta": "^2.2.0", "js-yaml": "^4.2.0", - "lodash-es": "^4.18.1", "oxfmt": "^0.56.0", "picocolors": "^1.1.1", "swagger2openapi": "^7.0.8", @@ -63,7 +63,6 @@ }, "devDependencies": { "@types/js-yaml": "^4.0.9", - "@types/lodash-es": "^4.17.12", "@types/node": "^20.19.0", "@types/swagger2openapi": "^7.0.4", "@vitest/coverage-v8": "^4.1.11", diff --git a/src/code-gen-process.ts b/src/code-gen-process.ts index d52525e..6f8060e 100644 --- a/src/code-gen-process.ts +++ b/src/code-gen-process.ts @@ -18,7 +18,7 @@ import { uniq, upperCase, values, -} from 'lodash-es'; +} from 'es-toolkit/compat'; import pc from 'picocolors'; import { CodeFormatter } from './code-formatter'; @@ -129,7 +129,11 @@ class CodeGenProcess { this.logger.event('Start generating your typescript api'); - this.config.update(this.config.hooks.onInit(this.config, this) || this.config); + const initConfig = this.config.hooks.onInit(this.config, this); + // returning the (mutated) config itself or nothing needs no update + if (initConfig && initConfig !== this.config) { + this.config.update(initConfig); + } this.schemaComponentsMap.clear(); diff --git a/src/configuration.ts b/src/configuration.ts index cd931b1..8d9e047 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -1,6 +1,7 @@ import path from 'node:path'; -import { cloneDeep, compact, join, map, merge, uniq } from 'lodash-es'; +import { cloneDeep } from 'es-toolkit'; +import { compact, join, map, merge, uniq } from 'es-toolkit/compat'; import type ts from 'typescript'; import { ComponentTypeNameResolver } from './component-type-name-resolver'; @@ -422,6 +423,16 @@ class CodeGenConfig { } update = (update: CodeGenConfigUpdate) => { + // big documents are replaced by reference: deep-merging them copied the whole schema + // on every update (the resolver already works on its own copy of `spec`) + if (update && typeof update === 'object') { + const { spec, swaggerSchema, originalSchema, ...rest } = update as Partial; + if (spec !== undefined) this.spec = spec; + if (swaggerSchema !== undefined) this.swaggerSchema = swaggerSchema; + if (originalSchema !== undefined) this.originalSchema = originalSchema; + objectAssign(this, rest); + return; + } objectAssign(this, update); }; } diff --git a/src/schema-components-map.ts b/src/schema-components-map.ts index 789c0f9..a403dc6 100644 --- a/src/schema-components-map.ts +++ b/src/schema-components-map.ts @@ -1,4 +1,4 @@ -import { filter, startsWith } from 'lodash-es'; +import { filter, startsWith } from 'es-toolkit/compat'; import type { CodeGenConfig } from './configuration'; import type { ComponentName } from './types/openapi'; diff --git a/src/schema-parser/base-schema-parsers/array.ts b/src/schema-parser/base-schema-parsers/array.ts index 201af6c..caae3a6 100644 --- a/src/schema-parser/base-schema-parsers/array.ts +++ b/src/schema-parser/base-schema-parsers/array.ts @@ -1,4 +1,4 @@ -import { isObject } from 'lodash-es'; +import { isObject } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../../constants'; import type { ParsedPrimitiveSchema } from '../../types/parsed'; diff --git a/src/schema-parser/base-schema-parsers/complex.ts b/src/schema-parser/base-schema-parsers/complex.ts index 27af979..e02f514 100644 --- a/src/schema-parser/base-schema-parsers/complex.ts +++ b/src/schema-parser/base-schema-parsers/complex.ts @@ -1,4 +1,4 @@ -import { clone, compact, isObject, omit } from 'lodash-es'; +import { clone, compact, isObject, omit } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../../constants'; import type { ParsedComplexSchema } from '../../types/parsed'; diff --git a/src/schema-parser/base-schema-parsers/discriminator.ts b/src/schema-parser/base-schema-parsers/discriminator.ts index 60021bd..82a37dd 100644 --- a/src/schema-parser/base-schema-parsers/discriminator.ts +++ b/src/schema-parser/base-schema-parsers/discriminator.ts @@ -1,14 +1,5 @@ -import { - clone, - cloneDeep, - compact, - entries, - isArray, - isObject, - keys, - omit, - reduce, -} from 'lodash-es'; +import { cloneDeep } from 'es-toolkit'; +import { clone, compact, entries, isArray, isObject, keys, omit, reduce } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../../constants'; import type { SchemaObject } from '../../types/openapi'; diff --git a/src/schema-parser/base-schema-parsers/enum.ts b/src/schema-parser/base-schema-parsers/enum.ts index 071782f..8121175 100644 --- a/src/schema-parser/base-schema-parsers/enum.ts +++ b/src/schema-parser/base-schema-parsers/enum.ts @@ -1,4 +1,4 @@ -import { includes, isArray, isObject, isUndefined, map, size } from 'lodash-es'; +import { includes, isArray, isObject, isUndefined, map, size } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../../constants'; import type { EnumFieldContent, ParsedEnumSchema, ParsedSchema } from '../../types/parsed'; diff --git a/src/schema-parser/base-schema-parsers/object.ts b/src/schema-parser/base-schema-parsers/object.ts index 8b64b14..055d283 100644 --- a/src/schema-parser/base-schema-parsers/object.ts +++ b/src/schema-parser/base-schema-parsers/object.ts @@ -1,4 +1,4 @@ -import { isObject, map, some, values } from 'lodash-es'; +import { isObject, map, some, values } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../../constants'; import type { SchemaObject } from '../../types/openapi'; diff --git a/src/schema-parser/base-schema-parsers/primitive.ts b/src/schema-parser/base-schema-parsers/primitive.ts index 2941036..478600c 100644 --- a/src/schema-parser/base-schema-parsers/primitive.ts +++ b/src/schema-parser/base-schema-parsers/primitive.ts @@ -1,4 +1,4 @@ -import { isObject } from 'lodash-es'; +import { isObject } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../../constants'; import type { SchemaObject } from '../../types/openapi'; diff --git a/src/schema-parser/complex-schema-parsers/all-of.ts b/src/schema-parser/complex-schema-parsers/all-of.ts index 57d9eb4..7fdc6ca 100644 --- a/src/schema-parser/complex-schema-parsers/all-of.ts +++ b/src/schema-parser/complex-schema-parsers/all-of.ts @@ -1,4 +1,4 @@ -import { map } from 'lodash-es'; +import { map } from 'es-toolkit/compat'; import { MonoSchemaParser } from '../mono-schema-parser'; diff --git a/src/schema-parser/complex-schema-parsers/any-of.ts b/src/schema-parser/complex-schema-parsers/any-of.ts index b589cb4..42a78ca 100644 --- a/src/schema-parser/complex-schema-parsers/any-of.ts +++ b/src/schema-parser/complex-schema-parsers/any-of.ts @@ -1,4 +1,4 @@ -import { map } from 'lodash-es'; +import { map } from 'es-toolkit/compat'; import { MonoSchemaParser } from '../mono-schema-parser'; diff --git a/src/schema-parser/complex-schema-parsers/one-of.ts b/src/schema-parser/complex-schema-parsers/one-of.ts index 3d1b78c..bb7bdc2 100644 --- a/src/schema-parser/complex-schema-parsers/one-of.ts +++ b/src/schema-parser/complex-schema-parsers/one-of.ts @@ -1,4 +1,4 @@ -import { map } from 'lodash-es'; +import { map } from 'es-toolkit/compat'; import { MonoSchemaParser } from '../mono-schema-parser'; diff --git a/src/schema-parser/schema-formatters.ts b/src/schema-parser/schema-formatters.ts index cf3c030..78f015a 100644 --- a/src/schema-parser/schema-formatters.ts +++ b/src/schema-parser/schema-formatters.ts @@ -1,4 +1,4 @@ -import { compact, includes, isString, map, replace, trim } from 'lodash-es'; +import { compact, includes, isString, map, replace, trim } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../constants'; import type { SchemaObject } from '../types/openapi'; diff --git a/src/schema-parser/schema-parser-fabric.ts b/src/schema-parser/schema-parser-fabric.ts index a471556..9f817de 100644 --- a/src/schema-parser/schema-parser-fabric.ts +++ b/src/schema-parser/schema-parser-fabric.ts @@ -1,4 +1,4 @@ -import { cloneDeep } from 'lodash-es'; +import { cloneDeep } from 'es-toolkit'; import type { CodeGenConfig } from '../configuration'; import type { SchemaComponentsMap } from '../schema-components-map'; diff --git a/src/schema-parser/schema-parser.ts b/src/schema-parser/schema-parser.ts index a149aed..db618bb 100644 --- a/src/schema-parser/schema-parser.ts +++ b/src/schema-parser/schema-parser.ts @@ -1,4 +1,4 @@ -import { first, merge, omit, values } from 'lodash-es'; +import { first, merge, omit, values } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../constants.js'; import type { SchemaPath } from '../types/config'; diff --git a/src/schema-parser/schema-utils.ts b/src/schema-parser/schema-utils.ts index 12bae36..3646c59 100644 --- a/src/schema-parser/schema-utils.ts +++ b/src/schema-parser/schema-utils.ts @@ -8,7 +8,7 @@ import { isString, keys, uniq, -} from 'lodash-es'; +} from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../constants'; import type { SchemaWalker } from '../schema-walker'; diff --git a/src/schema-routes/schema-routes.ts b/src/schema-routes/schema-routes.ts index 27c753f..64dfc3e 100644 --- a/src/schema-routes/schema-routes.ts +++ b/src/schema-routes/schema-routes.ts @@ -24,7 +24,7 @@ import { startsWith, uniq, values, -} from 'lodash-es'; +} from 'es-toolkit/compat'; import type { CodeGenConfig } from '../configuration'; import { diff --git a/src/schema-walker.ts b/src/schema-walker.ts index 85d7c1f..45a7e49 100644 --- a/src/schema-walker.ts +++ b/src/schema-walker.ts @@ -1,6 +1,7 @@ import path from 'node:path'; -import { cloneDeep, get } from 'lodash-es'; +import { cloneDeep } from 'es-toolkit'; +import { get } from 'es-toolkit/compat'; import type { SwaggerSchemaResolver } from './swagger-schema-resolver'; import type { Logger } from './util/logger'; diff --git a/src/swagger-schema-resolver.ts b/src/swagger-schema-resolver.ts index 55ee8d5..9921778 100644 --- a/src/swagger-schema-resolver.ts +++ b/src/swagger-schema-resolver.ts @@ -1,7 +1,8 @@ import path from 'node:path'; +import { cloneDeep } from 'es-toolkit'; +import { compact, each, find, get, merge, uniq } from 'es-toolkit/compat'; import yaml from 'js-yaml'; -import { cloneDeep, compact, each, find, get, merge, uniq } from 'lodash-es'; import pc from 'picocolors'; import converter from 'swagger2openapi'; import type { ConvertInputOptions } from 'swagger2openapi'; @@ -110,6 +111,15 @@ class SwaggerSchemaResolver { throw new Error(`Invalid swagger schema: expected an object, got ${typeof swaggerSchema}`); } + for (const key of ['paths', 'components', 'definitions'] as const) { + const value = swaggerSchema[key]; + if (value != null && (typeof value !== 'object' || Array.isArray(value))) { + throw new Error( + `Invalid swagger schema: "${key}" must be an object, got ${Array.isArray(value) ? 'array' : typeof value}` + ); + } + } + return new Promise((resolve, reject) => { const result = cloneDeep(swaggerSchema); diff --git a/src/templates-worker.ts b/src/templates-worker.ts index cb7fc9f..9116e41 100644 --- a/src/templates-worker.ts +++ b/src/templates-worker.ts @@ -1,9 +1,9 @@ import { createRequire } from 'node:module'; import path, { resolve } from 'node:path'; +import { endsWith, lowerCase, reduce, replace, startsWith } from 'es-toolkit/compat'; import * as Eta from 'eta'; import type { EtaConfig } from 'eta'; -import { endsWith, lowerCase, reduce, replace, startsWith } from 'lodash-es'; import type { CodeGenConfig } from './configuration'; import { TEMPLATES_DIR } from './constants'; diff --git a/src/type-name-formatter.ts b/src/type-name-formatter.ts index b1ff17b..35fc84e 100644 --- a/src/type-name-formatter.ts +++ b/src/type-name-formatter.ts @@ -1,4 +1,4 @@ -import { compact, replace, startCase } from 'lodash-es'; +import { compact, replace, startCase } from 'es-toolkit/compat'; import type { CodeGenConfig } from './configuration'; import type { FormattingSchemaType } from './types/config'; diff --git a/src/types/config.ts b/src/types/config.ts index d84e1a4..fb76735 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -370,7 +370,7 @@ export interface ApiConfig { version?: string; } -/** lodash functions available in templates as `utils._` */ +/** lodash-compatible functions (`es-toolkit/compat`) available in templates as `utils._` */ export type TemplateLodashUtils = Record< | 'compact' | 'merge' diff --git a/src/util/file-system.ts b/src/util/file-system.ts index dd2c506..429226c 100644 --- a/src/util/file-system.ts +++ b/src/util/file-system.ts @@ -1,7 +1,7 @@ import fs from 'node:fs'; import { resolve } from 'node:path'; -import { split } from 'lodash-es'; +import { split } from 'es-toolkit/compat'; import { Logger } from './logger'; diff --git a/src/util/internal-case.ts b/src/util/internal-case.ts index f0d74f3..b922796 100644 --- a/src/util/internal-case.ts +++ b/src/util/internal-case.ts @@ -1,4 +1,4 @@ -import { camelCase, lowerCase } from 'lodash-es'; +import { camelCase, lowerCase } from 'es-toolkit/compat'; const internalCase = (value: string | undefined) => camelCase(lowerCase(value)); diff --git a/src/util/logger.ts b/src/util/logger.ts index fd11653..f0226b4 100644 --- a/src/util/logger.ts +++ b/src/util/logger.ts @@ -1,4 +1,4 @@ -import { map } from 'lodash-es'; +import { map } from 'es-toolkit/compat'; const EMOJIS: Record = { ':sparkles:': '✨', diff --git a/src/util/name-resolver.ts b/src/util/name-resolver.ts index ff2cd63..9440b47 100644 --- a/src/util/name-resolver.ts +++ b/src/util/name-resolver.ts @@ -1,4 +1,4 @@ -import { compact, some, uniq } from 'lodash-es'; +import { compact, some, uniq } from 'es-toolkit/compat'; import type { CodeGenConfig } from '../configuration'; import type { Logger } from './logger'; diff --git a/src/util/object-assign.ts b/src/util/object-assign.ts index 2979cb5..83fe8a2 100644 --- a/src/util/object-assign.ts +++ b/src/util/object-assign.ts @@ -1,4 +1,4 @@ -import { merge, omitBy } from 'lodash-es'; +import { merge, omitBy } from 'es-toolkit/compat'; /** changes, or a function receiving the target and returning the changes */ export type ObjectUpdater = U | ((target: T) => U); diff --git a/src/util/pascal-case.ts b/src/util/pascal-case.ts index 9b31f99..cf67e2e 100644 --- a/src/util/pascal-case.ts +++ b/src/util/pascal-case.ts @@ -1,4 +1,4 @@ -import { camelCase, upperFirst } from 'lodash-es'; +import { camelCase, upperFirst } from 'es-toolkit/compat'; const pascalCase = (value: string | undefined) => upperFirst(camelCase(value)); diff --git a/src/util/request.ts b/src/util/request.ts index 6939b4b..9b8bdcc 100644 --- a/src/util/request.ts +++ b/src/util/request.ts @@ -1,4 +1,4 @@ -import { merge, startsWith } from 'lodash-es'; +import { merge, startsWith } from 'es-toolkit/compat'; import { Agent, EnvHttpProxyAgent, fetch, type Dispatcher } from 'undici'; import type { RequestOptions } from '../types/config'; diff --git a/src/util/type-guards.ts b/src/util/type-guards.ts index 2837417..b14e74d 100644 --- a/src/util/type-guards.ts +++ b/src/util/type-guards.ts @@ -1,4 +1,4 @@ -import { isPlainObject } from 'lodash-es'; +import { isPlainObject } from 'es-toolkit/compat'; import type { OpenAPIV3Document, OperationObject, SwaggerV2Document } from '../types/openapi'; diff --git a/tests/core/performance-caches.test.ts b/tests/core/performance-caches.test.ts index bff9a9d..55d3247 100644 --- a/tests/core/performance-caches.test.ts +++ b/tests/core/performance-caches.test.ts @@ -133,3 +133,56 @@ describe('caches do not leak between generations', () => { expect(typeCheck(modular.files)).toEqual([]); }); }); + +describe('config.update with big documents', () => { + it('replaces spec / swaggerSchema / originalSchema by reference instead of deep-merging', () => { + const config = new CodeGenConfig({}); + const first = { + openapi: '3.0.0', + info: { title: 'a', version: '1' }, + paths: { '/a': {} }, + } as any; + const second = { + openapi: '3.0.0', + info: { title: 'b', version: '1' }, + paths: { '/b': {} }, + } as any; + config.update({ swaggerSchema: first, originalSchema: first, spec: first }); + config.update({ swaggerSchema: second }); + expect(config.swaggerSchema).toBe(second); + // not merged with the previous document + expect(Object.keys(config.swaggerSchema!.paths!)).toEqual(['/b']); + expect(config.originalSchema).toBe(first); + expect(config.spec).toBe(first); + }); + + it('still deep-merges other options', () => { + const config = new CodeGenConfig({}); + config.update({ extractingOptions: { requestBodySuffix: ['Body'] } } as any); + // lodash semantics: arrays are merged index by index (defaults: Payload, Body, Input) + expect(config.extractingOptions.requestBodySuffix).toEqual(['Body', 'Body', 'Input']); + expect(config.extractingOptions.responseBodySuffix.length).toBeGreaterThan(0); + }); + + it('does not mutate the spec passed by the user', async () => { + const input = structuredClone(spec); + await generate(input, { modular: true, extractEnums: true }); + expect(input).toEqual(spec); + }); + + it('applies what onInit returns, and accepts the mutated config itself', async () => { + const a = await generate(spec, { + hooks: { onInit: (config: any) => ({ ...config, apiClassName: 'FromHook' }) }, + }); + expect(a.files['api.ts']).toContain('class FromHook'); + const b = await generate(spec, { + hooks: { + onInit: (config: any) => { + config.apiClassName = 'Mutated'; + return config; + }, + }, + }); + expect(b.files['api.ts']).toContain('class Mutated'); + }); +}); diff --git a/tests/core/swagger-schema-resolver.test.ts b/tests/core/swagger-schema-resolver.test.ts index 9c1e84f..31c4c71 100644 --- a/tests/core/swagger-schema-resolver.test.ts +++ b/tests/core/swagger-schema-resolver.test.ts @@ -138,3 +138,32 @@ describe('SwaggerSchemaResolver.fetchSwaggerSchemaFile', () => { ); }); }); + +describe('document structure validation', () => { + it.each([ + [ + 'paths', + { swagger: '2.0', info: { title: 't', version: '1' }, paths: 'nope' }, + /"paths" must be an object, got string/, + ], + [ + 'paths (array)', + { openapi: '3.0.0', info: { title: 't', version: '1' }, paths: [] }, + /"paths" must be an object, got array/, + ], + [ + 'components', + { openapi: '3.0.0', info: { title: 't', version: '1' }, paths: {}, components: 1 }, + /"components" must be an object, got number/, + ], + [ + 'definitions', + { swagger: '2.0', info: { title: 't', version: '1' }, paths: {}, definitions: 'x' }, + /"definitions" must be an object/, + ], + ])('rejects a non-object %s', async (_name, spec, message) => { + await expect( + generateApi({ spec: spec as any, output: false, silent: true } as any) + ).rejects.toThrow(message); + }); +}); From 2e8ff4120fff914ffe6dd3ce77b1a2e62f475e13 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 01:07:47 +0000 Subject: [PATCH 4/9] =?UTF-8?q?perf:=20remove=20O(routes=20=C3=97=20compon?= =?UTF-8?q?ents)=20lookups=20and=20other=20redundant=20work?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - index parsed components once per route parsing instead of scanning (and formatting the name of) every component for each request / response type: 3.4M -> 22k formatName calls on a 1500 schemas / 3000 operations spec - Map / Set lookups for component $refs and reserved names (were linear scans) - memoize pascalCase / internalCase, pool random bytes for route ids - don't deep-copy a document the resolver parsed itself (file / URL) - tests: file vs spec output equality, index consistency when internals are changed from outside, id format In-process generation of the large spec: 1.5s -> 0.7s; CLI 2.2s -> 1.3s. Byte-identical output on 27 spec / option combinations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- CHANGELOG.md | 13 ++++-- src/schema-components-map.ts | 28 ++++++++++- src/schema-routes/schema-routes.ts | 67 ++++++++++++++++++++------- src/swagger-schema-resolver.ts | 15 ++++-- src/util/id.ts | 17 ++++++- src/util/internal-case.ts | 12 ++++- src/util/name-resolver.ts | 28 +++++++++-- src/util/pascal-case.ts | 12 ++++- tests/core/performance-caches.test.ts | 67 +++++++++++++++++++++++++++ 9 files changed, 227 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cc8fff..f373855 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,9 +64,16 @@ core `cloneDeep` for documents). `utils._` in templates keeps the same lodash-compatible functions. - The config no longer deep-merges whole documents (`spec`, `swaggerSchema`, `originalSchema`) and skips the no-op `onInit` update, which copied the whole schema several times. -- CLI run (new process) on a small spec: ~800ms β†’ ~400ms; 1500 schemas / 3000 operations: ~3.4s β†’ ~2.2s. - Repeated in-process generation of that spec: ~2.7s β†’ ~1.5s (`npm run bench`). The generated output is - unchanged. +- Algorithmic fixes: + - response / request types were resolved by scanning (and re-formatting the names of) every + component for every route (O(routes Γ— components), 3.4M `formatName` calls on a 1500 / 3000 spec): + now an index built once; + - `$ref` lookups in the components map and reserved-name checks use a `Map` / `Set` instead of + linear scans; + - memoized `pascalCase` / `internalCase`, pooled random bytes for route ids, and a document read + from a file / URL is no longer deep-copied before use. +- CLI run (new process): small spec ~840ms β†’ ~380ms; 1500 schemas / 3000 operations ~3.6s β†’ ~1.3s. + In-process generation of that spec (`npm run bench`): ~2.6s β†’ ~0.7s. The generated output is unchanged. ### 🏎 Dependencies diff --git a/src/schema-components-map.ts b/src/schema-components-map.ts index a403dc6..23fcb8a 100644 --- a/src/schema-components-map.ts +++ b/src/schema-components-map.ts @@ -12,8 +12,28 @@ class SchemaComponentsMap { this.config = config; } + /** `$ref` -> index in `_data` of its first component (a cache, checked on every read) */ + private refIndexes = new Map(); + clear() { this._data = []; + this.refIndexes.clear(); + } + + /** index of the first component with this `$ref` (-1 if there is none) */ + private indexOf($ref: string) { + const cached = this.refIndexes.get($ref); + if (cached !== undefined && this._data[cached]?.$ref === $ref) { + return cached; + } + // not indexed yet, or `_data` was changed from outside (e.g. through `getComponents()`) + const index = this._data.findIndex((c) => c.$ref === $ref); + if (index === -1) { + this.refIndexes.delete($ref); + } else { + this.refIndexes.set($ref, index); + } + return index; } /** `["components", "schemas", "Pet"]` -> `#/components/schemas/Pet` */ @@ -40,10 +60,13 @@ class SchemaComponentsMap { const usageComponent = this.config.hooks.onCreateComponent(componentSchema) || componentSchema; - const refIndex = this._data.findIndex((c) => c.$ref === $ref); + const refIndex = this.indexOf($ref); if (refIndex === -1) { this._data.push(usageComponent); + if (!this.refIndexes.has(usageComponent.$ref)) { + this.refIndexes.set(usageComponent.$ref, this._data.length - 1); + } } else { this._data[refIndex] = usageComponent; } @@ -66,7 +89,8 @@ class SchemaComponentsMap { } get($ref: string) { - return this._data.find((c) => c.$ref === $ref) || null; + const index = this.indexOf($ref); + return index === -1 ? null : this._data[index]; } } diff --git a/src/schema-routes/schema-routes.ts b/src/schema-routes/schema-routes.ts index 64dfc3e..bd34182 100644 --- a/src/schema-routes/schema-routes.ts +++ b/src/schema-routes/schema-routes.ts @@ -6,11 +6,9 @@ import { each, endsWith, entries, - find, flatMap, forEach, includes, - isEqual, isNaN, isObject, keys, @@ -160,6 +158,15 @@ const isAllFieldsOptional = (parsedSchema: ParsedSchema) => /** vendor extension with a content type (`x-accepts`, `x-contentType`) */ const getExtraContentType = (value: unknown) => (typeof value === 'string' ? value : undefined); +interface ParsedSchemasIndex { + /** formatted names of the components */ + formattedNames: Set; + /** composite components by their (string) content */ + complexByContent: Map; + /** raw names of the components */ + names: Set; +} + class SchemaRoutes { config: SchemaRoutesConfig; schemaParserFabric: SchemaParserFabric; @@ -502,6 +509,43 @@ class SchemaRoutes { return null; }; + /** lookup tables of the parsed components, built once per `parsedSchemas` list */ + parsedSchemasIndexes = new WeakMap(); + + /** + * `getTypeFromRequestInfo` runs for every request / response: scanning all the components + * (and formatting their names) each time was O(routes Γ— components). + */ + getParsedSchemasIndex = (parsedSchemas: ParsedSchema[]): ParsedSchemasIndex => { + let index = this.parsedSchemasIndexes.get(parsedSchemas); + + if (!index) { + index = { formattedNames: new Set(), complexByContent: new Map(), names: new Set() }; + + for (const parsedSchema of parsedSchemas) { + index.names.add(parsedSchema.name); + index.formattedNames.add(this.typeNameFormatter.format(parsedSchema.name)); + + if ( + parsedSchema.schemaType === SCHEMA_TYPES.COMPLEX && + typeof parsedSchema.name === 'string' && + typeof parsedSchema.content === 'string' && + // the first matching component wins (as with `find`) + !index.complexByContent.has(parsedSchema.content) + ) { + index.complexByContent.set( + parsedSchema.content, + parsedSchema as ParsedSchema & { name: string } + ); + } + } + + this.parsedSchemasIndexes.set(parsedSchemas, index); + } + + return index; + }; + getTypeFromRequestInfo = ({ requestInfo, parsedSchemas, @@ -523,13 +567,10 @@ class SchemaRoutes { const content = this.schemaParserFabric.getInlineParseContent(schema, typeName, [ operationId, ]); - // formatted name of this component is equal to the content - const foundSchemaByName = find( - parsedSchemas, - (parsedSchema) => this.typeNameFormatter.format(parsedSchema.name) === content - ); + const index = this.getParsedSchemasIndex(parsedSchemas); - if (foundSchemaByName) { + // formatted name of this component is equal to the content + if (index.formattedNames.has(content)) { return content; } @@ -537,13 +578,7 @@ class SchemaRoutes { // Only composite (allOf/oneOf/anyOf/discriminator) components are considered: // for primitive components (e.g. `UserId: { type: string }`) an equal content // says nothing about identity and would type every `string` as `UserId`. - const foundSchemaByContent = find( - parsedSchemas, - (parsedSchema): parsedSchema is ParsedSchema & { name: string } => - parsedSchema.schemaType === SCHEMA_TYPES.COMPLEX && - typeof parsedSchema.name === 'string' && - isEqual(parsedSchema.content, content) - ); + const foundSchemaByContent = index.complexByContent.get(content); return foundSchemaByContent ? this.typeNameFormatter.format(foundSchemaByContent.name) @@ -558,7 +593,7 @@ class SchemaRoutes { const typeNameWithoutOpId = operationId ? replace(refTypeInfo.typeName, operationId, '') : refTypeInfo.typeName; - if (find(parsedSchemas, (schema) => schema.name === typeNameWithoutOpId)) { + if (this.getParsedSchemasIndex(parsedSchemas).names.has(typeNameWithoutOpId)) { return this.typeNameFormatter.format(typeNameWithoutOpId); } diff --git a/src/swagger-schema-resolver.ts b/src/swagger-schema-resolver.ts index 9921778..9202ead 100644 --- a/src/swagger-schema-resolver.ts +++ b/src/swagger-schema-resolver.ts @@ -97,7 +97,14 @@ class SwaggerSchemaResolver { authorizationToken ); const swaggerSchemaObject = this.processSwaggerSchemaFile(swaggerSchemaFile); - return await this.convertSwaggerObject(swaggerSchemaObject, { patch }); + // a document parsed here from the file / downloaded text is not shared with anyone: no copy needed + return await this.convertSwaggerObject( + swaggerSchemaObject, + { patch }, + { + owned: typeof swaggerSchemaFile === 'string', + } + ); } /** @@ -105,7 +112,9 @@ class SwaggerSchemaResolver { */ convertSwaggerObject( swaggerSchema: unknown, - converterOptions: ConverterOptions + converterOptions: ConverterOptions, + /** `owned`: the document was created by the resolver, so it can be changed without copying it */ + { owned = false }: { owned?: boolean } = {} ): Promise { if (!isRecord(swaggerSchema)) { throw new Error(`Invalid swagger schema: expected an object, got ${typeof swaggerSchema}`); @@ -121,7 +130,7 @@ class SwaggerSchemaResolver { } return new Promise((resolve, reject) => { - const result = cloneDeep(swaggerSchema); + const result = owned ? swaggerSchema : cloneDeep(swaggerSchema); result.info = merge( { diff --git a/src/util/id.ts b/src/util/id.ts index 7e68ad4..3a042ed 100644 --- a/src/util/id.ts +++ b/src/util/id.ts @@ -2,13 +2,26 @@ import { randomBytes } from 'node:crypto'; const ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'; +// random bytes are taken from a pool: one `randomBytes` call per id was a syscall per route +const POOL_SIZE = 4096; +let pool = randomBytes(POOL_SIZE); +let poolOffset = 0; + /** random 12 chars id (`[a-z0-9]`) */ const generateId = (size = 12) => { - const bytes = randomBytes(size); + if (size > POOL_SIZE) { + const bytes = randomBytes(size); + return Array.from(bytes, (byte) => ALPHABET[byte % ALPHABET.length]).join(''); + } + if (poolOffset + size > POOL_SIZE) { + pool = randomBytes(POOL_SIZE); + poolOffset = 0; + } let id = ''; for (let i = 0; i < size; i++) { - id += ALPHABET[bytes[i] % ALPHABET.length]; + id += ALPHABET[pool[poolOffset + i] % ALPHABET.length]; } + poolOffset += size; return id; }; diff --git a/src/util/internal-case.ts b/src/util/internal-case.ts index b922796..676fc33 100644 --- a/src/util/internal-case.ts +++ b/src/util/internal-case.ts @@ -1,5 +1,15 @@ import { camelCase, lowerCase } from 'es-toolkit/compat'; -const internalCase = (value: string | undefined) => camelCase(lowerCase(value)); +/** memoized: called with the same (type / route / param) names many times */ +const cache = new Map(); + +const internalCase = (value: string | undefined) => { + let result = cache.get(value); + if (result === undefined) { + result = camelCase(lowerCase(value)); + cache.set(value, result); + } + return result; +}; export { internalCase }; diff --git a/src/util/name-resolver.ts b/src/util/name-resolver.ts index 9440b47..4da88ff 100644 --- a/src/util/name-resolver.ts +++ b/src/util/name-resolver.ts @@ -1,4 +1,4 @@ -import { compact, some, uniq } from 'es-toolkit/compat'; +import { compact, uniq } from 'es-toolkit/compat'; import type { CodeGenConfig } from '../configuration'; import type { Logger } from './logger'; @@ -41,21 +41,41 @@ class NameResolver { this.reserve(reservedNames); } + /** lookup set of `reservedNames` (the array stays the public, ordered list) */ + private reservedNamesSet = new Set(); + + private reservedNamesSetSource: string[] | null = null; + + /** keeps the lookup set in sync, also when `reservedNames` was replaced / changed from outside */ + private getReservedNamesSet() { + if ( + this.reservedNamesSetSource !== this.reservedNames || + this.reservedNamesSet.size !== this.reservedNames.length + ) { + this.reservedNamesSet = new Set(this.reservedNames); + this.reservedNamesSetSource = this.reservedNames; + } + return this.reservedNamesSet; + } + reserve(names: (string | null | undefined)[]) { const fixedNames = uniq(compact(names)); + const reserved = this.getReservedNamesSet(); for (const name of fixedNames) { - if (!this.reservedNames.includes(name)) { + if (!reserved.has(name)) { this.reservedNames.push(name); + reserved.add(name); } } } unreserve(names: string[]) { - this.reservedNames = this.reservedNames.filter((reservedName) => !names.includes(reservedName)); + const toRemove = new Set(names); + this.reservedNames = this.reservedNames.filter((reservedName) => !toRemove.has(reservedName)); } isReserved(name: string) { - return some(this.reservedNames, (reservedName) => reservedName === name); + return this.getReservedNamesSet().has(name); } /** diff --git a/src/util/pascal-case.ts b/src/util/pascal-case.ts index cf67e2e..9054b0e 100644 --- a/src/util/pascal-case.ts +++ b/src/util/pascal-case.ts @@ -1,5 +1,15 @@ import { camelCase, upperFirst } from 'es-toolkit/compat'; -const pascalCase = (value: string | undefined) => upperFirst(camelCase(value)); +/** memoized: called with the same (type / route / param) names many times */ +const cache = new Map(); + +const pascalCase = (value: string | undefined) => { + let result = cache.get(value); + if (result === undefined) { + result = upperFirst(camelCase(value)); + cache.set(value, result); + } + return result; +}; export { pascalCase }; diff --git a/tests/core/performance-caches.test.ts b/tests/core/performance-caches.test.ts index 55d3247..c7f646d 100644 --- a/tests/core/performance-caches.test.ts +++ b/tests/core/performance-caches.test.ts @@ -186,3 +186,70 @@ describe('config.update with big documents', () => { expect(b.files['api.ts']).toContain('class Mutated'); }); }); + +describe('documents read from a file are not copied', () => { + const fixture = (name: string) => path.resolve(__dirname, '../fixtures', name); + + it.each(['petstore.json', 'swagger2.yaml'])( + '%s: input file and spec object give the same output', + async (name) => { + const content = fs.readFileSync(fixture(name), 'utf8'); + const specObject = name.endsWith('.json') + ? JSON.parse(content) + : (await import('js-yaml')).load(content); + for (const options of [ + {}, + { modular: true, extractEnums: true, extractRequestParams: true }, + ]) { + const fromFile = await generate(content, options); + const fromSpec = await generate(specObject as object, options); + expect(fromFile.files).toEqual(fromSpec.files); + } + } + ); +}); + +describe('lookup indexes', () => { + it('SchemaComponentsMap.get follows components replaced or changed from outside', async () => { + const { SchemaComponentsMap } = await import('../../src/schema-components-map'); + const map = new SchemaComponentsMap({ + config: { hooks: { onCreateComponent: (c: any) => c } } as any, + }); + const a = map.createComponent('#/components/schemas/A', { type: 'string' }); + map.createComponent('#/components/schemas/B', { type: 'string' }); + expect(map.get('#/components/schemas/A')).toBe(a); + const a2 = map.createComponent('#/components/schemas/A', { type: 'number' }); + expect(map.get('#/components/schemas/A')).toBe(a2); + expect(map.getComponents()).toHaveLength(2); + // changed through the returned array + map.getComponents().unshift({ ...a2, $ref: '#/components/schemas/C' }); + expect(map.get('#/components/schemas/A')).toBe(a2); + expect(map.get('#/components/schemas/C')?.$ref).toBe('#/components/schemas/C'); + map.clear(); + expect(map.get('#/components/schemas/A')).toBeNull(); + }); + + it('NameResolver stays in sync when reservedNames is changed from outside', async () => { + const { NameResolver } = await import('../../src/util/name-resolver'); + const resolver = new NameResolver({} as any, null, ['A'], null); + expect(resolver.isReserved('A')).toBe(true); + resolver.reservedNames.push('B'); + expect(resolver.isReserved('B')).toBe(true); + resolver.reservedNames = ['C']; + expect(resolver.isReserved('A')).toBe(false); + expect(resolver.isReserved('C')).toBe(true); + resolver.reserve(['C', 'D']); + expect(resolver.reservedNames).toEqual(['C', 'D']); + resolver.unreserve(['C']); + expect(resolver.isReserved('C')).toBe(false); + expect(resolver.reservedNames).toEqual(['D']); + }); + + it('generateId keeps the [a-z0-9]{12} format across pool refills', async () => { + const { generateId } = await import('../../src/util/id'); + const ids = Array.from({ length: 2000 }, () => generateId()); + expect(ids.every((id) => /^[a-z0-9]{12}$/.test(id))).toBe(true); + expect(new Set(ids).size).toBe(ids.length); + expect(generateId(5000)).toMatch(/^[a-z0-9]{5000}$/); + }); +}); From f025b84368c29dc1d20c07b00b544cbd623db825 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 01:24:28 +0000 Subject: [PATCH 5/9] perf: format modular output files concurrently Templates are still rendered one after another (a render can set flags read by later ones), only the async formatting of the files runs concurrently. ~16% faster modular generation of a 1500 schemas / 3000 operations spec, byte-identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- src/code-gen-process.ts | 57 ++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/src/code-gen-process.ts b/src/code-gen-process.ts index 6f8060e..42b5336 100644 --- a/src/code-gen-process.ts +++ b/src/code-gen-process.ts @@ -436,7 +436,9 @@ class CodeGenProcess { ): Promise => { const { routes } = configuration; const { fileNames, generateRouteTypes, generateClient } = configuration.config; - const modularApiFileInfos: TranslatorIO[] = []; + // templates are rendered in order (a render can set flags read by later ones, e.g. `internalTemplateOptions`), + // the (async) formatting of the files runs concurrently + const modularApiFileInfos: Promise[] = []; // routes without module (e.g. `GET /`) are a flat list of routes, // wrap them into a module-like structure expected by modular templates @@ -458,11 +460,11 @@ class CodeGenProcess { ); modularApiFileInfos.push( - ...(await this.createOutputFileInfo( + this.createOutputFileInfo( configuration, pascalCase(`${fileNames.outOfModuleApi}_Route`), outOfModuleRouteContent - )) + ) ); } if (generateClient) { @@ -472,11 +474,7 @@ class CodeGenProcess { }); modularApiFileInfos.push( - ...(await this.createOutputFileInfo( - configuration, - fileNames.outOfModuleApi, - outOfModuleApiContent - )) + this.createOutputFileInfo(configuration, fileNames.outOfModuleApi, outOfModuleApiContent) ); } } @@ -493,11 +491,11 @@ class CodeGenProcess { ); modularApiFileInfos.push( - ...(await this.createOutputFileInfo( + this.createOutputFileInfo( configuration, pascalCase(`${route.moduleName}_Route`), routeModuleContent - )) + ) ); } @@ -508,31 +506,32 @@ class CodeGenProcess { }); modularApiFileInfos.push( - ...(await this.createOutputFileInfo( - configuration, - pascalCase(route.moduleName), - apiModuleContent - )) + this.createOutputFileInfo(configuration, pascalCase(route.moduleName), apiModuleContent) ); } } } - return [ - ...(await this.createOutputFileInfo( - configuration, - fileNames.dataContracts, - this.templatesWorker.renderTemplate(templatesToRender.dataContracts, configuration) - )), - ...(generateClient - ? await this.createOutputFileInfo( - configuration, - fileNames.httpClient, - this.templatesWorker.renderTemplate(templatesToRender.httpClient, configuration) - ) - : []), + const dataContractsFileInfo = this.createOutputFileInfo( + configuration, + fileNames.dataContracts, + this.templatesWorker.renderTemplate(templatesToRender.dataContracts, configuration) + ); + const httpClientFileInfo = generateClient + ? this.createOutputFileInfo( + configuration, + fileNames.httpClient, + this.templatesWorker.renderTemplate(templatesToRender.httpClient, configuration) + ) + : []; + + const [dataContracts, httpClient, ...apiModules] = await Promise.all([ + dataContractsFileInfo, + httpClientFileInfo, ...modularApiFileInfos, - ]; + ]); + + return [...dataContracts, ...httpClient, ...apiModules.flat()]; }; createSingleFileInfo = ( From 8b7c82ec40258ec849a8912b31bb76fa33fdd2ff Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 01:58:26 +0000 Subject: [PATCH 6/9] perf: never change the input document, stop deep-copying it The parser cached its results on the schema objects (`schema.$parsed`) and fixed documents in place, so every document had to be deep-copied (resolver, original schema, schema walker). - parse results live in ParsedSchemaCache (WeakMap). Copies of schemas carry the parse result of their source (inherit / cloneDeep), exactly as the enumerable $parsed property was copied, so the output is unchanged - the fixes are applied to copies: items without type, discriminator mapping, default info, swagger 2 paths, fixSwaggerSchema consumes / produces / params - documents are deep-copied only when custom code (hooks, schema parsers, templates, type constructs) could change them (config.hasCustomSchemaCode) - $parsed removed from the SchemaObject type Safety net: byte-identical output for all 168 spec / option combinations of the test suite (recorded before / after) and 27 fixture combinations; new input-immutability tests with deep-frozen documents; npm run test:immutability runs the whole suite with frozen inputs (added to CI). ~25% faster in-process generation of a large spec, ~14% faster CLI run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- .github/workflows/main.yml | 2 + CHANGELOG.md | 10 + CLAUDE.md | 2 +- README.md | 30 +-- package.json | 1 + src/code-gen-process.ts | 6 +- src/configuration.ts | 14 ++ .../base-schema-parsers/discriminator.ts | 47 +++-- src/schema-parser/parsed-schema-cache.test.ts | 80 ++++++++ src/schema-parser/parsed-schema-cache.ts | 92 +++++++++ src/schema-parser/schema-formatters.ts | 8 +- src/schema-parser/schema-parser-fabric.ts | 7 +- src/schema-parser/schema-parser.ts | 45 ++++- src/schema-parser/schema-utils.ts | 29 ++- src/schema-routes/schema-routes.ts | 116 ++++++----- src/schema-walker.ts | 7 +- src/swagger-schema-resolver.ts | 57 ++++-- src/types/openapi.ts | 3 - src/types/parsed.ts | 2 +- tests/core/input-immutability.test.ts | 186 ++++++++++++++++++ tests/helpers/generate.ts | 16 +- 21 files changed, 641 insertions(+), 119 deletions(-) create mode 100644 src/schema-parser/parsed-schema-cache.test.ts create mode 100644 src/schema-parser/parsed-schema-cache.ts create mode 100644 tests/core/input-immutability.test.ts diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b5f965a..a54babb 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -31,6 +31,8 @@ jobs: - run: npm run fmt:check - run: npm run typecheck - run: npm test -- --run + # the whole suite again with deep-frozen input documents (the generator must not change them) + - run: npm run test:immutability - run: npm run build - run: node bin/cli.mjs --help diff --git a/CHANGELOG.md b/CHANGELOG.md index f373855..dcb129b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,9 @@ - **Boolean enums** are generated as union types (`true | false`) β€” a TS `enum` with boolean values does not compile. - **Type names are deterministic**: the same spec always produces the same names (they were picked randomly on name clashes). +- Schemas no longer get a `$parsed` property (an undocumented internal cache) and the `spec` object + passed to `generateApi` is never modified. + ### 🐞 Bug fixes - CLI: @@ -57,6 +60,13 @@ ### ⚑ Performance +- The generator no longer changes the input document, so it is not deep-copied anymore: + - parse results are cached aside (`ParsedSchemaCache`) instead of `schema.$parsed`, the + `items` without `type`, discriminator mapping and `consumes` / `produces` fixes are applied to copies; + - the document is copied only when custom code (hooks, schema parsers, templates, type constructs) + could change it; `originalSchema` shares the unchanged objects with the input; + - ~25% faster in-process generation of large specs, ~14% faster CLI run; guarded by + `npm run test:immutability` (the whole suite with deep-frozen inputs) in CI. - Compiled Eta templates are cached (they were recompiled for every route, model and include) and included template files are read once. - `typescript` is only loaded when `toJS` is used (~400ms less startup). diff --git a/CLAUDE.md b/CLAUDE.md index b9ddd0a..f63d229 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,7 @@ The core flow in `src/code-gen-process.ts`: 1. **Schema Resolution** (`src/swagger-schema-resolver.ts`) β€” fetches spec from URL or file, converts Swagger 2.0 β†’ OpenAPI 3.0 via `swagger2openapi`, resolves `$ref`s. 2. **Component Mapping** (`src/schema-components-map.ts`) β€” indexes all `#/components/schemas/*` entries. 3. **Schema Walking** (`src/schema-walker.ts`) β€” traverses and caches resolved schema nodes (WIP). -4. **Schema Parsing** (`src/schema-parser/`) β€” recursively parses schema nodes into internal type representations. +4. **Schema Parsing** (`src/schema-parser/`) β€” recursively parses schema nodes into internal type representations. Parse results are cached in `ParsedSchemaCache` (a `WeakMap`), **never on the schema objects**: the generator must not change the input document (it is not copied unless custom hooks / parsers / templates / constructs are used, see `config.hasCustomSchemaCode`). When copying a schema, carry its parse result with `parsedSchemaCache.inherit` / `cloneDeep` (as the old `$parsed` property was copied), and apply fixes to copies. `npm run test:immutability` runs the suite with deep-frozen inputs. 5. **Route Extraction** (`src/schema-routes/schema-routes.ts`) β€” converts OpenAPI paths/operations into method descriptors. 6. **Template Rendering** (`src/templates-worker.ts`) β€” uses the [Eta](https://eta.js.org/) template engine to emit TypeScript code. 7. **Code Formatting** (`src/code-formatter.ts`) β€” formats output with `oxfmt`. Options = `CONSTANTS.OXC_FORMAT_OPTIONS` < `.oxfmtrc.json` in `process.cwd()` (if present) < user `oxfmtOptrions`. diff --git a/README.md b/README.md index 068934a..cbb1ca0 100644 --- a/README.md +++ b/README.md @@ -427,7 +427,8 @@ import type { GenerateApiOutput, IOptions } from 'swagger-typescript-api-es'; ``` To pass a schema object you already have, use `spec` (typed as `OpenAPIDocument`, OpenAPI 3.x or -Swagger 2.0): +Swagger 2.0). The object is never modified by the generator, and it is not even copied unless hooks, +custom schema parsers, templates or type constructs are used: ```ts import { readFile } from 'node:fs/promises'; @@ -765,19 +766,20 @@ cd swagger-typescript-api-es npm install ``` -| Script | What it does | -| ----------------------- | --------------------------------------------------------------- | -| `npm run build` | Build with `unbuild` and copy `templates/` to `dist/templates/` | -| `npm run dev` | Stub build (`unbuild --stub`) for fast local development | -| `npm test` | Run the tests with Vitest (`npm test -- --run` runs them once) | -| `npm run test:coverage` | Run the tests once with v8 coverage | -| `npm run lint` | Lint with oxlint (`lint:fix` to fix) | -| `npm run fmt` | Format with oxfmt (`fmt:check` to check) | -| `npm run typecheck` | `tsc --noEmit` | -| `npm start` | Run the playground `play/test.ts` | -| `npm run bench` | Build, then benchmark generation on small / large specs | -| `npm run test:cli` | Run the built CLI (`node dist/cli.mjs`) | -| `npm run test:cli1` | Run the CLI from source (`tsx src/cli.ts`) | +| Script | What it does | +| --------------------------- | ------------------------------------------------------------------------------- | +| `npm run build` | Build with `unbuild` and copy `templates/` to `dist/templates/` | +| `npm run dev` | Stub build (`unbuild --stub`) for fast local development | +| `npm test` | Run the tests with Vitest (`npm test -- --run` runs them once) | +| `npm run test:coverage` | Run the tests once with v8 coverage | +| `npm run test:immutability` | Run the tests with deep-frozen input specs (the generator must not change them) | +| `npm run lint` | Lint with oxlint (`lint:fix` to fix) | +| `npm run fmt` | Format with oxfmt (`fmt:check` to check) | +| `npm run typecheck` | `tsc --noEmit` | +| `npm start` | Run the playground `play/test.ts` | +| `npm run bench` | Build, then benchmark generation on small / large specs | +| `npm run test:cli` | Run the built CLI (`node dist/cli.mjs`) | +| `npm run test:cli1` | Run the CLI from source (`tsx src/cli.ts`) | Tests live in `tests/`: diff --git a/package.json b/package.json index 172ddaa..013b84b 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "start": "tsx play/test.ts", "test": "vitest", "test:coverage": "vitest run --coverage", + "test:immutability": "STA_FREEZE=1 vitest run", "bench": "npm run build && node bench/index.mjs", "changelog": "npx changeloggithub@latest --all true && git add CHANGELOG.md && git commit -m 'chore: update CHANGELOG.md'", "prepublishOnly": "npm run build", diff --git a/src/code-gen-process.ts b/src/code-gen-process.ts index 42b5336..9ad69ee 100644 --- a/src/code-gen-process.ts +++ b/src/code-gen-process.ts @@ -124,8 +124,10 @@ class CodeGenProcess { originalSchema: swagger.originalSchema, }); - this.schemaWalker.addSchema('$usage', swagger.usageSchema); - this.schemaWalker.addSchema('$original', swagger.originalSchema); + // the documents are not changed by the generator (only custom code could change them) + const copy = this.config.hasCustomSchemaCode; + this.schemaWalker.addSchema('$usage', swagger.usageSchema, { copy }); + this.schemaWalker.addSchema('$original', swagger.originalSchema, { copy }); this.logger.event('Start generating your typescript api'); diff --git a/src/configuration.ts b/src/configuration.ts index 8d9e047..a882254 100644 --- a/src/configuration.ts +++ b/src/configuration.ts @@ -168,6 +168,11 @@ class CodeGenConfig { /** custom schema parsers */ schemaParsers: SchemaParsers = {}; + /** + * `true` when hooks, schema parsers, templates or type constructs are customized: they get the raw + * schemas and could change them, so the documents are deep-copied (the input is never changed) + */ + hasCustomSchemaCode = false; toJS = false; silent = false; typePrefix = ''; @@ -395,6 +400,15 @@ class CodeGenConfig { output, ...otherConfig }: CodeGenProcessOptions) { + // user code which receives the raw schemas (and could change them) + this.hasCustomSchemaCode = + Object.values(hooks || {}).some((hook) => typeof hook === 'function') || + Object.keys(otherConfig.schemaParsers || {}).length > 0 || + !!otherConfig.templates || + (otherConfig.extraTemplates?.length ?? 0) > 0 || + !!codeGenConstructs || + !!primitiveTypeConstructs; + objectAssign(this.Ts, codeGenConstructs); objectAssign(this.primitiveTypes, primitiveTypeConstructs); diff --git a/src/schema-parser/base-schema-parsers/discriminator.ts b/src/schema-parser/base-schema-parsers/discriminator.ts index 82a37dd..3ba03bb 100644 --- a/src/schema-parser/base-schema-parsers/discriminator.ts +++ b/src/schema-parser/base-schema-parsers/discriminator.ts @@ -1,4 +1,3 @@ -import { cloneDeep } from 'es-toolkit'; import { clone, compact, entries, isArray, isObject, keys, omit, reduce } from 'es-toolkit/compat'; import { SCHEMA_TYPES } from '../../constants'; @@ -197,7 +196,7 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { : undefined; const mappingPropertyRawSchema: SchemaObject | undefined = mappingPropertyComponent?.rawTypeData; - const parsedEnum = mappingPropertyRawSchema?.$parsed; + const parsedEnum = this.schemaParserFabric.parsedSchemaCache.get(mappingPropertyRawSchema); if (parsedEnum?.type === SCHEMA_TYPES.ENUM) { mappingPropertySchemaEnumKeysMap = reduce( @@ -230,21 +229,28 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { const abstractRef = abstractSchemaStruct?.component?.$ref; // override parent dependencies if (mappingSchema.$ref && abstractRef) { - const mappingRefSchema: SchemaObject | undefined = - this.schemaUtils.getSchemaRefType(mappingSchema)?.rawTypeData; - if (mappingRefSchema) { + const mappingComponent = this.schemaUtils.getSchemaRefType(mappingSchema); + const mappingRefSchema: SchemaObject | undefined = mappingComponent?.rawTypeData; + if (mappingComponent && mappingRefSchema) { + const cache = this.schemaParserFabric.parsedSchemaCache; + // the input document is not changed: the component gets a changed copy of its schema + // (the copies keep the parse results of the originals, as when they were changed in place) + let changedRefSchema: SchemaObject | null = null; for (const schemaKey of COMPLEX_SCHEMA_TYPES) { - const childSchemas = mappingRefSchema[schemaKey]; + const currentSchema: SchemaObject = changedRefSchema ?? mappingRefSchema; + const childSchemas: SchemaObject[keyof Pick] | SchemaObject = + currentSchema[schemaKey]; if (isSchemaList(childSchemas)) { - const mappedChildSchemas = childSchemas.map((schema): SchemaObject => { + const mappedChildSchemas: SchemaObject[] = childSchemas.map((schema): SchemaObject => { if (schema.$ref === refPath) { - return { + return cache.inherit(schema, { ...schema, $ref: abstractRef, - }; + }); } if (this.schemaUtils.getInternalSchemaType(schema) === SCHEMA_TYPES.OBJECT) { const properties = schema.properties || {}; + let changedProperties: Record | null = null; for (const schemaPropertyName in properties) { const schemaProperty = properties[schemaPropertyName]; if ( @@ -254,18 +260,32 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { schemaProperty.enum.length === 1 && mappingPropertySchemaEnumKeysMap[String(schemaProperty.enum[0])] ) { - properties[schemaPropertyName] = this.schemaParserFabric.createSchema({ + changedProperties ??= { ...properties }; + changedProperties[schemaPropertyName] = this.schemaParserFabric.createSchema({ content: mappingPropertySchemaEnumKeysMap[String(schemaProperty.enum[0])], }); } } + if (changedProperties) { + const changedSchema = cache.inherit(schema, { + ...schema, + properties: changedProperties, + }); + return changedSchema; + } } return schema; }); // `not` is a single schema (an array is mapped too) - Object.assign(mappingRefSchema, { [schemaKey]: mappedChildSchemas }); + changedRefSchema = cache.inherit(mappingRefSchema, { + ...currentSchema, + [schemaKey]: mappedChildSchemas, + }); } } + if (changedRefSchema) { + mappingComponent.rawTypeData = changedRefSchema; + } } } }; @@ -273,8 +293,9 @@ class DiscriminatorSchemaParser extends MonoSchemaParser { createAbstractSchemaStruct = (): DiscriminatorAbstractSchemaStruct | undefined => { const schema = omit(clone(this.schema), ['discriminator', ...COMPLEX_SCHEMA_TYPES]); const schemaIsAny = - this.schemaParserFabric.getInlineParseContent(cloneDeep(schema)) === - this.config.Ts.Keyword.Any; + this.schemaParserFabric.getInlineParseContent( + this.schemaParserFabric.parsedSchemaCache.cloneDeep(schema) + ) === this.config.Ts.Keyword.Any; const schemaIsEmpty = keys(schema).length === 0; if (schemaIsEmpty || schemaIsAny) { diff --git a/src/schema-parser/parsed-schema-cache.test.ts b/src/schema-parser/parsed-schema-cache.test.ts new file mode 100644 index 0000000..42c42d5 --- /dev/null +++ b/src/schema-parser/parsed-schema-cache.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; + +import type { ParsedSchema } from '../types/parsed'; +import { ParsedSchemaCache } from './parsed-schema-cache'; + +const parsed = (name: string) => ({ name, content: [] }) as unknown as ParsedSchema; + +describe('ParsedSchemaCache', () => { + it('stores parse results by object identity, ignores primitives', () => { + const cache = new ParsedSchemaCache(); + const schema = { type: 'string' }; + cache.set(schema, parsed('a')); + expect(cache.get(schema)).toEqual(parsed('a')); + expect(cache.get({ type: 'string' })).toBeUndefined(); + cache.set('text', parsed('b')); + expect(cache.get('text')).toBeUndefined(); + expect(cache.get(null)).toBeUndefined(); + }); + + it('inherit: a copy gets the result of its source, without overwriting its own', () => { + const cache = new ParsedSchemaCache(); + const source = { type: 'string' }; + const own = { type: 'number' }; + const result = parsed('source'); + cache.set(source, result); + cache.set(own, parsed('own')); + + const copy = cache.inherit(source, { ...source, nullable: true }); + expect(cache.get(copy)).toBe(result); + expect(cache.inherit(source, own)).toBe(own); + expect(cache.get(own)).toEqual(parsed('own')); + // nothing to inherit + const plain = cache.inherit({ type: 'boolean' }, { type: 'boolean' }); + expect(cache.get(plain)).toBeUndefined(); + }); + + it('cloneDeep copies the objects and their parse results (like cloneDeep with `$parsed`)', () => { + const cache = new ParsedSchemaCache(); + const shared = { type: 'string' }; + interface TestSchema { + type: string; + properties: { a: object; b: object; list: { type: string; items: object } }; + created: Date; + pattern: RegExp; + self?: TestSchema; + } + const schema: TestSchema = { + type: 'object', + properties: { a: shared, b: shared, list: { type: 'array', items: shared } }, + created: new Date(0), + pattern: /^a+$/g, + }; + schema.self = schema; + const nestedResult = { name: 'Nested', content: [{ rawSchema: shared }] }; + cache.set(shared, nestedResult as unknown as ParsedSchema); + + const copy = cache.cloneDeep(schema); + + expect(copy).not.toBe(schema); + expect(copy.properties.a).not.toBe(shared); + expect(copy.properties.a).toEqual(shared); + // shared references and cycles stay shared in the copy + expect(copy.properties.a).toBe(copy.properties.b); + expect(copy.properties.list.items).toBe(copy.properties.a); + expect(copy.self).toBe(copy); + expect(copy.created).toEqual(new Date(0)); + expect(copy.created).not.toBe(schema.created); + expect(copy.pattern.source).toBe('^a+$'); + expect(copy.pattern.flags).toBe('g'); + + // the parse result is copied too, and references the copied schema + const copiedResult = cache.get(copy.properties.a) as unknown as typeof nestedResult; + expect(copiedResult).toEqual(nestedResult); + expect(copiedResult).not.toBe(nestedResult); + expect(copiedResult.content[0].rawSchema).toBe(copy.properties.a); + // the source is untouched + expect(cache.get(shared)).toBe(nestedResult); + expect(cache.get(copy)).toBeUndefined(); + }); +}); diff --git a/src/schema-parser/parsed-schema-cache.ts b/src/schema-parser/parsed-schema-cache.ts new file mode 100644 index 0000000..65a5995 --- /dev/null +++ b/src/schema-parser/parsed-schema-cache.ts @@ -0,0 +1,92 @@ +import type { ParsedSchema } from '../types/parsed'; + +const isObjectLike = (value: unknown): value is object => + typeof value === 'object' && value !== null; + +/** + * Parse results of raw schemas, keyed by the schema object. + * + * They used to be stored on the schemas themselves (`schema.$parsed`), which mutated the input + * document (so it had to be deep-copied first). As an enumerable property, `$parsed` was also + * carried over by every copy of a schema (`{ ...schema }`, `clone`, `cloneDeep`, `omit`, ...): + * `inherit` and `cloneDeep` keep that behaviour where schemas are copied, so the output is unchanged. + */ +class ParsedSchemaCache { + private parsed = new WeakMap(); + + get(schema: unknown): ParsedSchema | undefined { + return isObjectLike(schema) ? this.parsed.get(schema) : undefined; + } + + set(schema: unknown, parsed: ParsedSchema) { + if (isObjectLike(schema)) { + this.parsed.set(schema, parsed); + } + } + + /** + * `copy` gets the parse result of `source` (as `{ ...source }` copied `source.$parsed`). + * @returns `copy` + */ + inherit(source: unknown, copy: T): T { + if (isObjectLike(source) && isObjectLike(copy) && !this.parsed.has(copy)) { + const parsed = this.parsed.get(source); + if (parsed !== undefined) { + this.parsed.set(copy, parsed); + } + } + return copy; + } + + /** + * Deep copy of a schema. Like `cloneDeep` did with `$parsed`, the parse results of the copied + * objects are deep-copied too (with the same copies of the objects they reference). + */ + cloneDeep(value: T): T { + return this.cloneValue(value, new Map()) as T; + } + + private cloneValue(value: unknown, copies: Map): unknown { + if (!isObjectLike(value)) { + return value; + } + + const existing = copies.get(value); + if (existing !== undefined) { + return existing; + } + + let copy: object; + + if (Array.isArray(value)) { + const array: unknown[] = []; + copies.set(value, array); + for (const item of value) { + array.push(this.cloneValue(item, copies)); + } + copy = array; + } else if (value instanceof Date) { + copy = new Date(value.getTime()); + copies.set(value, copy); + } else if (value instanceof RegExp) { + copy = new RegExp(value.source, value.flags); + copies.set(value, copy); + } else { + const object: Record = Object.create(Object.getPrototypeOf(value)); + copies.set(value, object); + for (const key of Object.keys(value)) { + object[key] = this.cloneValue((value as Record)[key], copies); + } + copy = object; + } + + const parsed = this.parsed.get(value); + if (parsed !== undefined) { + this.parsed.set(copy, this.cloneValue(parsed, copies) as ParsedSchema); + } + + return copy; + } +} + +export { ParsedSchemaCache }; diff --git a/src/schema-parser/schema-formatters.ts b/src/schema-parser/schema-formatters.ts index 78f015a..783df5a 100644 --- a/src/schema-parser/schema-formatters.ts +++ b/src/schema-parser/schema-formatters.ts @@ -9,6 +9,7 @@ import type { ParsedSchema, } from '../types/parsed'; import type { Logger } from '../util/logger'; +import type { ParsedSchemaCache } from './parsed-schema-cache'; import type { SchemaParserConfig, SchemaParserFabricDeps } from './schema-parser-fabric'; import type { SchemaUtils } from './schema-utils'; @@ -24,6 +25,8 @@ export interface SchemaFormattersDeps { logger: Partial>; schemaUtils: Pick; templatesWorker: SchemaParserFabricDeps['templatesWorker']; + /** parse results of raw schemas (a raw schema can be formatted too) */ + parsedSchemaCache?: Pick; } /** an item of a parsed content (the characters of a string content are iterated too, like by lodash `map`) */ @@ -52,6 +55,7 @@ class SchemaFormatters { config: SchemaFormattersDeps['config']; logger: SchemaFormattersDeps['logger']; templatesWorker: SchemaFormattersDeps['templatesWorker']; + parsedSchemaCache: SchemaFormattersDeps['parsedSchemaCache']; schemaUtils: SchemaFormattersDeps['schemaUtils']; /** @@ -62,6 +66,7 @@ class SchemaFormatters { this.logger = schemaParser.logger; this.schemaUtils = schemaParser.schemaUtils; this.templatesWorker = schemaParser.templatesWorker; + this.parsedSchemaCache = schemaParser.parsedSchemaCache; } base: Record<'enum' | 'object' | 'primitive', SchemaFormatter> = { @@ -169,7 +174,8 @@ class SchemaFormatters { ): FormattedSchema => { // a raw schema with a cached parsed schema can be passed too (e.g. from templates) const rawSchema: SchemaObject | undefined = parsedSchema; - const schemaType = parsedSchema?.schemaType || rawSchema?.$parsed?.schemaType; + const schemaType = + parsedSchema?.schemaType || this.parsedSchemaCache?.get(rawSchema)?.schemaType; const formatters: Partial> | undefined = this[formatType]; const formatterFn = schemaType ? formatters?.[schemaType] : undefined; return (formatterFn && formatterFn(parsedSchema)) || toUnformattedSchema(parsedSchema); diff --git a/src/schema-parser/schema-parser-fabric.ts b/src/schema-parser/schema-parser-fabric.ts index 9f817de..e267edb 100644 --- a/src/schema-parser/schema-parser-fabric.ts +++ b/src/schema-parser/schema-parser-fabric.ts @@ -1,5 +1,3 @@ -import { cloneDeep } from 'es-toolkit'; - import type { CodeGenConfig } from '../configuration'; import type { SchemaComponentsMap } from '../schema-components-map'; import type { SchemaWalker } from '../schema-walker'; @@ -9,6 +7,7 @@ import type { SchemaPath } from '../types/config'; import type { SchemaObject } from '../types/openapi'; import type { ParsedSchema, SchemaComponent } from '../types/parsed'; import type { Logger } from '../util/logger'; +import { ParsedSchemaCache } from './parsed-schema-cache'; import { SchemaFormatters } from './schema-formatters'; import { SchemaParser } from './schema-parser'; import type { SchemaParserOptions } from './schema-parser'; @@ -83,6 +82,8 @@ class SchemaParserFabric { templatesWorker: SchemaParserFabricDeps['templatesWorker']; schemaUtils: SchemaUtils; schemaWalker: SchemaWalker | undefined; + /** parse results of the raw schemas (they are not stored on the schemas) */ + parsedSchemaCache = new ParsedSchemaCache(); constructor({ config, @@ -144,7 +145,7 @@ class SchemaParserFabric { schema, schemaPath, }: CreateParsedComponentOptions): SchemaComponent & { typeData: ParsedSchema } => { - const schemaCopy = cloneDeep(schema); + const schemaCopy = this.parsedSchemaCache.cloneDeep(schema); const customComponent = this.schemaComponentsMap.createComponent( // `null` is joined as an empty string this.schemaComponentsMap.createRef(['components', 'schemas', typeName ?? '']), diff --git a/src/schema-parser/schema-parser.ts b/src/schema-parser/schema-parser.ts index db618bb..b8e6a3d 100644 --- a/src/schema-parser/schema-parser.ts +++ b/src/schema-parser/schema-parser.ts @@ -129,7 +129,7 @@ class SchemaParser { }; /** - * Parses the schema (the result is cached as `schema.$parsed`). + * Parses the schema (the result is cached in `schemaParserFabric.parsedSchemaCache`). * A string "schema" is returned as is. */ parseSchema = (): ParsedSchema => { @@ -144,7 +144,8 @@ class SchemaParser { return this.schema; } - let parsed = this.schema.$parsed; + const cache = this.schemaParserFabric.parsedSchemaCache; + let parsed = cache.get(this.schema); if (!parsed) { if (!this.typeName && this.schemaUtils.isRefSchema(this.schema)) { @@ -155,7 +156,10 @@ class SchemaParser { // schema has items but don't have array type if (this.schema.items && !Array.isArray(this.schema.items) && !this.schema.type) { - this.schema.type = SCHEMA_TYPES.ARRAY; + // a copy (the input document is not changed), its parse result is cached for both objects + const sourceSchema = this.schema; + this.schema = cache.inherit(sourceSchema, { ...sourceSchema, type: SCHEMA_TYPES.ARRAY }); + this.cacheAlso = sourceSchema; } // schema is enum with one null value if ( @@ -165,6 +169,8 @@ class SchemaParser { ) { this.logger.debug('invalid enum schema', this.schema); this.schema = { type: this.config.Ts.Keyword.Null }; + // the replaced schema is not cached (as before) + this.cacheAlso = null; } // schema is response schema if ('content' in this.schema && typeof this.schema.content === 'object') { @@ -175,7 +181,7 @@ class SchemaParser { schemaPath: this.schemaPath, }); const responseParsed = schemaParser.parseSchema(); - this.schema.$parsed = responseParsed; + this.setParsed(responseParsed); return responseParsed; } @@ -191,7 +197,7 @@ class SchemaParser { ); parsedSchema = this._baseSchemaParsers[schemaType](this.schema, this.typeName); parsed = this.config.hooks.onParseSchema(this.schema, parsedSchema) || parsedSchema; - this.schema.$parsed = parsed; + this.setParsed(parsed); if (this.config.sortTypes && Array.isArray(parsed?.content)) { // sorted in place @@ -204,6 +210,17 @@ class SchemaParser { return parsed; }; + /** the input schema replaced by a changed copy (its parse result is cached too) */ + private cacheAlso: SchemaObject | null = null; + + private setParsed = (parsed: ParsedSchema) => { + const cache = this.schemaParserFabric.parsedSchemaCache; + cache.set(this.schema, parsed); + if (this.cacheAlso) { + cache.set(this.cacheAlso, parsed); + } + }; + getInlineParseContent = (): string => { const parsedSchema = this.parseSchema(); const formattedSchema = this.schemaFormatters.formatSchema(parsedSchema, 'inline'); @@ -231,11 +248,19 @@ class SchemaParser { return; } - return { - ...extras, - ...omit(firstResponse, 'schema'), - ...firstSchema, - }; + const cache = this.schemaParserFabric.parsedSchemaCache; + // the parse result was carried over by the spread (`$parsed`): the last spread object wins + return cache.inherit( + responseStruct, + cache.inherit( + firstResponse, + cache.inherit(firstSchema, { + ...extras, + ...omit(firstResponse, 'schema'), + ...firstSchema, + }) + ) + ); }; } diff --git a/src/schema-parser/schema-utils.ts b/src/schema-parser/schema-utils.ts index 3646c59..3793409 100644 --- a/src/schema-parser/schema-utils.ts +++ b/src/schema-parser/schema-utils.ts @@ -23,6 +23,7 @@ import type { BaseSchemaType, ComplexSchemaType, SchemaComponent } from '../type import { internalCase } from '../util/internal-case'; import { pascalCase } from '../util/pascal-case'; import { isObjectRecord, isRecord } from '../util/type-guards'; +import type { ParsedSchemaCache } from './parsed-schema-cache'; import type { SchemaParserComponentsMap, SchemaParserConfig, @@ -57,6 +58,8 @@ export interface SchemaUtilsDeps { typeNameFormatter: Pick; /** not used yet */ schemaWalker?: SchemaWalker; + /** parse results of the raw schemas (carried over to their copies) */ + parsedSchemaCache?: Pick; } /** options of `SchemaUtils.resolveTypeName` */ @@ -76,14 +79,26 @@ class SchemaUtils { schemaComponentsMap: SchemaUtilsDeps['schemaComponentsMap']; typeNameFormatter: SchemaUtilsDeps['typeNameFormatter']; schemaWalker: SchemaWalker | undefined; - - constructor({ config, schemaComponentsMap, typeNameFormatter, schemaWalker }: SchemaUtilsDeps) { + parsedSchemaCache: SchemaUtilsDeps['parsedSchemaCache']; + + constructor({ + config, + schemaComponentsMap, + typeNameFormatter, + schemaWalker, + parsedSchemaCache, + }: SchemaUtilsDeps) { this.config = config; this.schemaComponentsMap = schemaComponentsMap; this.typeNameFormatter = typeNameFormatter; this.schemaWalker = schemaWalker; + this.parsedSchemaCache = parsedSchemaCache; } + /** `copy` of `source` keeps its parse result (see `ParsedSchemaCache.inherit`) */ + inheritParsed = (source: unknown, copy: T): T => + this.parsedSchemaCache ? this.parsedSchemaCache.inherit(source, copy) : copy; + getRequiredProperties = (schema: SchemaObject | null | undefined): string[] => { return uniq(schema && isArray(schema.required) ? schema.required : []); }; @@ -227,10 +242,10 @@ class SchemaUtils { return childSchema; } - return { + return this.inheritParsed(childSchema, { ...childSchema, $$requiredKeys: existedRequiredKeys, - }; + }); } else if (childSchema.properties) { const childSchemaProperties = keys(childSchema.properties); const existedRequiredKeys = childSchemaProperties.filter((key) => required.includes(key)); @@ -239,10 +254,10 @@ class SchemaUtils { return childSchema; } - return { + return this.inheritParsed(childSchema, { ...childSchema, required: uniq([...this.getRequiredProperties(childSchema), ...existedRequiredKeys]), - }; + }); } return childSchema; @@ -356,7 +371,7 @@ class SchemaUtils { return this.checkAndAddRequiredKeys( schema, this.safeAddNullToType( - isEnumWithNull ? { ...schema, nullable: true } : schema, + isEnumWithNull ? this.inheritParsed(schema, { ...schema, nullable: true }) : schema, this.typeNameFormatter.format(refTypeInfo.typeName) ) ); diff --git a/src/schema-routes/schema-routes.ts b/src/schema-routes/schema-routes.ts index bd34182..b330b79 100644 --- a/src/schema-routes/schema-routes.ts +++ b/src/schema-routes/schema-routes.ts @@ -13,7 +13,6 @@ import { isObject, keys, map, - omit, reduce, replace, slice, @@ -254,10 +253,10 @@ class SchemaRoutes { return acc; } - acc[method] = { + acc[method] = this.inheritParsed(requestInfo, { ...requestInfo, parameters: this.mergeParameters(parameters, requestInfo.parameters), - }; + }); return acc; }, @@ -398,10 +397,14 @@ class SchemaRoutes { routeParams[resolvedParameter.in] = []; } - const routeParam = { - ...resolvedParameter, - ...resolvedParameter.schema, - }; + // the parse result was carried over by the spread: the last spread object wins + const routeParam = this.inheritParsed( + resolvedParameter, + this.inheritParsed(resolvedParameter.schema, { + ...resolvedParameter, + ...resolvedParameter.schema, + }) + ); if (routeParam.in === 'path') { if (!routeParam.name) { @@ -499,16 +502,20 @@ class SchemaRoutes { for (const dataType in content) { const mediaType = content[dataType]; if (mediaType && mediaType.schema) { - return { + return this.inheritParsed(mediaType.schema, { ...mediaType.schema, dataType, - }; + }); } } return null; }; + /** `copy` of `source` keeps its parse result (see `ParsedSchemaCache.inherit`) */ + inheritParsed = (source: unknown, copy: T): T => + this.schemaParserFabric.parsedSchemaCache.inherit(source, copy); + /** lookup tables of the parsed components, built once per `parsedSchemas` list */ parsedSchemasIndexes = new WeakMap(); @@ -637,30 +644,35 @@ class SchemaRoutes { requestInfos, (acc: ResponseInfo[], requestInfo, status) => { const contentTypes = this.getContentTypes([requestInfo]); + // the spread copied the parse result as it was *before* `type` below parses `requestInfo` + const parsedBefore = this.schemaParserFabric.parsedSchemaCache.get(requestInfo); - return [ - ...acc, - { - ...requestInfo, - contentTypes, - contentKind: this.getContentKind(contentTypes), - type: this.schemaParserFabric.schemaUtils.safeAddNullToType( + const responseInfo: ResponseInfo = { + ...requestInfo, + contentTypes, + contentKind: this.getContentKind(contentTypes), + type: this.schemaParserFabric.schemaUtils.safeAddNullToType( + requestInfo, + this.getTypeFromRequestInfo({ requestInfo, - this.getTypeFromRequestInfo({ - requestInfo, - parsedSchemas, - operationId, - defaultType, - }) - ), - description: this.schemaParserFabric.schemaFormatters.formatDescription( - requestInfo.description || '', - true - ), - status: isNaN(+status) ? status : +status, - isSuccess: this.isSuccessStatus(status), - }, - ]; + parsedSchemas, + operationId, + defaultType, + }) + ), + description: this.schemaParserFabric.schemaFormatters.formatDescription( + requestInfo.description || '', + true + ), + status: isNaN(+status) ? status : +status, + isSuccess: this.isSuccessStatus(status), + }; + + if (parsedBefore !== undefined) { + this.schemaParserFabric.parsedSchemaCache.set(responseInfo, parsedBefore); + } + + return [...acc, responseInfo]; }, [] ); @@ -754,20 +766,24 @@ class SchemaRoutes { usageName = camelCase(usageName); } - const property: RouteParam = { - ...schemaPart, - ...schemaPart.schema, - $origName: schemaPart.name, - name: usageName, - }; + // the parse result was carried over by the spread: the last spread object wins + const property: RouteParam = this.inheritParsed( + schemaPart, + this.inheritParsed(schemaPart.schema, { + ...schemaPart, + ...schemaPart.schema, + $origName: schemaPart.name, + name: usageName, + }) + ); - return { + return this.inheritParsed(objectSchema, { ...objectSchema, properties: { ...objectSchema.properties, [usageName]: property, }, - }; + }); }, objectSchema ); @@ -881,10 +897,10 @@ class SchemaRoutes { (acc: Record, pathArgSchema) => { const name = 'name' in pathArgSchema ? pathArgSchema.name : undefined; if (typeof name === 'string' && name) { - acc[name] = { + acc[name] = this.inheritParsed(pathArgSchema, { ...pathArgSchema, in: 'path', - }; + }); } return acc; @@ -896,10 +912,10 @@ class SchemaRoutes { queryObjectSchema.properties ?? {}, (acc: Record, property, name) => { if (name && isObject(property)) { - acc[name] = { + acc[name] = this.inheritParsed(property, { ...property, in: 'query', - }; + }); } return acc; @@ -908,9 +924,9 @@ class SchemaRoutes { ); const schema: SchemaObject = { - // `$parsed` belongs to the query object schema only (it doesn't contain path params), + // the parse result of the query object schema is not reused (it doesn't contain path params), // parsed query properties are reused - ...omit(queryObjectSchema, '$parsed'), + ...queryObjectSchema, properties: { ...fixedQueryParams, ...pathParams, @@ -980,10 +996,16 @@ class SchemaRoutes { ); if (idx > -1) { - assign(responseBodyInfo.responses[idx], { + const response = responseBodyInfo.responses[idx]; + assign(response, { ...component, type: successResponse.type, }); + // `assign` copied (overwrote) the parse result of the component too + const componentParsed = this.schemaParserFabric.parsedSchemaCache.get(component); + if (componentParsed !== undefined) { + this.schemaParserFabric.parsedSchemaCache.set(response, componentParsed); + } } } } @@ -1034,7 +1056,7 @@ class SchemaRoutes { const component = this.schemaComponentsMap.createComponent( // `null` is joined as an empty string (`#/components/schemas/`) this.schemaComponentsMap.createRef(['components', 'schemas', typeName ?? '']), - { ...schema } + this.inheritParsed(schema, { ...schema }) ); responseBodyInfo.error.schemas = [component]; responseBodyInfo.error.type = this.typeNameFormatter.format(component.typeName); diff --git a/src/schema-walker.ts b/src/schema-walker.ts index 45a7e49..f61abbf 100644 --- a/src/schema-walker.ts +++ b/src/schema-walker.ts @@ -36,8 +36,11 @@ class SchemaWalker { this.swaggerSchemaResolver = swaggerSchemaResolver; } - addSchema = (name: string, schema: unknown) => { - this.schemas.set(name, cloneDeep(schema)); + /** + * @param copy store a deep copy (needed when custom code could change the document later) + */ + addSchema = (name: string, schema: unknown, { copy = true }: { copy?: boolean } = {}) => { + this.schemas.set(name, copy ? cloneDeep(schema) : schema); }; /** diff --git a/src/swagger-schema-resolver.ts b/src/swagger-schema-resolver.ts index 9202ead..ec81b4a 100644 --- a/src/swagger-schema-resolver.ts +++ b/src/swagger-schema-resolver.ts @@ -56,6 +56,7 @@ export type SwaggerSchemaResolverConfig = Pick< | 'authorizationToken' | 'requestOptions' | 'update' + | 'hasCustomSchemaCode' >; export interface SwaggerSchemaResolverDeps { @@ -130,20 +131,28 @@ class SwaggerSchemaResolver { } return new Promise((resolve, reject) => { - const result = owned ? swaggerSchema : cloneDeep(swaggerSchema); - - result.info = merge( - { - title: 'No title', - version: '', - }, - result.info - ); + // The generator never changes the documents, but custom code (hooks, schema parsers, + // templates, type constructs) gets the raw schemas and could: then it works on copies. + const copyDocuments = this.config.hasCustomSchemaCode; + const source = copyDocuments && !owned ? cloneDeep(swaggerSchema) : swaggerSchema; + + // a shallow copy: the input document is not changed + const result: Record = { + ...source, + info: merge( + { + title: 'No title', + version: '', + }, + source.info + ), + }; if (isOpenAPIV3Document(result)) { resolve({ usageSchema: result, - originalSchema: cloneDeep(result), + // its own top level object (`fixSwaggerSchema` replaces `paths` of the usage schema) + originalSchema: copyDocuments ? cloneDeep(result) : { ...result }, }); } else { result.paths = merge({}, result.paths); @@ -261,17 +270,32 @@ class SwaggerSchemaResolver { const usagePaths = usageSchema.paths; const originalPaths = originalSchema.paths; + if (!usagePaths) { + return; + } + + // the fixed operations are copies (the documents are not changed), `paths` of the usage schema + // is replaced by the fixed copy + const fixedPaths: Record = {}; + // walk by routes - each(usagePaths, (usagePathObject, route) => { + each(usagePaths, (usagePathObject: unknown, route) => { + if (!isRecord(usagePathObject)) { + fixedPaths[route] = usagePathObject; + return; + } + const originalPathObject: unknown = get(originalPaths, route); + const fixedPathObject: Record = { ...usagePathObject }; // walk by methods - each(usagePathObject, (usageRouteInfo: unknown, methodName) => { + each(usagePathObject, (usageRouteInfoValue: unknown, methodName) => { // skip path level keys which are not operations (`parameters`, `servers`, ...) - if (!isOperationObject(usageRouteInfo)) { + if (!isOperationObject(usageRouteInfoValue)) { return; } + const usageRouteInfo: OperationObject = { ...usageRouteInfoValue }; const originalRouteInfoValue: unknown = get(originalPathObject, methodName); const originalRouteInfo: OperationObject = isOperationObject(originalRouteInfoValue) ? originalRouteInfoValue @@ -293,12 +317,17 @@ class SwaggerSchemaResolver { return originalIn === paramIn && originalName === paramName; }); if (!existUsageParam) { - // attach the array, so params are not pushed into a throwaway default value usageRouteInfo.parameters = [...usageRouteParams, originalRouteParam]; } }); + + fixedPathObject[methodName] = usageRouteInfo; }); + + fixedPaths[route] = fixedPathObject; }); + + usageSchema.paths = fixedPaths as typeof usageSchema.paths; } } diff --git a/src/types/openapi.ts b/src/types/openapi.ts index f841bb3..c4bc7c6 100644 --- a/src/types/openapi.ts +++ b/src/types/openapi.ts @@ -7,7 +7,6 @@ * (where TypeScript widens literals to `string`) stay assignable * - `SchemaObject` also covers `$ref` schemas and a few keys added by the generator itself */ -import type { ParsedSchema } from './parsed'; /** `x-*` vendor extensions */ export type VendorExtensions = { [extension: `x-${string}`]: unknown }; @@ -123,8 +122,6 @@ export interface SchemaObject extends VendorExtensions { // #region keys added by the generator - /** result of the schema parser, cached on the schema */ - $parsed?: ParsedSchema; /** required keys of a referenced schema (`UtilRequiredKeys`) */ $$requiredKeys?: string[]; /** original name of a request param (`a.b` -> `aB`) */ diff --git a/src/types/parsed.ts b/src/types/parsed.ts index 0b4f0d0..5d8bb0e 100644 --- a/src/types/parsed.ts +++ b/src/types/parsed.ts @@ -135,7 +135,7 @@ export interface ParsedEnumSchema extends ParsedSchemaCommon { content: EnumFieldContent[]; } -/** result of `SchemaParser.parseSchema()` (stored as `schema.$parsed` and `component.typeData`) */ +/** result of `SchemaParser.parseSchema()` (cached in `ParsedSchemaCache`, stored as `component.typeData`) */ export type ParsedSchema = | ParsedPrimitiveSchema | ParsedComplexSchema diff --git a/tests/core/input-immutability.test.ts b/tests/core/input-immutability.test.ts new file mode 100644 index 0000000..4268762 --- /dev/null +++ b/tests/core/input-immutability.test.ts @@ -0,0 +1,186 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import yaml from 'js-yaml'; +import { describe, expect, it } from 'vitest'; + +import { generateApi } from '../../src'; +import { deepFreeze } from '../helpers/generate'; + +/** + * The generator must not change the input document: parse results are cached aside + * (`ParsedSchemaCache`) and fixes are applied to copies. Without custom code the input is not even + * copied, so a deep-frozen input throws (ESM is strict) if anything writes into it. + */ + +const fixture = (name: string): Record => { + const content = fs.readFileSync(path.resolve(__dirname, '../fixtures', name), 'utf8'); + return (name.endsWith('.json') ? JSON.parse(content) : yaml.load(content)) as Record< + string, + unknown + >; +}; + +/** every code path which used to change the document */ +const edgeCases = { + openapi: '3.0.3', + // no `info`: the default title / version is added + paths: { + '/pets': { + get: { + operationId: 'listPets', + parameters: [ + { name: 'status', in: 'query', schema: { type: 'string', enum: ['a', 'b'] } }, + { name: 'tags', in: 'query', schema: { items: { type: 'string' } } }, + ], + responses: { + 200: { + description: 'ok', + content: { + 'application/json': { + schema: { type: 'array', items: { $ref: '#/components/schemas/Pet' } }, + }, + }, + }, + 400: { $ref: '#/components/responses/Error' }, + }, + }, + post: { + operationId: 'createPet', + requestBody: { + content: { 'application/json': { schema: { $ref: '#/components/schemas/Dog' } } }, + }, + responses: { 204: { description: 'created' } }, + }, + }, + }, + components: { + responses: { + Error: { + description: 'error', + content: { + 'application/json': { + schema: { type: 'object', properties: { code: { type: 'integer' } } }, + }, + }, + }, + }, + schemas: { + // `items` without `type` (was fixed in place: `type = "array"`) + Names: { items: { type: 'string' } }, + // enum with a single `null` value + OnlyNull: { enum: [null] }, + PetType: { type: 'string', enum: ['dog', 'cat'] }, + // discriminator mapping (the mapped schemas were changed in place) + Pet: { + type: 'object', + required: ['petType'], + properties: { petType: { $ref: '#/components/schemas/PetType' }, name: { type: 'string' } }, + discriminator: { + propertyName: 'petType', + mapping: { dog: '#/components/schemas/Dog', cat: '#/components/schemas/Cat' }, + }, + }, + Dog: { + allOf: [ + { $ref: '#/components/schemas/Pet' }, + { + type: 'object', + properties: { petType: { type: 'string', enum: ['dog'] }, bark: { type: 'boolean' } }, + }, + ], + }, + Cat: { + allOf: [ + { $ref: '#/components/schemas/Pet' }, + { + type: 'object', + properties: { petType: { type: 'string', enum: ['cat'] }, lives: { type: 'integer' } }, + }, + ], + }, + WithRequired: { + allOf: [{ $ref: '#/components/schemas/Pet' }, { type: 'object', required: ['name'] }], + }, + Nullable31: { type: ['string', 'null'], enum: ['x', null] }, + }, + }, +}; + +const documents: Record> = { + 'petstore (OpenAPI 3)': fixture('petstore.json'), + 'runtime client (OpenAPI 3)': fixture('runtime-client.json'), + 'swagger 2': fixture('swagger2.yaml'), + 'edge cases': edgeCases, +}; + +const optionSets: Record> = { + default: {}, + 'modular + axios + route types': { + modular: true, + httpClientType: 'axios', + generateRouteTypes: true, + }, + 'all extractions': { + extractRequestParams: true, + extractRequestBody: true, + extractResponseBody: true, + extractResponseError: true, + extractEnums: true, + extractResponses: true, + }, + 'types options': { + generateUnionEnums: true, + addReadonly: true, + sortTypes: true, + generateResponses: true, + }, +}; + +const run = (spec: unknown, options: Record) => + generateApi({ spec: spec as any, output: false, silent: true, ...options }); + +describe('the input document is never changed', () => { + for (const [documentName, document] of Object.entries(documents)) { + for (const [optionsName, options] of Object.entries(optionSets)) { + it(`${documentName}, ${optionsName}: a frozen input gives the same output`, async () => { + const expected = await run(structuredClone(document), options); + const frozen = deepFreeze(structuredClone(document)); + const actual = await run(frozen, options); + expect(actual.files).toEqual(expected.files); + }); + } + } + + it('with custom code (hooks) the input is copied and stays unchanged', async () => { + const input = structuredClone(edgeCases); + const before = structuredClone(input); + const result = await run(input, { + extractEnums: true, + hooks: { + // changes the raw schemas it gets + onPreParseSchema: (schema: any) => ({ ...schema, 'x-touched': true }), + onParseSchema: (schema: any, parsed: any) => { + schema.description = 'changed by a hook'; + return parsed; + }, + }, + }); + expect(result.files.length).toBeGreaterThan(0); + expect(input).toEqual(before); + }); + + it('exposes an unchanged originalSchema and a fixed usage schema', async () => { + const input = deepFreeze(structuredClone(edgeCases)); + const { configuration } = await run(input, {}); + const config: any = configuration.config; + // `info` default is on the copies, not on the input + expect((input as any).info).toBeUndefined(); + expect(config.swaggerSchema.info).toEqual({ title: 'No title', version: '' }); + expect(config.originalSchema.info).toEqual({ title: 'No title', version: '' }); + // fixSwaggerSchema adds `consumes` / `produces` to copies of the operations + expect(config.swaggerSchema.paths['/pets'].get.consumes).toEqual([]); + expect((input as any).paths['/pets'].get.consumes).toBeUndefined(); + expect(config.originalSchema.paths['/pets'].get.consumes).toBeUndefined(); + }); +}); diff --git a/tests/helpers/generate.ts b/tests/helpers/generate.ts index df7b237..85cf5f8 100644 --- a/tests/helpers/generate.ts +++ b/tests/helpers/generate.ts @@ -24,6 +24,17 @@ const readDirRecursive = (dir: string, base = dir): GeneratedFiles => { return result; }; +/** freezes `value` and everything reachable from it */ +export const deepFreeze = (value: T): T => { + if (value && typeof value === 'object' && !Object.isFrozen(value)) { + Object.freeze(value); + for (const key of Reflect.ownKeys(value)) { + deepFreeze((value as Record)[key]); + } + } + return value; +}; + /** * Writes `spec` to a temp file, runs `generateApi` into a temp output dir and * returns every written file keyed by its path relative to the output dir. @@ -34,11 +45,14 @@ export const generate = async (spec: object | string, options: Record Date: Fri, 25 Sep 2026 02:18:51 +0000 Subject: [PATCH 7/9] docs(skill): update the agent skill for the current behaviour, add generated client usage - SKILL.md: triggers, install, quick start, gotchas (CLI values, precedence, schema source, undici download, optional body/query params, encoding, oxfmt) - references/options.md: every option with defaults, hooks with signatures, CLI flag table, exported API - references/patterns.md: 11 recipes - references/usage.md (new): fetch / axios / singleHttpClient / modular client usage All TypeScript snippets type-check (strict) against clients generated from the petstore fixture. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- skills/swagger-typescript-api-es/SKILL.md | 145 +++---- .../references/options.md | 363 ++++++++++++------ .../references/patterns.md | 214 +++++++---- .../references/usage.md | 218 +++++++++++ 4 files changed, 684 insertions(+), 256 deletions(-) create mode 100644 skills/swagger-typescript-api-es/references/usage.md diff --git a/skills/swagger-typescript-api-es/SKILL.md b/skills/swagger-typescript-api-es/SKILL.md index 5591567..e2588c8 100644 --- a/skills/swagger-typescript-api-es/SKILL.md +++ b/skills/swagger-typescript-api-es/SKILL.md @@ -1,6 +1,6 @@ --- name: swagger-typescript-api-es -description: Guide for using swagger-typescript-api-es β€” a CLI and Node.js tool that generates TypeScript API clients from Swagger/OpenAPI schemas (ESM rewrite). Use when user asks to generate TypeScript API types from Swagger or OpenAPI, auto-generate axios or fetch HTTP client from swagger.json, set up swagger-typescript-api.config.ts, run gen-api-types script, or use swagger-typescript-api-es CLI. +description: Guide for swagger-typescript-api-es, an ESM/TypeScript CLI and Node.js library that generates typed TypeScript API clients (fetch or axios) from Swagger 2.0 / OpenAPI 3.x schemas. Use when the user wants to generate TypeScript types or an API client from swagger.json / openapi.yaml, set up swagger-typescript-api.config.ts, run the swagger-typescript-api-es CLI or a gen-api-types script, call generateApi() programmatically, write hooks or custom templates, or use a generated Api / HttpClient class (baseUrl, securityWorker, auth headers, error handling, modular output). license: MIT metadata: author: hunghg255 @@ -10,106 +10,107 @@ metadata: # swagger-typescript-api-es -ESM + TypeScript rewrite of [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api). Generates fully-typed TypeScript API clients (axios or fetch) from a Swagger 2.0 / OpenAPI 3.0 schema URL or file. +ESM + TypeScript rewrite of [swagger-typescript-api](https://github.com/acacode/swagger-typescript-api). +Reads a Swagger 2.0 / OpenAPI 3.x schema (URL, local JSON/YAML file or in-memory object) and writes a +typed client: data contracts + an `HttpClient` (fetch or axios) + an `Api` class with one method per operation. ## Install -Requires Node.js >= 20. +Requires **Node.js >= 20**. ESM only (`import`, no `require`). ```bash -npm i swagger-typescript-api-es@latest --save-dev -# or -pnpm i swagger-typescript-api-es@latest -D +npm i -D swagger-typescript-api-es # pnpm add -D / yarn add -D / bun add -d +npm i axios # only if you generate with httpClientType: 'axios' ``` -## Quick Start (One-off CLI) - -No install needed β€” run directly with npx: +## Quick start ```bash +# one-off, no install npx swagger-typescript-api-es@latest -u https://petstore.swagger.io/v2/swagger.json -o ./src/api +# -> ./src/api/Api.ts (fetch client) ``` -## Project Setup (Config File) - -### Step 1: Create `swagger-typescript-api.config.ts` at project root +Project setup: `swagger-typescript-api.config.ts` (or `.js` / `.mjs` / `.cjs`) in the directory you +run the CLI from. It may export one config or an array (each entry is generated in turn). ```ts import { defaultConfig } from 'swagger-typescript-api-es'; export default defaultConfig({ - name: 'api-axios.ts', // output filename - output: './src/apis/axios-gentype', // output directory - url: 'http://localhost:5002/api-json', // swagger schema URL - httpClientType: 'axios', // 'axios' | 'fetch' + url: 'http://localhost:5002/api-json', // or input: './openapi.yaml', or spec: {...} + output: './src/api', // a directory (created if missing) + name: 'api.ts', // file name (default "Api.ts"), ignored with modular + httpClientType: 'axios', // default 'fetch' }); ``` -### Step 2: Add script to `package.json` - ```json -{ - "scripts": { - "gen-api-types": "swagger-typescript-api-es" - } -} +{ "scripts": { "gen-api-types": "swagger-typescript-api-es" } } ``` -### Step 3: Run +Programmatic: -```bash -npm run gen-api-types -# or -pnpm gen-api-types -``` - -## CLI Flags +```ts +import { generateApi } from 'swagger-typescript-api-es'; -```bash -npx swagger-typescript-api-es@latest --help +const { files } = await generateApi({ input: './openapi.json', output: false }); // in memory +// files: { fileName: 'Api', fileExtension: '.ts', fileContent: string }[] ``` -Key flags: - -| Flag | Description | -| ------------------------- | ------------------------------------------------- | -| `-u ` | Path/URL to swagger schema | -| `-o ` | Output directory (default: `./`) | -| `-n ` | Output filename (default: `Api.ts`) | -| `--httpClientType ` | `axios` or `fetch` (default: `fetch`) | -| `--modular true` | Separate files for http client, contracts, routes | -| `--custom-config ` | Extra options (hooks, ...) from a js/ts/json file | - -- Flags accept both kebab-case and camelCase (`--union-enums` / `--unionEnums`); boolean flags take `true`/`false` (e.g. `--modular true`). -- CLI flags are merged over `swagger-typescript-api.config.*` (if it exists) and the `--custom-config` file β€” CLI flags win. -- The CLI exits with code `1` on errors. - -## Using a Local Schema File - -Instead of `url`, use `input` for a local file: +Using the generated client (fetch): ```ts -export default defaultConfig({ - name: 'api.ts', - output: './src/api', - input: './swagger.json', // local file path - httpClientType: 'fetch', +import { Api } from './src/api/Api'; + +const api = new Api({ + baseUrl: 'https://api.example.com', + securityWorker: (token) => (token ? { headers: { Authorization: `Bearer ${token}` } } : {}), }); +api.setSecurityData('jwt'); +const { data: pet } = await api.pets.getPet(1); // rejects with the HttpResponse on non-2xx ``` -## Gotchas - -- **Config filename must be `swagger-typescript-api.config.ts`** (or `.js` / `.mjs` / `.cjs`) in the project root β€” the CLI looks for this name. It may export a single config or an array of configs. -- **Schema source precedence: `spec` > `input` > `url`** β€” `input` is used if the file exists; `url` also accepts a local file path. Set only one to avoid surprises. -- **`output` must be a directory** (default: `./`) β€” it is created (recursively) if missing; pointing it at an existing file fails. `output: false` generates in memory only (`generateApi` returns the files without writing). -- **`cleanOutput: true` deletes everything in the output folder before generating** β€” do not point it at a folder that has hand-written files. -- **`httpClientType` defaults to `fetch`** β€” explicitly set `'axios'` if your project uses axios, otherwise the generated client won't import it. -- **`unwrapResponseData: true` changes the return shape** β€” with it, `api.getUser()` returns the data directly instead of the full axios response; set consistently across your codebase. -- **`extractEnums: true` extracts inline enums** into separate enum declarations β€” without it, inline enums stay as union literals in types. -- **Request body is optional unless the schema marks it `required: true`**; with `extractRequestParams`, the extracted query params argument is optional when all its fields are optional. -- **`silent: true` hides logs but still prints errors.** -- **`sortRouters` is deprecated** β€” use `sortRoutes`. The schema download respects `HTTP(S)_PROXY` unless `disableProxy: true`. -- **Swagger 2.0 vs OpenAPI 3.0** β€” both are supported but some options like `generateResponses` behave differently between versions. Test with your actual schema. - -See `references/options.md` for the full IOptions reference. -See `references/patterns.md` for common usage patterns. +## Key gotchas + +- **CLI flags**: `-u/--u`, `-o/--o`, `-n/--n`, `-t/--t`, then kebab-case or camelCase + (`--union-enums` = `--unionEnums`). Every flag except `--extract-enums` **needs a value**: + `--modular true` (bare `--modular` fails with "value is missing"). Unknown flags are errors. +- **Precedence**: config file < `--custom-config ` (js/ts/json, one object) < CLI flags. With an + array config, flags are applied to every entry. Errors print `❌ SWAGGER-TYPESCRIPT-API error: ...` + and **exit with code 1**. `silent: true` hides logs but still prints errors. +- **Schema source**: `spec` > `input` (if the file exists) > `url`. `url` without `http(s)://` is read + as a local path. The `spec` object you pass is never modified. +- **`output` is a directory**, never a file (`name` sets the file). `output: false` writes nothing + and only returns the files. `cleanOutput: true` empties the directory first. +- **Download** (undici): respects `HTTP_PROXY`/`HTTPS_PROXY`/`NO_PROXY`; `disableProxy` connects + directly; `disableStrictSSL` skips TLS checks; `requestOptions.timeout` defaults to 60 s (`0` = off); + `requestOptions.dispatcher` for a custom undici dispatcher. node-fetch `agent` is not supported. + `authorizationToken` is sent verbatim as `Authorization` (include `Bearer `). +- **Generated signatures**: `(pathParams..., query, data, params: RequestParams = {})`, with + required arguments moved before optional ones (e.g. `updatePet(petId, data?, params)`). + The body is optional unless `requestBody.required: true`; with `extractRequestParams` the params + object is optional when there are no path params and all query params are optional. Path params + are wrapped in `encodeURIComponent`. +- **Modules** come from the first path segment (`/pets/{id}` -> `api.pets.getPet`), not tags, unless + `moduleNameFirstTag: true` or `moduleNameIndex` is set. Routes like `GET /` are methods on `Api` + (modular: `Common.ts`). +- **Fetch client throws on non-2xx** (the `HttpResponse`, with `.error`) unless `disableThrowOnError`. + `unwrapResponseData: true` makes methods resolve with the body instead of the response. +- A schema named `Error` generates `export interface Error`: import it as + `import type { Error as ApiError }` to avoid shadowing the global. +- Output is formatted with **oxfmt**: built-in defaults < `.oxfmtrc.json` in cwd < `oxfmtOptrions` + (that misspelling is the real option name). +- `sortRouters` is deprecated (use `sortRoutes`). `toJS: true` emits `.js` + `.d.ts`. + +## References + +- `references/options.md`: every `IOptions` key with defaults, CLI flag mapping, hooks with + signatures, exported types, `generateApi` return value. +- `references/patterns.md`: config recipes (axios, local file, multiple APIs, large schemas, hooks, + in-memory generation, custom templates, proxies/auth, CI). +- `references/usage.md`: using the generated client (fetch, axios, `singleHttpClient`, modular), + auth, cancellation, error handling, file upload. + +Docs: the repository README and the docs site with an online playground (the `docs/` Next.js app in +the repo) that generates clients from a pasted spec or URL. diff --git a/skills/swagger-typescript-api-es/references/options.md b/skills/swagger-typescript-api-es/references/options.md index f993c10..a634b5e 100644 --- a/skills/swagger-typescript-api-es/references/options.md +++ b/skills/swagger-typescript-api-es/references/options.md @@ -1,122 +1,259 @@ -# IOptions Full Reference - -All options for `defaultConfig()` in `swagger-typescript-api.config.ts`. - -## Core Options - -| Option | Type | Default | Description | -| ---------------- | -------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `name` | `string` | `"Api.ts"` | Output filename | -| `output` | `string \| false` | `"./"` | Output directory path (created if missing). `false` generates in memory: files are only returned by `generateApi` | -| `url` | `string` | β€” | URL to remote swagger/OpenAPI schema (a local file path also works) | -| `input` | `string` | β€” | Local path to swagger JSON/YAML file | -| `httpClientType` | `'axios' \| 'fetch'` | `'fetch'` | HTTP client to use in generated code | -| `cleanOutput` | `boolean` | `false` | Delete output folder contents before generating | -| `modular` | `boolean` | `false` | Separate files: `http-client`, `data-contracts` and one file per route module (routes outside any module go to `Common.ts`; their route types to `CommonRoute.ts`) | -| `apiClassName` | `string` | `"Api"` | Name of the generated API class | - -## Type Generation Options - -| Option | Type | Default | Description | -| ---------------------- | --------- | -------- | ------------------------------------------------------------- | -| `generateClient` | `boolean` | `true` | Generate HTTP client class | -| `generateRouteTypes` | `boolean` | `false` | Generate route type definitions | -| `generateResponses` | `boolean` | `false` | Generate response type definitions | -| `extractRequestParams` | `boolean` | `false` | Extract request params into separate types | -| `extractRequestBody` | `boolean` | `false` | Extract request body into separate types | -| `extractEnums` | `boolean` | `false` | Extract enums into separate declarations | -| `unwrapResponseData` | `boolean` | `false` | Return response data directly (not wrapped in axios response) | -| `generateUnionEnums` | `boolean` | `false` | Generate union types instead of enums | -| `enumNamesAsValues` | `boolean` | `false` | Use enum name as value | -| `toJS` | `boolean` | `false` | Generate JavaScript instead of TypeScript | -| `addReadonly` | `boolean` | `false` | Add `readonly` to generated properties | -| `anotherArrayType` | `boolean` | `false` | Use `Array` instead of `T[]` | -| `extractResponseBody` | `boolean` | `false` | Extract response body into separate types | -| `extractResponseError` | `boolean` | `false` | Extract response error into separate types | -| `defaultResponseType` | `string` | `"void"` | Type for empty response schemas | -| `disableThrowOnError` | `boolean` | `false` | Do not throw when `response.ok` is not true | - -## Naming Options - -| Option | Type | Description | -| -------------------------- | --------- | ------------------------------------------------------------ | -| `typePrefix` | `string` | Prefix for all generated type names | -| `typeSuffix` | `string` | Suffix for all generated type names | -| `enumKeyPrefix` | `string` | Prefix for enum keys | -| `enumKeySuffix` | `string` | Suffix for enum keys | -| `fixInvalidTypeNamePrefix` | `string` | Prefix to fix invalid type names | -| `fixInvalidEnumKeyPrefix` | `string` | Prefix to fix invalid enum keys | -| `moduleNameFirstTag` | `boolean` | Use first tag as module/class name | -| `moduleNameIndex` | `number` | Path segment index used for module separation (default: `0`) | - -## Sorting Options - -| Option | Type | Description | -| ------------ | --------- | -------------------------------------------------------------------------- | -| `sortTypes` | `boolean` | Sort generated types alphabetically | -| `sortRoutes` | `boolean` | Sort generated routes alphabetically (`sortRouters` is a deprecated alias) | - -## Formatting Options - -Generated code is formatted with [oxfmt](https://oxc.rs/docs/guide/usage/formatter). Options are merged in this order (later wins): - -1. built-in defaults: `singleQuote: true`, `jsxSingleQuote: true`, `printWidth: 100`, `trailingComma: 'es5'`, `tabWidth: 2`, `semi: true`, `sortImports` (grouped) -2. `.oxfmtrc.json` in the current working directory (if any) -3. `oxfmtOptrions` (note the spelling β€” it is the public option name) - -| Option | Type | Description | -| --------------- | ----------------------------- | ---------------------------------------------------------------------------------------------- | -| `oxfmtOptrions` | `FormatConfig` (from `oxfmt`) | Any oxfmt format option, e.g. `printWidth`, `tabWidth`, `trailingComma`, `singleQuote`, `semi` | - -There is no `parser` option β€” the parser is inferred from the file extension (a passed `parser` is ignored). - -## Advanced Options - -| Option | Type | Description | -| -------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------ | -| `templates` | `string` | Path to custom templates folder (`.ejs` / `.eta`, Eta engine) | -| `extraTemplates` | `[]` | Extra template files to generate additional output files | -| `singleHttpClient` | `boolean` | Use a single shared HTTP client instance | -| `defaultResponseAsSuccess` | `boolean` | Treat default response as success | -| `spec` | `object` | Inline swagger spec object (alternative to url/input) | -| `constants` | `Record` | Constants available in templates | -| `templateInfos` | `{ name: string; fileName: string }[]` | Template name -> template file mapping (e.g. `{ name: "api", fileName: "api" }`) | -| `patch` | `boolean` | Fix up small errors in the swagger source definition | -| `silent` | `boolean` | Output only errors to console | -| `debug` | `boolean` | Log additional information about the generation process | -| `authorizationToken` | `string` | Sent as `Authorization` header when downloading the schema from `url` | -| `disableStrictSSL` | `boolean` | Disable strict SSL when downloading the schema | -| `disableProxy` | `boolean` | Ignore `HTTP(S)_PROXY` env variables when downloading the schema | -| `requestOptions` | `Record & { timeout?: number }` | Extra `fetch` options for downloading the schema; `timeout` in ms (default: `60000`) | -| `codeGenConstructs` | `function` | Override code generation constructs | -| `primitiveTypeConstructs` | `function` | Override primitive type mappings | - -## Extracting Options +# Options reference + +All keys of `IOptions` (`import type { IOptions } from 'swagger-typescript-api-es'`), accepted by +`defaultConfig()`, `generateApi()`, config files and `--custom-config` files. Every key is optional. + +## Input / output + +| Option | Type | Default | Description | +| ------------- | -------------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `url` | `string` | β€” | Schema URL. A value without `http://` / `https://` is read as a file path relative to cwd | +| `input` | `string` | β€” | Local schema file (JSON or YAML). Used when the file exists, otherwise `url` is tried | +| `spec` | `OpenAPIDocument` | β€” | Schema object already in memory (OpenAPI 3.x or Swagger 2.0). Wins over `input` / `url`. Never modified | +| `output` | `string \| false` | `"./"` | Output **directory**, resolved from cwd and created if missing. `false`: nothing is written | +| `name` | `string` | `"Api.ts"` | Output file name (single-file mode only) | +| `cleanOutput` | `boolean` | `false` | Delete the contents of `output` before writing | +| `modular` | `boolean` | `false` | One file per module + `data-contracts.ts` + `http-client.ts` (see below) | +| `fileNames` | `Partial` | see below | Modular file names: `dataContracts` (`data-contracts`), `routeTypes` (`route-types`), `httpClient` (`http-client`), `outOfModuleApi` (`Common`) | +| `toJS` | `boolean` | `false` | Emit `.js` + `.d.ts` instead of `.ts` (loads `typescript` on demand) | +| `silent` | `boolean` | `false` | Hide logs (errors are still printed) | +| `debug` | `boolean` | `false` | Extra logs about the generation | +| `patch` | `boolean` | `false` | Fix small errors in a Swagger 2.0 document while converting it | + +Swagger 2.0 documents are converted to OpenAPI 3.0 (`swagger2openapi`) before parsing. + +## Schema download (`url`) + +| Option | Type | Default | Description | +| -------------------- | ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `authorizationToken` | `string` | β€” | Sent verbatim as the `Authorization` header (write `'Bearer '` yourself) | +| `disableStrictSSL` | `boolean` | `false` | Skip TLS certificate validation (self-signed certs) | +| `disableProxy` | `boolean` | `false` | Connect directly. By default `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` are respected (undici `EnvHttpProxyAgent`) | +| `requestOptions` | `RequestOptions` | β€” | undici `fetch` `RequestInit` (`headers`, `method`, `dispatcher`, `signal`, ...) + `timeout` in ms (default `60000`, `0` disables it) | + +A custom `requestOptions.dispatcher` (e.g. `new ProxyAgent(url)` from `undici`) replaces the proxy / +SSL handling. The node-fetch style `requestOptions.agent` is no longer supported (a warning is +logged). Non-2xx responses, network errors and timeouts reject with +`Failed to fetch swagger schema from "": ...`. + +## Client + +| Option | Type | Default | Description | +| ---------------------------- | -------------------- | ------------ | --------------------------------------------------------------------------------------- | +| `httpClientType` | `'fetch' \| 'axios'` | `'fetch'` | HTTP client of the generated code (axios must be installed in the consuming project) | +| `generateClient` | `boolean` | `true` | `false`: only types (no `HttpClient` / `Api`) | +| `apiClassName` | `string` | `"Api"` | Name of the main class (single-file mode) | +| `singleHttpClient` | `boolean` | `false` | `Api` does not extend `HttpClient`; its constructor takes an `HttpClient` instance | +| `unwrapResponseData` | `boolean` | `false` | Methods resolve with the response body instead of `HttpResponse` / `AxiosResponse` | +| `disableThrowOnError` | `boolean` | `false` | fetch client: resolve (not reject) on non-2xx; check `response.ok` / `response.error` | +| `defaultResponseAsSuccess` | `boolean` | `false` | Also use the `default` response as the success type | +| `successResponseStatusRange` | `[number, number]` | `[200, 299]` | Status codes treated as success when picking the response type | +| `defaultResponseType` | `string` | `"void"` | Type used for responses without a schema | +| `generateResponses` | `boolean` | `false` | Add an `@response ` JSDoc line per response to each method | + +## Types and enums + +| Option | Type | Default | Description | +| --------------------------------- | --------- | ----------------- | ---------------------------------------------------- | +| `generateUnionEnums` | `boolean` | `false` | Every enum becomes a union type (`'a' \| 'b'`) | +| `extractEnums` | `boolean` | `false` | Inline enums become named enum declarations | +| `enumNamesAsValues` | `boolean` | `false` | Use `x-enumNames` as values too (not only as keys) | +| `addReadonly` | `boolean` | `false` | `readonly` properties | +| `anotherArrayType` | `boolean` | `false` | `Array` instead of `T[]` | +| `sortTypes` | `boolean` | `false` | Sort types and fields | +| `typePrefix` / `typeSuffix` | `string` | `""` | Added to every data contract name | +| `enumKeyPrefix` / `enumKeySuffix` | `string` | `""` | Added to every enum key | +| `fixInvalidTypeNamePrefix` | `string` | `"Type"` | Prefix for type names that are not valid identifiers | +| `fixInvalidEnumKeyPrefix` | `string` | `"Value"` | Prefix for enum keys that are not valid identifiers | +| `typeNameResolverName` | `string` | `"ComponentType"` | Prefix of fallback type names | +| `enumKeyResolverName` | `string` | `"Value"` | Prefix of fallback enum keys | +| `specificArgNameResolverName` | `string` | `"arg"` | Prefix of fallback argument names | + +Boolean enums are always generated as unions. Type names are deterministic (the same spec gives the +same names). + +## Extraction + +| Option | Type | Default | Description | +| ---------------------- | ---------------------------- | ------- | ------------------------------------------------------------------------------------------- | +| `extractRequestParams` | `boolean` | `false` | Path + query params become one `Params` type and one argument | +| `extractRequestBody` | `boolean` | `false` | Inline bodies become `Payload` types | +| `extractResponseBody` | `boolean` | `false` | Inline success responses become `Data` types | +| `extractResponseError` | `boolean` | `false` | Inline error responses become `Error` types | +| `extractResponses` | `boolean` | `false` | `#/components/responses/*` become data contracts (renamed on a clash, e.g. `ErrorResponse`) | +| `extractingOptions` | `Partial` | below | Suffixes tried in order, plus optional `*NameResolver(typeName, reservedNames)` functions | + +Default suffixes: `requestBodySuffix: ['Payload', 'Body', 'Input']`, `requestParamsSuffix: ['Params']`, +`responseBodySuffix: ['Data', 'Result', 'Output']`, +`responseErrorSuffix: ['Error', 'Fail', 'Fails', 'ErrorData', 'HttpError', 'BadResponse']`, +`enumSuffix: ['Enum']`, `discriminatorMappingSuffix: ['Mapping', 'Mapper', 'MapType']`, +`discriminatorAbstractPrefix: ['Base', 'Abstract', 'Discriminator', 'Internal', 'Polymorph']`. +Resolvers: `requestBodyNameResolver`, `requestParamsNameResolver`, `responseBodyNameResolver`, +`responseErrorNameResolver`, `enumNameResolver`, `discriminatorMappingNameResolver`, +`discriminatorAbstractResolver`. Extracted types never overwrite a real component with the same name. + +## Routes and modules + +| Option | Type | Default | Description | +| -------------------- | --------- | ------- | ---------------------------------------------------------------------- | +| `moduleNameIndex` | `number` | `0` | Path segment used as module name (`/pets/{id}` -> `pets`) | +| `moduleNameFirstTag` | `boolean` | `false` | Use the first tag of the operation as module name | +| `generateRouteTypes` | `boolean` | `false` | Also emit `namespace` route types (request params/query/body/response) | +| `sortRoutes` | `boolean` | `false` | Sort routes alphabetically (`sortRouters` is a deprecated alias) | + +Method names come from `operationId` (camelCase); without one they are built from the method and path. + +### Modular output files + +- `data-contracts.ts`, `http-client.ts` (when `generateClient`) +- `.ts` per module, e.g. `Pets.ts` exporting `class Pets extends HttpClient`; routes outside + any module (`GET /`) go to `Common.ts` (`fileNames.outOfModuleApi`) +- with `generateRouteTypes`: `Route.ts` exporting `namespace `, and `CommonRoute.ts` +- a module whose name clashes with a data contract gets a suffix: class `HealthApi`, namespace + `HealthRoute` (the file names stay `Health.ts` / `HealthRoute.ts`) +- `name` and `apiClassName` are not used + +## Formatting + +Output is formatted with [oxfmt](https://oxc.rs/docs/guide/usage/formatter). Later wins: + +1. built-in defaults (`constants.OXC_FORMAT_OPTIONS`): `singleQuote: true`, `jsxSingleQuote: true`, + `printWidth: 100`, `trailingComma: 'es5'`, `tabWidth: 2`, `semi: true`, grouped `sortImports` +2. `.oxfmtrc.json` in `process.cwd()` (if present) +3. `oxfmtOptrions` (oxfmt `FormatConfig`; the spelling is the real public name). `parser` is ignored. + +## Templates and advanced + +| Option | Type | Description | +| ------------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `templates` | `string` | Folder of custom Eta templates (`.ejs` / `.eta`). Lookup: custom folder > `templates/base` > `templates/default` or `templates/modular` | +| `templateInfos` | `TemplateInfo[]` | Template name -> file name (`{ name: 'api', fileName: 'api' }`, ...) | +| `extraTemplates` | `{ name: string; path: string }[]` | Extra files rendered with the same data (`name` = output file, `path` = template file) | +| `constants` | `Record` | Merged into `config.constants` in templates | +| `codeGenConstructs` | object or `(ts) => object` | Changes deep-merged into `config.Ts` (TS code constructs: `Keyword`, `ArrayType`, `UnionType`, ...) | +| `primitiveTypeConstructs` | object or `(types) => object` | Changes deep-merged into schema type -> TS type map, e.g. `{ string: { 'date-time': 'Date' } }` | +| `schemaParsers` | `SchemaParsers` | Custom parser classes (extend `MonoSchemaParser`) for `object`, `enum`, `array`, `complexOneOf`, ... | +| `customTranslator` | `new (process) => Translator` | Custom code translator (extend the exported `Translator`) | +| `hooks` | `Partial` | See below | + +In templates: `it` is the `GenerateApiConfiguration` (`apiConfig`, `config`, `modelTypes`, `routes`, +`utils`, ...). `utils._` is a set of lodash-compatible functions from `es-toolkit/compat` (`get`, +`map`, `compact`, `sortBy`, `camelCase`, `upperCase`, ...); `utils.require()` resolves paths from +the templates folder and packages from your project. Use `includeFile('@base/...', it)` to include +built-in partials. Copy the built-in templates with `generateTemplates({ output, httpClientType, modular })`. + +## Hooks + +Returning `undefined` (or nothing) keeps the original value. Any hook (or custom parser / template / +construct) makes the generator work on a deep copy of the schema, so your input is never changed. ```ts -extractingOptions?: { - requestBodySuffix?: string[] // suffix for extracted request body types - requestParamsSuffix?: string[] // suffix for extracted request param types - responseBodySuffix?: string[] // suffix for extracted response body types - responseErrorSuffix?: string[] // suffix for extracted response error types +interface Hooks { + onInit(config: CodeGenConfig, process: CodeGenProcess): CodeGenConfig | void; // after the schema is loaded + onPrepareConfig(configuration: GenerateApiConfiguration): GenerateApiConfiguration | void; // template data + onCreateComponent(component: SchemaComponent): SchemaComponent | void; // each #/components/* entry + onPreParseSchema( + schema: SchemaObject, + typeName: string | null, + schemaType: BaseSchemaType + ): SchemaObject | void; // deep-merged into the schema + onParseSchema(schema: SchemaObject, parsed: ParsedSchema): ParsedSchema | void; + onPreBuildRoutePath(routePath: string): string | void; // raw path, before params are parsed + onBuildRoutePath(data: BuildRoutePathResult): BuildRoutePathResult | void; // { originalRoute, route, pathParams, queryParams } + onInsertPathParam( + paramName: string, + index: number, + pathParams: RouteNameParam[], + route: string + ): string | void; // expression put in `${...}` (not wrapped in encodeURIComponent) + onCreateRequestParams(rawType: SchemaObject): SchemaObject | SchemaComponent | void; + onCreateRoute(route: ParsedRoute): ParsedRoute | false | void; // false skips the route + onCreateRouteName(nameInfo: RouteNameInfo, raw: RawRouteInfo): RouteNameInfo | void; // { usage, original, duplicate } + onFormatRouteName(raw: RawRouteInfo, templateRouteName: string): string | void; // method name + onFormatTypeName( + typeName: string, + rawTypeName: string, + schemaType: 'type-name' | 'enum-key' + ): string | void; } ``` -## Hooks +Useful fields: `route.raw` (`operationId`, `method`, `route` = original path, `moduleName`, `tags`, +`summary`, ...), `route.request.path` / `.method` / `.security`, `route.routeName.usage`, +`route.namespace` (module name). + +## CLI flags + +`swagger-typescript-api-es [flags]` (`-h` help, `-v` version). Kebab-case and camelCase spellings +are equivalent. Boolean values: `false`, `0`, `no`, `off` and `""` are false, anything else is true. + +| Flag | Option | +| ------------------------------------------------------- | ---------------------------------------------------- | +| `-u, --u ` | `url` | +| `-o, --o ` | `output` | +| `-n, --n ` | `name` | +| `-t, --t ` | `templates` | +| `--httpClientType ` | `httpClientType` | +| `--modular ` | `modular` | +| `--js ` | `toJS` | +| `--noClient ` | `generateClient` (inverted) | +| `--d ` | `defaultResponseAsSuccess` | +| `--r ` | `generateResponses` | +| `--route-types ` | `generateRouteTypes` | +| `--union-enums ` | `generateUnionEnums` | +| `--extract-enums` (value optional) | `extractEnums` | +| `--enum-names-as-values ` | `enumNamesAsValues` | +| `--add-readonly ` | `addReadonly` | +| `--another-array-type ` | `anotherArrayType` | +| `--extract-request-params ` | `extractRequestParams` | +| `--extract-request-body ` | `extractRequestBody` | +| `--extract-response-body ` | `extractResponseBody` | +| `--extract-response-error ` | `extractResponseError` | +| `--module-name-index ` | `moduleNameIndex` | +| `--module-name-first-tag ` | `moduleNameFirstTag` | +| `--unwrap-response-data ` | `unwrapResponseData` | +| `--disable-throw-on-error ` | `disableThrowOnError` | +| `--single-http-client ` | `singleHttpClient` | +| `--default-response ` | `defaultResponseType` | +| `--type-prefix ` / `--type-suffix ` | `typePrefix` / `typeSuffix` | +| `--api-class-name ` | `apiClassName` | +| `--clean-output ` | `cleanOutput` | +| `--sort-types ` / `--sort-routes ` | `sortTypes` / `sortRoutes` | +| `--disableStrictSSL ` / `--disableProxy ` | `disableStrictSSL` / `disableProxy` | +| `--silent ` / `--debug ` / `--patch ` | `silent` / `debug` / `patch` | +| `--custom-config ` | loads a js/ts/json file exporting one options object | + +Options without a flag (`input`, `hooks`, `requestOptions`, `oxfmtOptrions`, `extractResponses`, +...) go in the config file or the `--custom-config` file. + +## Programmatic API and exported types ```ts -hooks?: { - onCreateComponent?: (component: any) => void - onCreateRequestParams?: (rawType: any) => void - onCreateRoute?: (routeData: any) => void - onCreateRouteName?: (routeNameInfo: any, rawRouteInfo: any) => void - onFormatRouteName?: (routeInfo: any, templateRouteName: any) => void - onFormatTypeName?: (typeName: any, rawTypeName: any, schemaType: any) => void - onInit?: (configuration: any) => void - onPreParseSchema?: (originalSchema: any, typeName: any, schemaType: any) => void - onParseSchema?: (originalSchema: any, parsedSchema: any) => void - onPrepareConfig?: (currentConfiguration: any) => void -} +import { + constants, + defaultConfig, + generateApi, + generateTemplates, + Translator, +} from 'swagger-typescript-api-es'; +import type { + GenerateApiOutput, + GeneratedFile, + Hooks, + IOptions, + OpenAPIDocument, + ParsedRoute, +} from 'swagger-typescript-api-es'; ``` -Hooks allow intercepting and customizing generation at various stages. Useful for renaming types, skipping routes, or injecting custom logic. +- `generateApi(options: IOptions): Promise`; an array of options returns an array + of results (generated one after another). Rejects on errors (no `process.exit`). +- `GenerateApiOutput`: `files: GeneratedFile[]` (`{ fileName, fileExtension, fileContent }`, returned + with or without `output: false`), `configuration` (template data), `getTemplate`, `renderTemplate`, + `createFile`, `formatTSContent(code): Promise`. +- `defaultConfig(options)`: identity function that types a config object or array. +- `generateTemplates({ output, httpClientType, modular, cleanOutput, rewrite, silent })`: copies the + built-in templates for customisation, resolves `{ files: SourceTemplate[] }`. +- Other exported types: `GenerateApiConfiguration`, `GenerateApiConfig`, `SchemaObject`, + `OpenAPIV3Document`, `ParsedSchema`, `RawRouteInfo`, `RouteNameInfo`, `BuildRoutePathResult`, + `SchemaComponent`, `RequestOptions`, `OxfmtOptions`, `ExtractingOptions`, `SchemaParsers`, ... diff --git a/skills/swagger-typescript-api-es/references/patterns.md b/skills/swagger-typescript-api-es/references/patterns.md index f45bef9..657e79f 100644 --- a/skills/swagger-typescript-api-es/references/patterns.md +++ b/skills/swagger-typescript-api-es/references/patterns.md @@ -1,149 +1,221 @@ -# Common Patterns +# Common patterns -## Pattern 1: Axios Client from Remote URL +All configs go in `swagger-typescript-api.config.ts` (or `.js` / `.mjs` / `.cjs`) in the directory +the CLI runs from, and are generated with `npx swagger-typescript-api-es` (or a `gen-api-types` +script). The same objects can be passed to `generateApi()`. + +## 1. Axios client from a remote URL ```ts -// swagger-typescript-api.config.ts import { defaultConfig } from 'swagger-typescript-api-es'; export default defaultConfig({ - name: 'api.ts', - output: './src/api', url: 'https://api.example.com/swagger.json', - httpClientType: 'axios', - unwrapResponseData: true, // api.getUser() returns data directly + output: './src/api', + name: 'api.ts', + httpClientType: 'axios', // install axios in the app + unwrapResponseData: true, // api.pets.getPet(1) resolves with Pet, not AxiosResponse extractEnums: true, - cleanOutput: true, + cleanOutput: true, // empties ./src/api first: keep hand-written files elsewhere }); ``` -## Pattern 2: Fetch Client from Local File +## 2. Fetch client from a local file ```ts import { defaultConfig } from 'swagger-typescript-api-es'; export default defaultConfig({ - name: 'api.ts', + input: './openapi.yaml', // JSON or YAML, relative to cwd output: './src/generated', - input: './openapi.json', // local OpenAPI file - httpClientType: 'fetch', - generateResponses: true, + generateResponses: true, // @response lines in the JSDoc sortTypes: true, }); ``` -## Pattern 3: Multiple API Services +## 3. Several APIs -Export an array of configs from a single `swagger-typescript-api.config.ts` β€” each entry is generated in turn: +An array config generates every entry in turn: ```ts -// swagger-typescript-api.config.ts import { defaultConfig } from 'swagger-typescript-api-es'; export default defaultConfig([ - { - name: 'auth-api.ts', - output: './src/api/auth', - url: 'https://auth.example.com/api-json', - httpClientType: 'axios', - }, - { - name: 'payment-api.ts', - output: './src/api/payment', - url: 'https://payment.example.com/api-json', - httpClientType: 'axios', - }, + { url: 'https://auth.example.com/api-json', output: './src/api/auth', name: 'auth.ts' }, + { url: 'https://pay.example.com/api-json', output: './src/api/payment', name: 'payment.ts' }, ]); ``` -Alternatively, keep per-service options in separate files and pass them with `--custom-config` (js/ts/json, must export an object). They are merged over `swagger-typescript-api.config.*` (if present), and CLI flags win over both: +Or one file per API with `--custom-config` (js/ts/json exporting one object). Order of precedence: +config file < custom config < CLI flags (with an array config, the custom config and flags are +applied to every entry): ```bash -swagger-typescript-api-es --custom-config ./auth-api.config.ts -swagger-typescript-api-es --custom-config ./payment-api.config.ts +swagger-typescript-api-es --custom-config ./api-auth.config.ts +swagger-typescript-api-es --custom-config ./api-payment.config.ts --httpClientType axios ``` -## Pattern 4: Extract & Sort for Large Schemas - -For large APIs with many endpoints: +## 4. Large schemas: extract and sort ```ts +import { defaultConfig } from 'swagger-typescript-api-es'; + export default defaultConfig({ - name: 'api.ts', - output: './src/generated', url: 'https://api.example.com/openapi.json', - httpClientType: 'axios', - extractRequestParams: true, // cleaner param types - extractRequestBody: true, // cleaner body types - extractEnums: true, // reusable enum declarations - sortTypes: true, // alphabetical types = easier diffs + output: './src/api', + modular: true, // data-contracts.ts, http-client.ts, one class per module + generateRouteTypes: true, // Route.ts namespaces + extractRequestParams: true, // listPets(query?: ListPetsParams); path + query -> getPet({ id, ...query }: GetPetParams) + extractRequestBody: true, // CreatePetPayload + extractResponseBody: true, + extractEnums: true, + sortTypes: true, // stable diffs sortRoutes: true, - cleanOutput: true, - unwrapResponseData: true, }); ``` -## Pattern 5: Type Prefixing to Avoid Conflicts +The generator is fast (a 1500-schema / 3000-operation spec takes about 1.3 s from the CLI). The input +document is never modified, and it is only deep-copied when hooks, custom parsers, templates or +type constructs are used. -When generated type names clash with existing types: +## 5. Naming: prefixes, suffixes, renames ```ts +import { defaultConfig } from 'swagger-typescript-api-es'; + export default defaultConfig({ - name: 'api.ts', + input: './openapi.json', output: './src/api', - url: 'https://api.example.com/swagger.json', - typePrefix: 'Api', // UserDto β†’ ApiUserDto - enumKeyPrefix: 'E', // Status.Active β†’ ApiStatus.EActive (with typePrefix above) + typePrefix: 'Api', // Pet -> ApiPet, PetStatus -> ApiPetStatus + enumKeyPrefix: 'E', // ApiPetStatus.ESold + apiClassName: 'PetStoreApi', + hooks: { + // receives the name with prefix/suffix applied; return undefined to keep it + onFormatTypeName: (typeName, _rawTypeName, schemaType) => + schemaType === 'type-name' ? typeName.replace(/Dto$/, '') : undefined, + onFormatRouteName: (routeInfo) => (routeInfo.operationId === 'getPet' ? 'findPet' : undefined), + }, }); ``` -## Pattern 6: Custom Hooks for Type Renaming +## 6. Skip or change routes and types with hooks ```ts +import { defaultConfig } from 'swagger-typescript-api-es'; + export default defaultConfig({ - name: 'api.ts', + input: './openapi.json', output: './src/api', - url: 'https://api.example.com/swagger.json', hooks: { - onFormatTypeName: (typeName, rawTypeName, schemaType) => { - // Remove trailing "Dto" suffix from all type names - return typeName.replace(/Dto$/, ''); - }, - onCreateRoute: (routeData) => { - // Log every generated route for debugging - console.log('Route:', routeData.request.path); - }, + onCreateRoute: (route) => (route.raw.route.startsWith('/internal') ? false : route), // false skips it + // rewrite the path before parsing: the request path (and module name) change too, + // so put '/api/v1' into baseUrl + onPreBuildRoutePath: (path) => path.replace(/^\/api\/v1/, ''), + onCreateComponent: (component) => component, + onPrepareConfig: (configuration) => configuration, // data passed to the templates }, + // `format: date-time` strings typed as Date (the client does not parse them for you) + primitiveTypeConstructs: { string: { 'date-time': 'Date' } }, }); ``` -## Pattern 7: Programmatic, In-Memory Generation +Hook arguments are typed (`Hooks`, `ParsedRoute`, `RawRouteInfo`, ...). Reading properties that are +not in those types needs a cast. + +## 7. Programmatic, in memory ```ts -import { generateApi } from 'swagger-typescript-api-es'; +import { generateApi, type GenerateApiOutput } from 'swagger-typescript-api-es'; -// `output: false` - nothing is written, the generated files are only returned -const { files } = await generateApi({ +const result: GenerateApiOutput = await generateApi({ url: 'https://api.example.com/swagger.json', - output: false, - requestOptions: { timeout: 30_000 }, // schema download timeout in ms (default: 60000) + output: false, // nothing is written + requestOptions: { timeout: 30_000 }, // schema download timeout (default 60000) }); -for (const { fileName, fileExtension, fileContent } of files) { +for (const { fileName, fileExtension, fileContent } of result.files) { console.log(fileName + fileExtension, fileContent.length); } -// an array of options returns an array of results (one per config) -const results = await generateApi([{ url: '...', output: './src/api' }]); +// spec already in memory (it is not modified); an array returns an array of results +const [first] = await generateApi([ + { spec: { openapi: '3.0.3', info: { title: 'x', version: '1' }, paths: {} }, output: false }, +]); +console.log(first.files.length); ``` -## package.json scripts +`generateApi` rejects on errors (bad schema, failed download, output path that is a file). + +## 8. Protected schema, proxies, self-signed certificates + +```ts +import { defaultConfig } from 'swagger-typescript-api-es'; +import { ProxyAgent } from 'undici'; // npm i -D undici + +export default defaultConfig({ + url: 'https://internal.example.com/swagger.json', + output: './src/api', + authorizationToken: `Bearer ${process.env.API_TOKEN}`, // sent as-is in Authorization + disableStrictSSL: true, // self-signed certificate + // HTTP(S)_PROXY / NO_PROXY are used by default; disableProxy: true connects directly, + // or pass your own undici dispatcher (replaces proxy + SSL handling): + requestOptions: { + dispatcher: new ProxyAgent('http://proxy:3128'), + headers: { 'X-Key': 'k' }, + timeout: 120_000, + }, +}); +``` + +## 9. Custom templates + +```ts +import { generateTemplates } from 'swagger-typescript-api-es'; + +// copy the built-in Eta templates once, then edit them +await generateTemplates({ output: './api-templates', httpClientType: 'fetch', modular: false }); +``` + +```ts +import { defaultConfig } from 'swagger-typescript-api-es'; + +export default defaultConfig({ + input: './openapi.json', + output: './src/api', + templates: './api-templates', // missing files fall back to the built-in ones + extraTemplates: [{ name: 'endpoints.ts', path: './api-templates/endpoints.ejs' }], + constants: { API_VERSION: 'v1' }, // `config.constants.API_VERSION` in templates +}); +``` + +In templates, `it` holds `apiConfig`, `config`, `modelTypes`, `routes` and `utils`; `utils._` has +lodash-compatible helpers (`es-toolkit/compat`), and `includeFile('@base/route-docs', { ... })` +includes built-in partials. + +## 10. Formatting of the output + +Defaults < `.oxfmtrc.json` in cwd < `oxfmtOptrions`: + +```ts +import { defaultConfig } from 'swagger-typescript-api-es'; + +export default defaultConfig({ + input: './openapi.json', + output: './src/api', + oxfmtOptrions: { singleQuote: false, printWidth: 120, semi: false }, +}); +``` + +## 11. Scripts and CI ```json { "scripts": { "gen-api-types": "swagger-typescript-api-es", - "gen-api-types:watch": "nodemon --watch openapi.json --exec 'npm run gen-api-types'" + "gen-api-types:check": "swagger-typescript-api-es && git diff --exit-code src/api" } } ``` + +The CLI exits with `1` on any error, so a broken schema fails the CI job. Flags need values: +`swagger-typescript-api-es -u ./openapi.json -o ./src/api --modular true --silent true`. diff --git a/skills/swagger-typescript-api-es/references/usage.md b/skills/swagger-typescript-api-es/references/usage.md new file mode 100644 index 0000000..202975b --- /dev/null +++ b/skills/swagger-typescript-api-es/references/usage.md @@ -0,0 +1,218 @@ +# Using the generated client + +Examples use a client generated from a petstore spec (`servers: [{ url: 'https://petstore.example.com/v1' }]`, +paths `/pets`, `/pets/{petId}`, `/store/...`, `/users/{username}`, `GET /`). All snippets type-check +with `strict: true` against the generated code. + +## Shape of the generated code + +- Data contracts: `export interface Pet`, `export enum PetStatus`, `export type OrderItem = ...`. +- `HttpClient` with `request()`, `setSecurityData()`, plus `ApiConfig`, + `RequestParams`, `FullRequestParams`, `ContentType` (a `const` object + type) and, for fetch, + `HttpResponse`. +- `class Api extends HttpClient`: routes without a module are + methods (`api.getRoot()`), the others are grouped by the first path segment + (`api.pets.listPets()`, `api.store.placeOrder()`). Names come from `operationId`. +- Method arguments: path params, `query`, `data` (body), `params: RequestParams = {}`; required + arguments come first. A body is optional unless the spec says `required: true`. Path params are + sent through `encodeURIComponent`. + +## fetch (default `httpClientType`) + +```ts +import { Api, ContentType, type HttpResponse } from './api/Api'; +import type { Error as ApiError, Pet } from './api/Api'; // `Error` would shadow the global + +const api = new Api({ + baseUrl: 'https://api.example.com', // default: servers[0].url of the spec + baseApiParams: { headers: { 'X-App': 'web' }, credentials: 'include' }, // merged into every request + // runs for routes with `security` (or `secure: true`); its result is merged into the request + securityWorker: (token) => (token ? { headers: { Authorization: `Bearer ${token}` } } : {}), + customFetch: (input, init) => fetch(input, init), // SSR, retries, tests, ... + injectHeaders: async (headers: Record) => ({ ...headers, 'X-Req': '1' }), +}); + +api.setSecurityData('jwt-token'); // `null` to log out + +try { + const res = await api.pets.getPet(1); // HttpResponse + const pet: Pet = res.data; + console.log(res.status, pet.name); +} catch (e) { + // non-2xx: rejects with the HttpResponse (network errors reject with a TypeError) + const res = e as HttpResponse; + console.error(res.status, res.error?.message); +} + +// optional query object, then per-request params (RequestInit + secure/type/format/baseUrl/cancelToken) +await api.pets.listPets({ limit: 10 }, { headers: { 'X-Trace': '1' } }); +await api.pets.listPets(); + +// the body is optional unless `requestBody.required: true` +await api.pets.updatePet('42'); // data?: NewPet +await api.pets.createPet({ name: 'Rex' }); // data: NewPet + +// multipart/form-data: pass File / Blob fields, the client builds the FormData +await api.pets.uploadPetPhoto('42', { file: new File(['x'], 'a.png'), caption: 'hi' }); + +// cancellation with a token... +const pending = api.pets.listPets({}, { cancelToken: 'pets' }); +api.abortRequest('pets'); +await pending.catch(() => {}); +// ...or a plain AbortSignal +await api.pets.listPets({}, { signal: AbortSignal.timeout(5_000) }); + +// low-level request +await api.request({ + path: '/pets', + method: 'POST', + body: { name: 'Rex' }, + type: ContentType.Json, + format: 'json', + secure: true, +}); +``` + +Notes: + +- `ApiConfig` (fetch): `baseUrl`, `baseApiParams` (defaults: `credentials: 'same-origin'`, + `redirect: 'follow'`, `referrerPolicy: 'no-referrer'`), `securityWorker`, `customFetch`, + `injectHeaders(headers) => headers | Promise`. +- `baseApiParams: { secure: true }` calls `securityWorker` for every request. +- The response body is read with `format` (`json`, `text`, `blob`, `formData`, ...); binary + responses use `blob`. On errors the parsed body is in `response.error`. +- Query values `undefined` / `null` are skipped; arrays are sent as repeated keys (`tags=a&tags=b`). + +### `disableThrowOnError: true` + +```ts +import { Api } from './api/Api'; + +const api = new Api(); +const res = await api.pets.getPet(1); // resolves for every status +if (!res.ok) { + console.error(res.status, res.error); +} else { + console.log(res.data.name); +} +``` + +### `unwrapResponseData: true` + +```ts +import { Api, type Pet } from './api/Api'; + +const api = new Api(); +const pet: Pet = await api.pets.getPet(1); // the body; failures still reject with the HttpResponse +``` + +### `extractRequestParams: true` + +```ts +import { Api, type ListPetsParams } from './api/Api'; + +const api = new Api(); +const query: ListPetsParams = { limit: 10 }; +await api.pets.listPets(query); +await api.pets.listPets(); // optional: no path params and every query param is optional +``` + +## axios (`httpClientType: 'axios'`) + +Install `axios` in the app. `ApiConfig` extends `AxiosRequestConfig` (so `baseURL` with a capital +`URL`, `timeout`, `headers`, ...) and adds `securityWorker`, `secure`, `format` (default +`responseType`), `instance` and `injectHeaders`. + +```ts +import axios from 'axios'; + +import { Api, type Pet } from './api/Api'; + +const api = new Api({ + baseURL: 'https://api.example.com', // default: servers[0].url of the spec + timeout: 10_000, + securityWorker: (token) => (token ? { headers: { Authorization: `Bearer ${token}` } } : {}), + secure: true, // call securityWorker for every request, not only secured routes + format: 'json', +}); +api.setSecurityData('jwt-token'); + +// reuse your own axios instance (interceptors, adapters, ...): the other axios options are then ignored +const shared = axios.create({ baseURL: 'https://api.example.com' }); +const api2 = new Api({ instance: shared }); + +try { + const { data, status } = await api.pets.getPet(1); // AxiosResponse + const pet: Pet = data; + console.log(status, pet.name); +} catch (e) { + if (axios.isAxiosError(e)) console.error(e.response?.status, e.response?.data); +} + +// per-request AxiosRequestConfig; cancel with an AbortSignal +const controller = new AbortController(); +await api2.pets.listPets({ limit: 5 }, { signal: controller.signal, headers: { 'X-Trace': '1' } }); + +api.instance.interceptors.request.use((config) => config); // the underlying instance +``` + +The axios client has no `abortRequest` / `cancelToken` and ignores `disableThrowOnError` (axios +itself rejects on non-2xx). `unwrapResponseData: true` resolves with `response.data`. + +## `singleHttpClient: true` + +`Api` no longer extends `HttpClient`; pass one shared instance (also works in modular mode, where +every module class takes the `HttpClient`): + +```ts +import { Api, HttpClient } from './api/Api'; + +const http = new HttpClient({ + baseUrl: 'https://api.example.com', + securityWorker: (token) => (token ? { headers: { Authorization: `Bearer ${token}` } } : {}), +}); +http.setSecurityData('jwt-token'); + +const api = new Api(http); // methods call this.http.request +const { data } = await api.pets.getPet(1); +api.http.abortRequest('some-token'); +``` + +## Modular (`modular: true`) + +Files: `data-contracts.ts`, `http-client.ts`, one class per module (`Pets.ts`, `Store.ts`, +`Users.ts`, `Common.ts` for `GET /`), and with `generateRouteTypes` `PetsRoute.ts`, ..., +`CommonRoute.ts`. Each module class extends `HttpClient` and has flat methods. + +```ts +import type { Pet } from './api/data-contracts'; +import type { ApiConfig } from './api/http-client'; +import { Pets } from './api/Pets'; +import type { Pets as PetsRoutes } from './api/PetsRoute'; +import { Store } from './api/Store'; + +const config: ApiConfig = { + baseUrl: 'https://api.example.com', + securityWorker: (token) => (token ? { headers: { Authorization: `Bearer ${token}` } } : {}), +}; +const pets = new Pets(config); +const store = new Store(config); +pets.setSecurityData('jwt-token'); // security data is per instance +store.setSecurityData('jwt-token'); + +const { data } = await pets.listPets({ limit: 10 }); +const first: Pet | undefined = data[0]; + +// route types (generateRouteTypes: true) +const query: PetsRoutes.ListPets.RequestQuery = { limit: 1 }; +const body: PetsRoutes.ListPets.ResponseBody = data; +``` + +A module named like a data contract becomes `class Api` (namespace `Route`). + +## Tips + +- Regenerate instead of editing generated files; customise with options, hooks or templates. +- Wrap the generated `Api` in your own module to centralise `baseUrl`, auth and error mapping. +- For React Query / SWR, call the methods in query functions: `queryFn: () => api.pets.getPet(id).then((r) => r.data)` + (or directly with `unwrapResponseData: true`). From 9fdd80f423a89fdf42b2fab11a70b085e0fd9597 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 02:32:16 +0000 Subject: [PATCH 8/9] feat(docs): benchmark against the original swagger-typescript-api - bench/compare: installs swagger-typescript-api (13.13.0) in its own folder and runs both libraries on the same documents and options (output: false), each measurement in a separate process: warm generation (median), cold run (import + one generation), peak RSS, output size; npm run bench:compare - /benchmark page: headline tiles, per-document chart (generation / cold run / memory) with tooltips and validated colours, full results table, method, caveats, environment and how to reproduce - README: Performance section with the results Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- README.md | 17 + bench/compare/package-lock.json | 1051 +++++++++++++++++ bench/compare/package.json | 9 + bench/compare/run.mjs | 265 +++++ docs/app/benchmark/page.tsx | 292 +++++ docs/app/globals.css | 8 + docs/components/benchmark/benchmark-chart.tsx | 205 ++++ docs/lib/benchmark/results.json | 376 ++++++ docs/lib/benchmark/types.ts | 63 + docs/tests/e2e/benchmark.spec.ts | 74 ++ package.json | 1 + 11 files changed, 2361 insertions(+) create mode 100644 bench/compare/package-lock.json create mode 100644 bench/compare/package.json create mode 100644 bench/compare/run.mjs create mode 100644 docs/app/benchmark/page.tsx create mode 100644 docs/components/benchmark/benchmark-chart.tsx create mode 100644 docs/lib/benchmark/results.json create mode 100644 docs/lib/benchmark/types.ts create mode 100644 docs/tests/e2e/benchmark.spec.ts diff --git a/README.md b/README.md index cbb1ca0..5bb9df5 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ Generate a fully typed TypeScript API client (`fetch` or `axios`) and data contr ## Table of contents - [Differences from the original](#differences-from-the-original) +- [Performance](#performance) - [Requirements](#requirements) - [Install](#install) - [Quick start](#quick-start) @@ -62,6 +63,22 @@ the same kind of client, with these differences: - There is no `generate-templates` CLI command. To copy the built-in templates, call [`generateTemplates()`](#custom-templates) from code. +## Performance + +Generation time compared with the original `swagger-typescript-api` v13.13.0 (median, warm process, +same documents and options, Node.js v22.22.2 on 4 cores): + +| Document | swagger-typescript-api-es | swagger-typescript-api | | +| ---------------------------------------- | ------------------------: | ---------------------: | -------------: | +| Petstore (15 schemas, 11 operations) | 8 ms | 74 ms | **10Γ— faster** | +| 300 schemas, 600 operations | 107 ms | 2.2 s | **20Γ— faster** | +| 1500 schemas, 3000 operations | 494 ms | 11.3 s | **23Γ— faster** | +| 1500 schemas, 3000 operations, `modular` | 426 ms | 14.9 s | **35Γ— faster** | + +A single cold run (new process, like the CLI) of the largest document takes about +938 ms instead of 13.1 s, with less than half the memory. All numbers, the method and +the caveats are on the docs site's Benchmark page; run it yourself with `npm run bench:compare`. + ## Requirements - **Node.js >= 20** diff --git a/bench/compare/package-lock.json b/bench/compare/package-lock.json new file mode 100644 index 0000000..9e98d64 --- /dev/null +++ b/bench/compare/package-lock.json @@ -0,0 +1,1051 @@ +{ + "name": "swagger-typescript-api-es-benchmark", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "swagger-typescript-api-es-benchmark", + "dependencies": { + "swagger-typescript-api": "13.13.0" + } + }, + "node_modules/@apidevtools/json-schema-ref-parser": { + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@apidevtools/json-schema-ref-parser/-/json-schema-ref-parser-14.0.1.tgz", + "integrity": "sha512-Oc96zvmxx1fqoSEdUmfmvvb59/KDOnUoJ7s2t7bISyAn0XEz57LCCw8k2Y4Pf3mwKaZLMciESALORLgfe2frCw==", + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.15", + "js-yaml": "^4.1.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/philsturgeon" + } + }, + "node_modules/@apidevtools/openapi-schemas": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@apidevtools/openapi-schemas/-/openapi-schemas-2.1.0.tgz", + "integrity": "sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/@apidevtools/swagger-methods": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@apidevtools/swagger-methods/-/swagger-methods-3.0.2.tgz", + "integrity": "sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg==", + "license": "MIT" + }, + "node_modules/@apidevtools/swagger-parser": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/@apidevtools/swagger-parser/-/swagger-parser-12.1.0.tgz", + "integrity": "sha512-e5mJoswsnAX0jG+J09xHFYQXb/bUc5S3pLpMxUuRUA2H8T2kni3yEoyz2R3Dltw5f4A6j6rPNMpWTK+iVDFlng==", + "license": "MIT", + "dependencies": { + "@apidevtools/json-schema-ref-parser": "14.0.1", + "@apidevtools/openapi-schemas": "^2.1.0", + "@apidevtools/swagger-methods": "^3.0.2", + "ajv": "^8.17.1", + "ajv-draft-04": "^1.0.0", + "call-me-maybe": "^1.0.2" + }, + "peerDependencies": { + "openapi-types": ">=7" + } + }, + "node_modules/@biomejs/js-api": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@biomejs/js-api/-/js-api-6.0.0.tgz", + "integrity": "sha512-8HP7wexjQo5Np1J9h0B2x8L5G0GZpCacgjykxLHtvLPvF0hNqSG754oh8bxo+OSFDpVGMfSjmLO+ZY/5KbfjmQ==", + "license": "MIT OR Apache-2.0", + "peerDependencies": { + "@biomejs/wasm-bundler": "^2.5.0", + "@biomejs/wasm-nodejs": "^2.5.0", + "@biomejs/wasm-web": "^2.5.0" + }, + "peerDependenciesMeta": { + "@biomejs/wasm-bundler": { + "optional": true + }, + "@biomejs/wasm-nodejs": { + "optional": true + }, + "@biomejs/wasm-web": { + "optional": true + } + } + }, + "node_modules/@biomejs/wasm-nodejs": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/@biomejs/wasm-nodejs/-/wasm-nodejs-2.5.2.tgz", + "integrity": "sha512-B0r7jLdCmXhq4+jnx1oA0/SChLy5G283r35HJr276T+w6qgqAPAhqfnlKs+UobclAfidNDbfj9ZmcuCijaHDxQ==", + "license": "MIT OR Apache-2.0" + }, + "node_modules/@exodus/schemasafe": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@exodus/schemasafe/-/schemasafe-1.3.0.tgz", + "integrity": "sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==", + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "license": "MIT" + }, + "node_modules/@types/swagger-schema-official": { + "version": "2.0.25", + "resolved": "https://registry.npmjs.org/@types/swagger-schema-official/-/swagger-schema-official-2.0.25.tgz", + "integrity": "sha512-T92Xav+Gf/Ik1uPW581nA+JftmjWPgskw/WBf4TJzxRG/SJ+DfNnNE+WuZ4mrXuzflQMqMkm1LSYjzYW7MB1Cg==", + "license": "MIT" + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-draft-04": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/ajv-draft-04/-/ajv-draft-04-1.0.0.tgz", + "integrity": "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==", + "license": "MIT", + "peerDependencies": { + "ajv": "^8.5.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/c12": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz", + "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==", + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "confbox": "^0.2.4", + "defu": "^6.1.6", + "dotenv": "^17.3.1", + "exsolve": "^1.0.8", + "giget": "^3.2.0", + "jiti": "^2.6.1", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^2.1.0", + "pkg-types": "^2.3.0", + "rc9": "^3.0.1" + }, + "peerDependencies": { + "magicast": "*" + }, + "peerDependenciesMeta": { + "magicast": { + "optional": true + } + } + }, + "node_modules/call-me-maybe": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz", + "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==", + "license": "MIT" + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/citty": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", + "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "license": "MIT" + }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "license": "Apache-2.0", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", + "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/dayjs": { + "version": "1.11.23", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", + "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", + "license": "MIT" + }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "license": "MIT" + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "license": "MIT" + }, + "node_modules/dompurify": { + "version": "3.4.16", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", + "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/es-toolkit": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", + "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, + "node_modules/es6-promise": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", + "integrity": "sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==", + "license": "MIT" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eta": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/eta/-/eta-3.5.0.tgz", + "integrity": "sha512-e3x3FBvGzeCIHhF+zhK8FZA2vC5uFn6b4HJjegUbIWrDb4mJ7JjTGMJY9VGIbRVpmSwHopNiaJibhjIr+HfLug==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + }, + "funding": { + "url": "https://github.com/eta-dev/eta?sponsor=1" + } + }, + "node_modules/exsolve": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.1.tgz", + "integrity": "sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g==", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/giget": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz", + "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==", + "license": "MIT", + "bin": { + "giget": "dist/cli.mjs" + } + }, + "node_modules/http2-client": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/http2-client/-/http2-client-1.3.5.tgz", + "integrity": "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==", + "license": "MIT" + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "5.1.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz", + "integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch-h2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/node-fetch-h2/-/node-fetch-h2-2.3.0.tgz", + "integrity": "sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==", + "license": "MIT", + "dependencies": { + "http2-client": "^1.2.5" + }, + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/node-readfiles": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/node-readfiles/-/node-readfiles-0.2.0.tgz", + "integrity": "sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==", + "license": "MIT", + "dependencies": { + "es6-promise": "^3.2.1" + } + }, + "node_modules/oas-kit-common": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/oas-kit-common/-/oas-kit-common-1.0.8.tgz", + "integrity": "sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==", + "license": "BSD-3-Clause", + "dependencies": { + "fast-safe-stringify": "^2.0.7" + } + }, + "node_modules/oas-linter": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/oas-linter/-/oas-linter-3.2.2.tgz", + "integrity": "sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==", + "license": "BSD-3-Clause", + "dependencies": { + "@exodus/schemasafe": "^1.0.0-rc.2", + "should": "^13.2.1", + "yaml": "^1.10.0" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-linter/node_modules/yaml": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/oas-resolver": { + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/oas-resolver/-/oas-resolver-2.5.6.tgz", + "integrity": "sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==", + "license": "BSD-3-Clause", + "dependencies": { + "node-fetch-h2": "^2.3.0", + "oas-kit-common": "^1.0.8", + "reftools": "^1.1.9", + "yaml": "^1.10.0", + "yargs": "^17.0.1" + }, + "bin": { + "resolve": "resolve.js" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-resolver/node_modules/yaml": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/oas-schema-walker": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/oas-schema-walker/-/oas-schema-walker-1.1.5.tgz", + "integrity": "sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==", + "license": "BSD-3-Clause", + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-validator": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/oas-validator/-/oas-validator-5.0.8.tgz", + "integrity": "sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==", + "license": "BSD-3-Clause", + "dependencies": { + "call-me-maybe": "^1.0.1", + "oas-kit-common": "^1.0.8", + "oas-linter": "^3.2.2", + "oas-resolver": "^2.5.6", + "oas-schema-walker": "^1.1.5", + "reftools": "^1.1.9", + "should": "^13.2.1", + "yaml": "^1.10.0" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-validator/node_modules/yaml": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/ohash": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", + "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", + "license": "MIT" + }, + "node_modules/openapi-types": { + "version": "12.1.3", + "resolved": "https://registry.npmjs.org/openapi-types/-/openapi-types-12.1.3.tgz", + "integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==", + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, + "node_modules/perfect-debounce": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", + "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", + "license": "MIT" + }, + "node_modules/pkg-types": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.3.tgz", + "integrity": "sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==", + "license": "MIT", + "dependencies": { + "confbox": "^0.3.1", + "exsolve": "^1.1.1", + "pathe": "^2.0.3" + } + }, + "node_modules/pkg-types/node_modules/confbox": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.1.tgz", + "integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==", + "license": "MIT" + }, + "node_modules/rc9": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.1.0.tgz", + "integrity": "sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==", + "license": "MIT", + "dependencies": { + "defu": "^6.1.7", + "destr": "^2.0.5" + } + }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/reftools": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/reftools/-/reftools-1.1.9.tgz", + "integrity": "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==", + "license": "BSD-3-Clause", + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/should": { + "version": "13.2.3", + "resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz", + "integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==", + "license": "MIT", + "dependencies": { + "should-equal": "^2.0.0", + "should-format": "^3.0.3", + "should-type": "^1.4.0", + "should-type-adaptors": "^1.0.1", + "should-util": "^1.0.0" + } + }, + "node_modules/should-equal": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz", + "integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==", + "license": "MIT", + "dependencies": { + "should-type": "^1.4.0" + } + }, + "node_modules/should-format": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz", + "integrity": "sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==", + "license": "MIT", + "dependencies": { + "should-type": "^1.3.0", + "should-type-adaptors": "^1.0.1" + } + }, + "node_modules/should-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz", + "integrity": "sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==", + "license": "MIT" + }, + "node_modules/should-type-adaptors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz", + "integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==", + "license": "MIT", + "dependencies": { + "should-type": "^1.3.0", + "should-util": "^1.0.0" + } + }, + "node_modules/should-util": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.1.tgz", + "integrity": "sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==", + "license": "MIT" + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/swagger-schema-official": { + "version": "2.0.0-bab6bed", + "resolved": "https://registry.npmjs.org/swagger-schema-official/-/swagger-schema-official-2.0.0-bab6bed.tgz", + "integrity": "sha512-rCC0NWGKr/IJhtRuPq/t37qvZHI/mH4I4sxflVM+qgVe5Z2uOCivzWaVbuioJaB61kvm5UvB7b49E+oBY0M8jA==", + "license": "ISC" + }, + "node_modules/swagger-typescript-api": { + "version": "13.13.0", + "resolved": "https://registry.npmjs.org/swagger-typescript-api/-/swagger-typescript-api-13.13.0.tgz", + "integrity": "sha512-4CEj48R1Kk3Zvul4c8NVeLOUQ86WIRq1MgqRaB12jKI70IT/UUc4/xn+vd9pWK+I8eRALX2UnUI1ld0YQHn16A==", + "license": "MIT", + "dependencies": { + "@apidevtools/swagger-parser": "12.1.0", + "@biomejs/js-api": "6.0.0", + "@biomejs/wasm-nodejs": "2.5.2", + "@types/swagger-schema-official": "^2.0.25", + "c12": "^3.3.4", + "citty": "^0.2.2", + "consola": "^3.4.2", + "es-toolkit": "^1.49.0", + "eta": "^3.5.0", + "nanoid": "^5.1.16", + "openapi-types": "^12.1.3", + "swagger-schema-official": "2.0.0-bab6bed", + "swagger2openapi": "^7.0.8", + "type-fest": "^5.7.0", + "typescript": "^6.0.3", + "yaml": "^2.9.0", + "yummies": "7.20.1" + }, + "bin": { + "swagger-typescript-api": "dist/cli.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/swagger2openapi": { + "version": "7.0.8", + "resolved": "https://registry.npmjs.org/swagger2openapi/-/swagger2openapi-7.0.8.tgz", + "integrity": "sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==", + "license": "BSD-3-Clause", + "dependencies": { + "call-me-maybe": "^1.0.1", + "node-fetch": "^2.6.1", + "node-fetch-h2": "^2.3.0", + "node-readfiles": "^0.2.0", + "oas-kit-common": "^1.0.8", + "oas-resolver": "^2.5.6", + "oas-schema-walker": "^1.1.5", + "oas-validator": "^5.0.8", + "reftools": "^1.1.9", + "yaml": "^1.10.0", + "yargs": "^17.0.1" + }, + "bin": { + "boast": "boast.js", + "oas-validate": "oas-validate.js", + "swagger2openapi": "swagger2openapi.js" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/swagger2openapi/node_modules/yaml": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.3.tgz", + "integrity": "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==", + "license": "ISC", + "engines": { + "node": ">= 6" + } + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tailwind-merge": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.7.0.tgz", + "integrity": "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/type-fest": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz", + "integrity": "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==", + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yummies": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/yummies/-/yummies-7.20.1.tgz", + "integrity": "sha512-H/AxRy+SjVlfpeI0TkiVkU/M2n+XpR1XGt5yS5r7GsP9Iz3mr17dbq9DLW18PmMlyKO78+yvH/9Z9VAnVuV3og==", + "license": "MIT", + "dependencies": { + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "dayjs": "^1.11.21", + "dompurify": "^3.4.11", + "nanoid": "^5.1.15", + "tailwind-merge": "^3.6.0" + }, + "peerDependencies": { + "mobx": "^6.12.4", + "react": "^18 || ^19" + }, + "peerDependenciesMeta": { + "mobx": { + "optional": true + }, + "react": { + "optional": true + } + } + } + } +} diff --git a/bench/compare/package.json b/bench/compare/package.json new file mode 100644 index 0000000..6e72a71 --- /dev/null +++ b/bench/compare/package.json @@ -0,0 +1,9 @@ +{ + "name": "swagger-typescript-api-es-benchmark", + "private": true, + "description": "Isolated install of the original acacode/swagger-typescript-api for the comparison benchmark", + "type": "module", + "dependencies": { + "swagger-typescript-api": "13.13.0" + } +} diff --git a/bench/compare/run.mjs b/bench/compare/run.mjs new file mode 100644 index 0000000..3c1c7a2 --- /dev/null +++ b/bench/compare/run.mjs @@ -0,0 +1,265 @@ +/** + * Compares swagger-typescript-api-es with the original acacode/swagger-typescript-api. + * + * npm run bench:compare # builds, installs the original, runs, writes the results + * node bench/compare/run.mjs --runs 5 --filter large --out /tmp/results.json + * + * Every measurement runs in its own Node.js process (no JIT / GC state shared between the libraries), + * both libraries get the same document (`spec`) and the same options, and write nothing to disk + * (`output: false`). Results are written to `docs/lib/benchmark/results.json` (read by the docs site). + */ +import { execFileSync, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { generateSpec } from '../generate-spec.mjs'; + +const benchDir = path.dirname(fileURLToPath(import.meta.url)); +const rootDir = path.resolve(benchDir, '../..'); +const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sta-compare-')); + +const args = process.argv.slice(2); +const argValue = (name, fallback) => { + const index = args.indexOf(`--${name}`); + return index === -1 ? fallback : args[index + 1]; +}; +const warmRuns = Number(argValue('runs', 5)); +const coldRuns = Number(argValue('cold-runs', 3)); +const filter = argValue('filter', ''); +const outFile = path.resolve( + argValue('out', path.join(rootDir, 'docs/lib/benchmark/results.json')) +); + +const readJson = (file) => JSON.parse(fs.readFileSync(file, 'utf8')); + +const libraries = [ + { + id: 'es', + name: 'swagger-typescript-api-es', + version: readJson(path.join(rootDir, 'package.json')).version, + entry: pathToFileURL(path.join(rootDir, 'dist/index.mjs')).href, + }, + { + id: 'original', + name: 'swagger-typescript-api', + version: readJson(path.join(benchDir, 'node_modules/swagger-typescript-api/package.json')) + .version, + entry: pathToFileURL(path.join(benchDir, 'node_modules/swagger-typescript-api/dist/index.mjs')) + .href, + }, +]; + +// ---- documents (written once, read by every child process) +const writeSpec = (name, spec) => { + const file = path.join(workDir, `${name}.json`); + fs.writeFileSync(file, JSON.stringify(spec)); + return file; +}; + +const documents = { + petstore: { + label: 'Petstore', + detail: 'OpenAPI 3, 15 schemas, 11 operations (tests/fixtures/petstore.json)', + file: path.join(rootDir, 'tests/fixtures/petstore.json'), + }, + medium: { + label: 'Medium', + detail: 'synthetic OpenAPI 3, 300 schemas, 600 operations', + file: writeSpec('medium', generateSpec({ schemas: 300, operations: 600 })), + }, + large: { + label: 'Large', + detail: 'synthetic OpenAPI 3, 1500 schemas, 3000 operations', + file: writeSpec('large', generateSpec({ schemas: 1500, operations: 3000 })), + }, +}; + +const optionSets = { + default: { label: 'default', options: {} }, + modular: { label: 'modular', options: { modular: true } }, + extract: { + label: 'extract* + route types', + options: { + extractRequestParams: true, + extractRequestBody: true, + extractResponseBody: true, + extractResponseError: true, + extractEnums: true, + generateRouteTypes: true, + }, + }, +}; + +const scenarios = [ + ['petstore', 'default'], + ['petstore', 'modular'], + ['medium', 'default'], + ['medium', 'modular'], + ['medium', 'extract'], + ['large', 'default'], + ['large', 'modular'], + ['large', 'extract'], +] + .map(([document, options]) => ({ id: `${document}-${options}`, document, options })) + .filter((scenario) => scenario.id.includes(filter)); + +// ---- child process: import + generate, reports timings as JSON on stdout +const childScript = ` +const [entry, specFile, optionsJson, mode, runs] = process.argv.slice(1); +const fs = await import('node:fs'); +const text = fs.readFileSync(specFile, 'utf8'); +const options = JSON.parse(optionsJson); +const importStart = performance.now(); +const { generateApi } = await import(entry); +const importMs = performance.now() - importStart; +const generate = async () => { + const spec = JSON.parse(text); + const start = performance.now(); + const result = await generateApi({ ...options, spec, output: false, silent: true }); + return { ms: performance.now() - start, result }; +}; +const times = []; +let outputBytes = 0; +let files = 0; +if (mode === 'cold') { + const { ms, result } = await generate(); + times.push(ms); + outputBytes = result.files.reduce((size, file) => size + Buffer.byteLength(file.fileContent), 0); + files = result.files.length; +} else { + await generate(); // warm-up (JIT, lazy loading) + for (let i = 0; i < Number(runs); i++) { + const { ms, result } = await generate(); + times.push(ms); + outputBytes = result.files.reduce((size, file) => size + Buffer.byteLength(file.fileContent), 0); + files = result.files.length; + } +} +process.stdout.write(JSON.stringify({ importMs, times, outputBytes, files, maxRssKb: process.resourceUsage().maxRSS })); +`; + +const runChild = (library, scenario, mode) => { + const started = performance.now(); + const { status, stdout, stderr } = spawnSync( + process.execPath, + [ + '--input-type=module', + '-e', + childScript, + library.entry, + documents[scenario.document].file, + JSON.stringify(optionSets[scenario.options].options), + mode, + String(warmRuns), + ], + { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, cwd: workDir } + ); + if (status !== 0) { + throw new Error(`${library.name} ${scenario.id} ${mode} failed:\n${stderr}`); + } + const lastLine = stdout.trim().split('\n').pop(); + return { ...JSON.parse(lastLine), processMs: performance.now() - started }; +}; + +const median = (values) => { + const sorted = [...values].sort((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; +}; +const round = (value) => Math.round(value * 10) / 10; + +const measure = (library, scenario) => { + // cold: a new process for every run (import + one generation), like running the CLI once + const cold = Array.from({ length: coldRuns }, () => runChild(library, scenario, 'cold')); + // warm: one process, one warm-up generation, then `warmRuns` measured generations + const warm = runChild(library, scenario, 'warm'); + return { + cold: { + medianMs: round(median(cold.map((run) => run.importMs + run.times[0]))), + minMs: round(Math.min(...cold.map((run) => run.importMs + run.times[0]))), + importMs: round(median(cold.map((run) => run.importMs))), + generateMs: round(median(cold.map((run) => run.times[0]))), + maxRssMb: round(median(cold.map((run) => run.maxRssKb / 1024))), + }, + warm: { + medianMs: round(median(warm.times)), + minMs: round(Math.min(...warm.times)), + runs: warm.times.length, + }, + outputKb: round(warm.outputBytes / 1024), + files: warm.files, + }; +}; + +const gitCommit = () => { + try { + return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { + cwd: rootDir, + encoding: 'utf8', + }).trim(); + } catch { + return null; + } +}; + +const main = () => { + const cpus = os.cpus(); + console.log( + `node ${process.version}, ${cpus[0]?.model ?? 'unknown CPU'} (${cpus.length} cores), ${warmRuns} warm / ${coldRuns} cold runs` + ); + + const results = []; + for (const scenario of scenarios) { + const row = { + id: scenario.id, + document: scenario.document, + options: scenario.options, + libraries: {}, + }; + // alternate the order so that neither library always runs first + const ordered = results.length % 2 ? [...libraries].reverse() : libraries; + for (const library of ordered) { + row.libraries[library.id] = measure(library, scenario); + } + const es = row.libraries.es; + const original = row.libraries.original; + console.log( + `${scenario.id.padEnd(18)} warm ${String(es.warm.medianMs).padStart(8)} ms vs ${String(original.warm.medianMs).padStart(9)} ms` + + ` (${(original.warm.medianMs / es.warm.medianMs).toFixed(1)}x) | cold ${es.cold.medianMs} vs ${original.cold.medianMs} ms` + + ` | rss ${es.cold.maxRssMb} vs ${original.cold.maxRssMb} MB` + ); + results.push(row); + } + + const report = { + generatedAt: new Date().toISOString(), + commit: gitCommit(), + environment: { + node: process.version, + platform: `${os.type()} ${os.release()} (${os.arch()})`, + cpu: cpus[0]?.model ?? 'unknown', + cores: cpus.length, + memoryGb: round(os.totalmem() / 1024 ** 3), + }, + settings: { warmRuns, coldRuns }, + libraries: Object.fromEntries( + libraries.map(({ id, name, version }) => [id, { name, version }]) + ), + documents: Object.fromEntries( + Object.entries(documents).map(([id, { label, detail }]) => [id, { label, detail }]) + ), + optionSets: Object.fromEntries( + Object.entries(optionSets).map(([id, { label, options }]) => [id, { label, options }]) + ), + results, + }; + + fs.mkdirSync(path.dirname(outFile), { recursive: true }); + fs.writeFileSync(outFile, `${JSON.stringify(report, null, 2)}\n`); + console.log(`\nwritten to ${path.relative(process.cwd(), outFile)}`); + fs.rmSync(workDir, { recursive: true, force: true }); +}; + +main(); diff --git a/docs/app/benchmark/page.tsx b/docs/app/benchmark/page.tsx new file mode 100644 index 0000000..190c7c5 --- /dev/null +++ b/docs/app/benchmark/page.tsx @@ -0,0 +1,292 @@ +import { ArrowRight, Cpu, Gauge, MemoryStick, Timer } from 'lucide-react'; +import type { Metadata } from 'next'; +import Link from 'next/link'; + +import { BenchmarkChart } from '@/components/benchmark/benchmark-chart'; +import { CodeBlock } from '@/components/code-block'; +import { site } from '@/components/site-config'; +import { SiteFooter } from '@/components/site-footer'; +import resultsJson from '@/lib/benchmark/results.json'; +import { + type BenchmarkReport, + type BenchmarkResult, + type Metric, + formatMetric, + formatRatio, + metricValue, + ratio, + versionLabel, +} from '@/lib/benchmark/types'; + +export const dynamic = 'force-static'; + +const report = resultsJson as BenchmarkReport; +const es = report.libraries.es; +const original = report.libraries.original; + +export const metadata: Metadata = { + title: 'Benchmark', + description: `${site.name} compared with the original swagger-typescript-api v${original.version}: generation time, cold run and memory on small to large OpenAPI documents.`, + openGraph: { title: `Benchmark Β· ${site.name}` }, +}; + +const find = (id: string) => report.results.find((result) => result.id === id); + +/** the largest scenario of each kind, for the headline numbers */ +const headline = find('large-default') ?? report.results[report.results.length - 1]; + +function StatTile({ + icon: Icon, + label, + result, + metric, + suffix, +}: { + icon: typeof Timer; + label: string; + result: BenchmarkResult; + metric: Metric; + suffix: string; +}) { + const value = ratio(result, metric); + return ( +
+

+ + {label} +

+

+ {formatRatio(value)} {suffix} +

+

+ {formatMetric(metricValue(result.libraries.es, metric), metric)} vs{' '} + {formatMetric(metricValue(result.libraries.original, metric), metric)} +

+
+ ); +} + +const cell = 'px-3 py-2.5 text-right font-mono text-xs tabular-nums whitespace-nowrap'; + +function ResultsTable() { + return ( +
+ + + + + + + + + + + + + ) + )} + + + + {report.results.map((result) => { + const { es: a, original: b } = result.libraries; + return ( + + + + + + + + + + + + + + ); + })} + +
All benchmark results
+ Scenario + + Generation (warm, median) + + Cold run + + Peak memory + + Output +
+ {['-es', 'original', 'ratio', '-es', 'original', 'ratio', '-es', 'original', '-es', 'original'].map( + (label, index) => ( + + {label} +
+ {report.documents[result.document]?.label}{' '} + + Β· {report.optionSets[result.options]?.label} + + {formatMetric(a.warm.medianMs, 'warm')}{formatMetric(b.warm.medianMs, 'warm')}{formatRatio(ratio(result, 'warm'))}{formatMetric(a.cold.medianMs, 'cold')}{formatMetric(b.cold.medianMs, 'cold')}{formatRatio(ratio(result, 'cold'))}{formatMetric(a.cold.maxRssMb, 'memory')}{formatMetric(b.cold.maxRssMb, 'memory')}{Math.round(a.outputKb)} KB{Math.round(b.outputKb)} KB
+
+ ); +} + +export default function BenchmarkPage() { + const date = new Date(report.generatedAt); + const optionList = Object.values(report.optionSets) + .map(({ label, options }) => + Object.keys(options).length ? `${label}: ${Object.keys(options).join(', ')}` : `${label}: no options` + ) + .join('; '); + + return ( + <> +
+
+

Benchmark

+

+ {es.name} vs{' '} + {original.name} +

+

+ Both generators run on the same machine, with the same OpenAPI documents and the same + options, in separate Node.js processes. The{' '} + + original swagger-typescript-api + {' '} + is the project this library is based on. +

+
+ +
+ + + +
+ +
+ +
+ +
+

+ All results +

+

+ Ratio = time of the original Γ· time of {es.name}. Memory is the peak resident set size of + the cold-run process. +

+
+ +
+
+ +
+
+

+ How it is measured +

+
    +
  • + Same input: each run parses the document from JSON + and passes it as spec, + with output: false{' '} + (no disk writes) and silent: true. +
  • +
  • + Same options for both libraries: {optionList}. +
  • +
  • + Generation: one process per library and scenario, one + warm-up generation, then the median of {report.settings.warmRuns} generations. +
  • +
  • + Cold run: a new process per run that imports the + library and generates once (what a single CLI run costs), median of {report.settings.coldRuns} runs. +
  • +
  • + Versions: {es.name} is measured from the repository + {report.commit ? ` at commit ${report.commit}` : ''} (including changes not published to npm + yet), the original is the latest npm release, v{original.version}. +
  • +
  • + Isolation: every measurement is a separate Node.js + process, and the libraries alternate which one runs first. +
  • +
  • + Formatting is included, because both generators format + their output: {es.name} with oxfmt, the original with Biome (WebAssembly). +
  • +
+ +

Keep in mind

+
    +
  • + The medium and large documents are synthetic (objects with enums, arrays, $refs,{' '} + oneOf and nullable fields, spread over tags). + Real documents have other shapes, so try yours in the{' '} + + playground + {' '} + or run the benchmark with them. +
  • +
  • + The generated code is similar but not identical (different templates and formatters), + which is why the output sizes differ. In modular mode each module file of {es.name}{' '} + imports every data contract, so its modular output is bigger. +
  • +
  • These numbers come from one machine; absolute times depend on the hardware.
  • +
+
+ + +
+ +
+

+ Run it yourself +

+

+ The benchmark lives in the repository (bench/compare). + It installs the original library in its own folder, runs every scenario and writes the + results shown on this page. +

+ + + Read the docs + +
+
+ + + ); +} diff --git a/docs/app/globals.css b/docs/app/globals.css index e9e9519..ed44e9b 100644 --- a/docs/app/globals.css +++ b/docs/app/globals.css @@ -32,6 +32,9 @@ --shadow-md: 0 1px 2px rgb(0 0 0 / 0.04), 0 8px 24px -6px rgb(0 0 0 / 0.1); --shadow-lg: 0 2px 4px rgb(0 0 0 / 0.04), 0 24px 48px -12px rgb(0 0 0 / 0.18); --grid-line: rgb(0 0 0 / 0.045); + /* benchmark chart series (validated: dataviz validate_palette, light surface #ffffff) */ + --series-es: #047857; + --series-original: #eb6834; } :root[data-theme='dark'] { @@ -60,6 +63,9 @@ --shadow-md: 0 1px 2px rgb(0 0 0 / 0.4), 0 8px 24px -6px rgb(0 0 0 / 0.6); --shadow-lg: 0 2px 4px rgb(0 0 0 / 0.4), 0 24px 48px -12px rgb(0 0 0 / 0.7); --grid-line: rgb(255 255 255 / 0.04); + /* benchmark chart series (validated against the dark surface #111114) */ + --series-es: #1baf7a; + --series-original: #d95926; } @theme inline { @@ -83,6 +89,8 @@ --color-danger-border: var(--danger-border); --color-ring: var(--ring); --color-code: var(--code-bg); + --color-series-es: var(--series-es); + --color-series-original: var(--series-original); --shadow-sm: var(--shadow-sm); --shadow-md: var(--shadow-md); --shadow-lg: var(--shadow-lg); diff --git a/docs/components/benchmark/benchmark-chart.tsx b/docs/components/benchmark/benchmark-chart.tsx new file mode 100644 index 0000000..ae2dd66 --- /dev/null +++ b/docs/components/benchmark/benchmark-chart.tsx @@ -0,0 +1,205 @@ +'use client'; + +import { useState } from 'react'; + +import { Segmented } from '@/components/ui/segmented'; +import { + type BenchmarkReport, + type BenchmarkResult, + type LibraryId, + type Metric, + formatMetric, + formatMs, + formatRatio, + metricValue, + ratio, + versionLabel, +} from '@/lib/benchmark/types'; + +const METRICS: { value: Metric; label: string; title: string; unitHint: string }[] = [ + { + value: 'warm', + label: 'Generation', + title: 'Generation time (warm process, median)', + unitHint: 'lower is better Β· median of the measured runs after a warm-up run', + }, + { + value: 'cold', + label: 'Cold run', + title: 'Cold run: import + one generation in a new process', + unitHint: 'lower is better Β· what a single CLI run costs', + }, + { + value: 'memory', + label: 'Memory', + title: 'Peak memory (RSS) of a cold run', + unitHint: 'lower is better', + }, +]; + +const SERIES: { id: LibraryId; className: string }[] = [ + { id: 'es', className: 'bg-series-es' }, + { id: 'original', className: 'bg-series-original' }, +]; + +export function BenchmarkLegend({ report }: { report: BenchmarkReport }) { + return ( +
    + {SERIES.map(({ id, className }) => ( +
  • + + {report.libraries[id].name} + {versionLabel(report, id)} +
  • + ))} +
+ ); +} + +function Bar({ + result, + library, + metric, + max, + report, + className, +}: { + result: BenchmarkResult; + library: LibraryId; + metric: Metric; + max: number; + report: BenchmarkReport; + className: string; +}) { + const measurement = result.libraries[library]; + const value = metricValue(measurement, metric); + // a visible minimum, so a tiny value still has a mark next to its label + const width = Math.max((value / max) * 100, 0.6); + const name = report.libraries[library].name; + const detail = + metric === 'warm' + ? `min ${formatMs(measurement.warm.minMs)} Β· ${measurement.warm.runs} runs` + : metric === 'cold' + ? `import ${formatMs(measurement.cold.importMs)} + generation ${formatMs(measurement.cold.generateMs)}` + : `${measurement.files} file${measurement.files === 1 ? '' : 's'} Β· ${Math.round(measurement.outputKb)} KB output`; + + return ( +
+
+
+
+
+ + {formatMetric(value, metric)} + +
+

+ + {name} +

+

{formatMetric(value, metric)}

+

{detail}

+
+
+
+ ); +} + +export function BenchmarkChart({ report }: { report: BenchmarkReport }) { + const [metric, setMetric] = useState('warm'); + const current = METRICS.find((item) => item.value === metric) ?? METRICS[0]; + const documents = Object.keys(report.documents).filter((id) => + report.results.some((result) => result.document === id) + ); + + return ( +
+
+
+

+ {current.title} +

+

{current.unitHint}

+
+ ({ value, label }))} + value={metric} + onChange={setMetric} + testIdPrefix="metric" + /> +
+ +
+ +
+ +
+ {documents.map((documentId) => { + const rows = report.results.filter((result) => result.document === documentId); + // one linear scale per document (both libraries and every option set share it) + const max = Math.max( + ...rows.flatMap((row) => SERIES.map(({ id }) => metricValue(row.libraries[id], metric))) + ); + const documentInfo = report.documents[documentId]; + return ( +
+
+

{documentInfo.label}

+

{documentInfo.detail}

+
+
+ {rows.map((row) => { + const factor = ratio(row, metric); + return ( +
+
+

+ {report.optionSets[row.options]?.label ?? row.options} +

+

+ {formatRatio(factor)} {metric === 'memory' ? 'less memory' : 'faster'} +

+
+
+ {SERIES.map(({ id, className }) => ( + + ))} +
+
+ ); + })} +
+
+ ); + })} +
+
+ ); +} diff --git a/docs/lib/benchmark/results.json b/docs/lib/benchmark/results.json new file mode 100644 index 0000000..0428469 --- /dev/null +++ b/docs/lib/benchmark/results.json @@ -0,0 +1,376 @@ +{ + "generatedAt": "2026-09-25T02:16:20.240Z", + "commit": "8b7c82e", + "environment": { + "node": "v22.22.2", + "platform": "Linux 6.18.44-fc-v37 (x64)", + "cpu": "Intel(R) Xeon(R) Processor @ 2.10GHz", + "cores": 4, + "memoryGb": 15.7 + }, + "settings": { + "warmRuns": 5, + "coldRuns": 3 + }, + "libraries": { + "es": { + "name": "swagger-typescript-api-es", + "version": "0.1.6" + }, + "original": { + "name": "swagger-typescript-api", + "version": "13.13.0" + } + }, + "documents": { + "petstore": { + "label": "Petstore", + "detail": "OpenAPI 3, 15 schemas, 11 operations (tests/fixtures/petstore.json)" + }, + "medium": { + "label": "Medium", + "detail": "synthetic OpenAPI 3, 300 schemas, 600 operations" + }, + "large": { + "label": "Large", + "detail": "synthetic OpenAPI 3, 1500 schemas, 3000 operations" + } + }, + "optionSets": { + "default": { + "label": "default", + "options": {} + }, + "modular": { + "label": "modular", + "options": { + "modular": true + } + }, + "extract": { + "label": "extract* + route types", + "options": { + "extractRequestParams": true, + "extractRequestBody": true, + "extractResponseBody": true, + "extractResponseError": true, + "extractEnums": true, + "generateRouteTypes": true + } + } + }, + "results": [ + { + "id": "petstore-default", + "document": "petstore", + "options": "default", + "libraries": { + "es": { + "cold": { + "medianMs": 281.2, + "minMs": 274.2, + "importMs": 237.4, + "generateMs": 43.8, + "maxRssMb": 100.4 + }, + "warm": { + "medianMs": 7.8, + "minMs": 6.8, + "runs": 5 + }, + "outputKb": 13.8, + "files": 1 + }, + "original": { + "cold": { + "medianMs": 1015.6, + "minMs": 1011.7, + "importMs": 660.7, + "generateMs": 356.7, + "maxRssMb": 284.7 + }, + "warm": { + "medianMs": 74.2, + "minMs": 69, + "runs": 5 + }, + "outputKb": 14, + "files": 1 + } + } + }, + { + "id": "petstore-modular", + "document": "petstore", + "options": "modular", + "libraries": { + "original": { + "cold": { + "medianMs": 1059, + "minMs": 1041.8, + "importMs": 649.1, + "generateMs": 409.9, + "maxRssMb": 308.6 + }, + "warm": { + "medianMs": 86.8, + "minMs": 84.5, + "runs": 5 + }, + "outputKb": 13.7, + "files": 5 + }, + "es": { + "cold": { + "medianMs": 278.8, + "minMs": 272.8, + "importMs": 229.7, + "generateMs": 50.4, + "maxRssMb": 101.5 + }, + "warm": { + "medianMs": 7.6, + "minMs": 6.7, + "runs": 5 + }, + "outputKb": 14.6, + "files": 6 + } + } + }, + { + "id": "medium-default", + "document": "medium", + "options": "default", + "libraries": { + "es": { + "cold": { + "medianMs": 444.6, + "minMs": 427.3, + "importMs": 225.6, + "generateMs": 210.6, + "maxRssMb": 144.8 + }, + "warm": { + "medianMs": 107.2, + "minMs": 104.3, + "runs": 5 + }, + "outputKb": 326.8, + "files": 1 + }, + "original": { + "cold": { + "medianMs": 3511.2, + "minMs": 3421.1, + "importMs": 688.1, + "generateMs": 2771.1, + "maxRssMb": 385.8 + }, + "warm": { + "medianMs": 2182.3, + "minMs": 2034.1, + "runs": 5 + }, + "outputKb": 315.6, + "files": 1 + } + } + }, + { + "id": "medium-modular", + "document": "medium", + "options": "modular", + "libraries": { + "original": { + "cold": { + "medianMs": 3908.3, + "minMs": 3828.4, + "importMs": 641.1, + "generateMs": 3267.2, + "maxRssMb": 363.4 + }, + "warm": { + "medianMs": 2780.6, + "minMs": 2630.5, + "runs": 5 + }, + "outputKb": 306.3, + "files": 52 + }, + "es": { + "cold": { + "medianMs": 437.9, + "minMs": 430.8, + "importMs": 230, + "generateMs": 207.9, + "maxRssMb": 148.5 + }, + "warm": { + "medianMs": 96.3, + "minMs": 87.4, + "runs": 5 + }, + "outputKb": 484.9, + "files": 52 + } + } + }, + { + "id": "medium-extract", + "document": "medium", + "options": "extract", + "libraries": { + "es": { + "cold": { + "medianMs": 562.2, + "minMs": 561.9, + "importMs": 229.6, + "generateMs": 333.2, + "maxRssMb": 159.7 + }, + "warm": { + "medianMs": 178.5, + "minMs": 164.1, + "runs": 5 + }, + "outputKb": 575.1, + "files": 1 + }, + "original": { + "cold": { + "medianMs": 5359.5, + "minMs": 5326.3, + "importMs": 668.9, + "generateMs": 4673.2, + "maxRssMb": 407.7 + }, + "warm": { + "medianMs": 3915.9, + "minMs": 3810.7, + "runs": 5 + }, + "outputKb": 600.7, + "files": 1 + } + } + }, + { + "id": "large-default", + "document": "large", + "options": "default", + "libraries": { + "original": { + "cold": { + "medianMs": 13072.8, + "minMs": 12792.5, + "importMs": 664.1, + "generateMs": 12408.6, + "maxRssMb": 587.6 + }, + "warm": { + "medianMs": 11302.2, + "minMs": 10994.4, + "runs": 5 + }, + "outputKb": 1557.9, + "files": 1 + }, + "es": { + "cold": { + "medianMs": 938.4, + "minMs": 909.3, + "importMs": 230.9, + "generateMs": 702.6, + "maxRssMb": 251.3 + }, + "warm": { + "medianMs": 494.1, + "minMs": 450, + "runs": 5 + }, + "outputKb": 1614.8, + "files": 1 + } + } + }, + { + "id": "large-modular", + "document": "large", + "options": "modular", + "libraries": { + "es": { + "cold": { + "medianMs": 880.4, + "minMs": 875.7, + "importMs": 231.8, + "generateMs": 649.5, + "maxRssMb": 259.8 + }, + "warm": { + "medianMs": 425.8, + "minMs": 366.9, + "runs": 5 + }, + "outputKb": 2413.7, + "files": 52 + }, + "original": { + "cold": { + "medianMs": 16482, + "minMs": 16384.1, + "importMs": 651.3, + "generateMs": 15830.8, + "maxRssMb": 618.3 + }, + "warm": { + "medianMs": 14854.4, + "minMs": 14597.9, + "runs": 5 + }, + "outputKb": 1476.4, + "files": 52 + } + } + }, + { + "id": "large-extract", + "document": "large", + "options": "extract", + "libraries": { + "original": { + "cold": { + "medianMs": 29373.5, + "minMs": 29156.1, + "importMs": 678.6, + "generateMs": 28695, + "maxRssMb": 743.5 + }, + "warm": { + "medianMs": 27309.2, + "minMs": 27216.1, + "runs": 5 + }, + "outputKb": 3005.3, + "files": 1 + }, + "es": { + "cold": { + "medianMs": 1904.7, + "minMs": 1526.5, + "importMs": 282.1, + "generateMs": 1622.7, + "maxRssMb": 313.3 + }, + "warm": { + "medianMs": 1032.9, + "minMs": 1004.2, + "runs": 5 + }, + "outputKb": 2866.2, + "files": 1 + } + } + } + ] +} diff --git a/docs/lib/benchmark/types.ts b/docs/lib/benchmark/types.ts new file mode 100644 index 0000000..996135f --- /dev/null +++ b/docs/lib/benchmark/types.ts @@ -0,0 +1,63 @@ +/** shape of `results.json`, written by `bench/compare/run.mjs` */ + +export type LibraryId = 'es' | 'original'; + +export interface LibraryMeasurement { + /** new process: import + one generation (like a CLI run) */ + cold: { + medianMs: number; + minMs: number; + importMs: number; + generateMs: number; + maxRssMb: number; + }; + /** one process, after a warm-up generation */ + warm: { medianMs: number; minMs: number; runs: number }; + outputKb: number; + files: number; +} + +export interface BenchmarkResult { + id: string; + document: string; + options: string; + libraries: Record; +} + +export interface BenchmarkReport { + generatedAt: string; + commit: string | null; + environment: { node: string; platform: string; cpu: string; cores: number; memoryGb: number }; + settings: { warmRuns: number; coldRuns: number }; + libraries: Record; + documents: Record; + optionSets: Record }>; + results: BenchmarkResult[]; +} + +export type Metric = 'warm' | 'cold' | 'memory'; + +export const metricValue = (measurement: LibraryMeasurement, metric: Metric) => + metric === 'warm' + ? measurement.warm.medianMs + : metric === 'cold' + ? measurement.cold.medianMs + : measurement.cold.maxRssMb; + +export const formatMs = (ms: number) => + ms >= 1000 ? `${(ms / 1000).toFixed(ms >= 10_000 ? 1 : 2)} s` : `${ms < 10 ? ms.toFixed(1) : Math.round(ms)} ms`; + +export const formatMetric = (value: number, metric: Metric) => + metric === 'memory' ? `${Math.round(value)} MB` : formatMs(value); + +/** how many times the original needs more (time / memory) than swagger-typescript-api-es */ +export const ratio = (result: BenchmarkResult, metric: Metric) => + metricValue(result.libraries.original, metric) / metricValue(result.libraries.es, metric); + +export const formatRatio = (value: number) => `${value >= 10 ? Math.round(value) : value.toFixed(1)}Γ—`; + +/** version label: the measured code of swagger-typescript-api-es is the repository at `commit` */ +export const versionLabel = (report: BenchmarkReport, library: LibraryId) => + library === 'es' && report.commit + ? `v${report.libraries.es.version}+${report.commit}` + : `v${report.libraries[library].version}`; diff --git a/docs/tests/e2e/benchmark.spec.ts b/docs/tests/e2e/benchmark.spec.ts new file mode 100644 index 0000000..54016c1 --- /dev/null +++ b/docs/tests/e2e/benchmark.spec.ts @@ -0,0 +1,74 @@ +import fs from 'node:fs'; + +import { expect, test } from '@playwright/test'; + +const results = JSON.parse( + fs.readFileSync(new URL('../../lib/benchmark/results.json', import.meta.url), 'utf8') +); + +test('benchmark page shows the headline numbers, the chart and every result', async ({ page }) => { + await page.goto('/benchmark'); + await expect(page).toHaveTitle(/Benchmark/); + await expect(page.getByRole('heading', { level: 1 })).toContainText( + 'swagger-typescript-api-es vs swagger-typescript-api' + ); + + // headline tiles + const headline = page.getByRole('region', { name: 'Headline results' }); + await expect(headline).toContainText('faster'); + await expect(headline).toContainText('less'); + + // legend names both libraries with their versions + const legend = page.getByRole('list', { name: 'Legend' }); + await expect(legend).toContainText(`v${results.libraries.es.version}`); + await expect(legend).toContainText(`v${results.libraries.original.version}`); + + // one figure per document, two bars per scenario + await expect(page.getByRole('figure')).toHaveCount(Object.keys(results.documents).length); + await expect(page.getByRole('img', { name: /^swagger-typescript-api-es: / })).toHaveCount( + results.results.length + ); + + // every scenario is in the table + const rows = page.getByRole('table').locator('tbody tr'); + await expect(rows).toHaveCount(results.results.length); + + // environment + reproduce command + await expect(page.getByText(results.environment.node).first()).toBeVisible(); + await expect(page.getByText('npm run bench:compare').first()).toBeVisible(); +}); + +test('the metric switch changes the chart', async ({ page }) => { + await page.goto('/benchmark'); + const chartHeading = page.locator('#chart-heading'); + await expect(chartHeading).toContainText('Generation time'); + await page.getByRole('radio', { name: 'Cold run' }).click(); + await expect(chartHeading).toContainText('Cold run'); + await page.getByRole('radio', { name: 'Memory' }).click(); + await expect(chartHeading).toContainText('Peak memory'); + await expect(page.getByText('less memory').first()).toBeVisible(); +}); + +test('bars have a tooltip on keyboard focus', async ({ page }) => { + await page.goto('/benchmark'); + const bar = page.getByRole('img', { name: /^swagger-typescript-api-es: / }).first(); + await bar.focus(); + await expect(page.getByRole('tooltip').filter({ visible: true }).first()).toContainText( + 'swagger-typescript-api-es' + ); +}); + +test('benchmark is linked from the header', async ({ page }) => { + await page.goto('/'); + await page.getByRole('navigation', { name: 'Main' }).getByRole('link', { name: 'Benchmark' }).click(); + await expect(page).toHaveURL(/\/benchmark$/); +}); + +test.describe('mobile', () => { + test.use({ viewport: { width: 375, height: 740 }, hasTouch: true, isMobile: true }); + test('no horizontal scroll on /benchmark', async ({ page }) => { + await page.goto('/benchmark'); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + expect(overflow).toBeLessThanOrEqual(0); + }); +}); diff --git a/package.json b/package.json index 013b84b..c9dece3 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "test:coverage": "vitest run --coverage", "test:immutability": "STA_FREEZE=1 vitest run", "bench": "npm run build && node bench/index.mjs", + "bench:compare": "npm run build && npm --prefix bench/compare ci --no-audit --no-fund && node bench/compare/run.mjs", "changelog": "npx changeloggithub@latest --all true && git add CHANGELOG.md && git commit -m 'chore: update CHANGELOG.md'", "prepublishOnly": "npm run build", "release": "bumpp -r && npm publish" From f0bf017aa6372c466f6c350ec602ccde1c5cb8ca Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 02:32:16 +0000 Subject: [PATCH 9/9] feat(docs): usage guide for the generated client and agent skill page - /usage: create the client (fetch / axios / own axios instance), call endpoints, headers and auth (injectHeaders, securityWorker + setSecurityData, secure routes), shared HttpClient, modular output, errors, cancellation, files, customFetch, React Query / SWR, Node.js, typing tips; fetch / axios tabs; every snippet type-checked against generated clients - /skills: what the agent skill is and covers, install (npx skills add or manual), example prompts, file list and SKILL.md preview read at build time - navigation: Docs, Usage, Playground, Benchmark, Skills (header, footer, links from the docs and landing pages); e2e tests for both pages Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5YqLdEWZQ4vnZ1Hdq8L3 --- docs/app/docs/page.tsx | 8 +- docs/app/page.tsx | 8 + docs/app/skills/_lib/skill.ts | 83 ++++ docs/app/skills/page.tsx | 360 +++++++++++++++++ docs/app/usage/_lib/snippets.ts | 634 ++++++++++++++++++++++++++++++ docs/app/usage/_lib/ui.tsx | 56 +++ docs/app/usage/page.tsx | 444 +++++++++++++++++++++ docs/components/client-tabs.tsx | 67 ++++ docs/components/docs/docs-nav.tsx | 27 +- docs/components/site-footer.tsx | 9 + docs/components/site-header.tsx | 25 +- docs/tests/e2e/skills.spec.ts | 63 +++ docs/tests/e2e/usage.spec.ts | 78 ++++ 13 files changed, 1853 insertions(+), 9 deletions(-) create mode 100644 docs/app/skills/_lib/skill.ts create mode 100644 docs/app/skills/page.tsx create mode 100644 docs/app/usage/_lib/snippets.ts create mode 100644 docs/app/usage/_lib/ui.tsx create mode 100644 docs/app/usage/page.tsx create mode 100644 docs/components/client-tabs.tsx create mode 100644 docs/tests/e2e/skills.spec.ts create mode 100644 docs/tests/e2e/usage.spec.ts diff --git a/docs/app/docs/page.tsx b/docs/app/docs/page.tsx index d582c7e..43b8036 100644 --- a/docs/app/docs/page.tsx +++ b/docs/app/docs/page.tsx @@ -1,4 +1,4 @@ -import { ArrowRight, FlaskConical } from 'lucide-react'; +import { ArrowRight, Code2, FlaskConical } from 'lucide-react'; import type { Metadata } from 'next'; import Link from 'next/link'; import { MarkdownAsync } from 'react-markdown'; @@ -53,6 +53,12 @@ export default async function DocsPage() { > Try it in the playground + + Using the generated client +
+

+ + Next: using the generated client + + + Install the AI agent skill + +

{/* Features */} diff --git a/docs/app/skills/_lib/skill.ts b/docs/app/skills/_lib/skill.ts new file mode 100644 index 0000000..2670212 --- /dev/null +++ b/docs/app/skills/_lib/skill.ts @@ -0,0 +1,83 @@ +import 'server-only'; + +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import path from 'node:path'; + +import { findRepoFile } from '@/components/repo-files'; + +export const SKILL_NAME = 'swagger-typescript-api-es'; +/** folder of the skill, relative to the repository root */ +export const SKILL_DIR = `skills/${SKILL_NAME}`; + +export interface SkillFile { + /** path relative to the skill folder, with `/` separators */ + path: string; + lines: number; + bytes: number; + /** first markdown heading, if any */ + heading: string | null; +} + +export interface SkillInfo { + name: string; + description: string; + version: string | null; + files: SkillFile[]; + /** SKILL.md without its front matter */ + body: string; +} + +function parseFrontMatter(text: string): { data: Record; body: string } { + const match = /^---\n([\s\S]*?)\n---\n?/.exec(text); + if (!match) return { data: {}, body: text }; + const data: Record = {}; + for (const line of match[1].split('\n')) { + const field = /^\s*([\w-]+):\s*(.*)$/.exec(line); + if (field && field[2]) data[field[1]] = field[2].replace(/^['"]|['"]$/g, '').trim(); + } + return { data, body: text.slice(match[0].length) }; +} + +function walk(dir: string, base = ''): string[] { + const entries = readdirSync(/*turbopackIgnore: true*/ dir, { withFileTypes: true }).sort((a, b) => { + // files of a folder first (SKILL.md on top), then sub folders + if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? 1 : -1; + return a.name.localeCompare(b.name); + }); + const files: string[] = []; + for (const entry of entries) { + if (entry.name.startsWith('.')) continue; + const relative = base ? `${base}/${entry.name}` : entry.name; + if (entry.isDirectory()) files.push(...walk(path.join(/*turbopackIgnore: true*/ dir, entry.name), relative)); + else if (entry.isFile()) files.push(relative); + } + return files; +} + +/** Reads the skill folder at build time, so the page always lists its current files. */ +export function loadSkill(): SkillInfo | null { + const skillFile = findRepoFile(`${SKILL_DIR}/SKILL.md`, `name: ${SKILL_NAME}`); + if (!skillFile) return null; + const dir = path.dirname(skillFile); + const { data, body } = parseFrontMatter(readFileSync(/*turbopackIgnore: true*/ skillFile, 'utf8').replace(/\r\n/g, '\n')); + + const files = walk(dir).map((relative): SkillFile => { + const absolute = path.join(/*turbopackIgnore: true*/ dir, relative); + const text = readFileSync(/*turbopackIgnore: true*/ absolute, 'utf8'); + const heading = /^#{1,3} (.+)$/m.exec(relative === 'SKILL.md' ? body : text)?.[1]?.trim() ?? null; + return { + path: relative, + lines: text.split('\n').length - (text.endsWith('\n') ? 1 : 0), + bytes: statSync(/*turbopackIgnore: true*/ absolute).size, + heading, + }; + }); + + return { + name: data.name ?? SKILL_NAME, + description: data.description ?? '', + version: data.version ?? null, + files, + body, + }; +} diff --git a/docs/app/skills/page.tsx b/docs/app/skills/page.tsx new file mode 100644 index 0000000..8623361 --- /dev/null +++ b/docs/app/skills/page.tsx @@ -0,0 +1,360 @@ +import { + AlertTriangle, + ArrowRight, + Braces, + ChevronRight, + FileCode2, + FileText, + Folder, + Plug, + Puzzle, + Rocket, + SlidersHorizontal, + Terminal, + type LucideIcon, +} from 'lucide-react'; +import type { Metadata } from 'next'; +import Link from 'next/link'; +import type { Components } from 'react-markdown'; +import { MarkdownAsync } from 'react-markdown'; +import remarkGfm from 'remark-gfm'; + +import { markdownComponents } from '@/app/docs/_lib/markdown-components'; +import { rehypeShiki } from '@/app/docs/_lib/rehype'; +import { CodeBlock } from '@/components/code-block'; +import { CopyButton } from '@/components/copy-button'; +import { GithubIcon } from '@/components/icons'; +import { site } from '@/components/site-config'; +import { SiteFooter } from '@/components/site-footer'; + +import { loadSkill, SKILL_DIR } from './_lib/skill'; + +export const dynamic = 'force-static'; + +export const metadata: Metadata = { + title: 'AI agent skill', + description: `An agent skill for Claude Code and other coding agents: teach your agent to set up ${site.name}, write its config, pick options and use the generated client.`, + openGraph: { title: `AI agent skill Β· ${site.name}` }, +}; + +/** exactly the command of the README "AI agent skill" section */ +const INSTALL_COMMAND = 'npx skills add hunghg255/swagger-typescript-api-es'; + +const skillUrl = `${site.repo}/tree/main/${SKILL_DIR}`; +const fileUrl = (file: string) => `${site.repo}/blob/main/${SKILL_DIR}/${file}`; + +const TOPICS: { icon: LucideIcon; title: string; body: string }[] = [ + { icon: Rocket, title: 'Setup', body: 'Installing the package, Node.js and ESM requirements, the first generation.' }, + { icon: Terminal, title: 'CLI and config file', body: 'Flags, swagger-typescript-api.config.ts, arrays of configs and precedence.' }, + { icon: SlidersHorizontal, title: 'Options', body: 'Every generator option: input, output, client, types, extraction, naming.' }, + { icon: Puzzle, title: 'Hooks', body: 'Renaming types and routes, changing parsed schemas and route data.' }, + { icon: FileCode2, title: 'Templates', body: 'Copying the built-in Eta templates and overriding parts of the output.' }, + { icon: Plug, title: 'The generated client', body: 'Creating the client, auth, errors, modular output and shared HttpClients.' }, + { icon: AlertTriangle, title: 'Gotchas', body: 'The mistakes agents (and people) make, with the right fix for each.' }, +]; + +const PROMPTS = [ + 'Set up swagger-typescript-api-es in this project: generate an axios client from http://localhost:3000/api-json into src/api and add a gen-api script.', + 'Our spec is ./openapi.yaml. Generate a modular fetch client where every module shares one HttpClient.', + 'Send a bearer token with every request of the generated client and refresh it when it expires.', + 'Rename every generated type so that it ends with Dto, and keep the enums as union types.', + 'Methods return the whole response; make them resolve with the data directly and update the callers.', + 'Wrap the generated pets endpoints in React Query hooks, with request cancellation.', +]; + +const STEPS = [ + { + title: 'Discovery', + body: 'At startup the agent only reads the name and description of each installed skill.', + }, + { + title: 'Activation', + body: 'When your request matches the description, the agent reads SKILL.md: the workflow and rules.', + }, + { + title: 'Details on demand', + body: 'Reference files (the full options list, patterns, …) are opened only when the task needs them.', + }, +]; + +function Code({ children }: { children: React.ReactNode }) { + return {children}; +} + +function SectionHeading({ id, children }: { id: string; children: React.ReactNode }) { + return ( +

+ {children} +

+ ); +} + +function formatSize(bytes: number) { + return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`; +} + +/** SKILL.md preview: headings are demoted below the page's h2 and relative links point to GitHub */ +const previewComponents: Components = { + ...markdownComponents, + h1: ({ children }) =>

{children}

, + h2: ({ children }) =>

{children}

, + h3: ({ children }) =>

{children}

, + h4: ({ children }) =>

{children}

, + a: ({ href, children }) => { + const external = !!href && /^[a-z]+:/i.test(href); + const resolved = !href || external || href.startsWith('#') ? href : fileUrl(href.replace(/^\.\//, '')); + return ( +
+ {children} + + ); + }, +}; + +export default async function SkillsPage() { + const skill = loadSkill(); + const preview = skill + ? await MarkdownAsync({ + children: skill.body, + remarkPlugins: [remarkGfm], + rehypePlugins: [rehypeShiki], + components: previewComponents, + }) + : null; + + return ( + <> +
+
+

AI agent skill

+

+ Teach your coding agent {site.name} +

+

+ The repository ships an agent skill: a folder of instructions that Claude Code and other coding agents load + when you ask them to generate or use an API client. With it, the agent knows the CLI flags, the config + file, every option and the usual pitfalls, instead of guessing from the original swagger-typescript-api. +

+ +
+ + $ + + + {INSTALL_COMMAND} + + +
+ + +
+ +
+ What is an agent skill? +
+
+

+ A skill is a folder with a SKILL.md file: a short front matter (a name and a description + of when to use it) followed by instructions in Markdown, plus optional reference files. Coding agents + such as Claude Code load skills from .claude/skills/ in your project or{' '} + ~/.claude/skills/ in your home folder. +

+

+ Skills are loaded progressively, so an installed skill costs almost nothing until it is needed: +

+
    + {STEPS.map((step, index) => ( +
  1. + + {index + 1} + +

    {step.title}

    +

    {step.body}

    +
  2. + ))} +
+
+ {skill?.description ? ( + + ) : null} +
+
+ +
+ What it covers +
    + {TOPICS.map(({ icon: Icon, title, body }) => ( +
  • + + + +

    {title}

    +

    {body}

    +
  • + ))} +
  • +

    The same ground as the human docs, written for an agent.

    + + Read the docs + +
  • +
+
+ +
+ Install +

With the skills CLI

+

+ Installs the skill of this repository with npx, nothing to add to your dependencies: +

+ + +

Manually

+

+ Copy the {SKILL_DIR} folder into a skills folder. In the project, the skill is shared with + everyone who clones it; in your home folder, it is available in all your projects. +

+ +

+ Start a new agent session afterwards: skills are discovered when the session starts. Update the skill the + same way when a new version of the library is released. +

+
+ +
+ Example prompts +

+ No special syntax: ask for what you want and the agent loads the skill when the request is about + generating or using the client. +

+
    + {PROMPTS.map((prompt) => ( +
  • + +

    {prompt}

    + +
  • + ))} +
+
+ +
+ What's inside + {skill ? ( + <> +

+ The files of {SKILL_DIR}, read when this site was built. +

+
+
+ + {SKILL_DIR}/ +
+ +
+ + ) : ( +

+ The skill folder was not available when this site was built.{' '} + + See it on GitHub + + . +

+ )} + + {preview ? ( +
+ + + + Preview SKILL.md + +
{preview}
+
+ ) : null} +
+ +
+ + Using the generated client + + + Read the docs + +
+
+ + + ); +} diff --git a/docs/app/usage/_lib/snippets.ts b/docs/app/usage/_lib/snippets.ts new file mode 100644 index 0000000..03d1870 --- /dev/null +++ b/docs/app/usage/_lib/snippets.ts @@ -0,0 +1,634 @@ +/** + * Code examples of the /usage page. + * + * Every TypeScript snippet is type-checked (strict mode) against a client generated from + * `tests/fixtures/petstore.json` with the options of its `client` variant: + * + * - `fetch` default options + * - `axios` `httpClientType: 'axios'` + * - `single` `singleHttpClient: true` + * - `modular` `modular: true` + * - `modularSingle` `modular: true, singleHttpClient: true` + * - `unwrap` `unwrapResponseData: true` + * - `noThrow` `disableThrowOnError: true` + * - `routeTypes` `generateRouteTypes: true` + * - `config` checked against the library's own types + * + * The generated client is at `./api/` next to the snippet; `./api-client` exports `api` + * (a `new Api()`). `prelude` lines are prepended when checking and are not shown. + * Keep method names in sync with the fixture (`api.pets.listPets`, `api.pets.getPet`, ...). + */ +export type SnippetClient = + | 'fetch' + | 'axios' + | 'single' + | 'modular' + | 'modularSingle' + | 'unwrap' + | 'noThrow' + | 'routeTypes' + | 'config'; + +export interface Snippet { + code: string; + lang: 'ts' | 'tsx' | 'bash'; + /** file name shown above the code */ + title?: string; + /** generated client the snippet is checked against (`null`: not type-checked, e.g. shell) */ + client: SnippetClient | null; + /** hidden code prepended when type-checking */ + prelude?: string; +} + +const API = `import { api } from './api-client';\n`; + +export const SNIPPETS = { + generateCli: { + lang: 'bash', + title: 'Terminal', + client: null, + code: `npm i -D swagger-typescript-api-es + +# fetch client (default): writes src/api/Api.ts +npx swagger-typescript-api-es -u ./openapi.json -o ./src/api + +# axios client (install axios in your app) +npm i axios +npx swagger-typescript-api-es -u ./openapi.json -o ./src/api --httpClientType axios`, + }, + + generateConfig: { + lang: 'ts', + title: 'swagger-typescript-api.config.ts', + client: 'config', + code: `import { defaultConfig } from 'swagger-typescript-api-es'; + +export default defaultConfig({ + input: './openapi.json', // or url: 'https://api.example.com/openapi.json' + output: './src/api', + name: 'Api.ts', + httpClientType: 'fetch', // or 'axios' +});`, + }, + + fetchCreate: { + lang: 'ts', + title: 'src/api-client.ts', + client: 'fetch', + code: `import { Api } from './api/Api'; + +export const api = new Api({ + // default: the first \`servers[].url\` of the spec + baseUrl: 'https://petstore.example.com/v1', + // RequestInit defaults for every request + baseApiParams: { + credentials: 'include', // send cookies to another origin + headers: { 'X-Client': 'web' }, + }, +});`, + }, + + axiosCreate: { + lang: 'ts', + title: 'src/api-client.ts', + client: 'axios', + code: `import { Api } from './api/Api'; + +// any AxiosRequestConfig option is accepted and passed to axios.create() +export const api = new Api({ + baseURL: 'https://petstore.example.com/v1', + headers: { 'X-Client': 'web' }, + timeout: 10_000, + withCredentials: true, +});`, + }, + + axiosInstance: { + lang: 'ts', + title: 'src/api-client.ts', + client: 'axios', + code: `import axios from 'axios'; + +import { Api } from './api/Api'; + +const instance = axios.create({ + baseURL: 'https://petstore.example.com/v1', + timeout: 10_000, +}); + +instance.interceptors.response.use(undefined, (error) => { + if (axios.isAxiosError(error) && error.response?.status === 401) { + window.location.assign('/login'); + } + return Promise.reject(error); +}); + +// with \`instance\`, the other axios options of the config are ignored +export const api = new Api({ instance }); + +// the instance is always available as \`api.instance\` +api.instance.defaults.headers.common['X-Client'] = 'web';`, + }, + + callMethods: { + lang: 'ts', + client: 'fetch', + prelude: API, + code: `import { PetStatus } from './api/Api'; + +// query parameters are one object (all optional here) +const { data: pets } = await api.pets.listPets({ status: PetStatus.Available, limit: 20 }); + +// path parameters are positional arguments +const { data: pet } = await api.pets.getPet(42); + +// the request body is typed from the schema (NewPet) +const { data: created } = await api.pets.createPet({ name: 'Rex', tags: ['good-boy'] }); + +// path parameters first, then the body +await api.pets.updatePet(created.id, { name: 'Rex II' }); +await api.pets.deletePet(created.id);`, + }, + + requestParams: { + lang: 'ts', + client: 'fetch', + prelude: API, + code: `const controller = new AbortController(); + +// the last argument of every method: RequestParams +await api.pets.listPets( + { limit: 10 }, + { + headers: { 'X-Request-Id': crypto.randomUUID() }, // merged over baseApiParams.headers + signal: controller.signal, // or any other RequestInit option + cache: 'no-store', + secure: false, // skip the securityWorker for this call + format: 'json', // how to read the body: 'json' | 'text' | 'blob' | ... + baseUrl: 'https://staging.petstore.example.com/v1', + } +);`, + }, + + requestParamsAxios: { + lang: 'ts', + client: 'axios', + prelude: API, + code: `// axios: RequestParams is an AxiosRequestConfig (+ secure, type, format) +await api.pets.listPets( + { limit: 10 }, + { headers: { 'X-Request-Id': crypto.randomUUID() }, timeout: 5_000, secure: false } +);`, + }, + + injectHeaders: { + lang: 'ts', + client: 'fetch', + prelude: `declare function getCsrfToken(): Promise;\n`, + code: `import { Api } from './api/Api'; + +export const api = new Api({ + // runs before every request with the merged headers; may be async + injectHeaders: async (headers: Record) => ({ + ...headers, + 'Accept-Language': navigator.language, + 'X-CSRF-Token': await getCsrfToken(), // your own helper + }), +});`, + }, + + securityWorker: { + lang: 'ts', + title: 'src/api-client.ts', + client: 'fetch', + code: `import { Api } from './api/Api'; + +// the type argument is the type of your "security data", here an access token +export const api = new Api({ + // called for every \`secure\` request with the value given to setSecurityData() + securityWorker: (token) => + token ? { headers: { Authorization: \`Bearer \${token}\` } } : {}, +}); + +export async function login(username: string, password: string) { + const response = await fetch('/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }); + const { accessToken } = (await response.json()) as { accessToken: string }; + api.setSecurityData(accessToken); // every secure request now sends the token +} + +export function logout() { + api.setSecurityData(null); +}`, + }, + + securityWorkerAsync: { + lang: 'ts', + client: 'fetch', + prelude: `declare const auth: { getFreshToken(): Promise };\n`, + code: `import { Api } from './api/Api'; + +// the worker may be async: refresh an expired token right before the request +export const api = new Api({ + securityWorker: async () => ({ + headers: { Authorization: \`Bearer \${await auth.getFreshToken()}\` }, + }), + // call the worker for every request, not only for routes with \`security\` + baseApiParams: { secure: true }, +});`, + }, + + securityWorkerAxios: { + lang: 'ts', + client: 'axios', + code: `import { Api } from './api/Api'; + +export const api = new Api({ + baseURL: 'https://petstore.example.com/v1', + // returns an AxiosRequestConfig + securityWorker: (token) => + token ? { headers: { Authorization: \`Bearer \${token}\` } } : {}, + secure: true, // optional: call the worker for every request +}); + +api.setSecurityData('my-jwt');`, + }, + + singleHttpClient: { + lang: 'ts', + title: 'src/api-client.ts', + client: 'single', + code: `import { Api, HttpClient } from './api/Api'; + +// configure the transport once... +export const http = new HttpClient({ + baseUrl: 'https://petstore.example.com/v1', + securityWorker: (token) => + token ? { headers: { Authorization: \`Bearer \${token}\` } } : {}, +}); + +// ...and hand it to the Api (it is available as api.http) +export const api = new Api(http); + +http.setSecurityData('my-jwt'); +const { data: pets } = await api.pets.listPets({ limit: 10 });`, + }, + + modularSeparate: { + lang: 'ts', + title: 'src/api-client.ts', + client: 'modular', + code: `import type { ApiConfig } from './api/http-client'; +import { Pets } from './api/Pets'; +import { Store } from './api/Store'; + +const config: ApiConfig = { + baseUrl: 'https://petstore.example.com/v1', + securityWorker: (token) => + token ? { headers: { Authorization: \`Bearer \${token}\` } } : {}, +}; + +// every module class extends HttpClient: each one has its own state +export const pets = new Pets(config); +export const store = new Store(config); + +export function setToken(token: string | null) { + pets.setSecurityData(token); + store.setSecurityData(token); +}`, + }, + + modularShared: { + lang: 'ts', + title: 'src/api-client.ts', + client: 'modularSingle', + code: `import type { Pet } from './api/data-contracts'; +import { HttpClient } from './api/http-client'; +import { Pets } from './api/Pets'; +import { Store } from './api/Store'; +import { Users } from './api/Users'; + +export const http = new HttpClient({ + baseUrl: 'https://petstore.example.com/v1', + securityWorker: (token) => + token ? { headers: { Authorization: \`Bearer \${token}\` } } : {}, +}); + +// one transport, one token, many modules +export const api = { + pets: new Pets(http), + store: new Store(http), + users: new Users(http), +}; + +http.setSecurityData('my-jwt'); +const { data } = await api.pets.listPets({ limit: 10 }); +const first: Pet | undefined = data[0];`, + }, + + fetchErrors: { + lang: 'ts', + client: 'fetch', + prelude: API, + code: `// the spec's \`Error\` schema would shadow the global Error: rename it on import +import type { Error as ApiError, HttpResponse } from './api/Api'; + +try { + const response = await api.pets.getPet(42); // HttpResponse + console.log(response.status, response.data.name); +} catch (e) { + if (e instanceof Response) { + // a non-2xx response rejects with the HttpResponse; \`error\` is the parsed body + const { status, error } = e as HttpResponse; + console.error(status, error.message); + } else { + throw e; // network error, aborted request, ... + } +}`, + }, + + noThrow: { + lang: 'ts', + client: 'noThrow', + prelude: API, + code: `// generated with disableThrowOnError: true +const response = await api.pets.getPet(42); + +if (response.ok) { + console.log(response.data.name); // Pet +} else { + console.error(response.status, response.error.message); // the spec's error type +}`, + }, + + axiosErrors: { + lang: 'ts', + client: 'axios', + prelude: API, + code: `import axios from 'axios'; + +import type { Error as ApiError } from './api/Api'; + +try { + const { data: pet, status } = await api.pets.getPet(42); // AxiosResponse + console.log(status, pet.name); +} catch (e) { + if (axios.isAxiosError(e)) { + // non-2xx responses reject with an AxiosError (axios' validateStatus) + console.error(e.response?.status, e.response?.data.message); + } else { + throw e; + } +}`, + }, + + unwrap: { + lang: 'ts', + client: 'unwrap', + prelude: API, + code: `// generated with unwrapResponseData: true +const pets = await api.pets.listPets({ limit: 10 }); // Pet[] +const pet = await api.pets.getPet(42); // Pet, not HttpResponse + +console.log(pets.length, pet.name);`, + }, + + cancelFetch: { + lang: 'ts', + client: 'fetch', + prelude: API, + code: `// tag a request with a cancelToken (string | number | symbol)... +const search = api.pets.listPets({ tags: ['cat'] }, { cancelToken: 'pet-search' }); + +// ...and abort it with the same token (e.g. when the user types again) +api.abortRequest('pet-search'); +await search.catch((e: unknown) => console.log('aborted', e)); + +// or pass your own AbortSignal +await api.pets.listPets({ limit: 10 }, { signal: AbortSignal.timeout(5_000) });`, + }, + + cancelAxios: { + lang: 'ts', + client: 'axios', + prelude: API, + code: `import axios from 'axios'; + +const controller = new AbortController(); +const search = api.pets.listPets({ tags: ['cat'] }, { signal: controller.signal }); + +controller.abort(); + +try { + await search; +} catch (e) { + if (axios.isCancel(e)) console.log('request canceled'); +}`, + }, + + upload: { + lang: 'ts', + client: 'fetch', + prelude: API, + code: `// POST /pets/{petId}/photo is multipart/form-data (type: ContentType.FormData): +// pass a plain object, the client builds the FormData +export async function onPhotoSelected(petId: string, event: Event) { + const file = (event.target as HTMLInputElement).files?.[0]; + if (!file) return; + + const { data: photo } = await api.pets.uploadPetPhoto(petId, { file, caption: 'Rex' }); + console.log(photo.url); +} + +// application/x-www-form-urlencoded bodies are serialized for you as well +await api.store.placeOrder({ petId: 'pet-1', quantity: 2 });`, + }, + + download: { + lang: 'ts', + client: 'fetch', + prelude: API, + code: `// routes whose response is \`format: binary\` are generated with format: 'blob'. +// For anything else, override the format per call or use api.request(): +const { data: blob } = await api.request({ + path: '/pets/export', + method: 'GET', + secure: true, + format: 'blob', +}); + +const link = document.createElement('a'); +link.href = URL.createObjectURL(blob); +link.download = 'pets.csv'; +link.click(); +URL.revokeObjectURL(link.href);`, + }, + + customFetchRetry: { + lang: 'ts', + client: 'fetch', + code: `import { Api } from './api/Api'; + +// retry GET requests on network errors and 5xx responses +const fetchWithRetry: typeof fetch = async (input, init) => { + const retries = (init?.method ?? 'GET') === 'GET' ? 2 : 0; + for (let attempt = 0; ; attempt++) { + try { + const response = await fetch(input, init); + if (response.status < 500 || attempt >= retries) return response; + } catch (e) { + if (attempt >= retries || init?.signal?.aborted) throw e; + } + await new Promise((resolve) => setTimeout(resolve, 300 * 2 ** attempt)); + } +}; + +export const api = new Api({ customFetch: fetchWithRetry });`, + }, + + customFetchTest: { + lang: 'ts', + title: 'pets.test.ts', + client: 'fetch', + code: `import { Api, type Pet } from './api/Api'; + +const rex: Pet = { id: '1', name: 'Rex', createdAt: '2026-01-01T00:00:00Z' }; + +// no network, no mocking library: answer with a Response +const api = new Api({ + customFetch: async (input) => { + if (String(input).endsWith('/pets/1')) return Response.json(rex); + return Response.json({ code: 404, message: 'Not found' }, { status: 404 }); + }, +}); + +const { data } = await api.pets.getPet(1); +console.assert(data.name === 'Rex');`, + }, + + ssr: { + lang: 'ts', + client: 'fetch', + code: `import { Api } from './api/Api'; + +// on the server, create a client per request and forward the caller's cookies +export function createServerApi(cookie: string) { + return new Api({ + baseUrl: process.env.PETSTORE_URL ?? 'https://petstore.example.com/v1', + baseApiParams: { headers: { cookie } }, + }); +}`, + }, + + reactQuery: { + lang: 'tsx', + title: 'src/pets/queries.ts', + client: 'fetch', + code: `import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; + +import { api } from '../api-client'; +import type { NewPet } from '../api/Api'; + +export function usePets(limit = 20) { + return useQuery({ + queryKey: ['pets', { limit }], + // pass React Query's signal so unmounted queries are canceled + queryFn: ({ signal }) => api.pets.listPets({ limit }, { signal }).then((r) => r.data), + }); +} + +export function useCreatePet() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (pet: NewPet) => api.pets.createPet(pet).then((r) => r.data), + onSuccess: () => queryClient.invalidateQueries({ queryKey: ['pets'] }), + }); +}`, + }, + + swr: { + lang: 'tsx', + title: 'src/pets/pet-name.tsx', + client: 'fetch', + code: `import useSWR from 'swr'; + +import { api } from '../api-client'; + +export function PetName({ petId }: { petId: number }) { + const { data: pet, error, isLoading } = useSWR(['pet', petId] as const, ([, id]) => + api.pets.getPet(id).then((r) => r.data) + ); + + if (isLoading) return

Loading…

; + if (error) return

Could not load the pet.

; + return

{pet?.name}

; +}`, + }, + + node: { + lang: 'ts', + title: 'scripts/sync-inventory.ts', + client: 'fetch', + code: `import { openAsBlob } from 'node:fs'; + +import { Api } from '../src/api/Api'; + +// Node.js 18+ has fetch, FormData and File built in: the fetch client works as is +const api = new Api({ + baseUrl: process.env.PETSTORE_URL ?? 'https://petstore.example.com/v1', + securityWorker: (token) => + token ? { headers: { Authorization: \`Bearer \${token}\` } } : {}, +}); +api.setSecurityData(process.env.PETSTORE_TOKEN ?? null); + +const { data: inventory } = await api.store.getInventory(); +console.table(inventory); + +// upload a file from disk +const blob = await openAsBlob('./rex.jpg', { type: 'image/jpeg' }); +const file = new File([blob], 'rex.jpg', { type: blob.type }); +await api.pets.uploadPetPhoto('pet-1', { file });`, + }, + + typesContracts: { + lang: 'ts', + client: 'fetch', + code: `// every schema of components/schemas is exported +// (from data-contracts.ts in modular mode) +import { PetStatus, type Api, type NewPet, type Pet } from './api/Api'; + +export const draft: NewPet = { name: 'Rex', status: PetStatus.Available }; + +export function isAvailable(pet: Pet) { + return pet.status === PetStatus.Available; +} + +// types of inline parameters and responses, derived from the methods +type PetsApi = Api['pets']; +export type ListPetsQuery = NonNullable[0]>; +export type ListPetsResult = Awaited>['data']; // Pet[]`, + }, + + typesRoutes: { + lang: 'ts', + client: 'routeTypes', + code: `// generated with generateRouteTypes: true +import type { Pets } from './api/Api'; + +type Query = Pets.ListPets.RequestQuery; // { status?, tags?, limit?, sort? } +type Body = Pets.CreatePet.RequestBody; // NewPet +type Result = Pets.GetPet.ResponseBody; // Pet + +export function toSearchParams(query: Query) { + const entries = Object.entries(query).map(([key, value]) => [key, String(value)]); + return new URLSearchParams(entries); +} + +export type { Body, Result };`, + }, +} satisfies Record; + +export type SnippetId = keyof typeof SNIPPETS; diff --git a/docs/app/usage/_lib/ui.tsx b/docs/app/usage/_lib/ui.tsx new file mode 100644 index 0000000..db40219 --- /dev/null +++ b/docs/app/usage/_lib/ui.tsx @@ -0,0 +1,56 @@ +import { ClientTabs } from '@/components/client-tabs'; +import { CodeBlock } from '@/components/code-block'; +import type { NavHeading } from '@/components/docs/docs-nav'; + +import { SNIPPETS, type SnippetId } from './snippets'; + +const LANG_LABEL = { ts: 'TypeScript', tsx: 'TSX', bash: 'Terminal' } as const; + +/** a verified code example of `snippets.ts` */ +export function Snippet({ id }: { id: SnippetId }) { + const snippet = SNIPPETS[id]; + return ( + + ); +} + +/** fetch / axios variants of an example */ +export function SnippetTabs({ fetch, axios }: { fetch: SnippetId; axios: SnippetId }) { + return } axios={} />; +} + +export function createHeadings>(map: T) { + const list: NavHeading[] = Object.entries(map).map(([id, { text, depth }]) => ({ id, text, depth })); + + function Heading({ id, children }: { id: keyof T & string; children?: React.ReactNode }) { + const { text, depth } = map[id]; + const Tag = depth === 2 ? 'h2' : 'h3'; + return ( + + + {children ?? text} + + # + + + + ); + } + + return { list, Heading }; +} + +/** highlighted aside (uses the docs blockquote style) */ +export function Note({ title = 'Note', children }: { title?: string; children: React.ReactNode }) { + return ( +
+

+ {title}. {children} +

+
+ ); +} diff --git a/docs/app/usage/page.tsx b/docs/app/usage/page.tsx new file mode 100644 index 0000000..be2501b --- /dev/null +++ b/docs/app/usage/page.tsx @@ -0,0 +1,444 @@ +import { ArrowRight, BookOpen, FlaskConical } from 'lucide-react'; +import type { Metadata } from 'next'; +import Link from 'next/link'; + +import { DocsMobileNav, DocsSidebar, DocsToc } from '@/components/docs/docs-nav'; +import { site } from '@/components/site-config'; +import { SiteFooter } from '@/components/site-footer'; + +import { createHeadings, Note, Snippet, SnippetTabs } from './_lib/ui'; + +export const dynamic = 'force-static'; + +export const metadata: Metadata = { + title: 'Using the generated client', + description: `What to do after generating a client with ${site.name}: create it, call endpoints, add headers and auth, handle errors, cancel requests, upload files, and use it with React Query, SWR and Node.js.`, + openGraph: { title: `Using the generated client Β· ${site.name}` }, +}; + +const { list: headings, Heading } = createHeadings({ + generate: { text: 'Generate the client', depth: 2 }, + 'create-a-client': { text: 'Create a client', depth: 2 }, + 'fetch-client': { text: 'fetch', depth: 3 }, + 'axios-client': { text: 'axios', depth: 3 }, + 'axios-instance': { text: 'Your own axios instance', depth: 3 }, + 'client-options': { text: 'Client options', depth: 3 }, + 'call-endpoints': { text: 'Call endpoints', depth: 2 }, + 'request-params': { text: 'Per-request options', depth: 3 }, + 'headers-and-auth': { text: 'Headers and auth', depth: 2 }, + 'inject-headers': { text: 'injectHeaders', depth: 3 }, + 'security-worker': { text: 'Tokens with securityWorker', depth: 3 }, + 'secure-routes': { text: 'Secure routes', depth: 3 }, + 'single-http-client': { text: 'Share one HttpClient', depth: 2 }, + 'modular-output': { text: 'Modular output', depth: 2 }, + 'responses-and-errors': { text: 'Responses and errors', depth: 2 }, + 'fetch-responses': { text: 'fetch: HttpResponse', depth: 3 }, + 'disable-throw-on-error': { text: 'disableThrowOnError', depth: 3 }, + 'axios-responses': { text: 'axios: AxiosError', depth: 3 }, + 'unwrap-response-data': { text: 'unwrapResponseData', depth: 3 }, + cancellation: { text: 'Cancel requests', depth: 2 }, + files: { text: 'Upload and download files', depth: 2 }, + 'custom-fetch': { text: 'Custom fetch', depth: 2 }, + 'react-query-swr': { text: 'React Query and SWR', depth: 2 }, + nodejs: { text: 'Node.js', depth: 2 }, + 'typing-tips': { text: 'Typing tips', depth: 2 }, + 'data-contracts': { text: 'Data contracts', depth: 3 }, + 'route-types': { text: 'Route types', depth: 3 }, +}); + +/** `code` spans in table cells */ +function rich(text: string) { + return text.split(/(`[^`]+`)/).map((part, index) => + part.startsWith('`') ? {part.slice(1, -1)} : part + ); +} + +const CLIENT_OPTIONS: [option: string, fetch: string, axios: string, description: string][] = [ + ['Server URL', '`baseUrl`', '`baseURL`', 'Defaults to the first `servers[].url` of the spec.'], + ['Request defaults', '`baseApiParams`', 'any `AxiosRequestConfig` option', 'Headers, credentials, timeout, … for every request.'], + ['`securityWorker`', 'βœ“', 'βœ“', 'Returns extra request params for secure requests, from `setSecurityData()`.'], + ['Always secure', '`baseApiParams.secure`', '`secure`', 'Call the `securityWorker` for every request.'], + ['Response format', '`baseApiParams.format`', '`format`', 'Default way to read the response body.'], + ['`injectHeaders`', 'βœ“', 'βœ“', 'Rewrites the final headers of every request (may be async).'], + ['`customFetch`', 'βœ“', '–', 'Replaces `fetch` (retries, tests, SSR).'], + ['`instance`', '–', 'βœ“', 'Your own `AxiosInstance` instead of `axios.create()`.'], +]; + +export default function UsagePage() { + return ( + <> +
+ + +
+ +
+
+

Usage

+

+ Using the generated client +

+
+

+ You generated Api.ts. Now what? This guide covers everything after generation: + configuring the client, auth, errors, cancellation, files and framework integration. Every example + uses the petstore test schema of the repository and is type-checked in strict mode + against the code the generator emits today. +

+
+
+ + Generator docs + + + See the generated code + +
+
+ +
+ +

+ Install the generator as a dev dependency and point it at your schema. The generated files are plain + TypeScript with no runtime dependency, except axios for the axios client. +

+ +

+ Or keep the options in a config file and run npx swagger-typescript-api-es (for example + from a gen-api script). All options are described in the{' '} + options reference. +

+ +

+ The examples below use the generated names of the petstore schema: api.pets.listPets,{' '} + api.pets.getPet, api.store.getInventory, … Method names come from{' '} + operationId, and routes are grouped by the first path segment (/pets/… β†’{' '} + api.pets). +

+ + +

+ Create the client once, in its own module, and import it everywhere. Api extends{' '} + HttpClient, so the constructor takes the HTTP client config. +

+ + fetch + + + + baseApiParams replaces the built-in defaults ( + credentials: 'same-origin', redirect: 'follow',{' '} + referrerPolicy: 'no-referrer'), so repeat the ones you still want. In the same + way, baseUrl: undefined (an unset environment variable) removes the default server URL: + write process.env.API_URL ?? 'https://…'. + + + axios + +

+ The axios client passes the config to axios.create(), so every{' '} + AxiosRequestConfig option works. +

+ + +

+ Pass instance to reuse an axios instance that already has interceptors, retries or + a custom adapter. The client then uses it as is. +

+ + +
+ + + + + + + + + + + {CLIENT_OPTIONS.map(([option, fetchValue, axiosValue, description]) => ( + + + + + + + ))} + +
OptionfetchaxiosWhat it does
{rich(option)}{rich(fetchValue)}{rich(axiosValue)}{rich(description)}
+
+ + +

+ Each operation is a method. Path parameters come first as positional arguments, then the query object, + then the request body. The last argument is always an optional RequestParams. Everything is + typed from the schema, so a wrong field or a missing required property is a compile error. +

+ + +

+ RequestParams is the per-call escape hatch. For the fetch client it accepts any{' '} + RequestInit option plus secure, type, format,{' '} + baseUrl and cancelToken. For axios it is an AxiosRequestConfig{' '} + plus secure, type and format. +

+ + + +

Headers are merged in this order, the last one wins:

+
    +
  1. + client defaults: baseApiParams.headers (fetch) or headers (axios); +
  2. +
  3. + the headers of the call's RequestParams; +
  4. +
  5. + what the securityWorker returns, for secure requests; +
  6. +
  7. + the Content-Type of the operation (not set for multipart/form-data, the + browser adds the boundary); +
  8. +
  9. + finally injectHeaders can rewrite the result. +
  10. +
+ + injectHeaders + +

+ Both clients accept injectHeaders: (headers) => headers | Promise<headers>. It + runs before every request, after all the merging, which makes it the place for values that change + over time: a CSRF token, the current locale, a tracing id. +

+ + + Tokens with securityWorker + +

+ The type argument of Api is the type of your security data. Store it with{' '} + api.setSecurityData() after login, and the securityWorker turns it into + request params (usually an Authorization header) for every secure request. +

+ +

The worker can be async, for example to refresh an expired token first:

+ + +
    +
  • + Operations with a security requirement, their own or the schema's global one, are + generated with secure: true and a @secure JSDoc tag. Only those call the + worker. An operation with security: [] opts out (like GET / in the + petstore). +
  • +
  • + To send credentials with every request, set baseApiParams: {'{ secure: true }'} (fetch) or{' '} + secure: true (axios) in the client config. +
  • +
  • + To skip the worker for one call, pass {'{ secure: false }'} as RequestParams. +
  • +
+ + +

+ With singleHttpClient: true, Api no longer extends HttpClient: + it receives one in its constructor and keeps it in api.http. The transport (base URL, + auth, fetch or axios instance) is configured and replaced independently of the API surface, which + helps with dependency injection and tests. +

+ + + HttpClient has private fields, so TypeScript treats the class of each generated output as + a different type. Share an instance between the modules of one output, not between two separately + generated APIs. + + + +

+ With modular: true the output is split into http-client.ts,{' '} + data-contracts.ts and one class per module (Pets.ts, Store.ts,{' '} + Users.ts, plus Common.ts for routes like GET /). By default each + module class extends HttpClient, so give them the same config: +

+ +

+ Add singleHttpClient: true to share one client instead: one config, one{' '} + setSecurityData() call, and you can group the modules into a single object. +

+ + + + + fetch: HttpResponse + +

+ Methods resolve with an HttpResponse<Data, Error>: the native{' '} + Response (status, headers, ok, …) with the parsed body in{' '} + data. A non-2xx response rejects with the same object, the parsed error + body in error, typed from the schema's error responses. +

+ + + disableThrowOnError + +

+ Generate with disableThrowOnError: true to resolve every HTTP response and branch on{' '} + ok instead of using try/catch. Network errors still reject. +

+ + + axios: AxiosError + +

+ The axios client resolves with an AxiosResponse<Data> and rejects with an{' '} + AxiosError. Pass the error type to axios.isAxiosError to type{' '} + e.response.data. +

+ + + unwrapResponseData + +

+ Generate with unwrapResponseData: true to get the body directly. This works for both + clients; failed requests still reject (with the HttpResponse or the{' '} + AxiosError). +

+ + + +

+ The fetch client can cancel by token: tag a request with cancelToken and call{' '} + api.abortRequest(token). Both clients also accept a standard AbortSignal{' '} + through signal. With the fetch client, cancelToken takes precedence over{' '} + signal. +

+ + + +

+ Operations with a multipart/form-data body are generated with{' '} + type: ContentType.FormData. Pass a plain object that matches the schema:{' '} + File and Blob values are appended as they are, other objects are sent as + JSON. Do not set the Content-Type header yourself. +

+ +

+ For downloads, the format decides how the body is read. Responses declared as{' '} + type: string, format: binary are generated with format: 'blob' and + typed File (at runtime the value is a Blob). For other routes, pass{' '} + format in RequestParams or call api.request(): +

+ +

+ With axios, format is the responseType: use 'blob' in + the browser and 'arraybuffer' or 'stream' in Node.js. +

+ + +

+ The fetch client calls customFetch instead of the global fetch when you pass + one. Wrap any fetch-compatible function: retries, logging, a polyfill, a test double. +

+ +

In tests, answer with real Response objects: no network and no mocking library.

+ +

+ For server-side rendering, create one client per incoming request so that headers such as cookies are + never shared between users: +

+ + + The client calls this.customFetch(…). Passing window.fetch itself can fail + with Illegal invocation in browsers; use (...args) => fetch(...args). + + + +

+ Generated methods return promises, so they plug into any data-fetching library. Map the response to + its data (or generate with unwrapResponseData and pass the method directly), + and forward the library's AbortSignal so unused requests are canceled. +

+ + +

+ A rejected request surfaces as the query's error: the HttpResponse{' '} + (fetch) or the AxiosError (axios). +

+ + +

+ Node.js 18 and later have fetch, FormData, Blob and{' '} + File built in, so the fetch client runs unchanged in scripts, CLIs and servers. The + axios client works too, with axios installed. +

+ + + + +

+ Every schema of components/schemas is exported as a type (and enums as{' '} + enums, or unions with generateUnionEnums). Import them from{' '} + Api.ts, or from data-contracts.ts in modular mode. Inline parameter and + response types can be derived from the methods. +

+ + +

+ With generateRouteTypes: true, each operation also gets a namespace with its{' '} + RequestParams, RequestQuery, RequestBody,{' '} + RequestHeaders and ResponseBody types, handy for forms, mocks and server + handlers. In modular mode they are written to PetsRoute.ts, StoreRoute.ts, … +

+ +

+ Need a different shape? Customize the output with{' '} + hooks or custom templates, + and preview the result in the playground. +

+
+ +
+ + Reference + + Options, CLI and hooks + + + + + AI agent skill + + Teach your coding agent + + + +
+
+
+ + +
+ + + ); +} diff --git a/docs/components/client-tabs.tsx b/docs/components/client-tabs.tsx new file mode 100644 index 0000000..db55069 --- /dev/null +++ b/docs/components/client-tabs.tsx @@ -0,0 +1,67 @@ +'use client'; + +import { useId, useSyncExternalStore } from 'react'; + +import { Segmented } from './ui/segmented'; + +export type HttpClientKind = 'fetch' | 'axios'; + +const STORAGE_KEY = 'sta-es:http-client'; +const listeners = new Set<() => void>(); +let current: HttpClientKind | null = null; + +function read(): HttpClientKind { + if (current) return current; + try { + const stored = window.localStorage.getItem(STORAGE_KEY); + current = stored === 'axios' ? 'axios' : 'fetch'; + } catch { + current = 'fetch'; + } + return current; +} + +function write(value: HttpClientKind) { + current = value; + try { + window.localStorage.setItem(STORAGE_KEY, value); + } catch {} + for (const listener of listeners) listener(); +} + +function subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +const ITEMS = [ + { value: 'fetch' as const, label: 'fetch' }, + { value: 'axios' as const, label: 'axios' }, +]; + +/** + * fetch / axios variants of a code example. The choice is shared by every block of the page + * (and remembered), so switching once shows the axios version everywhere. + */ +export function ClientTabs({ fetch, axios }: { fetch: React.ReactNode; axios: React.ReactNode }) { + const value = useSyncExternalStore(subscribe, read, () => 'fetch' as const); + const id = useId(); + return ( +
+
+ + HTTP client + + +
+
+ + +
+
+ ); +} diff --git a/docs/components/docs/docs-nav.tsx b/docs/components/docs/docs-nav.tsx index f65c719..5db6465 100644 --- a/docs/components/docs/docs-nav.tsx +++ b/docs/components/docs/docs-nav.tsx @@ -84,13 +84,23 @@ function SectionList({ ); } -export function DocsSidebar({ headings }: { headings: NavHeading[] }) { +export function DocsSidebar({ + headings, + title = 'Guide', + label = 'Documentation sections', +}: { + headings: NavHeading[]; + /** small caps title above the list */ + title?: string; + /** accessible name of the navigation landmark */ + label?: string; +}) { const ids = useMemo(() => headings.map((h) => h.id), [headings]); const groups = useMemo(() => groupHeadings(headings), [headings]); const active = useActiveHeading(ids); return ( -