kanagata 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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
- | 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
- | `--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,178 +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`, … (one per HTTP method of the Path Item, `query` included, 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.
81
-
82
- A method of `additionalOperations` (3.2) is called through `api.request`, named as the document writes it, which is how it is sent: `api.request("COPY", "/files/{name}", { path: { name: "a.png" } })`. fetch rejects CONNECT, TRACE and TRACK, and sends DELETE, GET, HEAD, OPTIONS, POST and PUT in upper case whatever their case (`Post` as POST), so `request` does not take them.
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
- ### Details
144
-
145
- - **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.
146
- - **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.
147
- - **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.
148
- - **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.
149
- - `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.
150
- - A binary body is a `Blob`, `ArrayBuffer`, typed array or `ReadableStream`.
151
- - 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`.
152
- - 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.
153
- - 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.
154
- - A raw body (string, `Blob`, `URLSearchParams`, …) is sent as it is for form media types too.
155
- - **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.
156
- - **`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.
157
- - **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.
158
- - **`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.
159
- - **`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.
160
-
161
- ### Owning the client
162
-
163
- `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.
164
-
165
- ## Library API
166
-
167
- ```ts
168
- import { readFileSync } from "node:fs";
169
- import { pathToFileURL } from "node:url";
170
- import { GenerateError, generate } from "kanagata";
171
-
172
- const file = "openapi.yaml";
173
- try {
174
- const { code, warnings } = generate(readFileSync(file, "utf8"), {
175
- url: pathToFileURL(file).href,
176
- read: (url) => readFileSync(new URL(url), "utf8"),
177
- });
178
- for (const w of warnings) console.warn(`${w.at}: ${w.msg}`);
179
- // code: the .d.ts text
180
- } catch (e) {
181
- if (e instanceof GenerateError)
182
- console.error(e.message); // e.kind: "json" | "yaml" | "input"
183
- else throw e;
184
- }
185
- ```
186
-
187
- `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`.
188
-
189
- ## Output
190
-
191
- - 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.
192
- - 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.
193
- - 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.
194
- - A schema with a `readOnly` / `writeOnly` property (on it or on a schema it references) gets a second type for requests, `UserInput`.
195
- - `description` and `deprecated` become JSDoc.
196
- - Header parameters named `Accept`, `Content-Type` or `Authorization`, and a response header `Content-Type`, are ignored, as OpenAPI requires.
197
- - 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.
198
- - 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.
199
-
200
- ### `$ref`
201
-
202
- - 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).
203
- - 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).
204
- - Parameters, request bodies, responses, headers, path items and media types (3.2) may be `$ref`s.
205
- - 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.
206
- - 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`.
207
- - 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.
208
- - 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.
209
-
210
- ### Schemas
211
-
212
- Types follow what the schema accepts, not another generator's output.
213
-
214
- | Schema | TypeScript |
215
- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
216
- | `true`, `{}` | `unknown` |
217
- | `false` | `never` |
218
- | `const`, `enum` | literal types; objects and arrays become exact object and tuple types |
219
- | `allOf`, `oneOf` / `anyOf`, sibling `type` / object keywords | all intersected: `A & B & (C \| D)` |
220
- | `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`) |
221
- | keywords next to `$ref` | intersected in 3.1 and 3.2; ignored in 3.0 (`readOnly` / `writeOnly` too) except `nullable` and `description` |
222
- | `type: [...]`, `nullable: true` (3.0) | union, with `null` |
223
- | `type` with `const` / `enum`, and these with each other | the values all allow: `type: string, enum: ["a", 1]` is `"a"`; a contradiction is `never` |
224
- | `type: integer` | `number`; non-integer `enum` / `const` values are dropped |
225
- | `format: binary`; binary `contentMediaType` without `contentEncoding` | `Blob` |
226
- | `prefixItems` | tuple; items past `minItems` are optional, `items` gives the rest |
227
- | `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 }` |
228
- | `additionalProperties`, `patternProperties` | an index signature that also admits the declared properties (TypeScript cannot check the pattern) |
229
- | `additionalProperties: false` with no properties, `const: {}`, `maxProperties: 0` | `{ [key: string]: never }`; with `maxProperties: 0` and a required key, `never` |
230
- | `additionalProperties: false` (no `patternProperties`) and a required key outside `properties` | `never`, as is an `allOf` / `oneOf` / `anyOf` member next to it that requires one |
231
- | object without properties | `Record<string, unknown>` |
232
- | object keywords without `type` | an object (non-objects are never meant), so `{ type: "string", allOf: [{ properties: … }] }` is `never` |
233
- | `readOnly` / `writeOnly` property | left out of what is sent / what is returned |
234
- | `not`, `if` / `then` / `else`, `dependentSchemas`, `unevaluated*`, `$dynamicRef` | ignored, with a warning |
235
-
236
- Content by media type:
237
-
238
- | Media type | Type |
239
- | ---------------------------------------------------------- | --------------------------------------- |
240
- | JSON | its schema |
241
- | `text/*`, XML | `string` |
242
- | forms (`application/x-www-form-urlencoded`, `multipart/*`) | request: its schema; response: `string` |
243
- | 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.
244
72
 
245
- A sequential media type's `itemSchema` (3.2) is checked like a schema but types nothing: the client reads the content whole, by the rules above (`application/jsonl` is `Blob`, `text/event-stream` `string`). Read it item by item with `parseAs: "stream"`.
73
+ Config, call options, results, typing a wrapper, how requests are built, and errors: [docs/client.md](docs/client.md).
246
74
 
247
- ### `nullable` (3.0)
75
+ ## Generated types
248
76
 
249
- `nullable: true` adds `null` even without `type` (`{ nullable: true, allOf: [{ $ref: … }] }`) and next to an `enum` (or `const`) 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.
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.
250
81
 
251
- `--strict-nullable-enum` (`generate(src, source, { strictNullableEnum: true })`) reads the `enum` case as OpenAPI 3.0.3 does: an `enum` or `const` that does not list `null` keeps it out, so `{ type: string, enum: [a, b], nullable: true }` is `"a" | "b"`. `nullable` without `type` still adds `null`.
82
+ Every rule, with `$ref` resolution and media types: [docs/types.md](docs/types.md).
252
83
 
253
84
  ## Not supported
254
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
- [--strict-nullable-enum]
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
- --strict-nullable-enum
25
- In 3.0, keep null out of an enum or const that does not
26
- list it, even with nullable: true (as OpenAPI 3.0.3 says)
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
- strictNullableEnum: false,
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 === "--strict-nullable-enum")
135
- f.strictNullableEnum = true;
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", "--strict-nullable-enum"]);
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), { strictNullableEnum: f.strictNullableEnum });
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/client.d.ts CHANGED
@@ -171,6 +171,22 @@ export type Result<O, A extends ParseAs | undefined = undefined, M extends strin
171
171
  * method given once (so HEAD has no body, as in the call).
172
172
  */
173
173
  export type ResultOf<P, M extends string, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined> = Result<Op<P, Path, M>, A, M>;
174
+ /**
175
+ * The results of R that `if (res.ok)` leaves: the 2xx statuses, and `default`, which
176
+ * covers an undocumented 2xx (its `ok` is `boolean`). `OkResult<ResultOf<…>>["data"]`
177
+ * types what a wrapper returns when it throws the others.
178
+ */
179
+ export type OkResult<R> = R extends {
180
+ ok: infer K;
181
+ } ? true extends K ? R & {
182
+ ok: true;
183
+ } : never : never;
184
+ /** The results of R that `if (!res.ok)` leaves: the other statuses, and `default`. */
185
+ export type NotOkResult<R> = R extends {
186
+ ok: infer K;
187
+ } ? false extends K ? R & {
188
+ ok: false;
189
+ } : never : never;
174
190
  type MaybePromise<T> = T | Promise<T>;
175
191
  export interface ClientConfig extends FetchOptions {
176
192
  /** Absolute, or relative to the page (`/api`) as fetch resolves it, on every call. */
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, keep `null` out of an `enum` or `const` that does not list it, even with
20
- * `nullable: true`, as OpenAPI 3.0.3 says. Off by default: documents mean "or null".
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
- strictNullableEnum?: boolean;
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.strictNullableEnum === true);
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 an `enum` or `const` that does not list `null` keeps it out despite 3.0 `nullable: true`. */
55
- readonly strictNullableEnum: boolean;
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, strictNullableEnum?: boolean);
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 an `enum` or `const` that does not list `null` keeps it out despite 3.0 `nullable: true`. */
96
- strictNullableEnum;
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, strictNullableEnum = false) {
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.strictNullableEnum = strictNullableEnum;
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 whatever the rest
66
- * of the schema gives, as documents mean it (see README); with `strictNullableEnum`,
67
- * an `enum` or `const` that does not list `null` keeps it out, as OAS 3.0.3 says.
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, except nullable.
77
+ // are ignored, nullable among them unless loose.
77
78
  if (!cx.refSiblings)
78
- return nullable ? union([target, NULL]) : target;
79
+ return loose ? union([target, NULL]) : target;
79
80
  out.push(target);
80
81
  }
81
82
  const c = v.get("const");
@@ -101,7 +102,8 @@ 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
- out.push(own(cx, v, at));
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"]) {
@@ -109,16 +111,7 @@ function parts(cx, v, at) {
109
111
  if (Array.isArray(members))
110
112
  out.push(union(admitted(members, list(cx, members, child(at, key)))));
111
113
  }
112
- const addsNull = nullable && (!cx.strictNullableEnum || valuesAdmitNull(v));
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;
114
+ return loose ? union([inter(out), NULL]) : inter(out);
122
115
  }
123
116
  /**
124
117
  * The keys a closed object admits (`additionalProperties: false`, no
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kanagata",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "TypeScript types from OpenAPI 3.0 / 3.1 / 3.2 (JSON or YAML), and a typed fetch client",
5
5
  "keywords": [
6
6
  "openapi",
package/src/client.ts CHANGED
@@ -278,6 +278,24 @@ export type ResultOf<
278
278
  A extends ParseAs | undefined = undefined,
279
279
  > = Result<Op<P, Path, M>, A, M>;
280
280
 
281
+ /**
282
+ * The results of R that `if (res.ok)` leaves: the 2xx statuses, and `default`, which
283
+ * covers an undocumented 2xx (its `ok` is `boolean`). `OkResult<ResultOf<…>>["data"]`
284
+ * types what a wrapper returns when it throws the others.
285
+ */
286
+ export type OkResult<R> = R extends { ok: infer K }
287
+ ? true extends K
288
+ ? R & { ok: true }
289
+ : never
290
+ : never;
291
+
292
+ /** The results of R that `if (!res.ok)` leaves: the other statuses, and `default`. */
293
+ export type NotOkResult<R> = R extends { ok: infer K }
294
+ ? false extends K
295
+ ? R & { ok: false }
296
+ : never
297
+ : never;
298
+
281
299
  type MaybePromise<T> = T | Promise<T>;
282
300
 
283
301
  export interface ClientConfig extends FetchOptions {