kanagata 0.0.0-stage → 0.0.1
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 +236 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +4 -0
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +215 -0
- package/dist/client.d.ts +228 -0
- package/dist/client.js +407 -0
- package/dist/emit.d.ts +42 -0
- package/dist/emit.js +173 -0
- package/dist/error.d.ts +13 -0
- package/dist/error.js +18 -0
- package/dist/ident.d.ts +24 -0
- package/dist/ident.js +79 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +162 -0
- package/dist/json.d.ts +42 -0
- package/dist/json.js +368 -0
- package/dist/node-io.d.ts +9 -0
- package/dist/node-io.js +53 -0
- package/dist/operation.d.ts +11 -0
- package/dist/operation.js +222 -0
- package/dist/pointer.d.ts +118 -0
- package/dist/pointer.js +345 -0
- package/dist/schema.d.ts +7 -0
- package/dist/schema.js +395 -0
- package/dist/ty.d.ts +138 -0
- package/dist/ty.js +399 -0
- package/dist/yaml.d.ts +7 -0
- package/dist/yaml.js +59 -0
- package/package.json +54 -3
- package/src/client.ts +784 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Koji Wakamiya
|
|
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,237 @@
|
|
|
1
|
-
#
|
|
1
|
+
# kanagata
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript types from an OpenAPI 3.0 / 3.1 document (JSON or YAML), and a typed `fetch` client for them.
|
|
4
|
+
|
|
5
|
+
- `kanagata generate` writes one `.d.ts` file.
|
|
6
|
+
- `createClient` from `kanagata/client` is one function over `fetch`, with no imports: the path, query, header and cookie parameters and the body are checked against the operation, and the result is a union per status code.
|
|
7
|
+
|
|
8
|
+
## Quick start
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pnpm add -D kanagata
|
|
12
|
+
pnpm kanagata generate openapi.yaml -o src/api/schema.d.ts
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createClient } from "kanagata/client";
|
|
17
|
+
import type { paths, User } from "./api/schema";
|
|
18
|
+
|
|
19
|
+
const api = createClient<paths>({ baseUrl: "https://api.example.com" });
|
|
20
|
+
|
|
21
|
+
const res = await api.get("/users/{id}", { path: { id: 1 } });
|
|
22
|
+
if (res.status === 200) {
|
|
23
|
+
const user: User = res.data;
|
|
24
|
+
} else {
|
|
25
|
+
res.data.message; // the 404 body
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Run `generate` again after upgrading kanagata: the types and the client come from the same version.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
- The CLI needs Node 24 or later (`engines`). Its one dependency is [`yaml`](https://github.com/eemeli/yaml), which has none.
|
|
34
|
+
- The client needs only the Fetch API (with `URL`, `FormData`, `Blob`, `ReadableStream`) and ES2022.
|
|
35
|
+
- The package is ES modules only.
|
|
36
|
+
- A dev dependency is enough when the app is bundled. Put kanagata in `dependencies` when `kanagata/client` is loaded from `node_modules` at run time: a Node server installed without dev dependencies, or a library you publish.
|
|
37
|
+
|
|
38
|
+
## CLI
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
kanagata generate openapi.yaml -o src/api/schema.d.ts # write a file
|
|
42
|
+
kanagata generate openapi.json -o src/api/schema.d.ts --check # CI: exit 1 if the file is stale
|
|
43
|
+
kanagata generate - < openapi.yaml > src/api/schema.d.ts # stdin to stdout
|
|
44
|
+
kanagata init -o src/api/client.ts # copy the client into your project
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
| Option | Meaning |
|
|
48
|
+
| ----------- | --------------------------------------------------------- |
|
|
49
|
+
| `-o <path>` | output file (`generate`: stdout; `init`: `./client.ts`) |
|
|
50
|
+
| `--check` | `generate`: compare with the `-o` file instead of writing |
|
|
51
|
+
| `--force` | `init`: overwrite an existing file |
|
|
52
|
+
|
|
53
|
+
- **Exit codes:** 0 success, 1 `--check` found a difference, 2 an error (document, command line, or file I/O), 3 a bug in kanagata (stack on stderr).
|
|
54
|
+
- **Messages** go to stderr as `location: message` or `location: warning: message`. The location is `line:col` for JSON and YAML syntax, a JSON Pointer otherwise, and starts with the file's path relative to the document for other files (`schemas/User.yaml#/properties/id`, `common.json:3:5`).
|
|
55
|
+
- **stdin** (`-`) has no location, so it cannot `$ref` other files.
|
|
56
|
+
- **Format:** a document that starts with `{` is JSON, anything else YAML 1.2. A key repeated in one object is an error in both.
|
|
57
|
+
- **YAML:** numbers keep their notation when it is a JSON number (`1.50` stays `1.50`); YAML-only forms become the number they mean (`0x1F` is `31`). An alias is a copy of its node. The merge key `<<` is YAML 1.1, so it is an ordinary key, with a warning.
|
|
58
|
+
|
|
59
|
+
## Client
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
const api = createClient<paths>({
|
|
63
|
+
baseUrl: "https://api.example.com",
|
|
64
|
+
fetch: (request) => {
|
|
65
|
+
request.headers.set("authorization", `Bearer ${token}`); // keeps the other headers
|
|
66
|
+
return fetch(request);
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
await api.put("/files/{name}", {
|
|
71
|
+
path: { name: "a.png" },
|
|
72
|
+
body: file,
|
|
73
|
+
contentType: "image/png",
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const events = await api.get("/events", { parseAs: "stream" }); // events.data: ReadableStream | null
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`api.get`, `api.post`, … (one per HTTP method but `trace`, which fetch rejects; the declarations still type trace operations) take the path template and an object of options, which is optional when nothing in it is required. A required body cannot be `undefined`, even when its schema admits any value. A union of path templates takes options that hold what every one of them needs.
|
|
80
|
+
|
|
81
|
+
### Config (`createClient`)
|
|
82
|
+
|
|
83
|
+
| Key | Meaning |
|
|
84
|
+
| -------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
85
|
+
| `baseUrl` | absolute (`https://api.example.com/v1`) or relative (`/api`, `""`); see below |
|
|
86
|
+
| `fetch` | `(request) => Promise<Response>` in place of the global `fetch`; wrap it for auth, retries, logging, tests |
|
|
87
|
+
| `headers` | an object, or a function (sync or async) called on every request |
|
|
88
|
+
| `arrayFormat` | arrays in queries and URL-encoded bodies: `repeat` (default), `brackets`, `comma`, `space`, `pipe` |
|
|
89
|
+
| `objectFormat` | objects in queries and URL-encoded bodies: `deepObject` (default), `json` |
|
|
90
|
+
| `onData` | `(data, call) => value` (sync or async): receives every parsed body; return the value to use, or throw |
|
|
91
|
+
| fetch options | `credentials`, `cache`, `mode`, `redirect`, `keepalive`, `signal`, … |
|
|
92
|
+
|
|
93
|
+
### Call options
|
|
94
|
+
|
|
95
|
+
| Key | Meaning |
|
|
96
|
+
| ----------------------------------- | --------------------------------------------------------------------------------------------- |
|
|
97
|
+
| `baseUrl` | required for an operation that declares `servers`: one of them, used in place of the config's |
|
|
98
|
+
| `path`, `query`, `header`, `cookie` | the parameters the operation declares |
|
|
99
|
+
| `body`, `contentType` | the request body and which of the operation's media types it is |
|
|
100
|
+
| `parseAs` | `json`, `text`, `blob`, `arrayBuffer` or `stream`: read the response this way |
|
|
101
|
+
| `headers` | headers for this call |
|
|
102
|
+
| `arrayFormat`, `objectFormat` | override the client's |
|
|
103
|
+
| fetch options | as in the config; a call's win. The client sets `method`, `headers` and `body` itself |
|
|
104
|
+
|
|
105
|
+
### Result
|
|
106
|
+
|
|
107
|
+
`{ status, ok, data, response }`, a union over the statuses the operation documents. `ResultOf<paths, "get", "/users/{id}">` is its type for `api.get("/users/{id}", …)`, and `ResultOf<paths, "get", "/users/{id}", "text">` with `parseAs: "text"`. `Result<Operation, ParseAs, Method>` is the same by operation; without the method, a HEAD result keeps the declared body.
|
|
108
|
+
|
|
109
|
+
- **`data`** is parsed by the response's content-type: JSON, text, or `Blob` for binary types. An empty body gives `undefined`. fetch gives HEAD responses and 204, 205 and 304 no body, so their `data` is typed `undefined` whatever the document declares. A status that declares `content` but sends none also gives `undefined`; check for it in `onData`.
|
|
110
|
+
- The content-type the server sends decides, not the document: content typed by a wildcard (`*/*`) is typed by its schema but read as whatever arrives, and a response without a content-type is text (`parseAs: "blob"` keeps its bytes).
|
|
111
|
+
- `data` is read once the whole body has arrived; for a stream that stays open (`text/event-stream`), use `parseAs: "stream"`.
|
|
112
|
+
- **`parseAs`** reads the body its way for one call and types `data` to match: `text` a string, `blob` a `Blob`, `arrayBuffer` an `ArrayBuffer`, `stream` the body (`null` when there is none), `json` the parsed JSON (`undefined` when empty), typed by the schemas of JSON and wildcard media types and `unknown` for the others.
|
|
113
|
+
- **`ok`** is fetch's: `true` for 2xx. For `default` (every status the operation does not list, 2xx included) it is `boolean`; narrow by `status` or `ok`.
|
|
114
|
+
- **Undocumented statuses:** list them with `default` or a range (`4XX`, `5XX`) in the document and they are typed. A status outside the document is still returned, in the branch the types call unreachable. An operation that documents no responses gives `status: number`, `ok: boolean` and `data: unknown`.
|
|
115
|
+
- **Response headers** are typed in the declarations (`responses[200].headers`); read them from `res.response.headers`.
|
|
116
|
+
|
|
117
|
+
### Details
|
|
118
|
+
|
|
119
|
+
- **baseUrl:** a relative one resolves on every call as fetch resolves it: against the page's base URL, or the worker's location. Where there is neither (Node), it throws a TypeError. `""` is the origin of the page's base URL. Its own query is kept, before the call's. An operation that declares `servers` (or whose path item does) is served there, not by the document's servers, so its call names one of them as `baseUrl`; other operations take the config's and cannot be given one.
|
|
120
|
+
- **Headers:** the config's `headers`, then the call's header parameters, then its cookie parameters, then its `headers`; a later one replaces an earlier one of the same name. Cookie parameters go in the `cookie` header, which browsers do not let fetch set. A `Date` is sent as its ISO string.
|
|
121
|
+
- **content-type** comes from the body, never from the config's `headers` (with or without a body); one in the call's `headers` replaces it, except for a multipart body made from an object or a `FormData`, which needs its boundary.
|
|
122
|
+
- **Request bodies:** a value is sent as JSON (strings included), URL-encoded, or as `FormData`, by its media type; text and binary bodies as they are.
|
|
123
|
+
- `contentType` may be left out for `application/json` (which is then sent) and for a `FormData` or `URLSearchParams`, with or without media type parameters. Other JSON types (`application/merge-patch+json`) must be named.
|
|
124
|
+
- A binary body is a `Blob`, `ArrayBuffer`, typed array or `ReadableStream`.
|
|
125
|
+
- A wildcard (`*/*`, `application/*`) names no media type: a string, `Blob` or other raw body is sent with its own content-type, and any other value as JSON with `application/json`.
|
|
126
|
+
- A URL-encoded or multipart value that is not a raw body must be an object; otherwise a TypeError. A `Blob` cannot be URL-encoded, in a body or a query; that is a TypeError too.
|
|
127
|
+
- Multipart fields: an array repeats the field, a `Blob` is a file, a `Date` its ISO string, another object JSON. Another multipart type (`multipart/mixed`, `multipart/related`) gets the same named parts under its own type.
|
|
128
|
+
- A raw body (string, `Blob`, `URLSearchParams`, …) is sent as it is for form media types too.
|
|
129
|
+
- **Parameters:** the delimiters `[`, `]` and `|` are percent-encoded, as OpenAPI requires (`filter%5Bname%5D=n`, `ids=1%7C2`). An object or array inside an array is JSON, in every `arrayFormat`. Path, header and cookie parameters take the same values: arrays `1,2`, objects `x,1,y,2`. Undefined and null are left out, and so is an empty array. A path parameter of `""`, `.` or `..` throws, since the URL would reach another endpoint.
|
|
130
|
+
- **Errors:** HTTP error statuses never throw; network failures are fetch's own errors. A body that is not valid JSON where its content-type or `parseAs: "json"` says JSON (HTML sent as JSON) throws `ResponseBodyError`, which carries the response and the text. An error thrown by `config.headers`, `config.fetch` or `onData` rejects the call as it is.
|
|
131
|
+
- **`config.fetch`** receives the built `Request`; what it returns is read. A request body can be sent once, so a retrying wrapper sends a `request.clone()` taken before the first attempt.
|
|
132
|
+
- **`onData`'s `call`** has `method`, `path` (the template, `/users/{id}`), `status`, `parseAs`, `request` and `response`. Plug a zod or valibot schema in here; `data` stays typed by the OpenAPI schema.
|
|
133
|
+
|
|
134
|
+
### Owning the client
|
|
135
|
+
|
|
136
|
+
`kanagata init -o src/api/client.ts` copies the client's source (one TypeScript file, no imports, stamped with the kanagata version) into your project; import it from there instead of `kanagata/client` and edit it as you like. After upgrading kanagata, refresh it with `kanagata init -o src/api/client.ts --force` and reapply your edits: the generated types follow the media type rules of the client of the same version.
|
|
137
|
+
|
|
138
|
+
## Library API
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import { readFileSync } from "node:fs";
|
|
142
|
+
import { pathToFileURL } from "node:url";
|
|
143
|
+
import { GenerateError, generate } from "kanagata";
|
|
144
|
+
|
|
145
|
+
const file = "openapi.yaml";
|
|
146
|
+
try {
|
|
147
|
+
const { code, warnings } = generate(readFileSync(file, "utf8"), {
|
|
148
|
+
url: pathToFileURL(file).href,
|
|
149
|
+
read: (url) => readFileSync(new URL(url), "utf8"),
|
|
150
|
+
});
|
|
151
|
+
for (const w of warnings) console.warn(`${w.at}: ${w.msg}`);
|
|
152
|
+
// code: the .d.ts text
|
|
153
|
+
} catch (e) {
|
|
154
|
+
if (e instanceof GenerateError)
|
|
155
|
+
console.error(e.message); // e.kind: "json" | "yaml" | "input"
|
|
156
|
+
else throw e;
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`generate(src, source?)` returns `{ code, warnings }` and throws `GenerateError`. `source` is the document's absolute URL and `read(url)`, which returns the text of a file a `$ref` points to; without it, `$ref`s to other files are errors.
|
|
161
|
+
|
|
162
|
+
## Output
|
|
163
|
+
|
|
164
|
+
- Every schema in `components.schemas` is a named type (`export type User = { … }`), referenced by name. Names are PascalCase, with `_` before one that would start with a digit; a taken or reserved name gets a number (`User2`). `export interface schemas` maps each original name to its type.
|
|
165
|
+
- Operations are `paths[path][method]`, `webhooks[name][method]` (3.1; every key is a name, `x-` ones included), and `operations[operationId]`.
|
|
166
|
+
- A schema with a `readOnly` / `writeOnly` property (on it or on a schema it references) gets a second type for requests, `UserInput`.
|
|
167
|
+
- `description` and `deprecated` become JSDoc.
|
|
168
|
+
- Header parameters named `Accept`, `Content-Type` or `Authorization`, and a response header `Content-Type`, are ignored, as OpenAPI requires.
|
|
169
|
+
- An operation's `servers`, or its path item's, is `servers: ["https://uploads.example.com"]` in its type; a URL with variables (`{region}`) is `string`. A webhook has none, since the API sends its request.
|
|
170
|
+
- A `requestBody` on a GET or HEAD operation is left out: OpenAPI 3.0 has consumers ignore it, and fetch cannot send one. A webhook keeps it, since the API sends that request.
|
|
171
|
+
|
|
172
|
+
### `$ref`
|
|
173
|
+
|
|
174
|
+
- Resolved as JSON Schema 2020-12 does: JSON Pointers, `$anchor`s (`#node`), and the `$id`s the document declares, relative to the nearest `$id` (3.1).
|
|
175
|
+
- Other files (`schemas/User.yaml`, `common.json#/Error`) resolve relative to the file the `$ref` is in; each is read once, JSON or YAML by its content. URLs are not fetched.
|
|
176
|
+
- A schema in another file is a named type. A component that is only a `$ref` to it (with at most `title` and `description`) gives the name (`User: { $ref: schemas/User.yaml }`); otherwise it is named after the file (`Order.yaml` → `Order`) or the pointer's last token (`common.json#/Error` → `Error`), numbered when taken, and listed in `schemas`.
|
|
177
|
+
- A component that is only a `$ref` within the document names its target the same way; other targets within the document are expanded where they are used.
|
|
178
|
+
- A schema may refer to itself through an object, array or tuple (`next?: Node`). A cycle among `$ref`s expanded inline becomes `unknown`, with a warning.
|
|
179
|
+
|
|
180
|
+
### Schemas
|
|
181
|
+
|
|
182
|
+
Types follow what the schema accepts, not another generator's output.
|
|
183
|
+
|
|
184
|
+
| Schema | TypeScript |
|
|
185
|
+
| ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
186
|
+
| `true`, `{}` | `unknown` |
|
|
187
|
+
| `false` | `never` |
|
|
188
|
+
| `const`, `enum` | literal types; objects and arrays become exact object and tuple types |
|
|
189
|
+
| `allOf`, `oneOf` / `anyOf`, sibling `type` / object keywords | all intersected: `A & B & (C \| D)` |
|
|
190
|
+
| `discriminator` | not read (it must not change what is accepted, OAS 3.0.4 / 3.1.1); members narrow where they fix the property (`const`, `enum`) |
|
|
191
|
+
| keywords next to `$ref` | intersected in 3.1; ignored in 3.0 (`readOnly` / `writeOnly` too) except `nullable` and `description` |
|
|
192
|
+
| `type: [...]`, `nullable: true` (3.0) | union, with `null` |
|
|
193
|
+
| `type` with `const` / `enum`, and these with each other | the values all allow: `type: string, enum: ["a", 1]` is `"a"`; a contradiction is `never` |
|
|
194
|
+
| `type: integer` | `number`; non-integer `enum` / `const` values are dropped |
|
|
195
|
+
| `format: binary`; binary `contentMediaType` without `contentEncoding` | `Blob` |
|
|
196
|
+
| `prefixItems` | tuple; items past `minItems` are optional, `items` gives the rest |
|
|
197
|
+
| `required` key without a property schema, or whose property schema admits any value (`{}`, `true`, a `$ref` to one) | `key: {} \| null` (any value but `undefined`; `Anything & ({} \| null)` for a reference), so another member's type for it holds: `{ a?: string } & { a: {} \| null }` |
|
|
198
|
+
| `additionalProperties`, `patternProperties` | an index signature that also admits the declared properties (TypeScript cannot check the pattern) |
|
|
199
|
+
| `additionalProperties: false` with no properties, `const: {}`, `maxProperties: 0` | `{ [key: string]: never }`; with `maxProperties: 0` and a required key, `never` |
|
|
200
|
+
| `additionalProperties: false` (no `patternProperties`) and a required key outside `properties` | `never`, as is an `allOf` / `oneOf` / `anyOf` member next to it that requires one |
|
|
201
|
+
| object without properties | `Record<string, unknown>` |
|
|
202
|
+
| object keywords without `type` | an object (non-objects are never meant), so `{ type: "string", allOf: [{ properties: … }] }` is `never` |
|
|
203
|
+
| `readOnly` / `writeOnly` property | left out of what is sent / what is returned |
|
|
204
|
+
| `not`, `if` / `then` / `else`, `dependentSchemas`, `unevaluated*`, `$dynamicRef` | ignored, with a warning |
|
|
205
|
+
|
|
206
|
+
Content by media type:
|
|
207
|
+
|
|
208
|
+
| Media type | Type |
|
|
209
|
+
| ---------------------------------------------------------- | --------------------------------------- |
|
|
210
|
+
| JSON | its schema |
|
|
211
|
+
| `text/*`, XML | `string` |
|
|
212
|
+
| forms (`application/x-www-form-urlencoded`, `multipart/*`) | request: its schema; response: `string` |
|
|
213
|
+
| any other (binary), not a wildcard | `Blob` |
|
|
214
|
+
|
|
215
|
+
### `nullable` (3.0)
|
|
216
|
+
|
|
217
|
+
`nullable: true` adds `null` even without `type` (`{ nullable: true, allOf: [{ $ref: … }] }`) and next to an `enum` that does not list `null`. OpenAPI 3.0.3 says neither takes effect, but documents use both to mean "this schema or null" (Stripe and GitHub among them) and their servers return `null`, so kanagata follows the intent.
|
|
218
|
+
|
|
219
|
+
## Not supported
|
|
220
|
+
|
|
221
|
+
- Runtime validation (use `onData`), middleware (wrap `config.fetch`), per-operation functions, framework bindings, mocks.
|
|
222
|
+
- Per-parameter `style` / `explode` / `encoding`: a server parses every query and form the same way, so one `arrayFormat` / `objectFormat` per client (or per call) matches it.
|
|
223
|
+
- Fetching `$ref`s over the network; Swagger 2.0.
|
|
224
|
+
- Pathological inputs: a schema that is directly itself (`A: { $ref: A }`), looping `$ref`s or YAML aliases, nesting thousands of levels deep, or exponential expansion may crash (exit code 3) or not finish.
|
|
225
|
+
|
|
226
|
+
## Development
|
|
227
|
+
|
|
228
|
+
```sh
|
|
229
|
+
pnpm install
|
|
230
|
+
pnpm test
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
[AGENTS.md](AGENTS.md) covers the layout, commands and how to make changes.
|
|
234
|
+
|
|
235
|
+
## License
|
|
236
|
+
|
|
237
|
+
[MIT](LICENSE)
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** What the CLI needs from the outside world. Failures throw IoError. */
|
|
2
|
+
export interface Io {
|
|
3
|
+
/** The bytes of a file; `0` is standard input. */
|
|
4
|
+
read(file: string | 0): Uint8Array;
|
|
5
|
+
write(path: string, text: string): void;
|
|
6
|
+
exists(path: string): boolean;
|
|
7
|
+
stdout(text: string): void;
|
|
8
|
+
stderr(text: string): void;
|
|
9
|
+
/** A file of the package, by its path from the package root. */
|
|
10
|
+
asset(name: "src/client.ts" | "package.json"): string;
|
|
11
|
+
}
|
|
12
|
+
/** An I/O failure; the message says what went wrong without naming the file (`no such file or directory`). */
|
|
13
|
+
export declare class IoError extends Error {
|
|
14
|
+
}
|
|
15
|
+
/** Runs the CLI and returns the exit code. Anything but a usage, input or I/O error propagates. */
|
|
16
|
+
export declare function run(args: readonly string[], io: Io): number;
|
|
17
|
+
/** `run`, with a bug reported on stderr and exit code 3 (1 means `--check` found a difference). */
|
|
18
|
+
export declare function main(args: readonly string[], io: Io): number;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// Command-line interface, over an `Io` so it runs the same against the real system
|
|
2
|
+
// (node-io.ts, used by bin.ts) and in tests.
|
|
3
|
+
import { relative, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
|
+
import { inspect } from "node:util";
|
|
6
|
+
import { GenerateError, generate } from "./index.js";
|
|
7
|
+
/** An I/O failure; the message says what went wrong without naming the file (`no such file or directory`). */
|
|
8
|
+
export class IoError extends Error {
|
|
9
|
+
}
|
|
10
|
+
const HELP = `kanagata - TypeScript types from OpenAPI 3.0 / 3.1 (JSON or YAML), and a typed fetch client
|
|
11
|
+
|
|
12
|
+
Usage:
|
|
13
|
+
kanagata generate <openapi.json|yaml> [-o <out.d.ts>] [--check]
|
|
14
|
+
kanagata init [-o <client.ts>] [--force]
|
|
15
|
+
|
|
16
|
+
Commands:
|
|
17
|
+
generate Write the type declarations for the document (- reads stdin)
|
|
18
|
+
init Copy the fetch client (kanagata/client) into your project to own it
|
|
19
|
+
|
|
20
|
+
Options:
|
|
21
|
+
-o <path> Output file (generate: stdout, init: ./client.ts)
|
|
22
|
+
--check Exit with 1 if the -o file differs from the generated output
|
|
23
|
+
--force Let init overwrite an existing file
|
|
24
|
+
-h, --help Show this help
|
|
25
|
+
-V, --version Show the version
|
|
26
|
+
|
|
27
|
+
Exit codes: 0 success, 1 --check found a difference, 2 an error in the
|
|
28
|
+
document, the command line or a file, 3 a bug in kanagata
|
|
29
|
+
`;
|
|
30
|
+
/** Exit code for usage, input and I/O errors. */
|
|
31
|
+
const INPUT_ERROR = 2;
|
|
32
|
+
/** A usage or I/O error: printed to stderr, exit code 2. */
|
|
33
|
+
class Failure extends Error {
|
|
34
|
+
}
|
|
35
|
+
const strictUtf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
36
|
+
/** Runs the CLI and returns the exit code. Anything but a usage, input or I/O error propagates. */
|
|
37
|
+
export function run(args, io) {
|
|
38
|
+
const out = (text) => attempt("stdout", () => io.stdout(text));
|
|
39
|
+
const err = (line) => {
|
|
40
|
+
try {
|
|
41
|
+
io.stderr(`${line}\n`);
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
if (!(e instanceof IoError))
|
|
45
|
+
throw e; // nowhere left to report an I/O failure
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
try {
|
|
49
|
+
switch (args[0]) {
|
|
50
|
+
case "generate":
|
|
51
|
+
return generateCommand(args.slice(1), io, out, err);
|
|
52
|
+
case "init":
|
|
53
|
+
return initCommand(args.slice(1), io, out);
|
|
54
|
+
case "-h":
|
|
55
|
+
case "--help":
|
|
56
|
+
out(HELP);
|
|
57
|
+
return 0;
|
|
58
|
+
case "-V":
|
|
59
|
+
case "--version":
|
|
60
|
+
out(`kanagata ${version(io)}\n`);
|
|
61
|
+
return 0;
|
|
62
|
+
case undefined:
|
|
63
|
+
throw new Failure(HELP);
|
|
64
|
+
default:
|
|
65
|
+
throw new Failure(`unknown command: ${args[0]} (see kanagata --help)`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
if (!(e instanceof Failure || e instanceof GenerateError))
|
|
70
|
+
throw e;
|
|
71
|
+
err(e.message);
|
|
72
|
+
return INPUT_ERROR;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Exit code for a bug in kanagata: an error `run` does not expect. */
|
|
76
|
+
const INTERNAL_ERROR = 3;
|
|
77
|
+
/** `run`, with a bug reported on stderr and exit code 3 (1 means `--check` found a difference). */
|
|
78
|
+
export function main(args, io) {
|
|
79
|
+
try {
|
|
80
|
+
return run(args, io);
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
try {
|
|
84
|
+
io.stderr(`internal error (a bug in kanagata): ${inspect(e)}\n`);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// nowhere left to report it; the exit code still says what happened
|
|
88
|
+
}
|
|
89
|
+
return INTERNAL_ERROR;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function version(io) {
|
|
93
|
+
return JSON.parse(io.asset("package.json")).version;
|
|
94
|
+
}
|
|
95
|
+
/** Runs an I/O step; its failure is reported as `label: message`. */
|
|
96
|
+
function attempt(label, f) {
|
|
97
|
+
try {
|
|
98
|
+
return f();
|
|
99
|
+
}
|
|
100
|
+
catch (e) {
|
|
101
|
+
if (e instanceof IoError)
|
|
102
|
+
throw new Failure(`${label}: ${e.message}`);
|
|
103
|
+
throw e;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function parseFlags(args, allowed) {
|
|
107
|
+
const f = { positional: [], check: false, force: false, help: false };
|
|
108
|
+
const rest = args[Symbol.iterator]();
|
|
109
|
+
for (const a of rest) {
|
|
110
|
+
const isOption = a.startsWith("-") && a !== "-";
|
|
111
|
+
const isHelp = a === "-h" || a === "--help";
|
|
112
|
+
if (isOption && !allowed.includes(a) && !isHelp)
|
|
113
|
+
throw new Failure(`unknown option: ${a}`);
|
|
114
|
+
if (a === "-o") {
|
|
115
|
+
const path = rest.next();
|
|
116
|
+
if (path.done)
|
|
117
|
+
throw new Failure("-o needs a path");
|
|
118
|
+
f.output = path.value;
|
|
119
|
+
}
|
|
120
|
+
else if (a === "--check")
|
|
121
|
+
f.check = true;
|
|
122
|
+
else if (a === "--force")
|
|
123
|
+
f.force = true;
|
|
124
|
+
else if (isHelp)
|
|
125
|
+
f.help = true;
|
|
126
|
+
else
|
|
127
|
+
f.positional.push(a);
|
|
128
|
+
}
|
|
129
|
+
return f;
|
|
130
|
+
}
|
|
131
|
+
function generateCommand(args, io, out, err) {
|
|
132
|
+
const f = parseFlags(args, ["-o", "--check"]);
|
|
133
|
+
if (f.help) {
|
|
134
|
+
out(HELP);
|
|
135
|
+
return 0;
|
|
136
|
+
}
|
|
137
|
+
const [input, extra] = f.positional;
|
|
138
|
+
if (input === undefined)
|
|
139
|
+
throw new Failure("missing <openapi.json|yaml> (use - for stdin)");
|
|
140
|
+
if (extra !== undefined)
|
|
141
|
+
throw new Failure(`unexpected argument: ${extra}`);
|
|
142
|
+
if (f.check && f.output === undefined)
|
|
143
|
+
throw new Failure("--check needs -o <out.d.ts>");
|
|
144
|
+
const label = input === "-" ? "stdin" : input;
|
|
145
|
+
const src = decode(label, attempt(label, () => io.read(input === "-" ? 0 : input)));
|
|
146
|
+
// A file has a location, so its $refs to other files can be followed; stdin has none.
|
|
147
|
+
const generated = generate(src, input === "-" ? undefined : fileSource(input, io));
|
|
148
|
+
for (const w of generated.warnings)
|
|
149
|
+
err(`${w.at}: warning: ${w.msg}`);
|
|
150
|
+
const target = f.output;
|
|
151
|
+
if (target === undefined) {
|
|
152
|
+
out(generated.code);
|
|
153
|
+
return 0;
|
|
154
|
+
}
|
|
155
|
+
if (f.check) {
|
|
156
|
+
// A file that is missing or not UTF-8 is simply out of date.
|
|
157
|
+
let current;
|
|
158
|
+
try {
|
|
159
|
+
current = strictUtf8.decode(io.read(target));
|
|
160
|
+
}
|
|
161
|
+
catch (e) {
|
|
162
|
+
if (!(e instanceof IoError || e instanceof TypeError))
|
|
163
|
+
throw e;
|
|
164
|
+
}
|
|
165
|
+
if (current === generated.code)
|
|
166
|
+
return 0;
|
|
167
|
+
err(`${target}: out of date; run kanagata generate`);
|
|
168
|
+
return 1;
|
|
169
|
+
}
|
|
170
|
+
attempt(target, () => io.write(target, generated.code));
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
function initCommand(args, io, out) {
|
|
174
|
+
const f = parseFlags(args, ["-o", "--force"]);
|
|
175
|
+
if (f.help) {
|
|
176
|
+
out(HELP);
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
179
|
+
if (f.positional.length > 0)
|
|
180
|
+
throw new Failure(`unexpected argument: ${f.positional[0]}`);
|
|
181
|
+
const target = f.output ?? "client.ts";
|
|
182
|
+
if (io.exists(target) && !f.force)
|
|
183
|
+
throw new Failure(`${target}: already exists (use --force to overwrite)`);
|
|
184
|
+
// The version tells which generator's rules (binary and text media types) the copy follows.
|
|
185
|
+
const client = `// Written by \`kanagata init\` (kanagata ${version(io)}). This copy is yours: edit it as you like.\n${io.asset("src/client.ts")}`;
|
|
186
|
+
attempt(target, () => io.write(target, client));
|
|
187
|
+
return 0;
|
|
188
|
+
}
|
|
189
|
+
/** The input file's location, and a reader for the local files its `$ref`s point to. */
|
|
190
|
+
function fileSource(input, io) {
|
|
191
|
+
return {
|
|
192
|
+
url: pathToFileURL(resolve(input)).href,
|
|
193
|
+
read: (url) => {
|
|
194
|
+
const target = new URL(url);
|
|
195
|
+
if (target.protocol !== "file:")
|
|
196
|
+
throw new Error("only local files are read");
|
|
197
|
+
// Io takes paths as the user gives them: relative to the working directory.
|
|
198
|
+
const bytes = io.read(relative(process.cwd(), fileURLToPath(target)));
|
|
199
|
+
try {
|
|
200
|
+
return strictUtf8.decode(bytes);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
throw new Error("not valid UTF-8");
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
function decode(label, bytes) {
|
|
209
|
+
try {
|
|
210
|
+
return strictUtf8.decode(bytes);
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
throw new Failure(`${label}: stream did not contain valid UTF-8`);
|
|
214
|
+
}
|
|
215
|
+
}
|