You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
⚠️ **Breaking**: Most optional objects are now always present in types, just typed as `:never`. This includes keys of the Components Object as well as HTTP methods.
⚠️ **Breaking**: No more `external` export in schemas anymore. Everything gets flattened into the `components` object instead (if referencing a schema object from a remote partial, note it may have had a minor name change to avoid conflict).
⚠️ **Breaking**: Drop auth/fetching options in favor of Redocly CLI’s
6
+
7
+
- The `auth`, `httpHeaders`, `httpMethod`, and `fetch` options were all removed from the CLI and Node.js API
8
+
- To migrate, you’ll need to create a [redocly.yaml config](https://redocly.com/docs/cli/configuration/) that specifies your auth options [in the http setting](https://redocly.com/docs/cli/configuration/#resolve-non-public-or-non-remote-urls)
9
+
- Worth noting your `redocly.yaml` config will be respected for any other related settings
✨ **Feature**: automatically validate schemas with Redocly CLI ([docs](https://redocly.com/docs/cli/)). No more need for external tools to report errors! 🎉
6
+
7
+
- By default, it will only throw on actual schema errors (uses Redocly’s default settings)
8
+
- For stricter linting or custom rules, you can create a [redocly.yaml config](https://redocly.com/docs/cli/configuration/)
⚠️ **Breaking**: The Node.js API now returns the TypeScript AST for the main method as well as `transform()` and `postTransform()`. To migrate, you’ll have to use the `typescript` compiler API:
6
+
7
+
```diff
8
+
+ import ts from "typescript";
9
+
10
+
+ const DATE = ts.factory.createIdentifier("Date");
Though it’s more verbose, it’s also more powerful, as now you have access to additional properties of the generated code you didn’t before (such as injecting comments).
26
+
27
+
For example syntax, search this codebae to see how the TypeScript AST is used.
28
+
29
+
Also see [AST Explorer](https://astexplorer.net/)’s `typescript` parser to inspect how TypeScript is interpreted as an AST.
Copy file name to clipboardExpand all lines: docs/src/content/docs/node.md
+42-23
Original file line number
Diff line number
Diff line change
@@ -15,32 +15,40 @@ npm i --save-dev openapi-typescript
15
15
16
16
## Usage
17
17
18
-
```js
18
+
The Node API accepts either a parsed OpenAPI schema in a JS object, or a `string` or `URL` pointing to the location of a schema. It returns `Promise<ts.Node[]>` (an array of TypeScript AST nodes).
19
+
20
+
```ts
19
21
importfsfrom"node:fs";
20
22
importopenapiTSfrom"openapi-typescript";
21
23
22
-
// example 1: load [object] as schema (JSON only)
24
+
// example 1: load [object] as schema (provide a `cwd` to resolve relative $refs)
23
25
const schema =awaitfs.promises.readFile("spec.json", "utf8"); // must be OpenAPI JSON
> **Note**: a YAML string isn’t supported in the Node.js API (you’ll need to <a href="https://www.npmjs.com/package/js-yaml" target="_blank" rel="noopener noreferrer">convert it to JSON</a>). But loading YAML via URL is still supported in Node.js
36
+
From the result, you can traverse / manipulate / modify the AST as you see fit.
37
+
38
+
To convert the TypeScript AST into a string, you can use `astToString()` helper which is a thin wrapper around [TypeScript’s printer](https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API#re-printing-sections-of-a-typescript-file):
39
+
40
+
```ts
41
+
import { astToString } from"openapi-typescript";
42
+
43
+
const contents =astToString(ast);
44
+
```
35
45
36
46
## Options
37
47
38
48
The Node API supports all the [CLI flags](/cli#options) in `camelCase` format, plus the following additional options:
| `commentHeader` | `string` | | Override the default “This file was auto-generated …” file heading |
43
-
| `inject` | `string` | | Inject arbitrary TypeScript types into the start of the file |
44
52
|`transform`|`Function`|| Override the default Schema Object ➝ TypeScript transformer in certain scenarios |
45
53
|`postTransform`|`Function`|| Same as `transform` but runs _after_ the TypeScript transformation |
46
54
|`cwd`|`string \| URL`|| (optional) Provide the current working directory to resolve remote `$ref`s (only needed for in-memory JSON objects). |
@@ -50,7 +58,7 @@ The Node API supports all the [CLI flags](/cli#options) in `camelCase` format, p
50
58
Use the `transform()` and `postTransform()` options to override the default Schema Object transformer with your own. This is useful for providing nonstandard modifications for specific parts of your schema.
51
59
52
60
-`transform()` runs **before** the conversion to TypeScript (you’re working with the original OpenAPI nodes)
53
-
- `postTransform()` runs **after** the conversion to TypeScript (you’re working with TypeScript types)
61
+
-`postTransform()` runs **after** the conversion to TypeScript (you’re working with TypeScript AST)
54
62
55
63
#### Example: `Date` types
56
64
@@ -65,11 +73,18 @@ properties:
65
73
66
74
By default, openapiTS will generate `updated_at?: string;` because it’s not sure which format you want by `"date-time"` (formats are nonstandard and can be whatever you’d like). But we can enhance this by providing our own custom formatter, like so:
67
75
68
-
```js
69
-
consttypes=openapiTS(mySchema, {
70
-
transform(schemaObject, metadata): string {
71
-
if ("format"in schemaObject &&schemaObject.format==="date-time") {
72
-
returnschemaObject.nullable?"Date | null":"Date";
76
+
```ts
77
+
import ts from "typescript";
78
+
79
+
const DATE = ts.factory.createIdentifier("Date"); // `Date`
Copy file name to clipboardExpand all lines: packages/openapi-typescript/CONTRIBUTING.md
+11-10
Original file line number
Diff line number
Diff line change
@@ -38,11 +38,17 @@ pnpm run dev
38
38
39
39
This will compile the code as you change automatically.
40
40
41
-
###Writing the PR
41
+
#### Tip: use ASTExplorer.net!
42
42
43
-
**Please fill out the template!** It’s a very lightweight template 🙂.
43
+
Working with the TypeScript AST can be daunting. Luckly, there’s [astexplorer.net](https://astexplorer.net) which makes it much more accessible. Rather than trying to build an AST from scratch (which is near impossible), instead:
44
44
45
-
### Use Test-driven Development!
45
+
1. Switch to the **typescript** parser in the top menu
46
+
2. Type out code in the left-hand panel
47
+
3. Inspect the right-hand panel to see what the desired AST is.
48
+
49
+
From there, you can refer to existing examples in the codebase. There may even be helper utilities in `src/lib/ts.ts` to make life easier.
50
+
51
+
#### Tip: Use Test-driven Development!
46
52
47
53
Contributing to this library is hard-bordering-on-impossible without a [test-driven development (TDD)](https://en.wikipedia.org/wiki/Test-driven_development) strategy. If you’re new to this, the basic workflow is:
48
54
@@ -60,7 +66,7 @@ To add a schema as a snapshot test, modify the [/scripts/download-schemas.ts](/s
60
66
61
67
### Generating types
62
68
63
-
It may be surprising to hear, but _generating TypeScript types from OpenAPI is opinionated!_ Even though TypeScript and OpenAPI are very close relatives, both being JavaScript/JSON-based, they are nonetheless 2 different languages and thus there is always some room for interpretation. Likewise, some parts of the OpenAPI specification can be ambiguous on how they’re used, and what the expected type outcomes may be (though this is generally for more advanced usecasees, such as specific implementations of `anyOf` as well as [discriminator](https://spec.openapis.org/oas/latest.html#discriminatorObject) and complex polymorphism).
69
+
It may be surprising to hear, but generating TypeScript types from OpenAPI is opinionated. Even though TypeScript and OpenAPI are close relatives—both JavaScript/JSON-based—they are nonetheless 2 different languages and thus there is room for interpretation. Further, some parts of the OpenAPI specification can be ambiguous on how they’re used, and what the expected type outcomes may be (though this is generally for more advanced usecasees, such as specific implementations of `anyOf` as well as [discriminator](https://spec.openapis.org/oas/latest.html#discriminatorObject) and complex polymorphism).
64
70
65
71
All that said, this library should strive to generate _the most predictable_ TypeScript output for a given schema. And to achieve that, it always helps to open an [issue](https://github.com/drwpow/openapi-typescript/issues) or [discussion](https://github.com/drwpow/openapi-typescript/discussions) to gather feedback.
66
72
@@ -131,7 +137,6 @@ pnpm run update:examples
131
137
132
138
This library has both unit tests (tests that test a tiny part of a schema) and snapshot tests (tests that run over an entire, complete schema). When opening a PR, the former are more valuable than the latter, and are always required. However, updating snapshot tests can help with the following:
133
139
134
-
- Fixing bugs that deal with multiple schemas with remote `$ref`s
135
140
- Fixing Node.js or OS-related bugs
136
141
- Adding a CLI option that changes the entire output
137
142
@@ -141,8 +146,4 @@ For most PRs, **snapshot tests can be avoided.** But for scenarios similar to th
141
146
142
147
### When I run tests, it’s not picking up my changes
143
148
144
-
Be sure to run `pnpm run build` to build the project. Most tests actually test the **compiled JS**, not the source TypeScript. It’s recommended to run `pnpm run dev` as you work so changes are always up-to-date.
145
-
146
-
### I get an obscure error when testing against my schema
147
-
148
-
Be sure your schema passes [Redocly lint](https://redocly.com/docs/cli/commands/lint/). Remember this library requires already-validated OpenAPI schemas, so even subtle errors will throw.
149
+
Some tests import the **built package** and not the source file. Be sure to run `pnpm run build` to build the project. You can also run `pnpm run dev` as you work so changes are always up-to-date.
0 commit comments