@moccona/apicodegen 0.1.1 → 1.0.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/README.md +517 -121
- package/bin/cli.cjs +15 -12
- package/npm/index.cjs +2520 -1025
- package/npm/index.cjs.map +1 -1
- package/npm/index.d.cts +409 -93
- package/npm/index.d.cts.map +1 -1
- package/npm/index.d.mts +409 -93
- package/npm/index.d.mts.map +1 -1
- package/npm/index.mjs +2390 -904
- package/npm/index.mjs.map +1 -1
- package/npm/vite/index.d.mts +38 -10
- package/npm/vite/index.d.mts.map +1 -1
- package/npm/vite/index.mjs +2140 -648
- package/npm/vite/index.mjs.map +1 -1
- package/package.json +41 -22
package/README.md
CHANGED
|
@@ -1,28 +1,88 @@
|
|
|
1
1
|
# @moccona/apicodegen
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The minimal, zero-config OpenAPI → TypeScript client generator. One output
|
|
4
|
+
file, no runtime dependencies, native Vite plugin, and a `--check` mode built
|
|
5
|
+
for CI. Generated code is predictable and JSDoc-rich, so it works well for
|
|
6
|
+
humans and AI assistants alike.
|
|
7
|
+
|
|
8
|
+
New here? See [How apicodegen compares](docs/comparison.md) and
|
|
9
|
+
[Upgrading from 0.1.x](docs/UPGRADING.md).
|
|
4
10
|
|
|
5
11
|
[](https://www.npmjs.com/package/@moccona/apicodegen)
|
|
6
12
|
[](https://opensource.org/licenses/MIT)
|
|
7
|
-
[](https://nodejs.org)
|
|
14
|
+
[](https://github.com/freemode1614/api-codegen)
|
|
15
|
+
[](https://github.com/freemode1614/api-codegen)
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Table of Contents
|
|
20
|
+
|
|
21
|
+
- [Features](#-features)
|
|
22
|
+
- [Quick Start](#-quick-start)
|
|
23
|
+
- [Installation](#-installation)
|
|
24
|
+
- [CLI Usage](#-cli-usage)
|
|
25
|
+
- [Vite Plugin](#-vite-plugin)
|
|
26
|
+
- [Bring Your Own HTTP Client](#bring-your-own-http-client)
|
|
27
|
+
- [Generated Code](#-generated-code)
|
|
28
|
+
- [Supported Features](#-supported-features)
|
|
29
|
+
- [Examples](#-examples)
|
|
30
|
+
- [Troubleshooting](#-troubleshooting)
|
|
31
|
+
- [Development](#-development)
|
|
32
|
+
- [Roadmap](#-roadmap)
|
|
33
|
+
|
|
34
|
+
---
|
|
8
35
|
|
|
9
36
|
## ✨ Features
|
|
10
37
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
38
|
+
| Feature | Description |
|
|
39
|
+
|---------|-------------|
|
|
40
|
+
| **Multi-version Support** | Core support for OpenAPI 2.0, 3.0, and 3.1 (see [Roadmap](ROADMAP.md) for gaps) |
|
|
41
|
+
| **JSON and YAML Specs** | Local files and remote URLs, with structured parse errors |
|
|
42
|
+
| **TypeScript First** | Generates complete type definitions and type-safe API functions |
|
|
43
|
+
| **Multiple Adaptors** | Built-in `fetch` and `axios` HTTP client support |
|
|
44
|
+
| **Auto Base URL** | Uses the spec's first `servers` entry (or V2 `host`) when `baseURL` is omitted |
|
|
45
|
+
| **Typed Response Maps** | 2xx return type plus an exported map of every declared status code |
|
|
46
|
+
| **CLI Tool** | Simple command-line interface with retro ASCII banner |
|
|
47
|
+
| **Vite Plugin** | Seamless integration into Vite build workflow |
|
|
48
|
+
| **File Upload** | Native support for multipart/form-data file uploads |
|
|
49
|
+
| **Complete Types** | Enums, union types, intersection types, complex nested objects |
|
|
50
|
+
|
|
51
|
+
### Key Highlights
|
|
52
|
+
|
|
53
|
+
- **Zero Runtime Dependencies** - Lightweight generated code with no external runtime
|
|
54
|
+
- **Zero Config** - A spec path and an output path are enough; the server URL comes from the spec
|
|
55
|
+
- **AI Friendly** - Predictable names, JSDoc from the spec, and one file that is easy to read or patch
|
|
56
|
+
- **CI Friendly** - `--check` fails the build when the committed client drifts, without writing files
|
|
57
|
+
- **Type-safe** - Full TypeScript support with strict type inference
|
|
58
|
+
- **Circular Reference Handling** - Properly handles `$ref` loops in OpenAPI schemas
|
|
59
|
+
- **JSDoc Generation** - Automatic documentation from OpenAPI descriptions
|
|
60
|
+
- **Watch Mode** - Auto-regenerate when OpenAPI spec changes
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 🚀 Quick Start
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Install globally
|
|
68
|
+
npm install -g @moccona/apicodegen
|
|
69
|
+
|
|
70
|
+
# Generate from URL
|
|
71
|
+
apicodegen https://petstore3.swagger.io/api/v3/openapi.json -o ./src/api/petstore.ts
|
|
72
|
+
|
|
73
|
+
# Or use npx (no installation)
|
|
74
|
+
npx @moccona/apicodegen ./openapi.json -o ./src/api.ts
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
---
|
|
18
78
|
|
|
19
79
|
## 📦 Installation
|
|
20
80
|
|
|
21
81
|
```bash
|
|
22
|
-
# Global installation (recommended for CLI
|
|
82
|
+
# Global installation (recommended for CLI)
|
|
23
83
|
npm install -g @moccona/apicodegen
|
|
24
84
|
|
|
25
|
-
# Local installation
|
|
85
|
+
# Local installation for project use
|
|
26
86
|
npm install -D @moccona/apicodegen
|
|
27
87
|
|
|
28
88
|
# Using pnpm
|
|
@@ -31,71 +91,232 @@ pnpm add -D @moccona/apicodegen
|
|
|
31
91
|
|
|
32
92
|
### Peer Dependencies
|
|
33
93
|
|
|
34
|
-
|
|
94
|
+
| Package | Version | Required For |
|
|
95
|
+
|---------|---------|--------------|
|
|
96
|
+
| `typescript` | v5 | Type checking generated code |
|
|
97
|
+
| `prettier` | v3 | Formatting output |
|
|
98
|
+
| `vite` | v7 / v8 | Vite plugin only (optional) |
|
|
35
99
|
|
|
36
|
-
|
|
37
|
-
- `prettier` (v3) - Used for formatting output
|
|
38
|
-
- `vite` (v7) - Required only if using the Vite plugin
|
|
39
|
-
|
|
40
|
-
## 🚀 Quick Start
|
|
41
|
-
|
|
42
|
-
### CLI Usage
|
|
43
|
-
|
|
44
|
-
```bash
|
|
45
|
-
# Basic usage
|
|
46
|
-
apicodegen <OpenAPI文档URL> -o ./src/api.ts
|
|
100
|
+
---
|
|
47
101
|
|
|
48
|
-
|
|
49
|
-
apicodegen https://api.example.com/openapi.json \
|
|
50
|
-
-o ./src/api.ts \
|
|
51
|
-
-a fetch \
|
|
52
|
-
-b https://api.example.com \
|
|
53
|
-
-v
|
|
54
|
-
```
|
|
102
|
+
## 📋 CLI Usage
|
|
55
103
|
|
|
56
|
-
### Options
|
|
104
|
+
### Basic Options
|
|
57
105
|
|
|
58
106
|
| Option | Short | Description | Default |
|
|
59
107
|
|--------|-------|-------------|---------|
|
|
60
108
|
| `--output` | `-o` | Output file path | `./output.ts` |
|
|
61
|
-
| `--spec` | `-s` | OpenAPI spec file path or URL |
|
|
62
|
-
| `--adaptor` | `-a` | HTTP client
|
|
63
|
-
| `--
|
|
109
|
+
| `--spec` | `-s` | OpenAPI spec file path or URL | Required |
|
|
110
|
+
| `--adaptor` | `-a` | HTTP client (`fetch` or `axios`) | `fetch` |
|
|
111
|
+
| `--importClientSource` | | Import line prepended to the output; required when `--adaptor axios` | none |
|
|
112
|
+
| `--baseURL` | `-b` | API base URL; `""` disables server-URL inference (default: the spec's first server) | - |
|
|
113
|
+
| `--error-mode` | | Non-2xx handling (`throw` or `result`) | as-is |
|
|
114
|
+
| `--split-by` | | Split output (`tag`); `--output` becomes a directory | single file |
|
|
115
|
+
| `--include-tags` | | Only generate operations with these comma-separated tags | all |
|
|
116
|
+
| `--exclude-tags` | | Skip operations with these comma-separated tags | none |
|
|
117
|
+
| `--include-paths` | | Only generate paths with these comma-separated prefixes | all |
|
|
118
|
+
| `--exclude-paths` | | Skip paths with these comma-separated prefixes | none |
|
|
119
|
+
| `--header` | | Extra header for spec fetch, `"Key: Value"` (repeatable) | none |
|
|
120
|
+
| `--timeout` | | Spec fetch timeout in milliseconds | - |
|
|
121
|
+
| `--insecure` | | Skip TLS verification when fetching the spec | `false` |
|
|
64
122
|
| `--config` | `-c` | Path to config file | - |
|
|
65
|
-
| `--watch` | `-w` | Watch for file changes |
|
|
123
|
+
| `--watch` | `-w` | Watch for file changes | `false` |
|
|
124
|
+
| `--check` | | Exit non-zero if output is out of date; never writes | `false` |
|
|
125
|
+
| `--typecheck` | | Type-check the generated output | `false` |
|
|
66
126
|
| `--verbose` | `-v` | Enable verbose logging | `false` |
|
|
67
127
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
### 1. Basic Code Generation
|
|
128
|
+
### Examples
|
|
71
129
|
|
|
72
130
|
```bash
|
|
73
|
-
# From remote
|
|
74
|
-
apicodegen https://
|
|
131
|
+
# From remote URL
|
|
132
|
+
apicodegen https://api.example.com/openapi.json -o ./src/api.ts
|
|
75
133
|
|
|
76
134
|
# From local file
|
|
77
135
|
apicodegen ./docs/openapi.json -o ./src/generated/api.ts
|
|
136
|
+
|
|
137
|
+
# With axios and custom baseURL (provide the client import, see "Bring Your Own HTTP Client")
|
|
138
|
+
apicodegen ./openapi.json -a axios \
|
|
139
|
+
--importClientSource "import axios from 'axios'" \
|
|
140
|
+
-b https://api.example.com -o ./src/api.ts
|
|
141
|
+
|
|
142
|
+
# Watch mode for development
|
|
143
|
+
apicodegen ./openapi.json -w -o ./src/api.ts -v
|
|
144
|
+
|
|
145
|
+
# One file per tag: types.ts, pets.ts, store.ts, index.ts
|
|
146
|
+
apicodegen ./openapi.json --split-by tag -o ./src/api
|
|
147
|
+
|
|
148
|
+
# Type-check the generated client
|
|
149
|
+
apicodegen ./openapi.json -o ./src/api.ts --typecheck
|
|
150
|
+
|
|
151
|
+
# CI: fail when the committed client is out of date
|
|
152
|
+
apicodegen ./openapi.json -o ./src/api.ts --check
|
|
153
|
+
|
|
154
|
+
# Authenticated, slow, or self-signed spec URL
|
|
155
|
+
apicodegen https://internal.example.com/openapi.json \
|
|
156
|
+
--header "Authorization: Bearer $TOKEN" \
|
|
157
|
+
--timeout 30000 --insecure \
|
|
158
|
+
-o ./src/api.ts
|
|
78
159
|
```
|
|
79
160
|
|
|
80
|
-
###
|
|
161
|
+
### CI drift check
|
|
162
|
+
|
|
163
|
+
Run generation with `--check` instead of writing. It compares the committed
|
|
164
|
+
client with a fresh generation and exits non-zero when it is missing or stale:
|
|
165
|
+
|
|
166
|
+
```yaml
|
|
167
|
+
# .github/workflows/api.yml
|
|
168
|
+
- uses: actions/checkout@v6
|
|
169
|
+
- uses: actions/setup-node@v6
|
|
170
|
+
with:
|
|
171
|
+
node-version: 22.18
|
|
172
|
+
- run: npx @moccona/apicodegen ./openapi.json -o ./src/api.ts --check
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
With `--split-by tag`, point `--output` at the directory; every generated file
|
|
176
|
+
is compared.
|
|
177
|
+
|
|
178
|
+
### Config file
|
|
179
|
+
|
|
180
|
+
`apicodegen.config.{json,js,mjs,ts}` (or `package.json` → `apicodegen`) is
|
|
181
|
+
loaded automatically; precedence is defaults < env < config file < CLI.
|
|
182
|
+
TypeScript configs use Node 22.18+'s native type stripping, so keep them to
|
|
183
|
+
erasable syntax (no enums/namespaces).
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
// apicodegen.config.ts — one API
|
|
187
|
+
export default { spec: './openapi.json', output: './src/api.ts' };
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// apicodegen.config.ts — multiple APIs
|
|
192
|
+
export default {
|
|
193
|
+
output: './src/api', // shared default
|
|
194
|
+
specs: [
|
|
195
|
+
{ name: 'pets', spec: './pets.json', output: './src/pets.ts' },
|
|
196
|
+
{ name: 'store', spec: './store.json', splitBy: 'tag' },
|
|
197
|
+
],
|
|
198
|
+
};
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`--spec` / `--output` are ignored when more than one entry is defined.
|
|
202
|
+
|
|
203
|
+
### Error handling
|
|
204
|
+
|
|
205
|
+
By default `fetch` clients return the response as-is and `axios` keeps its
|
|
206
|
+
default reject-on-non-2xx behaviour. Set `--error-mode` (or `errorMode` in
|
|
207
|
+
config) for an explicit contract:
|
|
208
|
+
|
|
209
|
+
- `throw` — rejects with an `Error` carrying `status` and the raw `body` text.
|
|
210
|
+
- `result` — resolves `{ ok: true, status, data }` or `{ ok: false, status, error }`.
|
|
81
211
|
|
|
82
212
|
```bash
|
|
83
|
-
apicodegen
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
213
|
+
apicodegen ./openapi.json --error-mode result -o ./src/api.ts
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### Authentication
|
|
217
|
+
|
|
218
|
+
When the spec declares `securitySchemes` (or Swagger 2.0
|
|
219
|
+
`securityDefinitions`), secured operations get an extra optional `auth`
|
|
220
|
+
argument:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
export type AuthOptions = {
|
|
224
|
+
[scheme: string]: string | { username: string; password: string };
|
|
225
|
+
};
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
- `apiKey` → sent as a header, query parameter or cookie using the scheme's `name`.
|
|
229
|
+
- `http` bearer / `oauth2` / `openIdConnect` → `Authorization: Bearer <token>`.
|
|
230
|
+
- `http` basic → `Authorization: Basic <base64>` from `{ username, password }`.
|
|
231
|
+
|
|
232
|
+
The same call shape works for both adaptors:
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
await getPet({ petId: '1' }, { BearerAuth: 'token' });
|
|
236
|
+
await getPet({ petId: '1' }, { BasicAuth: { username: 'u', password: 'p' } });
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Only credentials you pass are injected; omitting `auth` sends the request
|
|
240
|
+
unauthenticated. Operations that opt out with `security: []` get no `auth`
|
|
241
|
+
argument.
|
|
242
|
+
|
|
243
|
+
### Request control
|
|
244
|
+
|
|
245
|
+
Every generated function takes an optional trailing `options` argument:
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
export type RequestOptions = {
|
|
249
|
+
signal?: AbortSignal;
|
|
250
|
+
headers?: Record<string, string>;
|
|
251
|
+
timeout?: number;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
await getPet({ petId: '1' }, { signal: controller.signal, timeout: 5_000 });
|
|
255
|
+
await getPet({ petId: '1' }, { headers: { 'X-Request-Id': requestId } });
|
|
256
|
+
await getPet({ petId: '1' }, { BearerAuth: 'token' }, { timeout: 5_000 });
|
|
87
257
|
```
|
|
88
258
|
|
|
89
|
-
|
|
259
|
+
- `headers` are merged over generated ones, so callers can override or add.
|
|
260
|
+
- For `fetch`, `timeout` and `signal` are combined with `AbortSignal.any`;
|
|
261
|
+
either one alone works.
|
|
262
|
+
- For `axios`, `signal` and `timeout` map to the native axios config.
|
|
263
|
+
|
|
264
|
+
### Request and response types
|
|
265
|
+
|
|
266
|
+
Schemas that use `readOnly` / `writeOnly` get two extra exported aliases:
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
export type Pet = { id: number; name: string; secret?: string };
|
|
270
|
+
export type PetInput = { name: string; secret?: string }; // no readOnly id
|
|
271
|
+
export type PetOutput = { id: number; name: string }; // no writeOnly secret
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
Generated request bodies use the input shape (and the response cast uses the
|
|
275
|
+
output shape), following nested `$ref`s. The original `Pet` type is unchanged.
|
|
276
|
+
Variants are only created when the name is free; otherwise the original schema
|
|
277
|
+
is used.
|
|
278
|
+
|
|
279
|
+
### Filtering operations
|
|
280
|
+
|
|
281
|
+
Generate only part of a large spec with tag and path filters:
|
|
90
282
|
|
|
91
283
|
```bash
|
|
92
|
-
#
|
|
93
|
-
apicodegen ./openapi.
|
|
284
|
+
# Only the pets tag, and only /v1 paths
|
|
285
|
+
apicodegen ./openapi.json --include-tags pets --include-paths /v1 -o ./src/api.ts
|
|
286
|
+
|
|
287
|
+
# Everything except admin endpoints
|
|
288
|
+
apicodegen ./openapi.json --exclude-tags admin --exclude-paths /admin -o ./src/api.ts
|
|
94
289
|
```
|
|
95
290
|
|
|
291
|
+
Config equivalents are `includeTags`, `excludeTags`, `includePaths`, and
|
|
292
|
+
`excludePaths` (string arrays). Paths match by prefix. With `includeTags`,
|
|
293
|
+
operations that have no tags are skipped; filters combine (include first, then
|
|
294
|
+
exclude).
|
|
295
|
+
|
|
296
|
+
### Multi-file output
|
|
297
|
+
|
|
298
|
+
`--split-by tag` (config `splitBy: 'tag'`, env `APICODEGEN_SPLIT_BY=tag`)
|
|
299
|
+
treats `--output` as a directory and writes:
|
|
300
|
+
|
|
301
|
+
```
|
|
302
|
+
src/api/
|
|
303
|
+
index.ts # re-exports types and every tag file
|
|
304
|
+
types.ts # enums and schema type aliases
|
|
305
|
+
pets.ts # functions tagged "pets"
|
|
306
|
+
store.ts # functions tagged "store"
|
|
307
|
+
default.ts # operations without tags
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Each tag file imports shared types from `./types.js`; operations keep their
|
|
311
|
+
first tag as the file name. The Vite plugin writes the same files next to its
|
|
312
|
+
`output` path.
|
|
313
|
+
|
|
314
|
+
---
|
|
315
|
+
|
|
96
316
|
## 🔌 Vite Plugin
|
|
97
317
|
|
|
98
|
-
|
|
318
|
+
Generation runs in `buildStart`. In dev, the plugin watches each local spec
|
|
319
|
+
and triggers a full reload after regenerating.
|
|
99
320
|
|
|
100
321
|
```typescript
|
|
101
322
|
// vite.config.ts
|
|
@@ -107,7 +328,7 @@ export default defineConfig({
|
|
|
107
328
|
apiCodeGenPlugin([
|
|
108
329
|
{
|
|
109
330
|
name: 'petstore-api',
|
|
110
|
-
|
|
331
|
+
spec: 'https://petstore3.swagger.io/api/v3/openapi.json',
|
|
111
332
|
output: './src/api/petstore.ts',
|
|
112
333
|
adaptor: 'fetch',
|
|
113
334
|
baseURL: 'https://petstore3.swagger.io/api/v3',
|
|
@@ -117,22 +338,29 @@ export default defineConfig({
|
|
|
117
338
|
});
|
|
118
339
|
```
|
|
119
340
|
|
|
120
|
-
###
|
|
121
|
-
|
|
122
|
-
| Option | Type | Description |
|
|
123
|
-
|
|
124
|
-
| `name` | `string` | Human-readable API name
|
|
125
|
-
| `spec` | `string` | OpenAPI spec file path or URL |
|
|
126
|
-
| `
|
|
127
|
-
| `
|
|
128
|
-
| `
|
|
129
|
-
| `
|
|
130
|
-
| `
|
|
131
|
-
| `
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
341
|
+
### Plugin Options
|
|
342
|
+
|
|
343
|
+
| Option | Type | Required | Description |
|
|
344
|
+
|--------|------|----------|-------------|
|
|
345
|
+
| `name` | `string` | Yes | Human-readable API name |
|
|
346
|
+
| `spec` | `string` | Yes* | OpenAPI spec file path or URL |
|
|
347
|
+
| `docURL` | `string` | Yes* | OpenAPI document URL (alias for `spec`) |
|
|
348
|
+
| `output` | `string` | Yes | Output file path |
|
|
349
|
+
| `adaptor` | `'fetch' \| 'axios'` | No | HTTP client (default: `fetch`) |
|
|
350
|
+
| `errorMode` | `'throw' \| 'result'` | No | Non-2xx handling (default: leave response as-is) |
|
|
351
|
+
| `splitBy` | `'tag'` | No | Write `types.ts` + one file per tag next to `output` |
|
|
352
|
+
| `includeTags` | `string[]` | No | Only generate operations carrying one of these tags |
|
|
353
|
+
| `excludeTags` | `string[]` | No | Skip operations carrying one of these tags |
|
|
354
|
+
| `includePaths` | `string[]` | No | Only generate paths starting with one of these prefixes |
|
|
355
|
+
| `excludePaths` | `string[]` | No | Skip paths starting with one of these prefixes |
|
|
356
|
+
| `baseURL` | `string` | No | API base URL |
|
|
357
|
+
| `importClientSource` | `string` | No | Import line prepended to the output; required for the `axios` adaptor (see below) |
|
|
358
|
+
| `verbose` | `boolean` | No | Enable verbose logging |
|
|
359
|
+
| `typeCheck` | `boolean` | No | Run type check after generation |
|
|
360
|
+
|
|
361
|
+
*\*Either `spec` or `docURL` is required
|
|
362
|
+
|
|
363
|
+
### Custom Axios Instance
|
|
136
364
|
|
|
137
365
|
```typescript
|
|
138
366
|
// src/lib/api-client.ts
|
|
@@ -151,9 +379,7 @@ apiClient.interceptors.request.use((config) => {
|
|
|
151
379
|
|
|
152
380
|
```typescript
|
|
153
381
|
// vite.config.ts
|
|
154
|
-
import { defineConfig } from 'vite';
|
|
155
382
|
import { apiCodeGenPlugin } from '@moccona/apicodegen/vite';
|
|
156
|
-
import { apiClient } from './src/lib/api-client';
|
|
157
383
|
|
|
158
384
|
export default defineConfig({
|
|
159
385
|
plugins: [
|
|
@@ -163,6 +389,8 @@ export default defineConfig({
|
|
|
163
389
|
spec: './openapi.json',
|
|
164
390
|
output: './src/api/generated.ts',
|
|
165
391
|
adaptor: 'axios',
|
|
392
|
+
// Keep generated paths relative so the instance baseURL applies.
|
|
393
|
+
baseURL: '',
|
|
166
394
|
importClientSource: `import { apiClient as axios } from '@/lib/api-client';`,
|
|
167
395
|
},
|
|
168
396
|
]),
|
|
@@ -170,27 +398,99 @@ export default defineConfig({
|
|
|
170
398
|
});
|
|
171
399
|
```
|
|
172
400
|
|
|
173
|
-
|
|
401
|
+
Generated code will use your custom instance (aliased to `axios`, the identifier
|
|
402
|
+
the `axios` adaptor emits):
|
|
174
403
|
|
|
175
404
|
```typescript
|
|
176
|
-
// Generated code
|
|
177
405
|
import { apiClient as axios } from '@/lib/api-client';
|
|
178
406
|
|
|
179
|
-
// Uses apiClient under the hood
|
|
180
407
|
export async function getPetById({ petId }: { petId: number }) {
|
|
181
|
-
return
|
|
408
|
+
return axios(`/pets/${petId}`, { method: 'GET' });
|
|
182
409
|
}
|
|
183
410
|
```
|
|
184
411
|
|
|
185
|
-
##
|
|
412
|
+
## Bring Your Own HTTP Client
|
|
413
|
+
|
|
414
|
+
The generator does not import an HTTP client for you. `adaptor` selects the call
|
|
415
|
+
shape, and the generated code calls a fixed identifier:
|
|
416
|
+
|
|
417
|
+
| Adaptor | Generated call | Identifier the output expects |
|
|
418
|
+
|---------|----------------|-------------------------------|
|
|
419
|
+
| `fetch` | `fetch(url, init)` | `fetch` (global by default) |
|
|
420
|
+
| `axios` | `axios<T>(url, config)` | `axios` |
|
|
186
421
|
|
|
187
|
-
|
|
422
|
+
**Recommended: a configured axios instance.** Put `baseURL`, timeout,
|
|
423
|
+
interceptors and auth on the instance, then import it under the `axios` name:
|
|
424
|
+
|
|
425
|
+
```typescript
|
|
426
|
+
// src/lib/api-client.ts
|
|
427
|
+
import axios from 'axios';
|
|
428
|
+
|
|
429
|
+
export const apiClient = axios.create({
|
|
430
|
+
baseURL: 'https://api.example.com',
|
|
431
|
+
timeout: 10_000,
|
|
432
|
+
});
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
```typescript
|
|
436
|
+
// apicodegen.config.ts
|
|
437
|
+
export default {
|
|
438
|
+
spec: './openapi.json',
|
|
439
|
+
output: './src/api.ts',
|
|
440
|
+
adaptor: 'axios',
|
|
441
|
+
// Keep generated paths relative so the instance owns the origin.
|
|
442
|
+
baseURL: '',
|
|
443
|
+
importClientSource: "import { apiClient as axios } from './lib/api-client'",
|
|
444
|
+
};
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
If you just want the axios package default, a bare import works too:
|
|
448
|
+
|
|
449
|
+
```bash
|
|
450
|
+
apicodegen ./openapi.json -a axios \
|
|
451
|
+
--importClientSource "import axios from 'axios'" \
|
|
452
|
+
-o ./src/api.ts
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
The CLI otherwise uses the spec's `servers[0].url` as the base. Pass
|
|
456
|
+
`--baseURL ""` (or `baseURL: ''` in a config file) to keep paths relative and
|
|
457
|
+
let the instance own the origin; an absolute server URL or explicit base
|
|
458
|
+
overrides the instance `baseURL`.
|
|
459
|
+
|
|
460
|
+
The imported value must satisfy the adaptor's contract:
|
|
461
|
+
|
|
462
|
+
- **axios**: generic and callable as
|
|
463
|
+
`<T>(url, config) => Promise<{ data: T; status: number }>`. The generated
|
|
464
|
+
`config` contains `method`, `headers`, `data` (request body), `signal` and
|
|
465
|
+
`timeout`; query parameters are already encoded into the URL. With
|
|
466
|
+
`errorMode: 'result'`, rejected errors must carry
|
|
467
|
+
`response: { status: number; data: unknown }`.
|
|
468
|
+
- **fetch**: a `fetch`-compatible function (`(input, init) => Promise<Response>`).
|
|
469
|
+
To inject a wrapper, alias it to `fetch` (for example
|
|
470
|
+
`import { myFetch as fetch } from './fetch'`).
|
|
471
|
+
|
|
472
|
+
Limitations:
|
|
473
|
+
|
|
474
|
+
- **The identifier is fixed.** Your import has to use `as axios` or `as fetch`;
|
|
475
|
+
the generated call site cannot be renamed.
|
|
476
|
+
- **Only the axios and fetch shapes are supported.** Clients such as `ky` or
|
|
477
|
+
`ofetch` need a thin wrapper matching one of the contracts above.
|
|
478
|
+
- **`--adaptor axios` without `importClientSource` produces code that references
|
|
479
|
+
an undefined `axios`** and will not compile. This is not caught at generation
|
|
480
|
+
time, so check the output or run your own `tsc --noEmit`.
|
|
481
|
+
|
|
482
|
+
---
|
|
483
|
+
|
|
484
|
+
## 📝 Generated Code
|
|
485
|
+
|
|
486
|
+
Given this OpenAPI spec:
|
|
188
487
|
|
|
189
488
|
```yaml
|
|
190
489
|
paths:
|
|
191
490
|
/pets/{petId}:
|
|
192
491
|
get:
|
|
193
492
|
operationId: getPetById
|
|
493
|
+
summary: Get a pet by ID
|
|
194
494
|
parameters:
|
|
195
495
|
- name: petId
|
|
196
496
|
in: path
|
|
@@ -221,15 +521,6 @@ components:
|
|
|
221
521
|
The generated TypeScript code:
|
|
222
522
|
|
|
223
523
|
```typescript
|
|
224
|
-
/**
|
|
225
|
-
* Pet object
|
|
226
|
-
*/
|
|
227
|
-
export type Pet = {
|
|
228
|
-
id?: number;
|
|
229
|
-
name?: string;
|
|
230
|
-
status?: 'available' | 'pending' | 'sold';
|
|
231
|
-
};
|
|
232
|
-
|
|
233
524
|
/**
|
|
234
525
|
* Get a pet by ID
|
|
235
526
|
*/
|
|
@@ -238,71 +529,132 @@ export async function getPetById({ petId }: { petId: number }) {
|
|
|
238
529
|
method: 'GET',
|
|
239
530
|
}).then(async (response) => (await response.json()) as Pet);
|
|
240
531
|
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* Pet object
|
|
535
|
+
*/
|
|
536
|
+
export type Pet = {
|
|
537
|
+
id?: number;
|
|
538
|
+
name?: string;
|
|
539
|
+
status?: 'available' | 'pending' | 'sold';
|
|
540
|
+
};
|
|
241
541
|
```
|
|
242
542
|
|
|
243
|
-
|
|
543
|
+
---
|
|
544
|
+
|
|
545
|
+
## 🎯 Supported Features
|
|
244
546
|
|
|
245
547
|
### Schema Types
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
548
|
+
|
|
549
|
+
| Type | Status | Notes |
|
|
550
|
+
|------|--------|-------|
|
|
551
|
+
| `string` | ✅ | Full support with formats |
|
|
552
|
+
| `number` / `integer` | ✅ | int8, uint8, int16, etc. |
|
|
553
|
+
| `boolean` | ✅ | Full support |
|
|
554
|
+
| `object` | ✅ | Complex nested objects |
|
|
555
|
+
| `array` | ✅ | Nested and multi-dimensional |
|
|
556
|
+
| `enum` | ✅ | Auto-generated TypeScript enums |
|
|
557
|
+
| `oneOf` / `anyOf` | ✅ | Union types with deduplication; `discriminator.mapping` narrows `oneOf` members |
|
|
558
|
+
| `allOf` | ✅ | Intersection types |
|
|
559
|
+
| `$ref` | ✅ | Local, cross-file and remote URL references; circular refs supported |
|
|
560
|
+
| `binary` / `blob` / `file` | ✅ | File upload types |
|
|
254
561
|
|
|
255
562
|
### Parameter Locations
|
|
256
|
-
- ✅ Path parameters: `/users/{id}`
|
|
257
|
-
- ✅ Query parameters: `?page=1&limit=10`
|
|
258
|
-
- ✅ Header parameters: Custom request headers
|
|
259
|
-
- ✅ Cookie parameters: Request cookies
|
|
260
|
-
- ✅ Body parameters: JSON and FormData
|
|
261
563
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
564
|
+
| Location | Status | Example |
|
|
565
|
+
|----------|--------|---------|
|
|
566
|
+
| `path` | ✅ | `/users/{id}` |
|
|
567
|
+
| `query` | ✅ | `?page=1&limit=10` |
|
|
568
|
+
| `header` | ✅ | `X-API-Key: xxx` |
|
|
569
|
+
| `cookie` | ✅ | Sent as a `Cookie` header |
|
|
570
|
+
| `body` | ✅ | JSON and FormData |
|
|
266
571
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
572
|
+
Query arrays support `form`, `spaceDelimited`, and `pipeDelimited` with
|
|
573
|
+
`explode`. `deepObject` parameters serialize nested objects to
|
|
574
|
+
`filter[a]=1&filter[b][c]=2` at any depth.
|
|
270
575
|
|
|
271
576
|
### Request Body Formats
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
577
|
+
|
|
578
|
+
| Content-Type | Status |
|
|
579
|
+
|--------------|--------|
|
|
580
|
+
| `application/json` | ✅ |
|
|
581
|
+
| `multipart/form-data` | ✅ |
|
|
582
|
+
| `application/x-www-form-urlencoded` | ✅ |
|
|
583
|
+
| `text/plain` | ✅ |
|
|
584
|
+
| `image/*` | ✅ |
|
|
585
|
+
|
|
586
|
+
Multipart bodies always use `FormData` when the schema has only text parts
|
|
587
|
+
(string, number, boolean, arrays of those), not just for file uploads.
|
|
588
|
+
URL-encoded object bodies use `URLSearchParams`; arrays are sent as repeated
|
|
589
|
+
keys and nested objects/arrays are JSON-stringified.
|
|
590
|
+
|
|
591
|
+
### OpenAPI Versions
|
|
592
|
+
|
|
593
|
+
| Version | Status | Notes |
|
|
594
|
+
|---------|--------|-------|
|
|
595
|
+
| OpenAPI 2.0 (Swagger) | ✅ | |
|
|
596
|
+
| OpenAPI 3.0 | ✅ | |
|
|
597
|
+
| OpenAPI 3.1 | ⚠️ | `type` arrays, `const`, and `additionalProperties` supported; webhooks are not modelled |
|
|
598
|
+
|
|
599
|
+
---
|
|
600
|
+
|
|
601
|
+
## 📖 Examples
|
|
602
|
+
|
|
603
|
+
### Complete API with Authentication
|
|
604
|
+
|
|
605
|
+
```bash
|
|
606
|
+
apicodegen https://api.example.com/openapi.json \
|
|
607
|
+
-o ./src/api.ts \
|
|
608
|
+
-a fetch \
|
|
609
|
+
-b https://api.example.com \
|
|
610
|
+
-v
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
### Using Custom Axios with Interceptors
|
|
614
|
+
|
|
615
|
+
See [Custom Axios Instance](#custom-axios-instance) section above.
|
|
616
|
+
|
|
617
|
+
### Watch Mode for Development
|
|
618
|
+
|
|
619
|
+
```bash
|
|
620
|
+
apicodegen ./openapi.json \
|
|
621
|
+
--watch \
|
|
622
|
+
--output ./src/generated/api.ts \
|
|
623
|
+
--verbose
|
|
624
|
+
```
|
|
625
|
+
|
|
626
|
+
---
|
|
276
627
|
|
|
277
628
|
## 🔧 Troubleshooting
|
|
278
629
|
|
|
279
630
|
### Common Issues
|
|
280
631
|
|
|
281
632
|
**"Command not found" after installation**
|
|
282
|
-
If using the CLI globally but getting command not found, try:
|
|
283
633
|
```bash
|
|
284
634
|
# Reinstall globally
|
|
285
635
|
npm install -g @moccona/apicodegen
|
|
286
636
|
|
|
287
637
|
# Or use npx
|
|
288
|
-
npx @moccona/apicodegen <
|
|
638
|
+
npx @moccona/apicodegen <url> -o ./src/api.ts
|
|
289
639
|
```
|
|
290
640
|
|
|
291
641
|
**Network errors when fetching OpenAPI documents**
|
|
292
642
|
- Verify the URL is publicly accessible
|
|
293
643
|
- Try downloading the document locally first
|
|
294
644
|
- Check firewall/proxy settings
|
|
295
|
-
- Use `-v` flag for verbose logging
|
|
645
|
+
- Use `-v` flag for verbose logging
|
|
296
646
|
|
|
297
647
|
**TypeScript errors in generated code**
|
|
298
648
|
- Ensure `typescript` is installed: `npm install -D typescript`
|
|
299
649
|
- Run `tsc --noEmit` to see specific errors
|
|
300
|
-
-
|
|
650
|
+
- Verify your `tsconfig.json` is properly configured
|
|
651
|
+
- `Cannot find name 'axios'` means you used `--adaptor axios` without
|
|
652
|
+
`importClientSource`; see [Bring Your Own HTTP Client](#bring-your-own-http-client)
|
|
301
653
|
|
|
302
654
|
**Vite plugin not generating files**
|
|
303
|
-
- Ensure Node.js
|
|
655
|
+
- Ensure Node.js 22.18+ is installed
|
|
304
656
|
- Check that all required options (`name`, `output`) are provided
|
|
305
|
-
- Set `verbose: true` in plugin options
|
|
657
|
+
- Set `verbose: true` in plugin options
|
|
306
658
|
|
|
307
659
|
**Watch mode not triggering regeneration**
|
|
308
660
|
- Watch mode monitors the spec file, not your output file
|
|
@@ -311,8 +663,11 @@ npx @moccona/apicodegen <OpenAPI文档URL> -o ./src/api.ts
|
|
|
311
663
|
|
|
312
664
|
### Getting Help
|
|
313
665
|
|
|
314
|
-
-
|
|
315
|
-
-
|
|
666
|
+
- 📄 [CHANGELOG](CHANGELOG.md) - Recent updates
|
|
667
|
+
- 🐛 [GitHub Issues](https://github.com/freemode1614/api-codegen/issues) - Report bugs
|
|
668
|
+
- 📖 [ROADMAP.md](ROADMAP.md) - Future plans
|
|
669
|
+
|
|
670
|
+
---
|
|
316
671
|
|
|
317
672
|
## 🔧 Development
|
|
318
673
|
|
|
@@ -320,13 +675,13 @@ npx @moccona/apicodegen <OpenAPI文档URL> -o ./src/api.ts
|
|
|
320
675
|
# Install dependencies
|
|
321
676
|
pnpm install
|
|
322
677
|
|
|
323
|
-
# Development mode
|
|
678
|
+
# Development mode (watch)
|
|
324
679
|
pnpm dev
|
|
325
680
|
|
|
326
|
-
# Build
|
|
681
|
+
# Build for production
|
|
327
682
|
pnpm build
|
|
328
683
|
|
|
329
|
-
# Run tests
|
|
684
|
+
# Run all tests
|
|
330
685
|
pnpm test
|
|
331
686
|
|
|
332
687
|
# Type check
|
|
@@ -335,10 +690,40 @@ pnpm typecheck
|
|
|
335
690
|
# Lint
|
|
336
691
|
pnpm lint
|
|
337
692
|
|
|
338
|
-
# Format
|
|
693
|
+
# Format code
|
|
339
694
|
pnpm format
|
|
340
695
|
```
|
|
341
696
|
|
|
697
|
+
### Project Structure
|
|
698
|
+
|
|
699
|
+
```
|
|
700
|
+
src/
|
|
701
|
+
├── cli.ts # CLI entry point
|
|
702
|
+
├── cli/ # CLI modules
|
|
703
|
+
├── core/ # Core code generation
|
|
704
|
+
│ ├── generator/ # TypeScript AST generation
|
|
705
|
+
│ ├── client/ # fetch/axios adaptors
|
|
706
|
+
│ ├── base/ # Base utilities
|
|
707
|
+
│ └── constants/ # Constants
|
|
708
|
+
├── openapi/ # OpenAPI spec parsing
|
|
709
|
+
│ ├── V2.ts # OpenAPI 2.0
|
|
710
|
+
│ ├── V3.ts # OpenAPI 3.0
|
|
711
|
+
│ └── V3_1.ts # OpenAPI 3.1
|
|
712
|
+
├── vite-plugin/ # Vite plugin
|
|
713
|
+
└── types/ # TypeScript types
|
|
714
|
+
```
|
|
715
|
+
|
|
716
|
+
---
|
|
717
|
+
|
|
718
|
+
## 🗺️ Roadmap
|
|
719
|
+
|
|
720
|
+
See [ROADMAP.md](ROADMAP.md) for the detailed, versioned plan:
|
|
721
|
+
|
|
722
|
+
- **v1.0.0** - Stable contract, auto baseURL, YAML, OpenAPI 3.1 types, auth, error modes, `--check`, multi-file output, request/response type split, Node 22.18
|
|
723
|
+
- **v1.1.0** - Ecosystem parity: Zod, MSW, framework hooks, plugin API, path-prefix splitting
|
|
724
|
+
|
|
725
|
+
---
|
|
726
|
+
|
|
342
727
|
## 📄 License
|
|
343
728
|
|
|
344
729
|
[MIT](LICENSE) © freemode
|
|
@@ -347,6 +732,17 @@ pnpm format
|
|
|
347
732
|
|
|
348
733
|
Issues and Pull Requests are welcome!
|
|
349
734
|
|
|
735
|
+
- 📘 [Contributing Guide](./CONTRIBUTING.md) — dev setup, code style, PR process
|
|
736
|
+
- 📜 [Code of Conduct](./CODE_OF_CONDUCT.md) — community norms & engineering standards
|
|
737
|
+
- 🔒 [Security Policy](./SECURITY.md) — how to report vulnerabilities privately
|
|
738
|
+
- 💬 [GitHub Discussions](https://github.com/freemode1614/api-codegen/discussions) — questions & ideas
|
|
739
|
+
|
|
740
|
+
When opening an issue, you'll be guided through **Bug Report**, **Feature Request**,
|
|
741
|
+
**Documentation**, or **Question** templates so we can help you faster.
|
|
742
|
+
|
|
743
|
+
By participating in this project you agree to abide by the [Code of Conduct](./CODE_OF_CONDUCT.md).
|
|
744
|
+
|
|
350
745
|
---
|
|
351
746
|
|
|
352
|
-
Questions or suggestions?
|
|
747
|
+
*Questions or suggestions? [Start a discussion](https://github.com/freemode1614/api-codegen/discussions)
|
|
748
|
+
or [open an issue](https://github.com/freemode1614/api-codegen/issues).*
|