@jutsustack/api-codegen 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +764 -2
- package/bin/jutsu-api.js +14 -0
- package/dist/cache/manifest.d.ts +35 -0
- package/dist/cache/manifest.d.ts.map +1 -0
- package/dist/cache/manifest.js +37 -0
- package/dist/cache/manifest.js.map +1 -0
- package/dist/cjs/cache/manifest.d.ts +34 -0
- package/dist/cjs/cache/manifest.js +45 -0
- package/dist/cjs/cli.d.ts +8 -0
- package/dist/cjs/cli.js +245 -0
- package/dist/cjs/codegen/emit-api.d.ts +6 -0
- package/dist/cjs/codegen/emit-api.js +108 -0
- package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
- package/dist/cjs/codegen/emit-bindings.js +115 -0
- package/dist/cjs/codegen/emit-types.d.ts +10 -0
- package/dist/cjs/codegen/emit-types.js +232 -0
- package/dist/cjs/codegen/emit.d.ts +28 -0
- package/dist/cjs/codegen/emit.js +180 -0
- package/dist/cjs/codegen/files.d.ts +14 -0
- package/dist/cjs/codegen/files.js +66 -0
- package/dist/cjs/codegen/plan.d.ts +32 -0
- package/dist/cjs/codegen/plan.js +84 -0
- package/dist/cjs/codegen/print.d.ts +10 -0
- package/dist/cjs/codegen/print.js +65 -0
- package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
- package/dist/cjs/codegen/templates/bindings.js +707 -0
- package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
- package/dist/cjs/codegen/templates/runtime.js +1401 -0
- package/dist/cjs/codegen/templates/transports.d.ts +1 -0
- package/dist/cjs/codegen/templates/transports.js +272 -0
- package/dist/cjs/codegen/tsType.d.ts +15 -0
- package/dist/cjs/codegen/tsType.js +114 -0
- package/dist/cjs/collect/collect.d.ts +16 -0
- package/dist/cjs/collect/collect.js +472 -0
- package/dist/cjs/collect/naming.d.ts +25 -0
- package/dist/cjs/collect/naming.js +149 -0
- package/dist/cjs/collect/path.d.ts +10 -0
- package/dist/cjs/collect/path.js +67 -0
- package/dist/cjs/config/init.d.ts +37 -0
- package/dist/cjs/config/init.js +143 -0
- package/dist/cjs/config/load.d.ts +11 -0
- package/dist/cjs/config/load.js +121 -0
- package/dist/cjs/config/types.d.ts +88 -0
- package/dist/cjs/config/types.js +2 -0
- package/dist/cjs/config/validate.d.ts +8 -0
- package/dist/cjs/config/validate.js +200 -0
- package/dist/cjs/generate.d.ts +55 -0
- package/dist/cjs/generate.js +263 -0
- package/dist/cjs/index.d.ts +23 -0
- package/dist/cjs/index.js +48 -0
- package/dist/cjs/model/collection.d.ts +83 -0
- package/dist/cjs/model/collection.js +16 -0
- package/dist/cjs/model/infer.d.ts +7 -0
- package/dist/cjs/model/infer.js +95 -0
- package/dist/cjs/model/merge.d.ts +3 -0
- package/dist/cjs/model/merge.js +131 -0
- package/dist/cjs/model/reserved.d.ts +2 -0
- package/dist/cjs/model/reserved.js +128 -0
- package/dist/cjs/model/schema.d.ts +54 -0
- package/dist/cjs/model/schema.js +2 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
- package/dist/cjs/parsers/openapi-schema.js +241 -0
- package/dist/cjs/parsers/openapi.d.ts +8 -0
- package/dist/cjs/parsers/openapi.js +435 -0
- package/dist/cjs/parsers/postman.d.ts +20 -0
- package/dist/cjs/parsers/postman.js +493 -0
- package/dist/cjs/parsers/types.d.ts +52 -0
- package/dist/cjs/parsers/types.js +2 -0
- package/dist/cjs/sources/load.d.ts +25 -0
- package/dist/cjs/sources/load.js +296 -0
- package/dist/cjs/sources/parse.d.ts +4 -0
- package/dist/cjs/sources/parse.js +50 -0
- package/dist/cjs/util/errors.d.ts +9 -0
- package/dist/cjs/util/errors.js +23 -0
- package/dist/cjs/util/fs.d.ts +7 -0
- package/dist/cjs/util/fs.js +44 -0
- package/dist/cjs/util/hash.d.ts +3 -0
- package/dist/cjs/util/hash.js +26 -0
- package/dist/cjs/util/json.d.ts +10 -0
- package/dist/cjs/util/json.js +31 -0
- package/dist/cjs/util/log.d.ts +22 -0
- package/dist/cjs/util/log.js +45 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +238 -0
- package/dist/cli.js.map +1 -0
- package/dist/codegen/emit-api.d.ts +7 -0
- package/dist/codegen/emit-api.d.ts.map +1 -0
- package/dist/codegen/emit-api.js +105 -0
- package/dist/codegen/emit-api.js.map +1 -0
- package/dist/codegen/emit-bindings.d.ts +9 -0
- package/dist/codegen/emit-bindings.d.ts.map +1 -0
- package/dist/codegen/emit-bindings.js +112 -0
- package/dist/codegen/emit-bindings.js.map +1 -0
- package/dist/codegen/emit-types.d.ts +11 -0
- package/dist/codegen/emit-types.d.ts.map +1 -0
- package/dist/codegen/emit-types.js +230 -0
- package/dist/codegen/emit-types.js.map +1 -0
- package/dist/codegen/emit.d.ts +29 -0
- package/dist/codegen/emit.d.ts.map +1 -0
- package/dist/codegen/emit.js +177 -0
- package/dist/codegen/emit.js.map +1 -0
- package/dist/codegen/files.d.ts +15 -0
- package/dist/codegen/files.d.ts.map +1 -0
- package/dist/codegen/files.js +57 -0
- package/dist/codegen/files.js.map +1 -0
- package/dist/codegen/plan.d.ts +33 -0
- package/dist/codegen/plan.d.ts.map +1 -0
- package/dist/codegen/plan.js +79 -0
- package/dist/codegen/plan.js.map +1 -0
- package/dist/codegen/print.d.ts +11 -0
- package/dist/codegen/print.d.ts.map +1 -0
- package/dist/codegen/print.js +59 -0
- package/dist/codegen/print.js.map +1 -0
- package/dist/codegen/templates/bindings.d.ts +14 -0
- package/dist/codegen/templates/bindings.d.ts.map +1 -0
- package/dist/codegen/templates/bindings.js +705 -0
- package/dist/codegen/templates/bindings.js.map +1 -0
- package/dist/codegen/templates/runtime.d.ts +3 -0
- package/dist/codegen/templates/runtime.d.ts.map +1 -0
- package/dist/codegen/templates/runtime.js +1398 -0
- package/dist/codegen/templates/runtime.js.map +1 -0
- package/dist/codegen/templates/transports.d.ts +2 -0
- package/dist/codegen/templates/transports.d.ts.map +1 -0
- package/dist/codegen/templates/transports.js +270 -0
- package/dist/codegen/templates/transports.js.map +1 -0
- package/dist/codegen/tsType.d.ts +16 -0
- package/dist/codegen/tsType.d.ts.map +1 -0
- package/dist/codegen/tsType.js +111 -0
- package/dist/codegen/tsType.js.map +1 -0
- package/dist/collect/collect.d.ts +17 -0
- package/dist/collect/collect.d.ts.map +1 -0
- package/dist/collect/collect.js +469 -0
- package/dist/collect/collect.js.map +1 -0
- package/dist/collect/naming.d.ts +26 -0
- package/dist/collect/naming.d.ts.map +1 -0
- package/dist/collect/naming.js +137 -0
- package/dist/collect/naming.js.map +1 -0
- package/dist/collect/path.d.ts +11 -0
- package/dist/collect/path.d.ts.map +1 -0
- package/dist/collect/path.js +62 -0
- package/dist/collect/path.js.map +1 -0
- package/dist/config/init.d.ts +38 -0
- package/dist/config/init.d.ts.map +1 -0
- package/dist/config/init.js +134 -0
- package/dist/config/init.js.map +1 -0
- package/dist/config/load.d.ts +12 -0
- package/dist/config/load.d.ts.map +1 -0
- package/dist/config/load.js +112 -0
- package/dist/config/load.js.map +1 -0
- package/dist/config/types.d.ts +89 -0
- package/dist/config/types.d.ts.map +1 -0
- package/dist/config/types.js +2 -0
- package/dist/config/types.js.map +1 -0
- package/dist/config/validate.d.ts +9 -0
- package/dist/config/validate.d.ts.map +1 -0
- package/dist/config/validate.js +196 -0
- package/dist/config/validate.js.map +1 -0
- package/dist/generate.d.ts +56 -0
- package/dist/generate.d.ts.map +1 -0
- package/dist/generate.js +255 -0
- package/dist/generate.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/model/collection.d.ts +84 -0
- package/dist/model/collection.d.ts.map +1 -0
- package/dist/model/collection.js +13 -0
- package/dist/model/collection.js.map +1 -0
- package/dist/model/infer.d.ts +8 -0
- package/dist/model/infer.d.ts.map +1 -0
- package/dist/model/infer.js +91 -0
- package/dist/model/infer.js.map +1 -0
- package/dist/model/merge.d.ts +4 -0
- package/dist/model/merge.d.ts.map +1 -0
- package/dist/model/merge.js +129 -0
- package/dist/model/merge.js.map +1 -0
- package/dist/model/reserved.d.ts +3 -0
- package/dist/model/reserved.d.ts.map +1 -0
- package/dist/model/reserved.js +126 -0
- package/dist/model/reserved.js.map +1 -0
- package/dist/model/schema.d.ts +55 -0
- package/dist/model/schema.d.ts.map +1 -0
- package/dist/model/schema.js +2 -0
- package/dist/model/schema.js.map +1 -0
- package/dist/parsers/openapi-schema.d.ts +31 -0
- package/dist/parsers/openapi-schema.d.ts.map +1 -0
- package/dist/parsers/openapi-schema.js +238 -0
- package/dist/parsers/openapi-schema.js.map +1 -0
- package/dist/parsers/openapi.d.ts +9 -0
- package/dist/parsers/openapi.d.ts.map +1 -0
- package/dist/parsers/openapi.js +432 -0
- package/dist/parsers/openapi.js.map +1 -0
- package/dist/parsers/postman.d.ts +21 -0
- package/dist/parsers/postman.d.ts.map +1 -0
- package/dist/parsers/postman.js +488 -0
- package/dist/parsers/postman.js.map +1 -0
- package/dist/parsers/types.d.ts +53 -0
- package/dist/parsers/types.d.ts.map +1 -0
- package/dist/parsers/types.js +2 -0
- package/dist/parsers/types.js.map +1 -0
- package/dist/sources/load.d.ts +26 -0
- package/dist/sources/load.d.ts.map +1 -0
- package/dist/sources/load.js +291 -0
- package/dist/sources/load.js.map +1 -0
- package/dist/sources/parse.d.ts +5 -0
- package/dist/sources/parse.d.ts.map +1 -0
- package/dist/sources/parse.js +48 -0
- package/dist/sources/parse.js.map +1 -0
- package/dist/util/errors.d.ts +10 -0
- package/dist/util/errors.d.ts.map +1 -0
- package/dist/util/errors.js +18 -0
- package/dist/util/errors.js.map +1 -0
- package/dist/util/fs.d.ts +8 -0
- package/dist/util/fs.d.ts.map +1 -0
- package/dist/util/fs.js +36 -0
- package/dist/util/fs.js.map +1 -0
- package/dist/util/hash.d.ts +4 -0
- package/dist/util/hash.d.ts.map +1 -0
- package/dist/util/hash.js +23 -0
- package/dist/util/hash.js.map +1 -0
- package/dist/util/json.d.ts +11 -0
- package/dist/util/json.d.ts.map +1 -0
- package/dist/util/json.js +24 -0
- package/dist/util/json.js.map +1 -0
- package/dist/util/log.d.ts +23 -0
- package/dist/util/log.d.ts.map +1 -0
- package/dist/util/log.js +42 -0
- package/dist/util/log.js.map +1 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +4 -0
- package/dist/version.js.map +1 -0
- package/package.json +117 -4
- package/schema/config.schema.json +182 -0
package/README.md
CHANGED
|
@@ -1,3 +1,765 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @jutsustack/api-codegen
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generate a typed API layer from **Postman collections**, **Swagger 2.0** and **OpenAPI 3.x**
|
|
4
|
+
documents, so you never hand-write an API call, its types or its loading state again.
|
|
5
|
+
|
|
6
|
+
New here? Follow the step-by-step guide: **[Using api-codegen in your app](docs/USAGE.md)**.
|
|
7
|
+
|
|
8
|
+
- **Any framework:** React, React Native, Next.js, Vue, Angular, Svelte, SolidJS, or plain
|
|
9
|
+
TypeScript / JavaScript.
|
|
10
|
+
- **Any HTTP client:** `fetch`, `axios`, `@jutsustack/react-native-fetch`, Angular
|
|
11
|
+
`HttpClient`, or your own function. You choose the client; the generated code doesn't depend
|
|
12
|
+
on any of them.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
const user = await api.users.getUser({ params: { id: 42 } }); // → User
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
await api.auth.login({ body: { email, password } });
|
|
19
|
+
} catch (error) {
|
|
20
|
+
const failure = api.auth.login.errorOf(error); // { status: 401; data: LoginError } | undefined
|
|
21
|
+
toast(getErrorMessage(error)); // "Wrong email or password." (configurable per API)
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- **Duplicate requests become one endpoint.** "Login – Success" and "Login – Wrong password"
|
|
26
|
+
(or `/users/1` and `/users/:id`) merge into one function with typed success and error bodies.
|
|
27
|
+
- **Per-API control:** timeouts, retries with back-off, fallbacks, error messages, logging with
|
|
28
|
+
secrets redacted, performance metrics and loading state, set globally, per endpoint or per call.
|
|
29
|
+
- **Bindings for your framework:** hooks, composables, signals, stores or primitives with
|
|
30
|
+
`status`, `isLoading`, `error`, `refetch`, built on one tested framework-neutral core.
|
|
31
|
+
- **Codegen only.** The package generates code and adds no runtime dependency to your app.
|
|
32
|
+
The generated files import only your framework, and the HTTP library only in `client.ts`.
|
|
33
|
+
- **Skips work when nothing changed**, and **never overwrites hand-edited files**.
|
|
34
|
+
- **Strict-mode clean.** Generated code compiles under `strict`, `exactOptionalPropertyTypes`
|
|
35
|
+
and `noUncheckedIndexedAccess`.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
Pick your package manager. The package works the same with all of them, as ESM or CommonJS.
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm i -D @jutsustack/api-codegen
|
|
43
|
+
pnpm add -D @jutsustack/api-codegen
|
|
44
|
+
yarn add -D @jutsustack/api-codegen
|
|
45
|
+
bun add -d @jutsustack/api-codegen
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Requirements: Node.js 18.18+ (or Bun) to run the CLI, TypeScript 5+ in the app.
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
npx jutsu-api init --source ./api/my-app.postman_collection.json # creates my-app-api.config.json
|
|
54
|
+
npx jutsu-api # generates src/api
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Use `pnpm exec jutsu-api`, `yarn jutsu-api` or `bunx jutsu-api` with other package managers.
|
|
58
|
+
`init` reads your `package.json` to choose `framework` and `httpClient` (for example Vue with
|
|
59
|
+
axios); override with `--framework` and `--http-client`.
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
✎ src/api/api-collection.json
|
|
63
|
+
✎ src/api/runtime.ts
|
|
64
|
+
✎ src/api/types.ts
|
|
65
|
+
✎ src/api/api.ts
|
|
66
|
+
✎ src/api/hooks.ts
|
|
67
|
+
✎ src/api/index.ts
|
|
68
|
+
✎ src/api/client.ts
|
|
69
|
+
✔ Updated 7 file(s) in src/api: 10 endpoints in 4 group(s), 3 merged from duplicate requests [react + fetch]
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Configure the client once in `src/api/client.ts` (base URL, auth, retries, logging), then call
|
|
73
|
+
`api.<group>.<endpoint>()`. `init` adds the `.jutsu-api/` cache folder to an existing
|
|
74
|
+
`.gitignore`. If you use ESLint, also ignore the output folder: generated files start with
|
|
75
|
+
`/* eslint-disable */`, which ESLint 9 reports as unused.
|
|
76
|
+
|
|
77
|
+
## How it works
|
|
78
|
+
|
|
79
|
+
The package is a **build-time tool**. It reads your Postman or Swagger file and writes a typed
|
|
80
|
+
API folder into your app. Your app imports from that folder, not from
|
|
81
|
+
`@jutsustack/api-codegen`, which stays a dev dependency.
|
|
82
|
+
|
|
83
|
+
```text
|
|
84
|
+
Postman / Swagger file ──► npx jutsu-api ──► src/api/ (written for you)
|
|
85
|
+
(dev dependency) │
|
|
86
|
+
▼
|
|
87
|
+
your app imports from src/api
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
**1. Generate.** A Postman request such as `Get user GET {{baseUrl}}/users/:id` becomes:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
// src/api/types.ts (generated)
|
|
94
|
+
export interface GetUserResponse {
|
|
95
|
+
id: number;
|
|
96
|
+
name: string;
|
|
97
|
+
email: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// src/api/api.ts (generated)
|
|
101
|
+
getUser: endpoint<GetUserArgs, GetUserResponse, GetUserErrors>(client, {
|
|
102
|
+
id: 'users.getUser',
|
|
103
|
+
method: 'GET',
|
|
104
|
+
path: '/users/:id',
|
|
105
|
+
}),
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
**2. Connect your HTTP library**, once, in `src/api/client.ts`. This file is yours and is
|
|
109
|
+
never overwritten:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
// src/api/client.ts
|
|
113
|
+
import axios from 'axios';
|
|
114
|
+
import { createApi, createClient } from './index'; // the generated code
|
|
115
|
+
|
|
116
|
+
const http = axios.create();
|
|
117
|
+
http.interceptors.request.use((config) => {
|
|
118
|
+
config.headers['x-app-version'] = '1.0.0'; // your axios setup keeps working
|
|
119
|
+
return config;
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
export const client = createClient({
|
|
123
|
+
baseURL: 'https://api.example.com',
|
|
124
|
+
http, // leave it out to use fetch
|
|
125
|
+
getToken: () => localStorage.getItem('token'),
|
|
126
|
+
retry: true,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
export const api = createApi(client);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**3. Call it** anywhere, typed:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
import { api } from './api/client';
|
|
136
|
+
|
|
137
|
+
const user = await api.users.getUser({ params: { id: 7 } });
|
|
138
|
+
user.name; // string
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
**What happens on that call:**
|
|
142
|
+
|
|
143
|
+
```text
|
|
144
|
+
api.users.getUser({ params: { id: 7 } }) your code
|
|
145
|
+
→ endpoint users.getUser: GET /users/:id src/api/api.ts
|
|
146
|
+
→ client: URL, Bearer token, timeout, retries, middleware src/api/runtime.ts
|
|
147
|
+
→ your axios instance (interceptors run) axios
|
|
148
|
+
→ server: 200 { id: 7, … } or 404
|
|
149
|
+
→ client: data typed as GetUserResponse, or an ApiError with your message
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
When the API changes, update the collection and run `npx jutsu-api` again. To switch HTTP
|
|
153
|
+
library, change the `http` line in `client.ts`; the rest of your code stays the same.
|
|
154
|
+
|
|
155
|
+
## Config
|
|
156
|
+
|
|
157
|
+
One file per project, **`<project-name>-api.config.json`**, next to `package.json`. Use
|
|
158
|
+
`--config` when a folder holds several.
|
|
159
|
+
|
|
160
|
+
```json
|
|
161
|
+
{
|
|
162
|
+
"$schema": "./node_modules/@jutsustack/api-codegen/schema/config.schema.json",
|
|
163
|
+
"project": "shop-app",
|
|
164
|
+
"framework": "vue",
|
|
165
|
+
"httpClient": "axios",
|
|
166
|
+
"output": "src/api",
|
|
167
|
+
"sources": [
|
|
168
|
+
{ "id": "shop", "path": "./api/shop.postman_collection.json" },
|
|
169
|
+
{ "id": "payments", "url": "https://payments.example.com/openapi.yaml" }
|
|
170
|
+
]
|
|
171
|
+
}
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
| Option | Default | Description |
|
|
175
|
+
| ----------------- | ------------------------------- | ---------------------------------------------------------------------------------------- |
|
|
176
|
+
| `project` | required | Project name |
|
|
177
|
+
| `framework` | required | `react`, `react-native`, `next`, `vue`, `angular`, `svelte`, `solid` or `none` |
|
|
178
|
+
| `httpClient` | `fetch` (`angular` for Angular) | `fetch`, `axios`, `react-native-fetch`, `angular` or `custom`: what `client.ts` wires up |
|
|
179
|
+
| `output` | required | Output folder, relative to the config; must stay inside the project |
|
|
180
|
+
| `sources` | required | See [Sources](#sources) |
|
|
181
|
+
| `baseUrl` | first server found | Base URL for the `client.ts` scaffold |
|
|
182
|
+
| `methods` | `GET POST PUT PATCH DELETE` | Methods to generate (`HEAD`, `OPTIONS` also allowed) |
|
|
183
|
+
| `groupBy` | `folder` | `folder` / `tag`, `path` (first path segment) or `none` |
|
|
184
|
+
| `hooks` | `true` | Generate the framework bindings |
|
|
185
|
+
| `include` | all | Globs to keep, e.g. `"/users/**"`, `"GET /orders/*"` |
|
|
186
|
+
| `exclude` | none | Globs to skip |
|
|
187
|
+
| `format` | `none` | `prettier` formats output with the project's prettier |
|
|
188
|
+
| `importExtension` | `""` | `".js"` for apps using `moduleResolution: NodeNext` |
|
|
189
|
+
| `cacheDir` | `.jutsu-api` | Cache folder |
|
|
190
|
+
| `target` | deprecated | v0.1 option, still read; see [Migrating](#migrating-from-01) |
|
|
191
|
+
|
|
192
|
+
Unknown options are errors, reported with their path (`sources[1].url: must be an http(s) URL`).
|
|
193
|
+
|
|
194
|
+
## Sources
|
|
195
|
+
|
|
196
|
+
Each source has a unique `id` and one of `path`, `url` or `postman`. The format is detected
|
|
197
|
+
from the content; `type` (`postman`, `openapi`, `swagger`) enforces it.
|
|
198
|
+
|
|
199
|
+
| Source | Example |
|
|
200
|
+
| ------------------- | ----------------------------------------------------------------------------------------- |
|
|
201
|
+
| File (JSON / YAML) | `{ "id": "core", "path": "./api/core.postman_collection.json" }` |
|
|
202
|
+
| URL | `{ "id": "pets", "url": "https://api.example.com/openapi.json" }` |
|
|
203
|
+
| URL with auth | `{ "id": "pets", "url": "…", "headers": { "Authorization": "Bearer ${SPEC_TOKEN}" } }` |
|
|
204
|
+
| Postman workspace | `{ "id": "cloud", "postman": { "collectionId": "12345-abcd" } }` (key: `POSTMAN_API_KEY`) |
|
|
205
|
+
| Postman environment | add `"environment": "./api/dev.postman_environment.json"` to resolve `{{baseUrl}}` |
|
|
206
|
+
|
|
207
|
+
`${VAR}` values come from the environment and are never written to disk.
|
|
208
|
+
|
|
209
|
+
## How duplicate requests are merged
|
|
210
|
+
|
|
211
|
+
Two requests are the same API when the method matches and the paths match after parameter
|
|
212
|
+
segments are normalised: `GET /users/:id`, `/users/{{userId}}`, `/users/42` and a UUID path are
|
|
213
|
+
one endpoint.
|
|
214
|
+
|
|
215
|
+
- **Name:** the OpenAPI `operationId`, else the most common Postman title without scenario
|
|
216
|
+
words (`Login – Success`, `Login (401)` → `login`), else method + path (`getUsersById`).
|
|
217
|
+
- **Responses:** 2xx examples form the success type; 4xx/5xx examples the error type per
|
|
218
|
+
status.
|
|
219
|
+
- **Request body:** bodies of all examples are merged; fields only some examples send become
|
|
220
|
+
optional.
|
|
221
|
+
- **Precedence:** OpenAPI schemas win over Postman examples. Clashing model names from
|
|
222
|
+
different specs are renamed `<SourceId><Name>`, with a warning.
|
|
223
|
+
|
|
224
|
+
`api-collection.json` records every endpoint with its origins, so merges can be reviewed in
|
|
225
|
+
pull requests.
|
|
226
|
+
|
|
227
|
+
## What gets generated
|
|
228
|
+
|
|
229
|
+
| File | Contents |
|
|
230
|
+
| --------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
231
|
+
| `api-collection.json` | The merged collection |
|
|
232
|
+
| `runtime.ts` | `createClient`, `ApiError`, retries, messages, logging, metrics, middleware, request controllers, HTTP library adapters |
|
|
233
|
+
| `types.ts` | Models and `XArgs` / `XResponse` / `XErrors` types per endpoint |
|
|
234
|
+
| `api.ts` | `createApi(client, options)` → `{ group: { endpoint } }`, plus the `Endpoints` map |
|
|
235
|
+
| bindings | `hooks.ts`, `composables.ts`, `angular.ts`, `stores.ts` or `primitives.ts` |
|
|
236
|
+
| `index.ts` | Re-exports (on Next.js, import hooks from `./hooks`) |
|
|
237
|
+
| `client.ts` | **Yours:** created once, never overwritten |
|
|
238
|
+
|
|
239
|
+
`runtime.ts` imports nothing: every HTTP library adapter is typed structurally, so it
|
|
240
|
+
compiles whether or not axios, Angular or react-native-fetch is installed. Endpoints get
|
|
241
|
+
defaults from the sources: `skipAuth` for requests that opt out of auth (Postman `noauth`,
|
|
242
|
+
OpenAPI `security: []`), and `contentType` / `responseType` for non-JSON bodies.
|
|
243
|
+
|
|
244
|
+
## Choosing the HTTP client
|
|
245
|
+
|
|
246
|
+
Pass the library you already use as `http`. Leave it out to use `fetch`. You can switch at any
|
|
247
|
+
time in `client.ts` without regenerating.
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
import axios from 'axios';
|
|
251
|
+
import { createApi, createClient } from './api';
|
|
252
|
+
|
|
253
|
+
createClient({ baseURL }); // fetch: browser, Node, Bun, Deno, edge, React Native
|
|
254
|
+
createClient({ baseURL, http: myFetch }); // any fetch-compatible function
|
|
255
|
+
createClient({ baseURL, http: axios }); // axios itself…
|
|
256
|
+
createClient({ baseURL, http: axios.create({ … }) }); // …or your instance: interceptors keep working
|
|
257
|
+
createClient({ http: createJutsuClient({ baseURL, ssl, auth }) }); // react-native-fetch: SSL pinning, token refresh
|
|
258
|
+
createClient({ baseURL, http: inject(HttpClient) }); // Angular: interceptors, XSRF
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
The library is recognised by its shape: axios by its interceptors, Angular's `HttpClient` by
|
|
262
|
+
`jsonp`, any other object with `request(method, url, options)` as a react-native-fetch
|
|
263
|
+
client, and a plain function as fetch. To name it explicitly, use `fetchTransport({ fetch, init })`,
|
|
264
|
+
`axiosTransport(instance)`, `reactNativeFetchTransport(client)` or
|
|
265
|
+
`angularHttpTransport(http)` as `transport`.
|
|
266
|
+
|
|
267
|
+
For any other library, write a small `transport` function:
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
import { createClient, encodeBody } from './api';
|
|
271
|
+
|
|
272
|
+
createClient({
|
|
273
|
+
baseURL,
|
|
274
|
+
transport: async (request) => {
|
|
275
|
+
const headers = { ...request.headers };
|
|
276
|
+
const body = encodeBody(request.body, request.contentType, headers); // JSON, form, text…
|
|
277
|
+
const res = await myHttp.send(request.method, request.url, {
|
|
278
|
+
headers,
|
|
279
|
+
body,
|
|
280
|
+
signal: request.signal,
|
|
281
|
+
});
|
|
282
|
+
return { status: res.status, headers: res.headers, data: res.body }; // every status, even 4xx/5xx
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Resolve for every HTTP status; throw only when no response arrived (offline, DNS). Return the
|
|
288
|
+
library's fields as they are: headers in any shape (mixed case, arrays, a `Headers` object),
|
|
289
|
+
and `data` as parsed data or JSON text, which the client parses when the response is JSON.
|
|
290
|
+
[docs/USAGE.md](docs/USAGE.md#recipes-for-popular-libraries) has tested recipes for ky, got,
|
|
291
|
+
superagent and ofetch.
|
|
292
|
+
|
|
293
|
+
The client (not the HTTP library) owns timeouts, retries, error mapping and messages, so they
|
|
294
|
+
behave the same whatever you pass. Library-specific options go in `adapterOptions` (axios
|
|
295
|
+
config, Angular options, react-native-fetch's `cachePolicy`, …).
|
|
296
|
+
|
|
297
|
+
## Middleware
|
|
298
|
+
|
|
299
|
+
Middleware wraps every attempt, between the client and the transport, so the same code works
|
|
300
|
+
with fetch, axios, react-native-fetch, Angular `HttpClient` or your own transport. It gets the
|
|
301
|
+
request and `next`, and resolves with the response:
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
import type { Middleware } from './api';
|
|
305
|
+
|
|
306
|
+
// change the request
|
|
307
|
+
const trace: Middleware = (request, next) =>
|
|
308
|
+
next({
|
|
309
|
+
...request,
|
|
310
|
+
headers: { ...request.headers, 'x-trace-id': crypto.randomUUID() },
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
// change the response, e.g. unwrap { data: … }
|
|
314
|
+
const unwrap: Middleware = async (request, next) => {
|
|
315
|
+
const response = await next(request);
|
|
316
|
+
const body = response.data as { data?: unknown } | null;
|
|
317
|
+
return { ...response, data: body?.data ?? response.data };
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
// repeat the request: refresh the token once on 401
|
|
321
|
+
const refreshOn401: Middleware = async (request, next) => {
|
|
322
|
+
const response = await next(request);
|
|
323
|
+
if (response.status !== 401 || request.skipAuth) return response;
|
|
324
|
+
const token = await session.refresh();
|
|
325
|
+
return next({
|
|
326
|
+
...request,
|
|
327
|
+
headers: { ...request.headers, authorization: 'Bearer ' + token },
|
|
328
|
+
});
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
// answer without the network (mocks, offline cache)
|
|
332
|
+
const mock: Middleware = async (request, next) =>
|
|
333
|
+
request.endpoint === 'products.list'
|
|
334
|
+
? { status: 200, headers: {}, data: fixtures.products }
|
|
335
|
+
: next(request);
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
Add it at any level. Levels add up (they don't replace each other) and run outermost first:
|
|
339
|
+
client, then endpoint, then call, then the transport.
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
const client = createClient({
|
|
343
|
+
http: axios,
|
|
344
|
+
middleware: [trace, refreshOn401, unwrap],
|
|
345
|
+
});
|
|
346
|
+
const api = createApi(client, {
|
|
347
|
+
endpoints: { 'products.list': { middleware: [mock] } },
|
|
348
|
+
});
|
|
349
|
+
await api.orders.list({ middleware: [timing] });
|
|
350
|
+
|
|
351
|
+
// or build a transport once and use it anywhere
|
|
352
|
+
const transport = applyMiddleware(fetchTransport(), [trace, unwrap]);
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
The contract is the transport's: resolve for every HTTP status, and throw only when there is no
|
|
356
|
+
response. The client then applies timeouts, retries (middleware runs on each attempt and sees
|
|
357
|
+
`request.attempt`), error mapping, messages, logging and metrics as usual. A middleware that
|
|
358
|
+
throws gives a `NETWORK` error with the cause in `originalError`. A middleware that hangs still
|
|
359
|
+
times out. If a middleware sends a request to an origin that isn't trusted (see
|
|
360
|
+
[Credentials](#credentials-and-other-origins)), the client's token and headers are removed
|
|
361
|
+
before it goes out.
|
|
362
|
+
|
|
363
|
+
Middleware or `onRequest`? `onRequest` can only change headers, while middleware can also
|
|
364
|
+
change the response, repeat or short-circuit a call. Your HTTP library's own interceptors
|
|
365
|
+
(axios, Angular) keep working too, inside the transport.
|
|
366
|
+
|
|
367
|
+
## Per-API control
|
|
368
|
+
|
|
369
|
+
Every option works at three levels: **client** (`createClient`), **endpoint**
|
|
370
|
+
(`createApi(client, { endpoints })`, type-checked against your API) and **call** (the args of
|
|
371
|
+
one call). The more specific level wins.
|
|
372
|
+
|
|
373
|
+
```ts
|
|
374
|
+
export const client = createClient({
|
|
375
|
+
baseURL: 'https://api.example.com',
|
|
376
|
+
getToken: () => session.token, // Bearer header unless the endpoint skips auth
|
|
377
|
+
timeoutMs: 15_000, // per attempt (default 30 s)
|
|
378
|
+
retry: true, // see Retries
|
|
379
|
+
logger: import.meta.env.DEV, // see Logging
|
|
380
|
+
slowRequestMs: 2_000,
|
|
381
|
+
onMetrics: (m) => analytics.track('api_call', m),
|
|
382
|
+
onLoadingChange: (pending) => progressBar.toggle(pending > 0),
|
|
383
|
+
messages: { 401: 'Your session expired. Please sign in again.' },
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
export const api = createApi(client, {
|
|
387
|
+
endpoints: {
|
|
388
|
+
'auth.login': { messages: { 401: 'Wrong email or password.' }, log: false },
|
|
389
|
+
'products.list': { retry: 3, fallback: () => cachedProducts() },
|
|
390
|
+
'payments.charge': { timeoutMs: 60_000 },
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
await api.products.get({
|
|
395
|
+
params: { id },
|
|
396
|
+
timeoutMs: 5_000,
|
|
397
|
+
messages: { 404: 'This product is gone.' },
|
|
398
|
+
});
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
### Error handling and messages
|
|
402
|
+
|
|
403
|
+
Every failure is an `ApiError` with `kind` (`HTTP`, `NETWORK`, `TIMEOUT`, `ABORTED`, `PARSE`),
|
|
404
|
+
`status`, `data`, `headers`, `endpoint` and `userMessage`, a text safe to show people.
|
|
405
|
+
|
|
406
|
+
- `messages` maps an exact status (`404`), a class (`'4XX'`, `'5XX'`), a kind (`'NETWORK'`,
|
|
407
|
+
`'TIMEOUT'`) or `'default'` to a string or a function. Built-in English defaults cover the
|
|
408
|
+
rest (`defaultErrorMessages`).
|
|
409
|
+
- Server error text is **not** shown by default. Opt in with
|
|
410
|
+
`messageFromResponse: (e) => e.data?.message`.
|
|
411
|
+
- `getErrorMessage(error)` returns a message for anything thrown; `errorOf(error)` returns the
|
|
412
|
+
typed body of a documented error response.
|
|
413
|
+
- `ApiError.message` and `JSON.stringify(error)` leave out the query string, the response body
|
|
414
|
+
and response headers (`Set-Cookie`), so they stay out of logs and error trackers. The fields
|
|
415
|
+
themselves (`error.data`, `error.headers`) are still there in code.
|
|
416
|
+
|
|
417
|
+
### Retries
|
|
418
|
+
|
|
419
|
+
`retry: true` retries network errors, timeouts and 408 / 429 / 500 / 502 / 503 / 504 up to 2
|
|
420
|
+
times, with exponential back-off and jitter, honouring `Retry-After`.
|
|
421
|
+
|
|
422
|
+
- Only idempotent methods (GET, HEAD, OPTIONS, PUT, DELETE) are retried, plus calls with an
|
|
423
|
+
`idempotencyKey` (sent as `Idempotency-Key`). A payment is never sent twice by accident.
|
|
424
|
+
- `retry: 3` sets the attempts; `{ attempts, delayMs, maxDelayMs, retryOn }` gives full
|
|
425
|
+
control. Even a custom `retryOn` cannot retry a POST or PATCH that has no `idempotencyKey`.
|
|
426
|
+
- Cancelled calls are never retried; a cancel during back-off stops at once.
|
|
427
|
+
|
|
428
|
+
### Fallbacks
|
|
429
|
+
|
|
430
|
+
`fallback: (error) => value` resolves with a value instead of throwing, for example a cached
|
|
431
|
+
list when the server is down. It is typed against the endpoint's response.
|
|
432
|
+
|
|
433
|
+
- `.raw()` returns `fromFallback: true` and every binding's state has `fromFallback`, so the UI
|
|
434
|
+
can mark the data as stale or offline. Metrics count it too.
|
|
435
|
+
- A fallback never runs for cancelled calls. A fallback that throws replaces the error.
|
|
436
|
+
|
|
437
|
+
### Logging
|
|
438
|
+
|
|
439
|
+
`logger: true` logs to the console; any object with `debug` / `info` / `warn` / `error` works
|
|
440
|
+
(pino, Sentry breadcrumbs, …).
|
|
441
|
+
|
|
442
|
+
- `logLevel` defaults to `'info'`.
|
|
443
|
+
- Logs show the method, path template, status and duration. Headers such as `Authorization`,
|
|
444
|
+
`Cookie` and `X-Api-Key` are `[redacted]` (`redactHeaders` sets the list). Query strings
|
|
445
|
+
and bodies are left out unless `logBodies: true`.
|
|
446
|
+
- `logBodies` is for development only: bodies can hold passwords and tokens. Keep `log: false`
|
|
447
|
+
on auth endpoints if you turn it on.
|
|
448
|
+
- `log: false` silences one endpoint or call.
|
|
449
|
+
- A logger that throws never breaks a request.
|
|
450
|
+
|
|
451
|
+
### Performance
|
|
452
|
+
|
|
453
|
+
`onMetrics` receives every call: `endpoint`, `method`, `path` (template, no ids), `status`,
|
|
454
|
+
`ok`, `errorKind`, `durationMs`, `attempts`, `fromFallback` and `slow`. Calls slower than
|
|
455
|
+
`slowRequestMs` are also logged as warnings. `.raw()` exposes `durationMs` and `attempts`.
|
|
456
|
+
|
|
457
|
+
### Loading state
|
|
458
|
+
|
|
459
|
+
- **Global:** `onLoadingChange(pending)`, `client.pending` and `client.subscribe(listener)`;
|
|
460
|
+
each binding has a `usePendingRequests` / `injectPendingRequests` / `pendingRequests`
|
|
461
|
+
helper.
|
|
462
|
+
- **Per call:** `onLoading: (loading) => …` runs with `true` when the call starts and `false`
|
|
463
|
+
when it settles, failures included.
|
|
464
|
+
- **Per component:** the bindings below return `status`, `isLoading`, `isError`, `isSuccess`,
|
|
465
|
+
`data`, `error`, `fromFallback` and `refetch`.
|
|
466
|
+
|
|
467
|
+
### Credentials and other origins
|
|
468
|
+
|
|
469
|
+
`getToken` and the client `headers` go only to relative URLs and to `baseURL`'s origin. Any
|
|
470
|
+
other absolute URL, such as a presigned upload or a third-party API, gets only the headers of
|
|
471
|
+
that call. List extra origins that should receive them in `trustedOrigins`:
|
|
472
|
+
|
|
473
|
+
```ts
|
|
474
|
+
createClient({
|
|
475
|
+
baseURL,
|
|
476
|
+
transport,
|
|
477
|
+
getToken,
|
|
478
|
+
trustedOrigins: ['https://files.example.com'],
|
|
479
|
+
});
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
`timeoutMs` and retry delays are validated: a negative or non-numeric value uses the default
|
|
483
|
+
instead of turning the timeout off (`0` turns it off), and very large values are capped.
|
|
484
|
+
|
|
485
|
+
### Hooks and callbacks
|
|
486
|
+
|
|
487
|
+
`onRequest(request)` runs before each attempt and may add headers (trace ids). `onResponse` and
|
|
488
|
+
`onError` observe results. Observers that throw are ignored, so they can't break a call.
|
|
489
|
+
|
|
490
|
+
## Framework bindings
|
|
491
|
+
|
|
492
|
+
All bindings wrap the same `createQueryController` / `createMutationController`.
|
|
493
|
+
|
|
494
|
+
- **Queries** (GET / HEAD / OPTIONS) refetch when their args change by value, abort the
|
|
495
|
+
previous call, ignore stale responses and keep the last data while reloading.
|
|
496
|
+
- **Mutations** expose `run` (never rejects), `runAsync` and `reset`. The `dedupe` option
|
|
497
|
+
blocks double submits; it is off by default because concurrent writes (toggles) are
|
|
498
|
+
sometimes intended.
|
|
499
|
+
- **Query options:** `enabled`, `keepPreviousData`, `onSuccess`, `onError`, `onSettled`.
|
|
500
|
+
Mutations take the same callbacks plus `dedupe`.
|
|
501
|
+
- Every binding also accepts `configureApi(client)` for apps with one client.
|
|
502
|
+
|
|
503
|
+
### React and React Native
|
|
504
|
+
|
|
505
|
+
```tsx
|
|
506
|
+
<ApiProvider client={client}>
|
|
507
|
+
<App />
|
|
508
|
+
</ApiProvider>;
|
|
509
|
+
|
|
510
|
+
const user = useGetUser({ params: { id } }, { enabled: !!id });
|
|
511
|
+
const login = useLogin({ onSuccess: () => navigate('/home') });
|
|
512
|
+
const busy = usePendingRequests();
|
|
513
|
+
if (user.isLoading) return <Spinner />;
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
On React Native, `httpClient: "react-native-fetch"` keeps SSL pinning and token refresh:
|
|
517
|
+
|
|
518
|
+
```ts
|
|
519
|
+
const jutsu = createJutsuClient({
|
|
520
|
+
baseURL: 'https://api.example.com',
|
|
521
|
+
auth: {
|
|
522
|
+
tokenStore: createMemoryTokenStore(),
|
|
523
|
+
refresh: {
|
|
524
|
+
handler: async ({ refreshToken, http }) => {
|
|
525
|
+
// the refresh handler's `http` bypasses auth, so it can call a generated endpoint
|
|
526
|
+
const refreshApi = createApi(createClient({ http }));
|
|
527
|
+
const t = await refreshApi.auth.refreshSession({
|
|
528
|
+
body: { refreshToken: refreshToken ?? '' },
|
|
529
|
+
});
|
|
530
|
+
return { accessToken: t.accessToken, refreshToken: t.refreshToken };
|
|
531
|
+
},
|
|
532
|
+
},
|
|
533
|
+
},
|
|
534
|
+
});
|
|
535
|
+
export const client = createClient({ http: jutsu });
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
`fetch` and `axios` work on React Native too. Multipart file parts are `{ uri, name, type }`.
|
|
539
|
+
|
|
540
|
+
### Next.js
|
|
541
|
+
|
|
542
|
+
Endpoints are plain async functions, usable in Server Components, Route Handlers and Server
|
|
543
|
+
Actions. With Cache Components (the Next.js 16 default), cache a call in a `'use cache'`
|
|
544
|
+
function:
|
|
545
|
+
|
|
546
|
+
```ts
|
|
547
|
+
export async function getPets() {
|
|
548
|
+
'use cache';
|
|
549
|
+
cacheLife('minutes');
|
|
550
|
+
cacheTag('pets');
|
|
551
|
+
return api.pets.listPets();
|
|
552
|
+
}
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
Without Cache Components, pass `init: { next: { revalidate: 60, tags: ['pets'] } }`.
|
|
556
|
+
`hooks.ts` starts with `'use client'`; import it from `@/lib/api/hooks`. The scaffolded
|
|
557
|
+
`client.ts` reads `NEXT_PUBLIC_API_BASE_URL`. On the server, pass per-request tokens with
|
|
558
|
+
`headers` rather than module state.
|
|
559
|
+
|
|
560
|
+
### Vue 3.3+ (and Nuxt)
|
|
561
|
+
|
|
562
|
+
```ts
|
|
563
|
+
app.use(createApiPlugin(client)); // or provideApi(client) in a parent's setup()
|
|
564
|
+
|
|
565
|
+
const id = ref(1);
|
|
566
|
+
const user = useGetUser(() => ({ params: { id: id.value } })); // refs, getters or values
|
|
567
|
+
user.data.value;
|
|
568
|
+
user.isLoading.value;
|
|
569
|
+
user.refetch();
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
Composables are disposed with their effect scope, which aborts calls in flight.
|
|
573
|
+
|
|
574
|
+
### Angular 17+
|
|
575
|
+
|
|
576
|
+
```ts
|
|
577
|
+
// app.config.ts
|
|
578
|
+
providers: [provideHttpClient(withInterceptors([authInterceptor])), provideApi(createAppClient)];
|
|
579
|
+
|
|
580
|
+
// a component or service (injection context)
|
|
581
|
+
readonly id = signal(1);
|
|
582
|
+
readonly user = injectGetUser(() => ({ params: { id: this.id() } })); // signals in, signals out
|
|
583
|
+
readonly save = injectUpdateUser({ onSuccess: () => this.user.refetch() });
|
|
584
|
+
// template: @if (user.isLoading()) { … } {{ user.data()?.name }}
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
With `httpClient: "angular"`, calls go through `HttpClient`, so interceptors and XSRF
|
|
588
|
+
protection apply. `injectApi()` returns the api object; `from(api.users.getUser(…))` turns a
|
|
589
|
+
call into an Observable.
|
|
590
|
+
|
|
591
|
+
### Svelte 4 / 5 (and SvelteKit)
|
|
592
|
+
|
|
593
|
+
```svelte
|
|
594
|
+
<script>
|
|
595
|
+
import { derived, writable } from 'svelte/store';
|
|
596
|
+
import { createGetUser, setApiContext } from '$lib/api';
|
|
597
|
+
const id = writable(1);
|
|
598
|
+
const user = createGetUser(derived(id, (id) => ({ params: { id } })));
|
|
599
|
+
</script>
|
|
600
|
+
|
|
601
|
+
{#if $user.isLoading}…{:else}{$user.data?.name}{/if}
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
Call `setApiContext(client)` in a root component, or `configureApi(client)` once. Stores run
|
|
605
|
+
while subscribed and abort when the last subscriber leaves. In SvelteKit `load` functions,
|
|
606
|
+
call `api` directly.
|
|
607
|
+
|
|
608
|
+
### SolidJS 1.8+ and 2.x
|
|
609
|
+
|
|
610
|
+
```tsx
|
|
611
|
+
const value = apiContextValue(client);
|
|
612
|
+
<ApiContext.Provider value={value}>
|
|
613
|
+
<App />
|
|
614
|
+
</ApiContext.Provider>; // Solid 2: <ApiContext value={value}>
|
|
615
|
+
|
|
616
|
+
const [id, setId] = createSignal(1);
|
|
617
|
+
const user = createGetUser(() => ({ params: { id: id() } }));
|
|
618
|
+
user.data();
|
|
619
|
+
user.isLoading();
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
### Plain TypeScript / JavaScript (`framework: "none"`)
|
|
623
|
+
|
|
624
|
+
Use `api` directly. For another UI library (Lit, Qwik, Preact signals, …), bind
|
|
625
|
+
`createQueryController` / `createMutationController` from `runtime.ts`. Each has
|
|
626
|
+
`getState()` and `subscribe()`.
|
|
627
|
+
|
|
628
|
+
## Using the generated API
|
|
629
|
+
|
|
630
|
+
```ts
|
|
631
|
+
await api.users.getUser({ params: { id: 1 } }); // data
|
|
632
|
+
await api.users.getUser.raw({ params: { id: 1 } }); // { data, status, headers, durationMs, attempts, fromFallback }
|
|
633
|
+
api.users.getUser.errorOf(error); // typed documented error, or undefined
|
|
634
|
+
api.users.getUser.id; // 'users.getUser', the key in createApi(client, { endpoints })
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
`params`, `query` and `body` are required exactly when the API needs them. `errorOf(error)`
|
|
638
|
+
returns `{ status, data }` for documented error responses and `undefined` for anything else.
|
|
639
|
+
A `4XX` / `5XX` response matches any status of that class, and `default` matches any error status.
|
|
640
|
+
|
|
641
|
+
## Caching
|
|
642
|
+
|
|
643
|
+
A run is skipped when the generator version, the config and every source's content hash match
|
|
644
|
+
the last run and the generated files are untouched. The state lives in
|
|
645
|
+
`.jutsu-api/<project>/manifest.json`.
|
|
646
|
+
|
|
647
|
+
- URLs are fetched with `If-None-Match` / `If-Modified-Since`; a 304 reuses the saved copy.
|
|
648
|
+
- Network errors and 5xx fall back to the saved copy with a warning; 4xx fails.
|
|
649
|
+
- `--offline` uses only saved copies.
|
|
650
|
+
- Only files whose content changed are rewritten.
|
|
651
|
+
|
|
652
|
+
Each generated file carries a `// @checksum sha256:…` header. If a generated file was edited,
|
|
653
|
+
or a file with the same name was not created by the tool, generation stops and lists it. Move
|
|
654
|
+
the change to `client.ts`, or use `--force`.
|
|
655
|
+
|
|
656
|
+
## CLI
|
|
657
|
+
|
|
658
|
+
```text
|
|
659
|
+
jutsu-api [generate|check|collect|init] [options]
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
| Command | Description |
|
|
663
|
+
| ---------- | ------------------------------------------------------------------------------------ |
|
|
664
|
+
| `generate` | Build the collection and the client (default) |
|
|
665
|
+
| `check` | Exit 1 when generated files are out of date (CI) |
|
|
666
|
+
| `collect` | Only build `api-collection.json` |
|
|
667
|
+
| `init` | Create the config (`--name`, `--framework`, `--http-client`, `--source`, `--output`) |
|
|
668
|
+
|
|
669
|
+
Options: `-c, --config <file>`, `--cwd <dir>`, `-f, --force`, `--offline`, `--dry-run`,
|
|
670
|
+
`-q, --quiet`, `-v, --verbose`. Exit codes: `0` ok, `1` failure or stale, `2` usage / config
|
|
671
|
+
error.
|
|
672
|
+
|
|
673
|
+
In CI, commit the generated files and run `npx jutsu-api check`. It regenerates in memory
|
|
674
|
+
and ignores the cache. Remote sources need network access and their secrets in CI.
|
|
675
|
+
|
|
676
|
+
The same functions are exported for scripts, from `import` and `require` alike: `generate`,
|
|
677
|
+
`check`, `collect`, `init`, `detectFramework`, `detectHttpClient`, plus `parsePostman`,
|
|
678
|
+
`parseOpenApi`, `buildCollection` and `emitFiles`.
|
|
679
|
+
|
|
680
|
+
## Migrating from 0.1
|
|
681
|
+
|
|
682
|
+
0.2 makes the HTTP client your choice, so the generated code no longer depends on any library.
|
|
683
|
+
|
|
684
|
+
1. **Config:** replace `"target"` with `"framework"` and add `"httpClient"`.
|
|
685
|
+
- `react-native` becomes `"framework": "react-native"` + `"httpClient": "react-native-fetch"`.
|
|
686
|
+
- `react` / `next` become `"framework": "react"` / `"next"` + `"httpClient": "fetch"`.
|
|
687
|
+
|
|
688
|
+
Old configs still load, with a warning, and map exactly this way.
|
|
689
|
+
|
|
690
|
+
2. **`client.ts`** is yours, so it isn't regenerated. Wrap your client in `createClient`.
|
|
691
|
+
- Web: `createFetchClient({ … })` becomes `createClient({ … })`. A custom `fetch` becomes
|
|
692
|
+
`http: myFetch`; `init` moves to `transport: fetchTransport({ fetch, init })`.
|
|
693
|
+
- React Native: `createApi(createJutsuClient(…))` becomes
|
|
694
|
+
`createApi(createClient({ http: createJutsuClient(…) }))`.
|
|
695
|
+
|
|
696
|
+
Delete `client.ts` and regenerate to get the new scaffold.
|
|
697
|
+
|
|
698
|
+
3. **React Native hooks** now come from the generated `ApiProvider` (no `<JutsuProvider>`
|
|
699
|
+
needed for them). The `optimistic` mutation option is gone; use `onSuccess` / `onError`.
|
|
700
|
+
4. React Native call options that belong to the library (`cachePolicy`, `tag`, `dedupe`) move
|
|
701
|
+
into `adapterOptions`. `idempotencyKey`, `skipAuth`, `timeoutMs` and `signal` stay where
|
|
702
|
+
they are.
|
|
703
|
+
|
|
704
|
+
## Security
|
|
705
|
+
|
|
706
|
+
- Strings from specs are escaped before they reach generated code; identifiers are reduced
|
|
707
|
+
to `[A-Za-z0-9_$]`.
|
|
708
|
+
- API keys and `${VAR}` headers are never written to disk or logs, and are not forwarded on
|
|
709
|
+
redirects to another origin. URLs with embedded credentials are rejected.
|
|
710
|
+
- Output and cache folders must be inside the project.
|
|
711
|
+
- Downloads are capped at 50 MB and 30 s; YAML aliases and schema depth are limited.
|
|
712
|
+
- Generated runtime:
|
|
713
|
+
- Logs redact credentials and leave out bodies and query strings by default.
|
|
714
|
+
- Header values with line breaks are rejected (header injection).
|
|
715
|
+
- `.` / `..` path params are rejected (path traversal).
|
|
716
|
+
- Server error text is not shown to people unless you opt in.
|
|
717
|
+
- Non-idempotent requests are not retried without an idempotency key.
|
|
718
|
+
- The token and client headers never reach origins you did not trust.
|
|
719
|
+
- Serialised errors carry no response bodies, `Set-Cookie` or query strings.
|
|
720
|
+
|
|
721
|
+
Report vulnerabilities privately; see [SECURITY.md](SECURITY.md). The latest quality and
|
|
722
|
+
security audit is in [testcase.md](testcase.md).
|
|
723
|
+
|
|
724
|
+
## Troubleshooting
|
|
725
|
+
|
|
726
|
+
| Message / symptom | Fix |
|
|
727
|
+
| --------------------------------------- | ----------------------------------------------------------------------------------- |
|
|
728
|
+
| `No <project>-api.config.json` | Run `npx jutsu-api init` or pass `--config` |
|
|
729
|
+
| `generated file(s) were edited by hand` | Move the change to `client.ts`, then `--force` |
|
|
730
|
+
| `Source "x" … answered 401` | Check `headers` / `POSTMAN_API_KEY`; `--offline` uses the saved copy |
|
|
731
|
+
| `segment "{name}.{ext}" mixes text …` | Pass the whole segment as one param, e.g. `nameAndExt: 'a.pdf'` |
|
|
732
|
+
| A Postman field is `unknown` | Its example was `{{variable}}` or `null`; save a real example |
|
|
733
|
+
| Imports fail with `NodeNext` | Set `"importExtension": ".js"` |
|
|
734
|
+
| `No API client: …` | Add the provider / plugin the message names, or call `configureApi` |
|
|
735
|
+
| `"target" is deprecated` | Replace it with `framework` (and `httpClient`), see [Migrating](#migrating-from-01) |
|
|
736
|
+
|
|
737
|
+
## Examples
|
|
738
|
+
|
|
739
|
+
[`examples/shop-app`](examples/shop-app) is the generated output for a Postman collection
|
|
740
|
+
plus an OpenAPI document; CI checks that it is up to date.
|
|
741
|
+
|
|
742
|
+
[`examples/demo`](examples/demo) generates one Postman collection for the public
|
|
743
|
+
[dummyjson.com](https://dummyjson.com) API into React Native, React and Next.js apps, with
|
|
744
|
+
live tests against the real API. Run them with `examples/demo/verify.sh` (Node 22).
|
|
745
|
+
|
|
746
|
+
## Development
|
|
747
|
+
|
|
748
|
+
```bash
|
|
749
|
+
yarn install
|
|
750
|
+
yarn verify # lint, typecheck, tests, ESM + CJS build, CLI smoke test, tarball check
|
|
751
|
+
yarn smoke:pm # pack, install and run with npm, pnpm, yarn and bun
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
`src/parsers` reads sources, `src/collect` merges them into the collection, `src/codegen`
|
|
755
|
+
writes the files, and `src/generate.ts` handles caching and writes.
|
|
756
|
+
|
|
757
|
+
- `test/typecheck.test.ts` compiles the generated code for every framework and HTTP client
|
|
758
|
+
under strict settings, against the real axios, Angular, Vue, Svelte, Solid 1 and 2 and
|
|
759
|
+
React types.
|
|
760
|
+
- `test/runtime.test.ts` and `test/bindings*.test.ts` run the generated code in Node, React 19
|
|
761
|
+
(StrictMode), Vue and Svelte.
|
|
762
|
+
|
|
763
|
+
## License
|
|
764
|
+
|
|
765
|
+
MIT © JutsuStack
|