kanagata 0.1.0 → 0.2.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
@@ -1,6 +1,6 @@
1
1
  # kanagata
2
2
 
3
- TypeScript types from an OpenAPI 3.0 / 3.1 document (JSON or YAML), and a typed `fetch` client for them.
3
+ TypeScript types from an OpenAPI 3.0 / 3.1 / 3.2 document (JSON or YAML), and a typed `fetch` client for them.
4
4
 
5
5
  - `kanagata generate` writes one `.d.ts` file.
6
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.
@@ -76,7 +76,9 @@ await api.put("/files/{name}", {
76
76
  const events = await api.get("/events", { parseAs: "stream" }); // events.data: ReadableStream | null
77
77
  ```
78
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.
79
+ `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.
80
+
81
+ 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.
80
82
 
81
83
  ### Config (`createClient`)
82
84
 
@@ -96,6 +98,7 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
96
98
  | ----------------------------------- | --------------------------------------------------------------------------------------------- |
97
99
  | `baseUrl` | required for an operation that declares `servers`: one of them, used in place of the config's |
98
100
  | `path`, `query`, `header`, `cookie` | the parameters the operation declares |
101
+ | `querystring` | the operation's `in: querystring` parameter (3.2), the whole query; see Details |
99
102
  | `body`, `contentType` | the request body and which of the operation's media types it is |
100
103
  | `parseAs` | `json`, `text`, `blob`, `arrayBuffer` or `stream`: read the response this way |
101
104
  | `headers` | headers for this call |
@@ -104,7 +107,7 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
104
107
 
105
108
  ### Result
106
109
 
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.
110
+ `{ 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.
108
111
 
109
112
  - **`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
113
  - 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).
@@ -127,9 +130,10 @@ const events = await api.get("/events", { parseAs: "stream" }); // events.data:
127
130
  - 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
131
  - A raw body (string, `Blob`, `URLSearchParams`, …) is sent as it is for form media types too.
129
132
  - **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.
133
+ - **`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.
130
134
  - **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
135
  - **`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.
136
+ - **`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.
133
137
 
134
138
  ### Owning the client
135
139
 
@@ -162,7 +166,8 @@ try {
162
166
  ## Output
163
167
 
164
168
  - 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]`.
169
+ - 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.
170
+ - 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.
166
171
  - A schema with a `readOnly` / `writeOnly` property (on it or on a schema it references) gets a second type for requests, `UserInput`.
167
172
  - `description` and `deprecated` become JSDoc.
168
173
  - Header parameters named `Accept`, `Content-Type` or `Authorization`, and a response header `Content-Type`, are ignored, as OpenAPI requires.
@@ -171,8 +176,10 @@ try {
171
176
 
172
177
  ### `$ref`
173
178
 
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.
179
+ - 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).
180
+ - 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).
181
+ - Parameters, request bodies, responses, headers, path items and media types (3.2) may be `$ref`s.
182
+ - 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.
176
183
  - 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
184
  - 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
185
  - 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.
@@ -188,7 +195,7 @@ Types follow what the schema accepts, not another generator's output.
188
195
  | `const`, `enum` | literal types; objects and arrays become exact object and tuple types |
189
196
  | `allOf`, `oneOf` / `anyOf`, sibling `type` / object keywords | all intersected: `A & B & (C \| D)` |
190
197
  | `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` |
198
+ | keywords next to `$ref` | intersected in 3.1 and 3.2; ignored in 3.0 (`readOnly` / `writeOnly` too) except `nullable` and `description` |
192
199
  | `type: [...]`, `nullable: true` (3.0) | union, with `null` |
193
200
  | `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
201
  | `type: integer` | `number`; non-integer `enum` / `const` values are dropped |
@@ -212,6 +219,8 @@ Content by media type:
212
219
  | forms (`application/x-www-form-urlencoded`, `multipart/*`) | request: its schema; response: `string` |
213
220
  | any other (binary), not a wildcard | `Blob` |
214
221
 
222
+ 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"`.
223
+
215
224
  ### `nullable` (3.0)
216
225
 
217
226
  `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.
@@ -220,7 +229,7 @@ Content by media type:
220
229
 
221
230
  - Runtime validation (use `onData`), middleware (wrap `config.fetch`), per-operation functions, framework bindings, mocks.
222
231
  - 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.
232
+ - Fetching `$ref`s over the network; finding another file by its `$self` (3.2), since files are read by where they are; Swagger 2.0.
224
233
  - 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
234
 
226
235
  ## Development
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ import { GenerateError, generate } from "./index.js";
7
7
  /** An I/O failure; the message says what went wrong without naming the file (`no such file or directory`). */
8
8
  export class IoError extends Error {
9
9
  }
10
- const HELP = `kanagata - TypeScript types from OpenAPI 3.0 / 3.1 (JSON or YAML), and a typed fetch client
10
+ const HELP = `kanagata - TypeScript types from OpenAPI 3.0 / 3.1 / 3.2 (JSON or YAML), and a typed fetch client
11
11
 
12
12
  Usage:
13
13
  kanagata generate <openapi.json|yaml> [-o <out.d.ts>] [--check]
package/dist/client.d.ts CHANGED
@@ -1,11 +1,23 @@
1
- export type Method = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace";
1
+ export type Method = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace" | "query";
2
2
  type HeadersInit = NonNullable<ConstructorParameters<typeof Headers>[0]>;
3
3
  type Get<T, K> = K extends keyof T ? T[K] : never;
4
4
  /** Paths that have method M. */
5
- type PathsOf<P, M extends Method> = {
5
+ type PathsOf<P, M extends string> = {
6
6
  [K in keyof P]: M extends keyof P[K] ? K : never;
7
7
  }[keyof P] & string;
8
- type Op<P, Path, M extends Method> = Get<Get<P, Path>, M>;
8
+ type Op<P, Path, M extends string> = Get<Get<P, Path>, M>;
9
+ /**
10
+ * The methods of P's path items beyond OpenAPI's fixed fields: the keys of their
11
+ * `additionalOperations` (OpenAPI 3.2), as written, which is how they are sent.
12
+ */
13
+ type OtherMethod<P> = Exclude<{
14
+ [K in keyof P]: keyof P[K];
15
+ }[keyof P], Method> & string;
16
+ /**
17
+ * The methods fetch sends as written: not CONNECT, TRACE and TRACK, which it rejects, nor
18
+ * DELETE, GET, HEAD, OPTIONS, POST and PUT in another case, which it sends in upper case.
19
+ */
20
+ type Sendable<M extends string> = M extends unknown ? Uppercase<M> extends "CONNECT" | "TRACE" | "TRACK" ? never : Uppercase<M> extends "DELETE" | "GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" ? never : M : never;
9
21
  /** Union of every media type in `content`; `undefined` without content. */
10
22
  type Content<B> = B extends {
11
23
  content: infer C;
@@ -133,7 +145,7 @@ type Undocumented = {
133
145
  content: Record<string, unknown>;
134
146
  };
135
147
  /** Discriminated union over the documented statuses. */
136
- export type Result<O, A extends ParseAs | undefined = undefined, M extends Method = Method> = O extends {
148
+ export type Result<O, A extends ParseAs | undefined = undefined, M extends string = Method> = O extends {
137
149
  responses: infer R;
138
150
  } ? [keyof R] extends [never] ? {
139
151
  status: number;
@@ -153,7 +165,7 @@ export type Result<O, A extends ParseAs | undefined = undefined, M extends Metho
153
165
  * `ResultOf<paths, "get", "/users/{id}">`. `Result` of the path's operation, with the
154
166
  * method given once (so HEAD has no body, as in the call).
155
167
  */
156
- export type ResultOf<P, M extends Method, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined> = Result<Op<P, Path, M>, A, M>;
168
+ export type ResultOf<P, M extends string, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined> = Result<Op<P, Path, M>, A, M>;
157
169
  type MaybePromise<T> = T | Promise<T>;
158
170
  export interface ClientConfig extends FetchOptions {
159
171
  /** Absolute, or relative to the page (`/api`) as fetch resolves it, on every call. */
@@ -180,9 +192,12 @@ export interface ClientConfig extends FetchOptions {
180
192
  */
181
193
  onData?: (data: unknown, call: DataCall) => MaybePromise<unknown>;
182
194
  }
183
- /** Which call a body answers. `path` is the template as written, such as `/users/{id}`. */
195
+ /**
196
+ * Which call a body answers. `method` is the client function's name (`get`), or the
197
+ * method given to `request` (`COPY`); `path` is the template as written, such as `/users/{id}`.
198
+ */
184
199
  export interface DataCall {
185
- method: Method;
200
+ method: string;
186
201
  path: string;
187
202
  status: number;
188
203
  parseAs: ParseAs | undefined;
@@ -190,9 +205,16 @@ export interface DataCall {
190
205
  response: Response;
191
206
  }
192
207
  type Call<P, M extends Method> = <Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(path: Path, ...args: Args<NeedsAll<Op<P, Path, M>>, A>) => Promise<Result<Op<P, Path, M>, A, M>>;
193
- /** A function per method fetch sends: every one but TRACE, which fetch rejects. */
208
+ /** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
209
+ type OtherCall<P> = <M extends Sendable<OtherMethod<P>>, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(method: M, path: Path, ...args: Args<NeedsAll<Op<P, Path, M>>, A>) => Promise<Result<Op<P, Path, M>, A, M>>;
210
+ /**
211
+ * A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
212
+ * `request` for the methods of `additionalOperations`.
213
+ */
194
214
  export type Client<P> = {
195
215
  [M in Exclude<Method, "trace">]: Call<P, M>;
216
+ } & {
217
+ request: OtherCall<P>;
196
218
  };
197
219
  /** The HTTP methods of a Path Item, in OpenAPI's order. The generator reads them from here too. */
198
220
  export declare const METHODS: readonly Method[];
package/dist/client.js CHANGED
@@ -9,6 +9,7 @@ const OWN_KEYS = new Set([
9
9
  "onData",
10
10
  "path",
11
11
  "query",
12
+ "querystring",
12
13
  "header",
13
14
  "cookie",
14
15
  "body",
@@ -30,6 +31,7 @@ export const METHODS = [
30
31
  "head",
31
32
  "patch",
32
33
  "trace",
34
+ "query",
33
35
  ];
34
36
  /**
35
37
  * The base URL of a call. A relative one (`/api`) resolves as fetch resolves a relative URL:
@@ -64,7 +66,11 @@ export function createClient(config) {
64
66
  array: init.arrayFormat ?? config.arrayFormat ?? "repeat",
65
67
  object: init.objectFormat ?? config.objectFormat ?? "deepObject",
66
68
  };
67
- const query = [base.search.slice(1), urlEncode(init.query ?? {}, formats)]
69
+ const query = [
70
+ base.search.slice(1),
71
+ urlEncode(init.query ?? {}, formats),
72
+ queryString(init.querystring, formats),
73
+ ]
68
74
  .filter((q) => q !== "")
69
75
  .join("&");
70
76
  const url = `${base.origin}${base.pathname.replace(/\/+$/, "")}${fillPath(path, init.path)}${query === "" ? "" : `?${query}`}`;
@@ -88,7 +94,10 @@ export function createClient(config) {
88
94
  const requestInit = {
89
95
  ...fetchOptions(config),
90
96
  ...fetchOptions(init),
91
- method: method.toUpperCase(),
97
+ // A method of additionalOperations is sent as written; the fixed ones in upper case.
98
+ method: METHODS.includes(method)
99
+ ? method.toUpperCase()
100
+ : method,
92
101
  headers,
93
102
  };
94
103
  if (init.body !== undefined) {
@@ -117,8 +126,20 @@ export function createClient(config) {
117
126
  if (method !== "trace")
118
127
  client[method] = (path, init) => send(method, path, init);
119
128
  }
129
+ client.request = send;
120
130
  return client;
121
131
  }
132
+ /**
133
+ * A querystring parameter (OpenAPI 3.2), the whole query: an object is URL-encoded as
134
+ * a query is; a string, the text of another media type, is percent-encoded as one value.
135
+ */
136
+ function queryString(value, formats) {
137
+ if (value == null)
138
+ return "";
139
+ if (typeof value === "string")
140
+ return encodeURIComponent(value);
141
+ return urlEncode(value, formats);
142
+ }
122
143
  /**
123
144
  * Encodes a body by its contentType and sets content-type for it, unless the call's
124
145
  * headers did: a value is JSON without a contentType, a form for a form media type; a
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // Generate TypeScript declarations from OpenAPI 3.0 / 3.1 (JSON or YAML).
1
+ // Generate TypeScript declarations from OpenAPI 3.0 / 3.1 / 3.2 (JSON or YAML).
2
2
  import { render } from "./emit.js";
3
3
  import { GenerateError } from "./error.js";
4
4
  import { inputNames, typeNames } from "./ident.js";
@@ -28,7 +28,9 @@ export function generate(src, source) {
28
28
  throw new DiagError("#/components/schemas", "schemas must be an object");
29
29
  }
30
30
  const schemas = s?.entries ?? [];
31
- const cx = new Ctx(root, new Set(schemas.map(([k]) => k)), root.get("openapi").startsWith("3.1."), source && {
31
+ const cx = new Ctx(root, new Set(schemas.map(([k]) => k)),
32
+ // 3.1 and 3.2 Schema Objects are JSON Schema 2020-12.
33
+ !root.get("openapi").startsWith("3.0."), source && {
32
34
  url: source.url,
33
35
  load: (url) => loadText(cx, url, source.read(url)),
34
36
  });
@@ -149,9 +151,9 @@ function differingViews(components) {
149
151
  function checkVersion(root) {
150
152
  const v = root.get("openapi");
151
153
  if (typeof v === "string") {
152
- if (v.startsWith("3.0.") || v.startsWith("3.1."))
154
+ if (v.startsWith("3.0.") || v.startsWith("3.1.") || v.startsWith("3.2."))
153
155
  return;
154
- throw new DiagError("#/openapi", `unsupported OpenAPI version ${JSON.stringify(v)} (3.0.x or 3.1.x required)`);
156
+ throw new DiagError("#/openapi", `unsupported OpenAPI version ${JSON.stringify(v)} (3.0.x, 3.1.x or 3.2.x required)`);
155
157
  }
156
158
  if (v !== undefined)
157
159
  throw new DiagError("#/openapi", "openapi must be a string");
@@ -3,7 +3,7 @@ import { type Ctx } from "./pointer.ts";
3
3
  import { type Prop } from "./ty.ts";
4
4
  export interface Paths {
5
5
  paths: Prop[];
6
- /** Present only when the document has `webhooks` (3.1). */
6
+ /** Present only when the document has `webhooks` (3.1 and later). */
7
7
  webhooks?: Prop[];
8
8
  operations: Prop[];
9
9
  }
package/dist/operation.js CHANGED
@@ -4,7 +4,7 @@ import { JsonObject } from "./json.js";
4
4
  import { child, DiagError } from "./pointer.js";
5
5
  import { doc, schema } from "./schema.js";
6
6
  import { BLOB, lit, object, opRef, prop, STRING, tuple, UNKNOWN, } from "./ty.js";
7
- const LOCATIONS = ["path", "query", "header", "cookie"];
7
+ const LOCATIONS = ["path", "query", "querystring", "header", "cookie"];
8
8
  /** Header parameters OpenAPI says to ignore, in lower case. */
9
9
  const RESERVED_HEADERS = ["accept", "content-type", "authorization"];
10
10
  /** A property with optional documentation. */
@@ -39,11 +39,7 @@ function pathItems(cx, root, key, operations) {
39
39
  const methods = cx.derefIn(rawItem, itemAt, (value) => {
40
40
  const item = value;
41
41
  const methods = [];
42
- for (const method of METHODS) {
43
- const op = item.get(method);
44
- if (op === undefined)
45
- continue;
46
- const opAt = child(itemAt, method);
42
+ for (const [method, op, opAt] of itemOperations(cx, item, itemAt)) {
47
43
  // A webhook is called by the API: it sends the request and reads the response.
48
44
  const sent = key === "webhooks" ? "read" : "write";
49
45
  // fetch cannot send a body with GET or HEAD (OpenAPI 3.0 has consumers ignore
@@ -66,6 +62,36 @@ function pathItems(cx, root, key, operations) {
66
62
  }
67
63
  return out;
68
64
  }
65
+ /**
66
+ * A Path Item's operations, keyed by method: its fixed fields in OpenAPI's order, then its
67
+ * `additionalOperations`, whose keys are methods as they are sent (`COPY`). `query` and
68
+ * `additionalOperations` are OpenAPI 3.2 fields.
69
+ */
70
+ function itemOperations(cx, item, itemAt) {
71
+ const out = [];
72
+ for (const method of METHODS) {
73
+ if (method === "query" && !cx.v32)
74
+ continue;
75
+ const op = item.get(method);
76
+ if (op !== undefined)
77
+ out.push([method, op, child(itemAt, method)]);
78
+ }
79
+ const more = cx.v32
80
+ ? item.get("additionalOperations")
81
+ : undefined;
82
+ const moreAt = child(itemAt, "additionalOperations");
83
+ for (const [method, op] of more?.entries ?? []) {
84
+ const at = child(moreAt, method);
85
+ // OpenAPI forbids the method a fixed field sends (`POST` for `post`); the field's own
86
+ // name would be that field in the declarations. Methods are case-sensitive, so
87
+ // `Patch` is another method.
88
+ const field = METHODS.find((m) => method === m || method === m.toUpperCase());
89
+ if (field !== undefined)
90
+ throw new DiagError(at, `${method} is the Path Item's ${field} field, so additionalOperations must not have it`);
91
+ out.push([method, op, at]);
92
+ }
93
+ return out;
94
+ }
69
95
  function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
70
96
  const fields = [];
71
97
  const received = sent === "write" ? "read" : "write";
@@ -80,13 +106,21 @@ function operation(cx, { item, itemAt, op: o, at, sent, body: hasBody }) {
80
106
  collectParams(cx, params, o, at);
81
107
  const groups = [];
82
108
  for (const loc of LOCATIONS) {
109
+ // `in: querystring` is OpenAPI 3.2.
110
+ if (loc === "querystring" && !cx.v32)
111
+ continue;
83
112
  const props = [];
84
113
  for (const [p, pAt, base] of params) {
85
114
  if (p.str("in") !== loc)
86
115
  continue;
87
116
  const optional = loc !== "path" && p.get("required") !== true;
88
- const ty = cx.inMode(sent, () => cx.withBase(base, () => paramType(cx, p, pAt)));
89
- props.push(documented(p.str("name"), ty, optional, doc(p)));
117
+ const whole = loc === "querystring";
118
+ const ty = cx.inMode(sent, () => cx.withBase(base, () => paramType(cx, p, pAt, whole)));
119
+ // The whole query string (3.2) is one value; its name is not sent.
120
+ if (whole)
121
+ groups.push(documented(loc, ty, optional, doc(p)));
122
+ else
123
+ props.push(documented(p.str("name"), ty, optional, doc(p)));
90
124
  }
91
125
  if (props.length === 0)
92
126
  continue;
@@ -159,8 +193,10 @@ function collectParam(cx, out, value, pAt) {
159
193
  const loc = p.str("in");
160
194
  if (loc === "header" && RESERVED_HEADERS.includes(asciiLower(name)))
161
195
  return;
162
- // Header names are case-insensitive, so `X-Id` replaces `x-id`.
163
- const same = (n) => loc === "header" ? asciiLower(n) === asciiLower(name) : n === name;
196
+ // Header names are case-insensitive, so `X-Id` replaces `x-id`; an operation has one
197
+ // querystring, whose name is not sent.
198
+ const same = (n) => loc === "querystring" ||
199
+ (loc === "header" ? asciiLower(n) === asciiLower(name) : n === name);
164
200
  // Collected parameters all have a name.
165
201
  const slot = out.findIndex(([q]) => q.str("in") === loc && same(q.str("name")));
166
202
  // Its schema is converted later, against the document the parameter is in.
@@ -174,13 +210,35 @@ function collectParam(cx, out, value, pAt) {
174
210
  function asciiLower(s) {
175
211
  return s.replace(/[A-Z]/g, (c) => c.toLowerCase());
176
212
  }
177
- /** The type of a parameter or header: its `schema`, or the schema of its one `content` media type. */
178
- function paramType(cx, p, at) {
213
+ /**
214
+ * The type of a parameter or header: its `schema`, or the schema of its one `content`
215
+ * media type. A querystring (`whole`) is that schema for application/x-www-form-urlencoded,
216
+ * which the client URL-encodes; for any other media type it is the serialized text, a string.
217
+ */
218
+ function paramType(cx, p, at, whole = false) {
179
219
  const s = p.get("schema");
180
220
  if (s !== undefined)
181
221
  return schema(cx, s, child(at, "schema"));
182
- const [[mt, m]] = p.get("content").entries;
183
- return schema(cx, m.get("schema"), child(child(child(at, "content"), mt), "schema"));
222
+ const [[mt, raw]] = p.get("content").entries;
223
+ const mAt = child(child(at, "content"), mt);
224
+ return mediaType(cx, raw, mAt, (m) => {
225
+ const ty = schema(cx, m.get("schema"), child(mAt, "schema"));
226
+ const urlEncoded = essence(mt) === "application/x-www-form-urlencoded";
227
+ return whole && !urlEncoded ? STRING : ty;
228
+ });
229
+ }
230
+ /** The media type without parameters, in lower case, as the client compares it. */
231
+ function essence(mt) {
232
+ return mt.split(";")[0].trim().toLowerCase();
233
+ }
234
+ /**
235
+ * Runs `f` on a Media Type Object, which may be a `$ref` in OpenAPI 3.2
236
+ * (`components.mediaTypes`); before 3.2, `$ref` is no field of it.
237
+ */
238
+ function mediaType(cx, raw, at, f) {
239
+ if (!cx.v32)
240
+ return f(raw);
241
+ return cx.derefIn(raw, at, (m) => f(m));
184
242
  }
185
243
  /** `{ Name: T }` for a response's `headers`; Content-Type is ignored, as OpenAPI requires. */
186
244
  function headers(cx, response, at) {
@@ -204,18 +262,24 @@ function headers(cx, response, at) {
204
262
  * `{ "<media type>": T }` for a non-empty `content`, keeping every media type.
205
263
  * A binary media type is `Blob` and a text one `string` whatever its schema says, as is
206
264
  * a form in a response (read view): that is what the client reads and sends. The schema
207
- * is still converted so its errors are reported.
265
+ * is still converted so its errors are reported, and so is `itemSchema` (3.2): the client
266
+ * reads a sequential media type (`application/jsonl`, `text/event-stream`) whole, as these
267
+ * rules say, not item by item.
208
268
  */
209
269
  function content(cx, owner, at) {
210
270
  const media = owner.get("content");
211
271
  if (media === undefined || media.entries.length === 0)
212
272
  return undefined;
213
273
  const base = child(at, "content");
214
- return object(media.entries.map(([mt, m]) => {
215
- const s = m.get("schema");
216
- const ty = s === undefined
217
- ? UNKNOWN
218
- : schema(cx, s, child(child(base, mt), "schema"));
274
+ return object(media.entries.map(([mt, raw]) => {
275
+ const mAt = child(base, mt);
276
+ const ty = mediaType(cx, raw, mAt, (m) => {
277
+ const items = cx.v32 ? m.get("itemSchema") : undefined;
278
+ if (items !== undefined)
279
+ schema(cx, items, child(mAt, "itemSchema"));
280
+ const s = m.get("schema");
281
+ return s === undefined ? UNKNOWN : schema(cx, s, child(mAt, "schema"));
282
+ });
219
283
  const text = isTextMedia(mt) || (cx.mode === "read" && isFormMedia(mt));
220
284
  return prop(mt, isBinaryMedia(mt) ? BLOB : text ? STRING : ty);
221
285
  }));
package/dist/pointer.d.ts CHANGED
@@ -38,6 +38,10 @@ export declare class Ctx {
38
38
  readonly root: Value;
39
39
  /** The document's URL: from its Location, or a placeholder when it has none. */
40
40
  readonly documentUrl: string;
41
+ /** The document's base URI: its `$self` (3.2), resolved against its URL, or the URL. */
42
+ readonly documentBase: string;
43
+ /** Whether the document is OpenAPI 3.2, whose fields (`$self`, `query`, …) are read. */
44
+ readonly v32: boolean;
41
45
  /** Keys of `#/components/schemas`. */
42
46
  readonly schemas: ReadonlySet<string>;
43
47
  /**
package/dist/pointer.js CHANGED
@@ -74,6 +74,10 @@ export class Ctx {
74
74
  root;
75
75
  /** The document's URL: from its Location, or a placeholder when it has none. */
76
76
  documentUrl;
77
+ /** The document's base URI: its `$self` (3.2), resolved against its URL, or the URL. */
78
+ documentBase;
79
+ /** Whether the document is OpenAPI 3.2, whose fields (`$self`, `query`, …) are read. */
80
+ v32;
77
81
  #load;
78
82
  /** `$ref`s being expanded inline, for cycle detection. */
79
83
  #stack = [];
@@ -128,7 +132,16 @@ export class Ctx {
128
132
  ? DOCUMENT
129
133
  : withoutFragment(new URL(location.url));
130
134
  this.#load = location?.load;
131
- this.base = this.documentUrl;
135
+ this.v32 = str(root, "openapi")?.startsWith("3.2.") === true;
136
+ const self = this.v32 ? get(root, "$self") : undefined;
137
+ if (self !== undefined &&
138
+ (typeof self !== "string" || !URL.canParse(self, this.documentUrl)))
139
+ throw new DiagError("#/$self", "$self must be a URI reference");
140
+ this.documentBase =
141
+ self === undefined
142
+ ? this.documentUrl
143
+ : withoutFragment(new URL(self, this.documentUrl));
144
+ this.base = this.documentBase;
132
145
  }
133
146
  warn(at, msg) {
134
147
  const key = `${at}\n${msg}`;
@@ -173,7 +186,7 @@ export class Ctx {
173
186
  base;
174
187
  /** Whether `$ref`s resolve against the document itself (not another file, nor inside a schema with `$id`). */
175
188
  get inDocument() {
176
- return this.base === this.documentUrl;
189
+ return this.base === this.documentBase;
177
190
  }
178
191
  /**
179
192
  * How a location is written in messages: a JSON Pointer in the document (`#/a`), a
@@ -181,7 +194,7 @@ export class Ctx {
181
194
  */
182
195
  where(resource, fragment) {
183
196
  const hash = fragment === undefined ? "" : `#${fragment}`;
184
- if (resource === this.documentUrl)
197
+ if (resource === this.documentBase)
185
198
  return hash;
186
199
  const url = new URL(resource);
187
200
  const doc = new URL(this.documentUrl);
@@ -218,10 +231,12 @@ export class Ctx {
218
231
  */
219
232
  locate(r, at) {
220
233
  const url = new URL(r, this.base);
221
- const resource = withoutFragment(url);
222
234
  const fragment = url.hash.slice(1);
235
+ // A reference by the URL the document was read from still means the document.
236
+ const named = withoutFragment(url);
237
+ const resource = named === this.documentUrl ? this.documentBase : named;
223
238
  const index = this.#ids();
224
- const doc = resource === this.documentUrl
239
+ const doc = resource === this.documentBase
225
240
  ? this.root
226
241
  : (index.ids.get(resource) ?? this.#read(resource, r, at));
227
242
  const value = fragment === "" || fragment.startsWith("/")
@@ -236,7 +251,10 @@ export class Ctx {
236
251
  where: this.where(resource, fragment),
237
252
  };
238
253
  }
239
- /** Loads another document, once, and indexes its `$id`s and `$anchor`s. */
254
+ /**
255
+ * Loads another document, once, and indexes its `$id`s and `$anchor`s. It is known by
256
+ * the URL it is read from: kanagata reads files, so another document's `$self` is not read.
257
+ */
240
258
  #read(resource, r, at) {
241
259
  if (this.#load === undefined)
242
260
  throw new DiagError(at, `external $ref, but the document's location is unknown: ${r}`);
@@ -275,7 +293,7 @@ export class Ctx {
275
293
  if (this.#index !== undefined)
276
294
  return this.#index;
277
295
  const index = { ids: new Map(), anchors: new Map() };
278
- indexIds(index, this.root, this.documentUrl);
296
+ indexIds(index, this.root, this.documentBase);
279
297
  this.#index = index;
280
298
  return index;
281
299
  }
@@ -309,7 +327,7 @@ export class Ctx {
309
327
  !s.entries.every(([k]) => ALIAS_KEYS.has(k)))
310
328
  continue;
311
329
  // A target that does not resolve is reported where the component is converted.
312
- const target = this.withBase(this.documentUrl, () => this.tryLocate(r)?.value);
330
+ const target = this.withBase(this.documentBase, () => this.tryLocate(r)?.value);
313
331
  if (target !== undefined && !aliases.has(target))
314
332
  aliases.set(target, key);
315
333
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kanagata",
3
- "version": "0.1.0",
4
- "description": "TypeScript types from OpenAPI 3.0 / 3.1 (JSON or YAML), and a typed fetch client",
3
+ "version": "0.2.0",
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",
7
7
  "typescript",
package/src/client.ts CHANGED
@@ -8,7 +8,8 @@ export type Method =
8
8
  | "options"
9
9
  | "head"
10
10
  | "patch"
11
- | "trace";
11
+ | "trace"
12
+ | "query";
12
13
 
13
14
  // Derived from fetch itself, so this file type-checks with Node's types as well as the DOM's.
14
15
  type HeadersInit = NonNullable<ConstructorParameters<typeof Headers>[0]>;
@@ -17,12 +18,37 @@ type BodyInit = NonNullable<RequestInit["body"]>;
17
18
  type Get<T, K> = K extends keyof T ? T[K] : never;
18
19
 
19
20
  /** Paths that have method M. */
20
- type PathsOf<P, M extends Method> = {
21
+ type PathsOf<P, M extends string> = {
21
22
  [K in keyof P]: M extends keyof P[K] ? K : never;
22
23
  }[keyof P] &
23
24
  string;
24
25
 
25
- type Op<P, Path, M extends Method> = Get<Get<P, Path>, M>;
26
+ type Op<P, Path, M extends string> = Get<Get<P, Path>, M>;
27
+
28
+ /**
29
+ * The methods of P's path items beyond OpenAPI's fixed fields: the keys of their
30
+ * `additionalOperations` (OpenAPI 3.2), as written, which is how they are sent.
31
+ */
32
+ type OtherMethod<P> = Exclude<{ [K in keyof P]: keyof P[K] }[keyof P], Method> &
33
+ string;
34
+
35
+ /**
36
+ * The methods fetch sends as written: not CONNECT, TRACE and TRACK, which it rejects, nor
37
+ * DELETE, GET, HEAD, OPTIONS, POST and PUT in another case, which it sends in upper case.
38
+ */
39
+ type Sendable<M extends string> = M extends unknown
40
+ ? Uppercase<M> extends "CONNECT" | "TRACE" | "TRACK"
41
+ ? never
42
+ : Uppercase<M> extends
43
+ | "DELETE"
44
+ | "GET"
45
+ | "HEAD"
46
+ | "OPTIONS"
47
+ | "POST"
48
+ | "PUT"
49
+ ? never
50
+ : M
51
+ : never;
26
52
 
27
53
  /** Union of every media type in `content`; `undefined` without content. */
28
54
  type Content<B> = B extends { content: infer C } ? C[keyof C] : undefined;
@@ -206,7 +232,7 @@ type Undocumented = { content: Record<string, unknown> };
206
232
  export type Result<
207
233
  O,
208
234
  A extends ParseAs | undefined = undefined,
209
- M extends Method = Method,
235
+ M extends string = Method,
210
236
  > = O extends {
211
237
  responses: infer R;
212
238
  }
@@ -234,7 +260,7 @@ export type Result<
234
260
  */
235
261
  export type ResultOf<
236
262
  P,
237
- M extends Method,
263
+ M extends string,
238
264
  Path extends PathsOf<P, M>,
239
265
  A extends ParseAs | undefined = undefined,
240
266
  > = Result<Op<P, Path, M>, A, M>;
@@ -267,9 +293,12 @@ export interface ClientConfig extends FetchOptions {
267
293
  onData?: (data: unknown, call: DataCall) => MaybePromise<unknown>;
268
294
  }
269
295
 
270
- /** Which call a body answers. `path` is the template as written, such as `/users/{id}`. */
296
+ /**
297
+ * Which call a body answers. `method` is the client function's name (`get`), or the
298
+ * method given to `request` (`COPY`); `path` is the template as written, such as `/users/{id}`.
299
+ */
271
300
  export interface DataCall {
272
- method: Method;
301
+ method: string;
273
302
  path: string;
274
303
  status: number;
275
304
  parseAs: ParseAs | undefined;
@@ -285,13 +314,30 @@ type Call<P, M extends Method> = <
285
314
  ...args: Args<NeedsAll<Op<P, Path, M>>, A>
286
315
  ) => Promise<Result<Op<P, Path, M>, A, M>>;
287
316
 
288
- /** A function per method fetch sends: every one but TRACE, which fetch rejects. */
289
- export type Client<P> = { [M in Exclude<Method, "trace">]: Call<P, M> };
317
+ /** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
318
+ type OtherCall<P> = <
319
+ M extends Sendable<OtherMethod<P>>,
320
+ Path extends PathsOf<P, M>,
321
+ A extends ParseAs | undefined = undefined,
322
+ >(
323
+ method: M,
324
+ path: Path,
325
+ ...args: Args<NeedsAll<Op<P, Path, M>>, A>
326
+ ) => Promise<Result<Op<P, Path, M>, A, M>>;
327
+
328
+ /**
329
+ * A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
330
+ * `request` for the methods of `additionalOperations`.
331
+ */
332
+ export type Client<P> = { [M in Exclude<Method, "trace">]: Call<P, M> } & {
333
+ request: OtherCall<P>;
334
+ };
290
335
 
291
336
  interface AnyInit extends RequestOptions {
292
337
  baseUrl?: string;
293
338
  path?: Record<string, unknown>;
294
339
  query?: Record<string, unknown>;
340
+ querystring?: unknown;
295
341
  header?: Record<string, unknown>;
296
342
  cookie?: Record<string, unknown>;
297
343
  body?: unknown;
@@ -316,6 +362,7 @@ const OWN_KEYS = new Set([
316
362
  "onData",
317
363
  "path",
318
364
  "query",
365
+ "querystring",
319
366
  "header",
320
367
  "cookie",
321
368
  "body",
@@ -343,6 +390,7 @@ export const METHODS: readonly Method[] = [
343
390
  "head",
344
391
  "patch",
345
392
  "trace",
393
+ "query",
346
394
  ];
347
395
 
348
396
  /**
@@ -379,7 +427,7 @@ function resolveBase(baseUrl: string): URL {
379
427
  */
380
428
  export function createClient<P>(config: ClientConfig): Client<P> {
381
429
  async function send(
382
- method: Method,
430
+ method: string,
383
431
  path: string,
384
432
  init: AnyInit = {},
385
433
  ): Promise<AnyResult> {
@@ -389,7 +437,11 @@ export function createClient<P>(config: ClientConfig): Client<P> {
389
437
  array: init.arrayFormat ?? config.arrayFormat ?? "repeat",
390
438
  object: init.objectFormat ?? config.objectFormat ?? "deepObject",
391
439
  };
392
- const query = [base.search.slice(1), urlEncode(init.query ?? {}, formats)]
440
+ const query = [
441
+ base.search.slice(1),
442
+ urlEncode(init.query ?? {}, formats),
443
+ queryString(init.querystring, formats),
444
+ ]
393
445
  .filter((q) => q !== "")
394
446
  .join("&");
395
447
  const url = `${base.origin}${base.pathname.replace(/\/+$/, "")}${fillPath(path, init.path)}${query === "" ? "" : `?${query}`}`;
@@ -414,7 +466,10 @@ export function createClient<P>(config: ClientConfig): Client<P> {
414
466
  const requestInit: RequestInit & { duplex?: "half" } = {
415
467
  ...fetchOptions(config),
416
468
  ...fetchOptions(init),
417
- method: method.toUpperCase(),
469
+ // A method of additionalOperations is sent as written; the fixed ones in upper case.
470
+ method: (METHODS as readonly string[]).includes(method)
471
+ ? method.toUpperCase()
472
+ : method,
418
473
  headers,
419
474
  };
420
475
  if (init.body !== undefined) {
@@ -446,14 +501,31 @@ export function createClient<P>(config: ClientConfig): Client<P> {
446
501
 
447
502
  const client: Partial<
448
503
  Record<Method, (path: string, init?: AnyInit) => Promise<AnyResult>>
449
- > = {};
504
+ > & {
505
+ request?: (
506
+ method: string,
507
+ path: string,
508
+ init?: AnyInit,
509
+ ) => Promise<AnyResult>;
510
+ } = {};
450
511
  for (const method of METHODS) {
451
512
  if (method !== "trace")
452
513
  client[method] = (path, init) => send(method, path, init);
453
514
  }
515
+ client.request = send;
454
516
  return client as unknown as Client<P>;
455
517
  }
456
518
 
519
+ /**
520
+ * A querystring parameter (OpenAPI 3.2), the whole query: an object is URL-encoded as
521
+ * a query is; a string, the text of another media type, is percent-encoded as one value.
522
+ */
523
+ function queryString(value: unknown, formats: Formats): string {
524
+ if (value == null) return "";
525
+ if (typeof value === "string") return encodeURIComponent(value);
526
+ return urlEncode(value as Record<string, unknown>, formats);
527
+ }
528
+
457
529
  /**
458
530
  * Encodes a body by its contentType and sets content-type for it, unless the call's
459
531
  * headers did: a value is JSON without a contentType, a form for a form media type; a