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
34 changes: 31 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ This file has two parts:

1. a TypeScript HTTP client (types, one function per operation and a small fetch or axios runtime) in `<output>/requests/`
2. TanStack Query v5 hooks and helpers on top of that client in `<output>/queries/`
3. with `--mock msw`, mock data and MSW request handlers in `<output>/mocks/`

Docs: https://orqc.7nohe.dev (summary for LLMs: https://orqc.7nohe.dev/llms.txt)

Expand Down Expand Up @@ -40,8 +41,9 @@ Add a script and run it whenever the spec changes:
| `-i, --input <path\|url\|content>` | (required) | OpenAPI 3.0/3.1 spec |
| `-o, --output <dir>` | `openapi` | `requests/` and `queries/` are created inside |
| `-c, --client <name>` | `fetch` | or `axios` |
| `--format <biome\|prettier>` | none | formats `queries/` only |
| `--lint <biome\|eslint>` | none | lints/fixes `queries/` only |
| `--format <biome\|prettier>` | none | formats `queries/` (and `mocks/`) only |
| `--lint <biome\|eslint>` | none | lints/fixes `queries/` (and `mocks/`) only |
| `--mock <msw>` | off | also generate mock data and MSW handlers into `mocks/` (see below) |
| `--enums <javascript\|typescript>` | none | emit enum objects |
| `--useDateType` | off | `Date` for `date`/`date-time`, converted in successful responses |
| `--noOperationId` | off | derive names from paths instead of `operationId` |
Expand Down Expand Up @@ -78,6 +80,8 @@ Pass the **same flags** every time (keep them in the package.json script). Diffe
└── transformers.gen.ts # date conversion (only with --useDateType)
```

With `--mock msw` there is also `<output>/mocks/`: `data.ts` (mock functions), `handlers.ts` (MSW handlers) and `index.ts`.

Never edit generated files; change the spec or the flags and regenerate. Whether to commit the output is the project's choice. If it is committed, add the `--check` step below to CI.

### Using the generated code
Expand Down Expand Up @@ -123,6 +127,28 @@ mutate({ body: { name: "Fluffy" } });

Wrap the app in TanStack Query's `QueryClientProvider` as usual.

### Mocks: `--mock msw`

```bash
orqc -i ./openapi.yaml -o ./src/openapi --mock msw
```

Writes `<output>/mocks/` and needs `msw` (2 or 3) in the project. For an operation `findPets` and a schema `Pet` it exports:

- `findPetsHandler(override?)`: an MSW handler that answers with the operation's lowest successful status. `override` is a body of the response type, or an MSW resolver for anything else (an error, a body that depends on the request).
- `handlers`: every handler, ordered so that `/pets/mine` matches before `/pets/{id}`.
- `findPetsResponseMock()` and `petMock(overrides?)`: the mock data, typed by `requests/types.gen.ts`. `overrides` exists for object schemas only.

```ts
import { setupServer } from "msw/node"; // or setupWorker from "msw/browser"
import { findPetsHandler, handlers, petMock } from "./openapi/mocks";

const server = setupServer(...handlers);
server.use(findPetsHandler([petMock({ name: "Momo" })])); // own handlers win: MSW takes the first match
```

The values are fixed, not random: the specification's `example`/`default`, else the first `enum` value, else a value made up from the type. To change the data everywhere, add `example`s to the specification and regenerate; do not edit `mocks/`. The handlers keep no state and ignore the request, so pagination, errors and "created items show up in the list" need a handler of your own.

### Looking an operation up: `--agentsMd`

The generated files can be very large. Do not read them whole: an operation's function, hook and types each start a line, so `grep` finds them.
Expand All @@ -144,7 +170,7 @@ With `--agentsMd` in the codegen script, the generator keeps these instructions,
orqc -i ./openapi.yaml -o ./src/openapi --check
```

Generates into a temporary directory (`.openapi-rq-check-*` inside `<output>/queries`, removed afterwards), compares it with `<output>/requests` and `<output>/queries`, and changes no existing file. `--format`/`--lint` rules that target the output directory by path also apply to the temporary copy; a rule that names an exact file or depth from the project root (`src/openapi/queries/*.ts`) does not, so write such rules as `src/openapi/queries/**`. Each file is `added` (would be created), `modified` or `removed` (no longer generated).
Generates into a temporary directory (`.openapi-rq-check-*` inside `<output>/queries`, removed afterwards), compares it with `<output>/requests` and `<output>/queries` (and `<output>/mocks` with `--mock`), and changes no existing file. `--format`/`--lint` rules that target the output directory by path also apply to the temporary copy; a rule that names an exact file or depth from the project root (`src/openapi/queries/*.ts`) does not, so write such rules as `src/openapi/queries/**`. Each file is `added` (would be created), `modified` or `removed` (no longer generated).

The `queries/` headers include the package version, so after upgrading this package `--check` fails until you regenerate. Upgrade and regenerate in the same change.

Expand Down Expand Up @@ -219,10 +245,12 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
- A hook builder takes the names it declares and refers to from `hookNames(op)` (`src/hooks/hookNames.mts`), never from the operation's name directly: `settleHookNames` numbers a name that its file already imports or declares, and the files are then built again with those names.
- A hook builder declares what its statement needs from the generated client: `service` (the SDK function) and `models` (types from `types.gen`). The fixed names (TanStack Query, `Options`, `Common`, `AxiosError`) are imported when the code mentions them, which is only safe because the client generator reserves them. When hook code starts using a new name, add it to `RESERVED_TYPE_NAMES` or `RESERVED_FUNCTION_NAMES` and to the list in `tests/hooks/imports.test.ts`.
- The generated hooks rely on a small SDK contract: `Options<XData, ThrowOnError>` exported from `sdk.gen`, calls returning `{ data }` and rejecting when `throwOnError` is set, and the `XData` / `XError` type names. Keep it in sync with `src/client/emitSdk.mts` and the runtimes in `src/client/runtime/`.
- The mocks (`src/client/emitMocks.mts`, `mockValue.mts`) are typed by `types.gen.ts`, so a value has to be one `renderSchema` gives a type for: `mockValue` reads a schema with the same helpers (`componentSchemaView`, `inheritedRequired`, `discriminatorValues`). When the type of a schema changes, change its value with it; `tests/client/mocksCompile.test.ts` compiles the mocks of every specification under `tests/inputs` and fails when the two disagree. An `example` is only used after `exampleValue` has checked it against the schema.
- The runtimes (`src/client/runtime/*.runtime.ts`) are plain TypeScript that is copied verbatim into users' projects. Keep them dependency-free (axios aside), strict-mode clean, and free of syntax that needs a newer TypeScript than the generated code supports. `scripts/copy-runtime.mjs` ships them next to the compiled generator.

### Dependencies
- Runtime dependencies are deliberately few (`cross-spawn`, `yaml`). Adding one needs a reason; the generator replaced `@hey-api/openapi-ts` to cut the supply-chain surface.
- `msw` is a devDependency only, for the tests that compile and run the generated handlers. The generated code imports it from the user's project, so it is neither a dependency nor a peer dependency of this package.

### Agent-Specific Notes
- The generators build source text as strings. After changing one, run the tests that compile the generated output (`tests/createSource.test.ts`, `tests/client/`) to confirm it is still valid TypeScript.
Expand Down
6 changes: 5 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ npm run preview:tanstack-router
2. **Generate** (`src/generate.mts`): Orchestrates the generation process:
- Calls `generateClient()` (`src/client/index.mts`) to build the client in `openapi/requests/` and the normalized operations
- Calls `createSource()` to generate React Query hooks in `openapi/queries/`
3. **Client Generator** (`src/client/`): `spec.mts` loads/bundles the document, `operations.mts` normalizes operations, `schema.mts` renders types, `emitTypes.mts` / `emitSdk.mts` write the files, and `runtime/*.runtime.ts` are the fetch/axios runtimes copied into the output
- With `--mock msw`, writes the mock data and MSW handlers that `generateClient()` returns to `openapi/mocks/`
3. **Client Generator** (`src/client/`): `spec.mts` loads/bundles the document, `operations.mts` normalizes operations, `schema.mts` renders types, `emitTypes.mts` / `emitSdk.mts` write the files, `emitMocks.mts` / `mockValue.mts` write the mocks, and `runtime/*.runtime.ts` are the fetch/axios runtimes copied into the output
4. **Hook Generators** (`src/hooks/`): `generateFiles.mts` routes operations by HTTP method (GET → queries, suspense, infinite, prefetch, ensure; POST/PUT/PATCH/DELETE → mutations) to the `build*.mts` builders, which return statements as strings; `statement.mts` and `imports.mts` print them and the imports each file needs
5. **Write**: `writeGeneratedFiles()` (`src/client/index.mts`) writes both directories

Expand All @@ -54,10 +55,13 @@ The tool generates files in `openapi/queries/`:
- `ensureQueryData.ts`: `ensureQueryData` functions
- `index.ts`: Re-exports

With `--mock msw` it also generates `openapi/mocks/`: `data.ts` (mock functions typed by `types.gen.ts`), `handlers.ts` (MSW handlers) and `index.ts`.

### Key Dependencies

- **typescript** (dev only): building this package and compiling generated output in tests
- **yaml**: parsing YAML specifications
- **msw** (dev only): compiling and running the generated handlers in tests; generated code imports it from the user's project

## Testing

Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- **SSR helpers**: `prefetchQuery`, `prefetchInfiniteQuery`, and `ensureQueryData` functions per operation — ready for Next.js App Router hydration
- **Hierarchical query keys** with exported key constants and functions: invalidate one exact query, all infinite pages of an operation, or every cache entry of an operation with a single prefix
- **Pure TypeScript client** (types, SDK functions and a small fetch or axios runtime) generated from the same OpenAPI 3.0/3.1 document — no separate client generator to install
- **MSW mocks from the same spec** (`--mock msw`): typed mock data and a request handler per operation, with fixed values taken from the spec's examples — build the frontend before the backend exists, and reuse the handlers in tests
- **CI- and agent-friendly**: `--check` fails CI when committed output is out of date, `--json` prints errors as machine-readable JSON, `--agentsMd` keeps a guide in your `AGENTS.md` that lets a coding agent look one operation up instead of reading the generated files, and the package ships an [`AGENTS.md`](./AGENTS.md) for coding agents

## Quick start
Expand Down Expand Up @@ -63,7 +64,7 @@ function Pets() {
}
```

See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7nohe.dev/guides/cli-options/), [usage](https://orqc.7nohe.dev/guides/usage/) (SSR, infinite queries, mutations) and [CI and coding agents](https://orqc.7nohe.dev/guides/ci-and-agents/).
See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7nohe.dev/guides/cli-options/), [usage](https://orqc.7nohe.dev/guides/usage/) (SSR, infinite queries, mutations), [mocking with MSW](https://orqc.7nohe.dev/guides/mocking/) and [CI and coding agents](https://orqc.7nohe.dev/guides/ci-and-agents/).

## Examples

Expand All @@ -86,15 +87,15 @@ See the [documentation](https://orqc.7nohe.dev) for [CLI options](https://orqc.7
| SSR helpers (`prefetchQuery` / `prefetchInfiniteQuery` / `ensureQueryData`) | ✅ | ❌ | Partial (`usePrefetch`) | Not provided (use `queryOptions`) |
| Hierarchical query keys for granular invalidation | ✅ | ✅ (tags) | Partial | Not documented |
| Stable release line | ✅ SemVer | pre-1.0, frequent breaking changes | ✅ | ⚠️ upstream openapi-typescript is in [maintenance mode](https://github.com/openapi-ts/openapi-typescript/issues/2874) |
| MSW mock generation | ❌ (out of scope) | ❌ | ✅ | ❌ |
| MSW mock generation | ✅ (`--mock msw`, fixed values) | ❌ | ✅ (random values with Faker) | ❌ |
| Vue / Solid / Svelte / Angular | ❌ React-focused | ✅ | ✅ | ❌ |
| Generation time, GitHub REST API (1,272 operations)¹ | **0.46 s** | 2.98 s | 4.31 s | 2.10 s |
| Packages added by installing the generator¹ | **9** (2.1 MB) | 51 (10.8 MB) | 89 (101.5 MB) | 35 (20.5 MB) |
| Type errors in the generated code, Stripe / GitHub APIs¹ | **0 / 0** | 274 / 0 | 219 / 1 | 0 / 0 |

¹ Measured on 2026-11-13 on an Apple M2 with Node.js 24 (generation time is the median wall-clock time of the CLI), with 4.0.0-beta.4, `@hey-api/openapi-ts` 0.99.0, Orval 8.46.0 and openapi-typescript 7.13.0 + openapi-react-query 0.5.4. Methods, the other specifications and type-checking times are on the [Benchmarks](https://orqc.7nohe.dev/guides/benchmarks/) page; the scripts are in [`benchmarks/`](./benchmarks).

**Scope**: this library is deliberately React-focused and does not generate API mocks — use Orval if MSW mocks are your priority, or the hey-api plugin if you need non-React frameworks.
**Scope**: this library is deliberately React-focused — use the hey-api plugin if you need non-React frameworks. Its [MSW mocks](https://orqc.7nohe.dev/guides/mocking/) answer with fixed values taken from the spec and keep no state; use Orval if you want randomly generated mock data.

**Coming from openapi-typescript / openapi-fetch / openapi-react-query?** See the [migration guide](https://orqc.7nohe.dev/guides/migrating-from-openapi-react-query/).

Expand Down
1 change: 1 addition & 0 deletions docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export default defineConfig({
{ slug: "guides/introduction" },
{ slug: "guides/usage" },
{ slug: "guides/cli-options" },
{ slug: "guides/mocking" },
{ slug: "guides/ci-and-agents" },
{ slug: "guides/benchmarks" },
{ slug: "guides/migrating-to-v3" },
Expand Down
1 change: 1 addition & 0 deletions docs/public/llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Key facts for agents:
- [Introduction](https://orqc.7nohe.dev/guides/introduction/): install, first run, generated layout, client setup
- [Usage](https://orqc.7nohe.dev/guides/usage/): using the generated query, suspense, mutation, infinite, prefetch and ensureQueryData exports
- [CLI Options](https://orqc.7nohe.dev/guides/cli-options/): every flag with defaults
- [Mocking with MSW](https://orqc.7nohe.dev/guides/mocking/): `--mock msw`, generated mock data and request handlers, overriding a response, how the values are chosen
- [CI and Coding Agents](https://orqc.7nohe.dev/guides/ci-and-agents/): `--check`, `--json`, exit codes, error codes, AGENTS.md
- [AGENTS.md](https://github.com/7nohe/openapi-react-query-codegen/blob/main/AGENTS.md): agent guide, also at `node_modules/@7nohe/openapi-react-query-codegen/AGENTS.md`

Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/docs/guides/ci-and-agents.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Use exactly the same options as your normal codegen script. Different options pr
`--check`:

- generates into a temporary directory inside `<output>/queries` (`.openapi-rq-check-*`) and deletes it afterwards. `--format` and `--lint` run on that copy with the same configuration files, and overrides or ignore rules that target the output directory by path (`src/openapi/**`, a folder named `openapi`) apply to it as well
- compares only the directories the generator owns: `<output>/requests` and `<output>/queries`
- compares only the directories the generator owns: `<output>/requests` and `<output>/queries`, and `<output>/mocks` when `--mock` is passed
- never changes an existing file in the output directory
- exits with `0` when everything matches, and with `1` when files differ

Expand Down
15 changes: 13 additions & 2 deletions docs/src/content/docs/guides/cli-options.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ The v3 spellings `@hey-api/client-fetch` and `@hey-api/client-axios` are still a

### --format \<value\>

Process the generated queries output folder (`openapi/queries`) with a formatter. The `openapi/requests` directory is not affected by this option. The default value is `false`.
Process the generated queries output folder (`openapi/queries`) with a formatter, and `openapi/mocks` when `--mock` is set. The `openapi/requests` directory is not affected by this option. The default value is `false`.
The available options are:

- `biome`
- `prettier`

### --lint \<value\>

Process the generated queries output folder (`openapi/queries`) with a linter. The `openapi/requests` directory is not affected by this option. The default value is `false`.
Process the generated queries output folder (`openapi/queries`) with a linter, and `openapi/mocks` when `--mock` is set. The `openapi/requests` directory is not affected by this option. The default value is `false`.
The available options are:

- `biome`
Expand Down Expand Up @@ -101,6 +101,17 @@ The available options are:
- `json`: the schemas as the specification writes them
- `form`: without `title`, `description` and the `x-enum-*` names, for use in form libraries

## Mock Options

### --mock \<value\>

Also generate mock data and request handlers from the specification, into `openapi/mocks`. Nothing is generated by default.
The available options are:

- `msw`: [MSW](https://mswjs.io) request handlers (version 2 or 3; install `msw` in your project)

See [Mocking with MSW](/guides/mocking/) for how to use them.

## CI and Automation Options

See [CI and Coding Agents](/guides/ci-and-agents/) for details and examples.
Expand Down
Loading
Loading