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 aa2c166..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: @@ -55,10 +58,37 @@ - `primitiveTypeConstructs` without `$default` could produce `[object Object]` types. - `$ref` names containing "undefined" could resolve to the wrong schema for operations without `operationId`. +### ⚡ 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). +- `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. +- 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 - 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/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 6834e86..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** @@ -427,7 +444,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'; @@ -645,7 +663,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 @@ -764,18 +783,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 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/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/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/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/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/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/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 ( -