@jutsustack/api-codegen 0.0.0-stage → 0.1.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.
Files changed (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +331 -2
  3. package/bin/jutsu-api.js +14 -0
  4. package/dist/cache/manifest.d.ts +36 -0
  5. package/dist/cache/manifest.d.ts.map +1 -0
  6. package/dist/cache/manifest.js +37 -0
  7. package/dist/cache/manifest.js.map +1 -0
  8. package/dist/cli.d.ts +7 -0
  9. package/dist/cli.d.ts.map +1 -0
  10. package/dist/cli.js +208 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/codegen/emit-api.d.ts +5 -0
  13. package/dist/codegen/emit-api.d.ts.map +1 -0
  14. package/dist/codegen/emit-api.js +80 -0
  15. package/dist/codegen/emit-api.js.map +1 -0
  16. package/dist/codegen/emit-hooks.d.ts +5 -0
  17. package/dist/codegen/emit-hooks.d.ts.map +1 -0
  18. package/dist/codegen/emit-hooks.js +67 -0
  19. package/dist/codegen/emit-hooks.js.map +1 -0
  20. package/dist/codegen/emit-types.d.ts +4 -0
  21. package/dist/codegen/emit-types.d.ts.map +1 -0
  22. package/dist/codegen/emit-types.js +228 -0
  23. package/dist/codegen/emit-types.js.map +1 -0
  24. package/dist/codegen/emit.d.ts +20 -0
  25. package/dist/codegen/emit.d.ts.map +1 -0
  26. package/dist/codegen/emit.js +72 -0
  27. package/dist/codegen/emit.js.map +1 -0
  28. package/dist/codegen/files.d.ts +24 -0
  29. package/dist/codegen/files.d.ts.map +1 -0
  30. package/dist/codegen/files.js +66 -0
  31. package/dist/codegen/files.js.map +1 -0
  32. package/dist/codegen/plan.d.ts +33 -0
  33. package/dist/codegen/plan.d.ts.map +1 -0
  34. package/dist/codegen/plan.js +79 -0
  35. package/dist/codegen/plan.js.map +1 -0
  36. package/dist/codegen/print.d.ts +14 -0
  37. package/dist/codegen/print.d.ts.map +1 -0
  38. package/dist/codegen/print.js +62 -0
  39. package/dist/codegen/print.js.map +1 -0
  40. package/dist/codegen/templates/hooks.d.ts +11 -0
  41. package/dist/codegen/templates/hooks.d.ts.map +1 -0
  42. package/dist/codegen/templates/hooks.js +272 -0
  43. package/dist/codegen/templates/hooks.js.map +1 -0
  44. package/dist/codegen/templates/runtime.d.ts +2 -0
  45. package/dist/codegen/templates/runtime.d.ts.map +1 -0
  46. package/dist/codegen/templates/runtime.js +485 -0
  47. package/dist/codegen/templates/runtime.js.map +1 -0
  48. package/dist/codegen/tsType.d.ts +16 -0
  49. package/dist/codegen/tsType.d.ts.map +1 -0
  50. package/dist/codegen/tsType.js +111 -0
  51. package/dist/codegen/tsType.js.map +1 -0
  52. package/dist/collect/collect.d.ts +27 -0
  53. package/dist/collect/collect.d.ts.map +1 -0
  54. package/dist/collect/collect.js +476 -0
  55. package/dist/collect/collect.js.map +1 -0
  56. package/dist/collect/naming.d.ts +29 -0
  57. package/dist/collect/naming.d.ts.map +1 -0
  58. package/dist/collect/naming.js +140 -0
  59. package/dist/collect/naming.js.map +1 -0
  60. package/dist/collect/path.d.ts +18 -0
  61. package/dist/collect/path.d.ts.map +1 -0
  62. package/dist/collect/path.js +69 -0
  63. package/dist/collect/path.js.map +1 -0
  64. package/dist/config/init.d.ts +29 -0
  65. package/dist/config/init.d.ts.map +1 -0
  66. package/dist/config/init.js +86 -0
  67. package/dist/config/init.js.map +1 -0
  68. package/dist/config/load.d.ts +12 -0
  69. package/dist/config/load.d.ts.map +1 -0
  70. package/dist/config/load.js +87 -0
  71. package/dist/config/load.js.map +1 -0
  72. package/dist/config/types.d.ts +81 -0
  73. package/dist/config/types.d.ts.map +1 -0
  74. package/dist/config/types.js +2 -0
  75. package/dist/config/types.js.map +1 -0
  76. package/dist/config/validate.d.ts +13 -0
  77. package/dist/config/validate.d.ts.map +1 -0
  78. package/dist/config/validate.js +185 -0
  79. package/dist/config/validate.js.map +1 -0
  80. package/dist/generate.d.ts +62 -0
  81. package/dist/generate.d.ts.map +1 -0
  82. package/dist/generate.js +254 -0
  83. package/dist/generate.js.map +1 -0
  84. package/dist/index.d.ts +24 -0
  85. package/dist/index.d.ts.map +1 -0
  86. package/dist/index.js +15 -0
  87. package/dist/index.js.map +1 -0
  88. package/dist/model/collection.d.ts +84 -0
  89. package/dist/model/collection.d.ts.map +1 -0
  90. package/dist/model/collection.js +13 -0
  91. package/dist/model/collection.js.map +1 -0
  92. package/dist/model/infer.d.ts +15 -0
  93. package/dist/model/infer.d.ts.map +1 -0
  94. package/dist/model/infer.js +98 -0
  95. package/dist/model/infer.js.map +1 -0
  96. package/dist/model/merge.d.ts +8 -0
  97. package/dist/model/merge.d.ts.map +1 -0
  98. package/dist/model/merge.js +133 -0
  99. package/dist/model/merge.js.map +1 -0
  100. package/dist/model/reserved.d.ts +6 -0
  101. package/dist/model/reserved.d.ts.map +1 -0
  102. package/dist/model/reserved.js +67 -0
  103. package/dist/model/reserved.js.map +1 -0
  104. package/dist/model/schema.d.ts +58 -0
  105. package/dist/model/schema.d.ts.map +1 -0
  106. package/dist/model/schema.js +2 -0
  107. package/dist/model/schema.js.map +1 -0
  108. package/dist/parsers/openapi-schema.d.ts +35 -0
  109. package/dist/parsers/openapi-schema.d.ts.map +1 -0
  110. package/dist/parsers/openapi-schema.js +241 -0
  111. package/dist/parsers/openapi-schema.js.map +1 -0
  112. package/dist/parsers/openapi.d.ts +9 -0
  113. package/dist/parsers/openapi.d.ts.map +1 -0
  114. package/dist/parsers/openapi.js +432 -0
  115. package/dist/parsers/openapi.js.map +1 -0
  116. package/dist/parsers/postman.d.ts +24 -0
  117. package/dist/parsers/postman.d.ts.map +1 -0
  118. package/dist/parsers/postman.js +491 -0
  119. package/dist/parsers/postman.js.map +1 -0
  120. package/dist/parsers/types.d.ts +53 -0
  121. package/dist/parsers/types.d.ts.map +1 -0
  122. package/dist/parsers/types.js +2 -0
  123. package/dist/parsers/types.js.map +1 -0
  124. package/dist/sources/load.d.ts +32 -0
  125. package/dist/sources/load.d.ts.map +1 -0
  126. package/dist/sources/load.js +294 -0
  127. package/dist/sources/load.js.map +1 -0
  128. package/dist/sources/parse.d.ts +7 -0
  129. package/dist/sources/parse.d.ts.map +1 -0
  130. package/dist/sources/parse.js +48 -0
  131. package/dist/sources/parse.js.map +1 -0
  132. package/dist/util/errors.d.ts +10 -0
  133. package/dist/util/errors.d.ts.map +1 -0
  134. package/dist/util/errors.js +18 -0
  135. package/dist/util/errors.js.map +1 -0
  136. package/dist/util/fs.d.ts +8 -0
  137. package/dist/util/fs.d.ts.map +1 -0
  138. package/dist/util/fs.js +36 -0
  139. package/dist/util/fs.js.map +1 -0
  140. package/dist/util/hash.d.ts +4 -0
  141. package/dist/util/hash.d.ts.map +1 -0
  142. package/dist/util/hash.js +23 -0
  143. package/dist/util/hash.js.map +1 -0
  144. package/dist/util/json.d.ts +11 -0
  145. package/dist/util/json.d.ts.map +1 -0
  146. package/dist/util/json.js +24 -0
  147. package/dist/util/json.js.map +1 -0
  148. package/dist/util/log.d.ts +23 -0
  149. package/dist/util/log.d.ts.map +1 -0
  150. package/dist/util/log.js +42 -0
  151. package/dist/util/log.js.map +1 -0
  152. package/dist/version.d.ts +3 -0
  153. package/dist/version.d.ts.map +1 -0
  154. package/dist/version.js +4 -0
  155. package/dist/version.js.map +1 -0
  156. package/package.json +89 -4
  157. package/schema/config.schema.json +136 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JutsuStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,332 @@
1
- # Temporary Holding Version
1
+ # @jutsustack/api-codegen
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Generate a typed API layer for **React Native**, **React** and **Next.js** from **Postman
4
+ collections**, **Swagger 2.0** and **OpenAPI 3.x** documents.
5
+
6
+ ```ts
7
+ const user = await api.users.getUser({ params: { id: 42 } }); // → User
8
+
9
+ try {
10
+ await api.auth.login({ body: { email, password } });
11
+ } catch (error) {
12
+ const failure = api.auth.login.errorOf(error); // { status: 401; data: LoginError } | undefined
13
+ }
14
+ ```
15
+
16
+ - **Duplicate requests become one endpoint.** "Login – Success" and "Login – Wrong password"
17
+ (or `/users/1` and `/users/:id`) merge into one function with typed success and error bodies.
18
+ - **Three targets.** On React Native the code runs on
19
+ [`@jutsustack/react-native-fetch`](https://github.com/JutsuStack/react-native-fetch), so SSL
20
+ pinning, token refresh and retries keep working. React and Next.js get a small generated
21
+ `fetch` client.
22
+ - **Skips work when nothing changed.** Unchanged sources, config and generator version mean
23
+ nothing is parsed or written.
24
+ - **Safe to re-run.** Hand-edited generated files are detected, never silently overwritten.
25
+ - **Strict-mode clean**, one runtime dependency (`yaml`).
26
+
27
+ ## Requirements
28
+
29
+ - Node.js 18.18+ for the CLI, TypeScript 5+ in the app
30
+ - `react-native` target: `@jutsustack/react-native-fetch` installed in the app
31
+ - Hooks: React 18 or 19
32
+
33
+ ## Quick start
34
+
35
+ ```bash
36
+ npm i -D @jutsustack/api-codegen
37
+ npx jutsu-api init --source ./api/my-app.postman_collection.json # creates my-app-api.config.json
38
+ npx jutsu-api # generates src/api
39
+ ```
40
+
41
+ ```text
42
+ ✎ src/api/api-collection.json
43
+ ✎ src/api/runtime.ts
44
+ ✎ src/api/types.ts
45
+ ✎ src/api/api.ts
46
+ ✎ src/api/hooks.ts
47
+ ✎ src/api/index.ts
48
+ ✎ src/api/client.ts
49
+ ✔ Updated 7 file(s) in src/api: 10 endpoints in 4 group(s), 3 merged from duplicate requests [react-native]
50
+ ```
51
+
52
+ Configure the client once in `src/api/client.ts` (base URL, auth, SSL pins), then call
53
+ `api.<group>.<endpoint>()`. `init` adds the `.jutsu-api/` cache folder to an existing `.gitignore`. If you
54
+ use ESLint, also ignore the output folder: generated files start with `/* eslint-disable */`,
55
+ which ESLint 9 reports as unused.
56
+
57
+ ## Examples
58
+
59
+ [`examples/demo`](examples/demo) generates one Postman collection for the public
60
+ [dummyjson.com](https://dummyjson.com) API into three apps. The collection holds success and
61
+ failure examples of the same requests, which merge into one typed endpoint each.
62
+
63
+ | App | Shows |
64
+ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
65
+ | [`rn-app`](examples/demo/rn-app) | React Native 0.86 on `@jutsustack/react-native-fetch`: hooks, typed 400/404, login into the token store, 401 → refresh |
66
+ | [`react-app`](examples/demo/react-app) | Vite + React 19: generated hooks, tested with Testing Library against the live API |
67
+ | [`next-app`](examples/demo/next-app) | Next.js 16: Server Component with `'use cache'`, typed 404 in `<Suspense>`, Route Handler, client hooks |
68
+
69
+ <p>
70
+ <img src="examples/demo/screenshots/rn-app-1.png" alt="React Native app: product, typed 404 and product list" width="200">
71
+ <img src="examples/demo/screenshots/rn-app-2-login-error.png" alt="React Native app: wrong password shows the typed 400 error" width="200">
72
+ <img src="examples/demo/screenshots/rn-app-3-login-ok.png" alt="React Native app: login succeeds and /auth/me returns the user" width="200">
73
+ </p>
74
+ <p>
75
+ <img src="examples/demo/screenshots/react-app.png" alt="React app built with Vite" width="300">
76
+ <img src="examples/demo/screenshots/next-app.png" alt="Next.js app: Server Components and client hooks" width="300">
77
+ </p>
78
+
79
+ Run them with the steps in [`examples/demo/README.md`](examples/demo/README.md).
80
+ [`examples/shop-app`](examples/shop-app) is the generated output for a Postman collection plus
81
+ an OpenAPI document; CI checks that it is up to date.
82
+
83
+ ## Config
84
+
85
+ One file per project, **`<project-name>-api.config.json`**, next to `package.json`. Use
86
+ `--config` when a folder holds several.
87
+
88
+ ```json
89
+ {
90
+ "$schema": "./node_modules/@jutsustack/api-codegen/schema/config.schema.json",
91
+ "project": "shop-app",
92
+ "target": "react-native",
93
+ "output": "src/api",
94
+ "sources": [
95
+ { "id": "shop", "path": "./api/shop.postman_collection.json" },
96
+ { "id": "payments", "url": "https://payments.example.com/openapi.yaml" }
97
+ ]
98
+ }
99
+ ```
100
+
101
+ | Option | Default | Description |
102
+ | ----------------- | --------------------------- | ------------------------------------------------------------------- |
103
+ | `project` | required | Project name |
104
+ | `target` | required | `react-native`, `react` or `next` |
105
+ | `output` | required | Output folder, relative to the config; must stay inside the project |
106
+ | `sources` | required | See [Sources](#sources) |
107
+ | `baseUrl` | first server found | Base URL for the `client.ts` scaffold |
108
+ | `methods` | `GET POST PUT PATCH DELETE` | Methods to generate (`HEAD`, `OPTIONS` also allowed) |
109
+ | `groupBy` | `folder` | `folder` / `tag`, `path` (first path segment) or `none` |
110
+ | `hooks` | `true` | Generate React hooks |
111
+ | `include` | all | Globs to keep, e.g. `"/users/**"`, `"GET /orders/*"` |
112
+ | `exclude` | none | Globs to skip |
113
+ | `format` | `none` | `prettier` formats output with the project's prettier |
114
+ | `importExtension` | `""` | `".js"` for apps using `moduleResolution: NodeNext` |
115
+ | `cacheDir` | `.jutsu-api` | Cache folder |
116
+
117
+ Unknown options are errors, reported with their path (`sources[1].url: must be an http(s) URL`).
118
+
119
+ ## Sources
120
+
121
+ Each source has a unique `id` and one of `path`, `url` or `postman`. The format is detected
122
+ from the content; `type` (`postman`, `openapi`, `swagger`) enforces it.
123
+
124
+ | Source | Example |
125
+ | ------------------- | ----------------------------------------------------------------------------------------- |
126
+ | File (JSON / YAML) | `{ "id": "core", "path": "./api/core.postman_collection.json" }` |
127
+ | URL | `{ "id": "pets", "url": "https://api.example.com/openapi.json" }` |
128
+ | URL with auth | `{ "id": "pets", "url": "…", "headers": { "Authorization": "Bearer ${SPEC_TOKEN}" } }` |
129
+ | Postman workspace | `{ "id": "cloud", "postman": { "collectionId": "12345-abcd" } }` (key: `POSTMAN_API_KEY`) |
130
+ | Postman environment | add `"environment": "./api/dev.postman_environment.json"` to resolve `{{baseUrl}}` |
131
+
132
+ `${VAR}` values come from the environment and are never written to disk.
133
+
134
+ ## How duplicate requests are merged
135
+
136
+ Two requests are the same API when the method matches and the paths match after parameter
137
+ segments are normalised: `GET /users/:id`, `/users/{{userId}}`, `/users/42` and a UUID path are
138
+ one endpoint.
139
+
140
+ - **Name:** the OpenAPI `operationId`, else the most common Postman title without scenario
141
+ words (`Login – Success`, `Login (401)` → `login`), else method + path (`getUsersById`).
142
+ - **Responses:** 2xx examples form the success type; 4xx/5xx examples the error type per
143
+ status.
144
+ - **Request body:** bodies of all examples are merged; fields only some examples send become
145
+ optional.
146
+ - **Precedence:** OpenAPI schemas win over Postman examples. Clashing model names from
147
+ different specs are renamed `<SourceId><Name>`, with a warning.
148
+
149
+ `api-collection.json` records every endpoint with its origins, so merges can be reviewed in
150
+ pull requests.
151
+
152
+ ## What gets generated
153
+
154
+ | File | Contents |
155
+ | --------------------- | --------------------------------------------------------------------- |
156
+ | `api-collection.json` | The merged collection |
157
+ | `runtime.ts` | Transport types, the `endpoint()` helper; on web, `createFetchClient` |
158
+ | `types.ts` | Models and `XArgs` / `XResponse` / `XErrors` types per endpoint |
159
+ | `api.ts` | `createApi(client)` → `{ group: { endpoint } }` |
160
+ | `hooks.ts` | Query hooks for GET/HEAD, mutation hooks for the rest |
161
+ | `index.ts` | Re-exports (on Next.js, import hooks from `./hooks`) |
162
+ | `client.ts` | **Yours:** created once, never overwritten |
163
+
164
+ Endpoints get defaults from the sources: `skipAuth` for requests that opt out of auth
165
+ (Postman `noauth`, OpenAPI `security: []`), and `contentType` / `responseType` for non-JSON
166
+ bodies. [`examples/shop-app`](examples/shop-app) shows the full output, and
167
+ [Examples](#examples) shows it running.
168
+
169
+ ## Using the generated API
170
+
171
+ ```ts
172
+ await api.users.getUser({ params: { id: 1 } }); // data
173
+ await api.users.getUser.raw({ params: { id: 1 } }); // { data, status, headers, … }
174
+ api.users.getUser.errorOf(error); // typed documented error, or undefined
175
+ ```
176
+
177
+ `params`, `query` and `body` are required exactly when the API needs them; every other
178
+ option of the transport can be passed too.
179
+
180
+ `errorOf(error)` returns `{ status, data }` for documented error responses and `undefined`
181
+ for anything else. A `4XX` / `5XX` response matches any status of that class, and
182
+ `default` any error status.
183
+
184
+ ### React Native
185
+
186
+ ```ts
187
+ // src/api/client.ts
188
+ export const client = createJutsuClient({
189
+ baseURL: 'https://api.example.com',
190
+ auth: {
191
+ tokenStore: createMemoryTokenStore(),
192
+ // the refresh handler's `http` bypasses auth, so it can call a generated endpoint
193
+ refresh: {
194
+ handler: async ({ refreshToken, http }) => {
195
+ const t = await createApi(http).auth.refreshSession({
196
+ body: { refreshToken: refreshToken ?? '' },
197
+ });
198
+ return { accessToken: t.accessToken, refreshToken: t.refreshToken };
199
+ },
200
+ },
201
+ },
202
+ });
203
+ export const api = createApi(client);
204
+ ```
205
+
206
+ ```ts
207
+ await api.users.listUsers({
208
+ query: { page: 1 },
209
+ cachePolicy: 'stale-while-revalidate',
210
+ });
211
+ const { data, status, refetch } = useGetUser({ params: { id: 1 } }); // inside <JutsuProvider>
212
+ ```
213
+
214
+ Jest needs react-native-fetch's ES modules transformed and its test setup:
215
+
216
+ ```js
217
+ module.exports = {
218
+ preset: '@react-native/jest-preset',
219
+ transformIgnorePatterns: [
220
+ 'node_modules/(?!((jest-)?react-native|@react-native(-community)?|@jutsustack)/)',
221
+ ],
222
+ setupFiles: ['@jutsustack/react-native-fetch/testing/jestSetup'],
223
+ };
224
+ ```
225
+
226
+ ### React
227
+
228
+ ```ts
229
+ export const client = createFetchClient({
230
+ baseURL: 'https://api.example.com',
231
+ getToken: () => sessionToken, // sent as Bearer unless the endpoint skips auth
232
+ timeoutMs: 15_000,
233
+ });
234
+ export const api = createApi(client);
235
+ ```
236
+
237
+ Wrap the tree in `<ApiProvider client={client}>` to use the hooks. Other options: `headers`,
238
+ `fetch`, `init`, `arrayFormat`, `onError`. Errors are `ApiError` (`kind`, `status`, `data`,
239
+ `url`); `isApiError()` checks for one.
240
+
241
+ ### Next.js
242
+
243
+ Endpoints are plain async functions, usable in Server Components, Route Handlers and Server
244
+ Actions. With Cache Components (the Next.js 16 default), cache a call in a `'use cache'`
245
+ function and wrap uncached ones in `<Suspense>`:
246
+
247
+ ```ts
248
+ export async function getPets() {
249
+ 'use cache';
250
+ cacheLife('minutes');
251
+ cacheTag('pets');
252
+ return api.pets.listPets();
253
+ }
254
+ ```
255
+
256
+ Without Cache Components, pass `init: { next: { revalidate: 60, tags: ['pets'] } }`.
257
+ `hooks.ts` starts with `'use client'`; import it from `@/lib/api/hooks`. The scaffolded
258
+ `client.ts` reads `NEXT_PUBLIC_API_BASE_URL`.
259
+
260
+ ## Caching
261
+
262
+ A run is skipped when the generator version, the config and every source's content hash match
263
+ the last run and the generated files are untouched. The state lives in
264
+ `.jutsu-api/<project>/manifest.json`.
265
+
266
+ - URLs are fetched with `If-None-Match` / `If-Modified-Since`; a 304 reuses the saved copy.
267
+ - Network errors and 5xx fall back to the saved copy with a warning; 4xx fails.
268
+ - `--offline` uses only saved copies.
269
+ - Only files whose content changed are rewritten.
270
+
271
+ Each generated file carries a `// @checksum sha256:…` header. If a generated file was edited,
272
+ or a file with the same name was not created by the tool, generation stops and lists it. Move
273
+ the change to `client.ts`, or use `--force`.
274
+
275
+ ## CLI
276
+
277
+ ```text
278
+ jutsu-api [generate|check|collect|init] [options]
279
+ ```
280
+
281
+ | Command | Description |
282
+ | ---------- | ---------------------------------------------------------------- |
283
+ | `generate` | Build the collection and the client (default) |
284
+ | `check` | Exit 1 when generated files are out of date (CI) |
285
+ | `collect` | Only build `api-collection.json` |
286
+ | `init` | Create the config (`--name`, `--target`, `--source`, `--output`) |
287
+
288
+ Options: `-c, --config <file>`, `--cwd <dir>`, `-f, --force`, `--offline`, `--dry-run`,
289
+ `-q, --quiet`, `-v, --verbose`. Exit codes: `0` ok, `1` failure or stale, `2` usage / config
290
+ error.
291
+
292
+ In CI, commit the generated files and run `npx jutsu-api check`. It regenerates in memory
293
+ and ignores the cache. Remote sources need network access and their secrets in CI.
294
+
295
+ The same functions are exported for scripts: `generate`, `check`, `collect`, `init`, plus
296
+ `parsePostman`, `parseOpenApi`, `buildCollection` and `emitFiles`.
297
+
298
+ ## Security
299
+
300
+ - Strings from specs are escaped before they reach generated code; identifiers are reduced
301
+ to `[A-Za-z0-9_$]`.
302
+ - API keys and `${VAR}` headers are never written to disk or logs, and are not forwarded on
303
+ redirects to another origin. URLs with embedded credentials are rejected.
304
+ - Output and cache folders must be inside the project.
305
+ - Downloads are capped at 50 MB and 30 s; YAML aliases and schema depth are limited.
306
+
307
+ ## Troubleshooting
308
+
309
+ | Message / symptom | Fix |
310
+ | --------------------------------------- | -------------------------------------------------------------------- |
311
+ | `No <project>-api.config.json` | Run `npx jutsu-api init` or pass `--config` |
312
+ | `generated file(s) were edited by hand` | Move the change to `client.ts`, then `--force` |
313
+ | `Source "x" … answered 401` | Check `headers` / `POSTMAN_API_KEY`; `--offline` uses the saved copy |
314
+ | `segment "{name}.{ext}" mixes text …` | Pass the whole segment as one param, e.g. `nameAndExt: 'a.pdf'` |
315
+ | A Postman field is `unknown` | Its example was `{{variable}}` or `null`; save a real example |
316
+ | Imports fail with `NodeNext` | Set `"importExtension": ".js"` |
317
+
318
+ ## Development
319
+
320
+ ```bash
321
+ yarn install
322
+ yarn verify # lint, typecheck, tests, build, CLI smoke test
323
+ ```
324
+
325
+ `src/parsers` reads sources, `src/collect` merges them into the collection, `src/codegen`
326
+ writes the files, and `src/generate.ts` handles caching and writes. `test/typecheck.test.ts`
327
+ compiles generated code for every target under strict settings. `test/stubs/` mirrors the
328
+ react-native-fetch types that generated code uses; update it when those types change.
329
+
330
+ ## License
331
+
332
+ MIT © JutsuStack
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../dist/cli.js';
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => {
6
+ process.exitCode = code;
7
+ },
8
+ (error) => {
9
+ console.error(
10
+ error instanceof Error ? (error.stack ?? error.message) : error
11
+ );
12
+ process.exitCode = 1;
13
+ }
14
+ );
@@ -0,0 +1,36 @@
1
+ export interface ManifestSource {
2
+ id: string;
3
+ /** file path (relative to the config) or URL; never contains credentials */
4
+ origin: string;
5
+ /** sha256 of the source content (plus its Postman environment, if any) */
6
+ hash: string;
7
+ etag?: string;
8
+ lastModified?: string;
9
+ /** Postman API `updatedAt` */
10
+ updatedAt?: string;
11
+ /** local file modification time */
12
+ mtime?: string;
13
+ fetchedAt: string;
14
+ }
15
+ /** `.jutsu-api/<project>/manifest.json`: what the last generation was made from. */
16
+ export interface Manifest {
17
+ version: 1;
18
+ generator: string;
19
+ generatedAt: string;
20
+ /** hash of generator version + config + source hashes */
21
+ inputKey: string;
22
+ configHash: string;
23
+ sources: ManifestSource[];
24
+ /** output path (relative to the config dir, `/`-separated) → sha256 of its content */
25
+ outputs: Record<string, string>;
26
+ }
27
+ export declare function manifestPath(cacheDir: string): string;
28
+ export declare function snapshotPath(cacheDir: string, sourceId: string): string;
29
+ export declare function readManifest(cacheDir: string): Promise<Manifest | undefined>;
30
+ export declare function writeManifest(cacheDir: string, manifest: Manifest): Promise<void>;
31
+ /** Same inputs → same key → the previous output is still correct. */
32
+ export declare function computeInputKey(configHash: string, sources: {
33
+ id: string;
34
+ hash: string;
35
+ }[]): string;
36
+ //# sourceMappingURL=manifest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../src/cache/manifest.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,4EAA4E;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,8BAA8B;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mCAAmC;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,oFAAoF;AACpF,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,CAAC,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,yDAAyD;IACzD,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,sFAAsF;IACtF,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAED,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAErD;AAED,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEvE;AAED,wBAAsB,YAAY,CAChC,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAY/B;AAED,wBAAsB,aAAa,CACjC,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,QAAQ,GACjB,OAAO,CAAC,IAAI,CAAC,CAKf;AAED,qEAAqE;AACrE,wBAAgB,eAAe,CAC7B,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,GACtC,MAAM,CAQR"}
@@ -0,0 +1,37 @@
1
+ import path from 'node:path';
2
+ import { readTextIfExists, writeFileAtomic } from '../util/fs.js';
3
+ import { sha256, stableStringify } from '../util/hash.js';
4
+ import { PACKAGE_NAME, VERSION } from '../version.js';
5
+ export function manifestPath(cacheDir) {
6
+ return path.join(cacheDir, 'manifest.json');
7
+ }
8
+ export function snapshotPath(cacheDir, sourceId) {
9
+ return path.join(cacheDir, 'sources', `${sourceId}.txt`);
10
+ }
11
+ export async function readManifest(cacheDir) {
12
+ const text = await readTextIfExists(manifestPath(cacheDir));
13
+ if (text === undefined)
14
+ return undefined;
15
+ try {
16
+ const value = JSON.parse(text);
17
+ // an unreadable or foreign manifest just means "no cache"
18
+ return value && value.version === 1 && typeof value.inputKey === 'string'
19
+ ? value
20
+ : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ export async function writeManifest(cacheDir, manifest) {
27
+ await writeFileAtomic(manifestPath(cacheDir), JSON.stringify(manifest, null, 2) + '\n');
28
+ }
29
+ /** Same inputs → same key → the previous output is still correct. */
30
+ export function computeInputKey(configHash, sources) {
31
+ return sha256(stableStringify({
32
+ generator: `${PACKAGE_NAME}@${VERSION}`,
33
+ config: configHash,
34
+ sources: sources.map((s) => [s.id, s.hash]),
35
+ }));
36
+ }
37
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/cache/manifest.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AA8BtD,MAAM,UAAU,YAAY,CAAC,QAAgB;IAC3C,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,eAAe,CAAC,CAAC;AAC9C,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,QAAgB,EAAE,QAAgB;IAC7D,OAAO,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,GAAG,QAAQ,MAAM,CAAC,CAAC;AAC3D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,QAAgB;IAEhB,MAAM,IAAI,GAAG,MAAM,gBAAgB,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC5D,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACzC,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAa,CAAC;QAC3C,0DAA0D;QAC1D,OAAO,KAAK,IAAI,KAAK,CAAC,OAAO,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,QAAQ,KAAK,QAAQ;YACvE,CAAC,CAAC,KAAK;YACP,CAAC,CAAC,SAAS,CAAC;IAChB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,aAAa,CACjC,QAAgB,EAChB,QAAkB;IAElB,MAAM,eAAe,CACnB,YAAY,CAAC,QAAQ,CAAC,EACtB,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CACzC,CAAC;AACJ,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,eAAe,CAC7B,UAAkB,EAClB,OAAuC;IAEvC,OAAO,MAAM,CACX,eAAe,CAAC;QACd,SAAS,EAAE,GAAG,YAAY,IAAI,OAAO,EAAE;QACvC,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;KAC5C,CAAC,CACH,CAAC;AACJ,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { Logger } from './util/log.js';
2
+ export declare const HELP = "@jutsustack/api-codegen 0.1.0\nGenerate a typed API layer for React Native, React and Next.js from Postman,\nSwagger and OpenAPI collections.\n\nUsage\n jutsu-api [command] [options]\n\nCommands\n generate Build api-collection.json and the typed client (default)\n check Exit 1 when generated files are out of date (CI)\n collect Only build api-collection.json\n init Create <project>-api.config.json\n\nOptions\n -c, --config <file> Config file (default: the *-api.config.json in the cwd)\n --cwd <dir> Run as if started in <dir>\n -f, --force Regenerate even if nothing changed; overwrite edited files\n --offline Use cached copies of remote sources, never the network\n --dry-run Show what would change without writing\n -q, --quiet Only print warnings and errors\n -v, --verbose Print debug details\n -h, --help Show this help\n -V, --version Show the version\n\ninit options\n --name <project> Project name (default: package.json name)\n --target <t> react-native | react | next (default: detected)\n --source <s> Path or URL of the first collection / spec\n --output <dir> Output folder (default: src/api, lib/api for Next.js)\n\nExit codes\n 0 success / up to date 1 failure or stale (check) 2 usage or config error\n\nEnvironment\n POSTMAN_API_KEY Key for \"postman\": { \"collectionId\" } sources\n NO_COLOR Disable colours\n";
3
+ /** Run the CLI; resolves the process exit code. */
4
+ export declare function main(argv: string[], io?: {
5
+ logger?: Logger;
6
+ }): Promise<number>;
7
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAG5C,eAAO,MAAM,IAAI,w+CAoChB,CAAC;AAwCF,mDAAmD;AACnD,wBAAsB,IAAI,CACxB,IAAI,EAAE,MAAM,EAAE,EACd,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAC3B,OAAO,CAAC,MAAM,CAAC,CA0DjB"}