Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
32 changes: 31 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
49 changes: 35 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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**
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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/`:

Expand Down
Loading
Loading