kanagata 0.2.3 → 0.3.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/README.md +11 -195
- package/dist/cli.js +10 -9
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/pointer.d.ts +3 -3
- package/dist/pointer.js +4 -4
- package/dist/schema.js +108 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,18 +44,7 @@ kanagata generate - < openapi.yaml > src/api/schema.d.ts # stdin to stdout
|
|
|
44
44
|
kanagata init -o src/api/client.ts # copy the client into your project
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
|
|
48
|
-
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
49
|
-
| `-o <path>` | output file (`generate`: stdout; `init`: `./client.ts`) |
|
|
50
|
-
| `--check` | `generate`: compare with the `-o` file instead of writing |
|
|
51
|
-
| `--strict-nullable-enum` | `generate`: in 3.0, keep `null` out of an `enum` or `const` that does not list it, even with `nullable: true`; see [`nullable`](#nullable-30) |
|
|
52
|
-
| `--force` | `init`: overwrite an existing file |
|
|
53
|
-
|
|
54
|
-
- **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).
|
|
55
|
-
- **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`).
|
|
56
|
-
- **stdin** (`-`) has no location, so it cannot `$ref` other files.
|
|
57
|
-
- **Format:** a document that starts with `{` is JSON, anything else YAML 1.2. A key repeated in one object is an error in both.
|
|
58
|
-
- **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.
|
|
47
|
+
`--loose-nullable` reads 3.0 `nullable: true` as "this schema or null" (see [Generated types](#generated-types)). Every option, the exit codes and messages, and `generate` as a library: [docs/cli.md](docs/cli.md).
|
|
59
48
|
|
|
60
49
|
## Client
|
|
61
50
|
|
|
@@ -77,193 +66,20 @@ await api.put("/files/{name}", {
|
|
|
77
66
|
const events = await api.get("/events", { parseAs: "stream" }); // events.data: ReadableStream | null
|
|
78
67
|
```
|
|
79
68
|
|
|
80
|
-
`api.get`, `api.post`, …
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
### Config (`createClient`)
|
|
85
|
-
|
|
86
|
-
| Key | Meaning |
|
|
87
|
-
| -------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
88
|
-
| `baseUrl` | absolute (`https://api.example.com/v1`) or relative (`/api`, `""`); see below |
|
|
89
|
-
| `fetch` | `(request) => Promise<Response>` in place of the global `fetch`; wrap it for auth, retries, logging, tests |
|
|
90
|
-
| `headers` | an object, or a function (sync or async) called on every request |
|
|
91
|
-
| `arrayFormat` | arrays in queries and URL-encoded bodies: `repeat` (default), `brackets`, `comma`, `space`, `pipe` |
|
|
92
|
-
| `objectFormat` | objects in queries and URL-encoded bodies: `deepObject` (default), `json` |
|
|
93
|
-
| `onData` | `(data, call) => value` (sync or async): receives every parsed body; return the value to use, or throw |
|
|
94
|
-
| fetch options | `credentials`, `cache`, `mode`, `redirect`, `keepalive`, `signal`, … |
|
|
95
|
-
|
|
96
|
-
### Call options
|
|
97
|
-
|
|
98
|
-
| Key | Meaning |
|
|
99
|
-
| ----------------------------------- | --------------------------------------------------------------------------------------------- |
|
|
100
|
-
| `baseUrl` | required for an operation that declares `servers`: one of them, used in place of the config's |
|
|
101
|
-
| `path`, `query`, `header`, `cookie` | the parameters the operation declares |
|
|
102
|
-
| `querystring` | the operation's `in: querystring` parameter (3.2), the whole query; see Details |
|
|
103
|
-
| `body`, `contentType` | the request body and which of the operation's media types it is |
|
|
104
|
-
| `parseAs` | `json`, `text`, `blob`, `arrayBuffer` or `stream`: read the response this way |
|
|
105
|
-
| `headers` | headers for this call |
|
|
106
|
-
| `arrayFormat`, `objectFormat` | override the client's |
|
|
107
|
-
| fetch options | as in the config; a call's win. The client sets `method`, `headers` and `body` itself |
|
|
108
|
-
|
|
109
|
-
### Result
|
|
110
|
-
|
|
111
|
-
`{ 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}", …)`, `ResultOf<paths, "COPY", "/files/{name}">` for `api.request("COPY", "/files/{name}", …)`, 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.
|
|
112
|
-
|
|
113
|
-
- **`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`.
|
|
114
|
-
- 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).
|
|
115
|
-
- `data` is read once the whole body has arrived; for a stream that stays open (`text/event-stream`), use `parseAs: "stream"`.
|
|
116
|
-
- **`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.
|
|
117
|
-
- **`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`.
|
|
118
|
-
- **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`.
|
|
119
|
-
- **Response headers** are typed in the declarations (`responses[200].headers`); read them from `res.response.headers`.
|
|
120
|
-
|
|
121
|
-
### Wrapping a call
|
|
122
|
-
|
|
123
|
-
`PathsOf<paths, "get">` (the path templates with that method), `ArgsOf<paths, "get", Path, ParseAs>` (the arguments after the path) and `ResultOf` type a function that wraps a call, with no assertion. TypeScript cannot infer `parseAs` through the spread, so the call names its type arguments:
|
|
124
|
-
|
|
125
|
-
```ts
|
|
126
|
-
import type { ArgsOf, ParseAs, PathsOf, ResultOf } from "kanagata/client";
|
|
127
|
-
|
|
128
|
-
async function get<
|
|
129
|
-
Path extends PathsOf<paths, "get">,
|
|
130
|
-
A extends ParseAs | undefined = undefined,
|
|
131
|
-
>(
|
|
132
|
-
path: Path,
|
|
133
|
-
...args: ArgsOf<paths, "get", Path, A>
|
|
134
|
-
): Promise<ResultOf<paths, "get", Path, A>> {
|
|
135
|
-
const res = await api.get<Path, A>(path, ...args);
|
|
136
|
-
log(path, res.status);
|
|
137
|
-
return res;
|
|
138
|
-
}
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
For `api.request`, the method takes the place of `"get"`: `ArgsOf<paths, "COPY", Path>`.
|
|
142
|
-
|
|
143
|
-
`OkResult<R>` and `NotOkResult<R>` are the results `if (res.ok)` leaves on each side. `default` is on both, since it covers an undocumented 2xx; `Extract<R, { ok: true }>` would drop it. A wrapper that throws the others returns `OkResult<…>["data"]`:
|
|
144
|
-
|
|
145
|
-
```ts
|
|
146
|
-
import type { ArgsOf, OkResult, PathsOf, ResultOf } from "kanagata/client";
|
|
147
|
-
|
|
148
|
-
async function getOk<Path extends PathsOf<paths, "get">>(
|
|
149
|
-
path: Path,
|
|
150
|
-
...args: ArgsOf<paths, "get", Path>
|
|
151
|
-
): Promise<OkResult<ResultOf<paths, "get", Path>>["data"]> {
|
|
152
|
-
const res = await api.get(path, ...args);
|
|
153
|
-
if (!res.ok) throw res; // NotOkResult<ResultOf<paths, "get", Path>>
|
|
154
|
-
return res.data;
|
|
155
|
-
}
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
### Details
|
|
159
|
-
|
|
160
|
-
- **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.
|
|
161
|
-
- **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.
|
|
162
|
-
- **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.
|
|
163
|
-
- **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.
|
|
164
|
-
- `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.
|
|
165
|
-
- A binary body is a `Blob`, `ArrayBuffer`, typed array or `ReadableStream`.
|
|
166
|
-
- 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`.
|
|
167
|
-
- 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.
|
|
168
|
-
- 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.
|
|
169
|
-
- A raw body (string, `Blob`, `URLSearchParams`, …) is sent as it is for form media types too.
|
|
170
|
-
- **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 missing path parameter, or one of `""`, `.` or `..` (the URL would reach another endpoint), throws `PathParameterError` before anything is sent; see Errors.
|
|
171
|
-
- **`querystring`** is the whole query, after any other: for `application/x-www-form-urlencoded` an object, encoded as `query` is (`foo=a%20%2B%20b&bar=true`); for any other media type the text that media type serializes to (`JSON.stringify(value)` for JSON), percent-encoded as one value (`%7B%22n%22%3A1%7D`), as OpenAPI 3.2's examples show.
|
|
172
|
-
- **Errors:** HTTP error statuses never throw; network failures are fetch's own errors. A path parameter the URL cannot carry throws `PathParameterError`, a `TypeError` with `parameter` (its name) and `value`, before `config.fetch` is called; a server passing on a client's value can answer 404 for it (`e instanceof PathParameterError`), apart from fetch's network errors, which are `TypeError`s too. 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. The client's own errors are named as their classes (`e.name` is `"PathParameterError"`, `"ResponseBodyError"`), so logs tell them apart.
|
|
173
|
-
- **`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.
|
|
174
|
-
- **`onData`'s `call`** has `method` (the function's name, `get`, or the method given to `request`, `COPY`), `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.
|
|
175
|
-
|
|
176
|
-
### Owning the client
|
|
177
|
-
|
|
178
|
-
`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.
|
|
179
|
-
|
|
180
|
-
## Library API
|
|
181
|
-
|
|
182
|
-
```ts
|
|
183
|
-
import { readFileSync } from "node:fs";
|
|
184
|
-
import { pathToFileURL } from "node:url";
|
|
185
|
-
import { GenerateError, generate } from "kanagata";
|
|
186
|
-
|
|
187
|
-
const file = "openapi.yaml";
|
|
188
|
-
try {
|
|
189
|
-
const { code, warnings } = generate(readFileSync(file, "utf8"), {
|
|
190
|
-
url: pathToFileURL(file).href,
|
|
191
|
-
read: (url) => readFileSync(new URL(url), "utf8"),
|
|
192
|
-
});
|
|
193
|
-
for (const w of warnings) console.warn(`${w.at}: ${w.msg}`);
|
|
194
|
-
// code: the .d.ts text
|
|
195
|
-
} catch (e) {
|
|
196
|
-
if (e instanceof GenerateError)
|
|
197
|
-
console.error(e.message); // e.kind: "json" | "yaml" | "input"
|
|
198
|
-
else throw e;
|
|
199
|
-
}
|
|
200
|
-
```
|
|
201
|
-
|
|
202
|
-
`generate(src, source?, options?)` returns `{ code, warnings }` and throws `GenerateError` (`e.name` is `"GenerateError"` for every `kind`). `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. `options` is `{ strictNullableEnum?: boolean }`, as `--strict-nullable-enum`.
|
|
203
|
-
|
|
204
|
-
## Output
|
|
205
|
-
|
|
206
|
-
- 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.
|
|
207
|
-
- Operations are `paths[path][method]`, `webhooks[name][method]` (3.1 and 3.2; every key is a name, `x-` ones included), and `operations[operationId]`. The methods are the Path Item's fields in OpenAPI's order (`get` … `trace`, then `query`), then the keys of `additionalOperations` (3.2) as written (`COPY`). A key that is a fixed field's method (`POST`), which OpenAPI forbids, or its name (`post`) is an error; methods are case-sensitive, so `Patch` is another method. The fields OpenAPI 3.2 adds (`$self`, `query`, `additionalOperations`, `in: querystring`, a `$ref` as a media type, `itemSchema`) are read in 3.2 documents only.
|
|
208
|
-
- An `in: querystring` parameter (3.2) is `parameters.querystring`, without its name, which is not sent: the schema of its media type for `application/x-www-form-urlencoded`, `string` (the serialized text) for any other.
|
|
209
|
-
- A schema with a `readOnly` / `writeOnly` property (on it or on a schema it references) gets a second type for requests, `UserInput`.
|
|
210
|
-
- `description` and `deprecated` become JSDoc.
|
|
211
|
-
- Header parameters named `Accept`, `Content-Type` or `Authorization`, and a response header `Content-Type`, are ignored, as OpenAPI requires.
|
|
212
|
-
- 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.
|
|
213
|
-
- 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.
|
|
214
|
-
|
|
215
|
-
### `$ref`
|
|
216
|
-
|
|
217
|
-
- 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 and 3.2).
|
|
218
|
-
- The document's `$self` (3.2), resolved against where it was read, is its base URI: relative `$ref`s in it resolve against `$self`, and a `$ref` to `$self` means the document (so does one to the URL it was read from). A `$self` that is not a URI reference is an error. With `$self: https://api.example.com/openapi.yaml`, `schemas/User.yaml` is `https://api.example.com/schemas/User.yaml`, which is not read (below).
|
|
219
|
-
- Parameters, request bodies, responses, headers, path items and media types (3.2) may be `$ref`s.
|
|
220
|
-
- Other files (`schemas/User.yaml`, `common.json#/Error`) resolve against the base URI where the `$ref` is: the file it is in, or the document's `$self`. Each is read once, JSON or YAML by its content, and known by where it is read: another file's `$self` is not read. URLs are not fetched.
|
|
221
|
-
- 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`.
|
|
222
|
-
- 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.
|
|
223
|
-
- 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.
|
|
224
|
-
|
|
225
|
-
### Schemas
|
|
226
|
-
|
|
227
|
-
Types follow what the schema accepts, not another generator's output.
|
|
228
|
-
|
|
229
|
-
| Schema | TypeScript |
|
|
230
|
-
| ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
231
|
-
| `true`, `{}` | `unknown` |
|
|
232
|
-
| `false` | `never` |
|
|
233
|
-
| `const`, `enum` | literal types; objects and arrays become exact object and tuple types |
|
|
234
|
-
| `allOf`, `oneOf` / `anyOf`, sibling `type` / object keywords | all intersected: `A & B & (C \| D)` |
|
|
235
|
-
| `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`) |
|
|
236
|
-
| keywords next to `$ref` | intersected in 3.1 and 3.2; ignored in 3.0 (`readOnly` / `writeOnly` too) except `nullable` and `description` |
|
|
237
|
-
| `type: [...]`, `nullable: true` (3.0) | union, with `null` |
|
|
238
|
-
| `type` with `const` / `enum`, and these with each other | the values all allow: `type: string, enum: ["a", 1]` is `"a"`; a contradiction is `never` |
|
|
239
|
-
| `type: integer` | `number`; non-integer `enum` / `const` values are dropped |
|
|
240
|
-
| `format: binary`; binary `contentMediaType` without `contentEncoding` | `Blob` |
|
|
241
|
-
| `prefixItems` | tuple; items past `minItems` are optional, `items` gives the rest |
|
|
242
|
-
| `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 }` |
|
|
243
|
-
| `additionalProperties`, `patternProperties` | an index signature that also admits the declared properties (TypeScript cannot check the pattern) |
|
|
244
|
-
| `additionalProperties: false` with no properties, `const: {}`, `maxProperties: 0` | `{ [key: string]: never }`; with `maxProperties: 0` and a required key, `never` |
|
|
245
|
-
| `additionalProperties: false` (no `patternProperties`) and a required key outside `properties` | `never`, as is an `allOf` / `oneOf` / `anyOf` member next to it that requires one |
|
|
246
|
-
| object without properties | `Record<string, unknown>` |
|
|
247
|
-
| object keywords without `type` | an object (non-objects are never meant), so `{ type: "string", allOf: [{ properties: … }] }` is `never` |
|
|
248
|
-
| `readOnly` / `writeOnly` property | left out of what is sent / what is returned |
|
|
249
|
-
| `not`, `if` / `then` / `else`, `dependentSchemas`, `unevaluated*`, `$dynamicRef` | ignored, with a warning |
|
|
250
|
-
|
|
251
|
-
Content by media type:
|
|
252
|
-
|
|
253
|
-
| Media type | Type |
|
|
254
|
-
| ---------------------------------------------------------- | --------------------------------------- |
|
|
255
|
-
| JSON | its schema |
|
|
256
|
-
| `text/*`, XML | `string` |
|
|
257
|
-
| forms (`application/x-www-form-urlencoded`, `multipart/*`) | request: its schema; response: `string` |
|
|
258
|
-
| any other (binary), not a wildcard | `Blob` |
|
|
69
|
+
- `api.get`, `api.post`, … take the path template and the operation's parameters and body; a method of `additionalOperations` (3.2) goes through `api.request("COPY", …)`.
|
|
70
|
+
- The result is `{ status, ok, data, response }`, a union over the statuses the operation documents: checking `status` or `ok` narrows `data`. HTTP error statuses never throw.
|
|
71
|
+
- `kanagata init` copies the client's source into your project to edit as you like.
|
|
259
72
|
|
|
260
|
-
|
|
73
|
+
Config, call options, results, typing a wrapper, how requests are built, and errors: [docs/client.md](docs/client.md).
|
|
261
74
|
|
|
262
|
-
|
|
75
|
+
## Generated types
|
|
263
76
|
|
|
264
|
-
|
|
77
|
+
- Every schema in `components.schemas` is a named type; operations are `paths[path][method]`, `webhooks[name][method]` and `operations[operationId]`.
|
|
78
|
+
- Types follow what the schema accepts, not another generator's output.
|
|
79
|
+
- A schema with a `readOnly` / `writeOnly` property gets a second type for requests, `UserInput`.
|
|
80
|
+
- In 3.0, `nullable: true` adds `null` to the `type` next to it, as OpenAPI 3.0.3 says, so it takes no effect without `type`, next to `$ref`, or past an `enum` without `null`. Many documents mean "this schema or null" instead; `--loose-nullable` reads them that way.
|
|
265
81
|
|
|
266
|
-
|
|
82
|
+
Every rule, with `$ref` resolution and media types: [docs/types.md](docs/types.md).
|
|
267
83
|
|
|
268
84
|
## Not supported
|
|
269
85
|
|
package/dist/cli.js
CHANGED
|
@@ -11,7 +11,7 @@ const HELP = `kanagata - TypeScript types from OpenAPI 3.0 / 3.1 / 3.2 (JSON or
|
|
|
11
11
|
|
|
12
12
|
Usage:
|
|
13
13
|
kanagata generate <openapi.json|yaml> [-o <out.d.ts>] [--check]
|
|
14
|
-
[--
|
|
14
|
+
[--loose-nullable]
|
|
15
15
|
kanagata init [-o <client.ts>] [--force]
|
|
16
16
|
|
|
17
17
|
Commands:
|
|
@@ -21,9 +21,10 @@ Commands:
|
|
|
21
21
|
Options:
|
|
22
22
|
-o <path> Output file (generate: stdout, init: ./client.ts)
|
|
23
23
|
--check Exit with 1 if the -o file differs from the generated output
|
|
24
|
-
--
|
|
25
|
-
In 3.0,
|
|
26
|
-
|
|
24
|
+
--loose-nullable
|
|
25
|
+
In 3.0, read nullable: true as "this schema or null", even
|
|
26
|
+
where OpenAPI 3.0.3 gives it no effect (no type, next to
|
|
27
|
+
$ref, an enum without null)
|
|
27
28
|
--force Let init overwrite an existing file
|
|
28
29
|
-h, --help Show this help
|
|
29
30
|
-V, --version Show the version
|
|
@@ -112,7 +113,7 @@ function parseFlags(args, allowed) {
|
|
|
112
113
|
positional: [],
|
|
113
114
|
check: false,
|
|
114
115
|
force: false,
|
|
115
|
-
|
|
116
|
+
looseNullable: false,
|
|
116
117
|
help: false,
|
|
117
118
|
};
|
|
118
119
|
const rest = args[Symbol.iterator]();
|
|
@@ -131,8 +132,8 @@ function parseFlags(args, allowed) {
|
|
|
131
132
|
f.check = true;
|
|
132
133
|
else if (a === "--force")
|
|
133
134
|
f.force = true;
|
|
134
|
-
else if (a === "--
|
|
135
|
-
f.
|
|
135
|
+
else if (a === "--loose-nullable")
|
|
136
|
+
f.looseNullable = true;
|
|
136
137
|
else if (isHelp)
|
|
137
138
|
f.help = true;
|
|
138
139
|
else
|
|
@@ -141,7 +142,7 @@ function parseFlags(args, allowed) {
|
|
|
141
142
|
return f;
|
|
142
143
|
}
|
|
143
144
|
function generateCommand(args, io, out, err) {
|
|
144
|
-
const f = parseFlags(args, ["-o", "--check", "--
|
|
145
|
+
const f = parseFlags(args, ["-o", "--check", "--loose-nullable"]);
|
|
145
146
|
if (f.help) {
|
|
146
147
|
out(HELP);
|
|
147
148
|
return 0;
|
|
@@ -156,7 +157,7 @@ function generateCommand(args, io, out, err) {
|
|
|
156
157
|
const label = input === "-" ? "stdin" : input;
|
|
157
158
|
const src = decode(label, attempt(label, () => io.read(input === "-" ? 0 : input)));
|
|
158
159
|
// A file has a location, so its $refs to other files can be followed; stdin has none.
|
|
159
|
-
const generated = generate(src, input === "-" ? undefined : fileSource(input, io), {
|
|
160
|
+
const generated = generate(src, input === "-" ? undefined : fileSource(input, io), { looseNullable: f.looseNullable });
|
|
160
161
|
for (const w of generated.warnings)
|
|
161
162
|
err(`${w.at}: warning: ${w.msg}`);
|
|
162
163
|
const target = f.output;
|
package/dist/index.d.ts
CHANGED
|
@@ -16,10 +16,11 @@ export interface Source {
|
|
|
16
16
|
/** How the document is read. */
|
|
17
17
|
export interface Options {
|
|
18
18
|
/**
|
|
19
|
-
* In 3.0,
|
|
20
|
-
*
|
|
19
|
+
* In 3.0, read `nullable: true` as "this schema or null": `null` even without `type`,
|
|
20
|
+
* next to `$ref`, and past an `enum`, `const` or `allOf` that does not admit it.
|
|
21
|
+
* Off by default: `nullable` adds `null` to `type` only, as OpenAPI 3.0.3 says.
|
|
21
22
|
*/
|
|
22
|
-
|
|
23
|
+
looseNullable?: boolean;
|
|
23
24
|
}
|
|
24
25
|
/**
|
|
25
26
|
* Converts an OpenAPI document (JSON or YAML) to a `.d.ts` file. With a `source`,
|
package/dist/index.js
CHANGED
|
@@ -33,7 +33,7 @@ export function generate(src, source, options = {}) {
|
|
|
33
33
|
!root.get("openapi").startsWith("3.0."), source && {
|
|
34
34
|
url: source.url,
|
|
35
35
|
load: (url) => loadText(cx, url, source.read(url)),
|
|
36
|
-
}, options.
|
|
36
|
+
}, options.looseNullable === true);
|
|
37
37
|
const p = paths(cx, root);
|
|
38
38
|
// Every component schema, then every schema from another file that got a key (the
|
|
39
39
|
// list grows as they are converted), named, in both views; the write view gets its
|
package/dist/pointer.d.ts
CHANGED
|
@@ -51,8 +51,8 @@ export declare class Ctx {
|
|
|
51
51
|
mode: View;
|
|
52
52
|
/** Whether keywords next to `$ref` apply (OpenAPI 3.1) or are ignored (3.0). */
|
|
53
53
|
readonly refSiblings: boolean;
|
|
54
|
-
/** Whether
|
|
55
|
-
readonly
|
|
54
|
+
/** Whether 3.0 `nullable: true` means "this schema or null" instead of adding `null` to `type`. */
|
|
55
|
+
readonly looseNullable: boolean;
|
|
56
56
|
/** Schemas from other files that got a key, in the order they were first referred to. */
|
|
57
57
|
readonly hoisted: Hoisted[];
|
|
58
58
|
/**
|
|
@@ -65,7 +65,7 @@ export declare class Ctx {
|
|
|
65
65
|
uri: string;
|
|
66
66
|
where: string;
|
|
67
67
|
}): string;
|
|
68
|
-
constructor(root: Value, schemas?: ReadonlySet<string>, refSiblings?: boolean, location?: Location,
|
|
68
|
+
constructor(root: Value, schemas?: ReadonlySet<string>, refSiblings?: boolean, location?: Location, looseNullable?: boolean);
|
|
69
69
|
warn(at: string, msg: string): void;
|
|
70
70
|
get warnings(): Diag[];
|
|
71
71
|
leftOutIn(v: Value): ReadonlySet<string>;
|
package/dist/pointer.js
CHANGED
|
@@ -92,8 +92,8 @@ export class Ctx {
|
|
|
92
92
|
mode = "read";
|
|
93
93
|
/** Whether keywords next to `$ref` apply (OpenAPI 3.1) or are ignored (3.0). */
|
|
94
94
|
refSiblings;
|
|
95
|
-
/** Whether
|
|
96
|
-
|
|
95
|
+
/** Whether 3.0 `nullable: true` means "this schema or null" instead of adding `null` to `type`. */
|
|
96
|
+
looseNullable;
|
|
97
97
|
/** Schemas from other files that got a key, in the order they were first referred to. */
|
|
98
98
|
hoisted = [];
|
|
99
99
|
/** Hoisted keys by the URI of the schema. */
|
|
@@ -125,11 +125,11 @@ export class Ctx {
|
|
|
125
125
|
this.hoisted.push({ key, value, base: target.base, where: target.where });
|
|
126
126
|
return key;
|
|
127
127
|
}
|
|
128
|
-
constructor(root, schemas = new Set(), refSiblings = false, location,
|
|
128
|
+
constructor(root, schemas = new Set(), refSiblings = false, location, looseNullable = false) {
|
|
129
129
|
this.root = root;
|
|
130
130
|
this.schemas = schemas;
|
|
131
131
|
this.refSiblings = refSiblings;
|
|
132
|
-
this.
|
|
132
|
+
this.looseNullable = looseNullable;
|
|
133
133
|
this.documentUrl =
|
|
134
134
|
location === undefined
|
|
135
135
|
? DOCUMENT
|
package/dist/schema.js
CHANGED
|
@@ -62,20 +62,21 @@ export function doc(v) {
|
|
|
62
62
|
return desc === undefined ? "@deprecated" : `${desc}\n@deprecated`;
|
|
63
63
|
}
|
|
64
64
|
/**
|
|
65
|
-
* `nullable: true` (3.0 only; 3.1 has no such keyword) adds `null` to
|
|
66
|
-
*
|
|
67
|
-
*
|
|
65
|
+
* `nullable: true` (3.0 only; 3.1 has no such keyword) adds `null` to the `type` next
|
|
66
|
+
* to it, and only then; the other keywords still apply to `null` (OAS 3.0.3). With
|
|
67
|
+
* `looseNullable` it adds `null` to whatever the rest of the schema gives (see docs/types.md).
|
|
68
68
|
*/
|
|
69
69
|
function parts(cx, v, at) {
|
|
70
70
|
const nullable = !cx.refSiblings && v.get("nullable") === true;
|
|
71
|
+
const loose = nullable && cx.looseNullable;
|
|
71
72
|
const out = [];
|
|
72
73
|
const r = v.str("$ref");
|
|
73
74
|
if (r !== undefined) {
|
|
74
75
|
const target = reference(cx, r, at);
|
|
75
76
|
// In 3.1 (JSON Schema 2020-12) the keywords next to $ref apply too; in 3.0 they
|
|
76
|
-
// are ignored,
|
|
77
|
+
// are ignored, nullable among them unless loose.
|
|
77
78
|
if (!cx.refSiblings)
|
|
78
|
-
return
|
|
79
|
+
return loose ? union([target, NULL]) : target;
|
|
79
80
|
out.push(target);
|
|
80
81
|
}
|
|
81
82
|
const c = v.get("const");
|
|
@@ -101,24 +102,18 @@ function parts(cx, v, at) {
|
|
|
101
102
|
const members = cx.withLeftOut(allOf, group, () => list(cx, allOf, child(at, "allOf")));
|
|
102
103
|
out.push(...admitted(allOf, members));
|
|
103
104
|
}
|
|
104
|
-
|
|
105
|
+
const typedNull = nullable && !loose && v.get("type") !== undefined;
|
|
106
|
+
out.push(typedNull ? union([own(cx, v, at), NULL]) : own(cx, v, at));
|
|
105
107
|
// `discriminator` is not read: it must not change what the schema accepts (OAS 3.0.4, 3.1.1),
|
|
106
108
|
// and a member is narrowed by the property only where the member itself fixes it.
|
|
107
109
|
for (const key of ["oneOf", "anyOf"]) {
|
|
108
110
|
const members = v.get(key);
|
|
109
|
-
if (Array.isArray(members))
|
|
110
|
-
|
|
111
|
+
if (!Array.isArray(members))
|
|
112
|
+
continue;
|
|
113
|
+
const tys = admitted(members, list(cx, members, child(at, key)));
|
|
114
|
+
out.push(union(key === "oneOf" ? exclusive(cx, members, tys, child(at, key)) : tys));
|
|
111
115
|
}
|
|
112
|
-
|
|
113
|
-
return addsNull ? union([inter(out), NULL]) : inter(out);
|
|
114
|
-
}
|
|
115
|
-
/** Whether the schema's own `enum` and `const`, where present, admit `null`. */
|
|
116
|
-
function valuesAdmitNull(v) {
|
|
117
|
-
const e = v.get("enum");
|
|
118
|
-
if (Array.isArray(e) && !e.includes(null))
|
|
119
|
-
return false;
|
|
120
|
-
const c = v.get("const");
|
|
121
|
-
return c === undefined || c === null;
|
|
116
|
+
return loose ? union([inter(out), NULL]) : inter(out);
|
|
122
117
|
}
|
|
123
118
|
/**
|
|
124
119
|
* The keys a closed object admits (`additionalProperties: false`, no
|
|
@@ -148,6 +143,101 @@ function requiredKeys(cx, s) {
|
|
|
148
143
|
...cx.withBase(target.base, () => requiredKeys(cx, target.value)),
|
|
149
144
|
];
|
|
150
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* oneOf admits a value only one member admits. A member that asks nothing but some
|
|
148
|
+
* keys (`{ required: [a] }`) does not admit exactly the objects without one of them.
|
|
149
|
+
* So among such members, each lacks one of the keys each other requires: `b?: never`,
|
|
150
|
+
* or `({ b?: never } | { c?: never })` for `required: [b, c]`, with `b?: unknown;
|
|
151
|
+
* c?: unknown` so that an object literal with one of them is not excess. One that has
|
|
152
|
+
* all of another's keys admits nothing. Other members stay as they are: TypeScript
|
|
153
|
+
* cannot say what they do not admit.
|
|
154
|
+
*/
|
|
155
|
+
function exclusive(cx, members, tys, at) {
|
|
156
|
+
const keys = members.map((m, i) => keysOnly(cx, m, child(at, String(i))));
|
|
157
|
+
const without = (key, ty) => ({ key, ty, optional: true });
|
|
158
|
+
return tys.map((t, i) => {
|
|
159
|
+
const own = keys[i];
|
|
160
|
+
if (own === undefined)
|
|
161
|
+
return t;
|
|
162
|
+
// Each key another member requires: never here, or unknown where only one of several must lack.
|
|
163
|
+
const others = new Map();
|
|
164
|
+
const either = [];
|
|
165
|
+
for (const [j, other] of keys.entries()) {
|
|
166
|
+
if (j === i || other === undefined)
|
|
167
|
+
continue;
|
|
168
|
+
const missing = other.filter((k) => !own.includes(k));
|
|
169
|
+
if (missing.length === 0)
|
|
170
|
+
return NEVER;
|
|
171
|
+
if (missing.length === 1) {
|
|
172
|
+
others.set(missing[0], NEVER);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
for (const k of missing)
|
|
176
|
+
if (!others.has(k))
|
|
177
|
+
others.set(k, UNKNOWN);
|
|
178
|
+
either.push(union(missing.map((k) => ({ kind: "object", props: [without(k, NEVER)] }))));
|
|
179
|
+
}
|
|
180
|
+
if (others.size === 0)
|
|
181
|
+
return t;
|
|
182
|
+
const props = [...others].map(([k, ty]) => without(k, ty));
|
|
183
|
+
return inter([t, { kind: "object", props }, ...either]);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/** Keywords that do not change which values are valid. */
|
|
187
|
+
const ANNOTATIONS = new Set([
|
|
188
|
+
"title",
|
|
189
|
+
"description",
|
|
190
|
+
"$comment",
|
|
191
|
+
"default",
|
|
192
|
+
"example",
|
|
193
|
+
"examples",
|
|
194
|
+
"deprecated",
|
|
195
|
+
"externalDocs",
|
|
196
|
+
"xml",
|
|
197
|
+
]);
|
|
198
|
+
const isAnnotation = (k) => ANNOTATIONS.has(k) || k.startsWith("x-");
|
|
199
|
+
/**
|
|
200
|
+
* The keys a schema requires, when that is all it asks of an object: a non-empty
|
|
201
|
+
* `required`, with at most `type: object`, properties that admit any value and
|
|
202
|
+
* annotations; or a `$ref`, with annotations at most, to such a schema.
|
|
203
|
+
*/
|
|
204
|
+
function keysOnly(cx, s, at) {
|
|
205
|
+
if (!(s instanceof JsonObject))
|
|
206
|
+
return undefined;
|
|
207
|
+
const r = s.str("$ref");
|
|
208
|
+
if (r !== undefined)
|
|
209
|
+
return s.entries.every(([k]) => k === "$ref" || isAnnotation(k))
|
|
210
|
+
? follow(cx, r, at, (t, where) => keysOnly(cx, t, where))
|
|
211
|
+
: undefined;
|
|
212
|
+
const props = child(at, "properties");
|
|
213
|
+
const allowed = s.entries.every(([k, x]) => k === "required" ||
|
|
214
|
+
isAnnotation(k) ||
|
|
215
|
+
(k === "type" && x === "object") ||
|
|
216
|
+
(k === "properties" &&
|
|
217
|
+
x instanceof JsonObject &&
|
|
218
|
+
x.entries.every(([p, ps]) => admitsAnyValue(cx, ps, child(props, p)))));
|
|
219
|
+
const req = s.get("required");
|
|
220
|
+
return allowed && Array.isArray(req) && req.length > 0
|
|
221
|
+
? req.filter((n) => typeof n === "string")
|
|
222
|
+
: undefined;
|
|
223
|
+
}
|
|
224
|
+
/** Whether a schema admits every value: `true`, annotations alone, or a `$ref` to such a schema next to them. */
|
|
225
|
+
function admitsAnyValue(cx, s, at) {
|
|
226
|
+
if (s === true)
|
|
227
|
+
return true;
|
|
228
|
+
if (!(s instanceof JsonObject))
|
|
229
|
+
return false;
|
|
230
|
+
if (!s.entries.every(([k]) => k === "$ref" || isAnnotation(k)))
|
|
231
|
+
return false;
|
|
232
|
+
const r = s.str("$ref");
|
|
233
|
+
return (r === undefined ||
|
|
234
|
+
follow(cx, r, at, (t, where) => admitsAnyValue(cx, t, where)));
|
|
235
|
+
}
|
|
236
|
+
/** `f` on the schema a `$ref` reaches, with the base URI of the document it is in. */
|
|
237
|
+
function follow(cx, r, at, f) {
|
|
238
|
+
const { value, base, where } = cx.locate(r, at);
|
|
239
|
+
return cx.withBase(base, () => f(value, where));
|
|
240
|
+
}
|
|
151
241
|
/** Keywords that only apply to objects; their presence implies `type: object`. */
|
|
152
242
|
function hasObjectKeywords(v) {
|
|
153
243
|
return [
|