api 4.5.1 → 5.0.0-beta.2

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.
Files changed (70) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +32 -162
  3. package/bin/api +2 -0
  4. package/dist/bin.d.ts +1 -0
  5. package/dist/bin.js +91 -0
  6. package/dist/cache.d.ts +30 -0
  7. package/dist/cache.js +217 -0
  8. package/dist/cli/codegen/index.d.ts +4 -0
  9. package/dist/cli/codegen/index.js +23 -0
  10. package/dist/cli/codegen/language.d.ts +27 -0
  11. package/dist/cli/codegen/language.js +19 -0
  12. package/dist/cli/codegen/languages/typescript.d.ts +99 -0
  13. package/dist/cli/codegen/languages/typescript.js +769 -0
  14. package/dist/cli/commands/index.d.ts +4 -0
  15. package/dist/cli/commands/index.js +9 -0
  16. package/dist/cli/commands/install.d.ts +3 -0
  17. package/dist/cli/commands/install.js +230 -0
  18. package/dist/cli/lib/prompt.d.ts +9 -0
  19. package/dist/cli/lib/prompt.js +81 -0
  20. package/dist/cli/logger.d.ts +1 -0
  21. package/dist/cli/logger.js +16 -0
  22. package/dist/cli/storage.d.ts +105 -0
  23. package/dist/cli/storage.js +264 -0
  24. package/dist/core/getJSONSchemaDefaults.d.ts +15 -0
  25. package/dist/core/getJSONSchemaDefaults.js +62 -0
  26. package/dist/core/index.d.ts +32 -0
  27. package/dist/core/index.js +143 -0
  28. package/dist/core/parseResponse.d.ts +1 -0
  29. package/dist/core/parseResponse.js +65 -0
  30. package/dist/core/prepareAuth.d.ts +5 -0
  31. package/dist/core/prepareAuth.js +55 -0
  32. package/dist/core/prepareParams.d.ts +24 -0
  33. package/dist/core/prepareParams.js +351 -0
  34. package/dist/core/prepareServer.d.ts +13 -0
  35. package/dist/core/prepareServer.js +50 -0
  36. package/dist/fetcher.d.ts +54 -0
  37. package/dist/fetcher.js +165 -0
  38. package/dist/index.d.ts +6 -0
  39. package/dist/index.js +276 -0
  40. package/dist/packageInfo.d.ts +2 -0
  41. package/dist/packageInfo.js +6 -0
  42. package/package.json +67 -28
  43. package/src/.sink.d.ts +1 -0
  44. package/src/bin.ts +20 -0
  45. package/src/cache.ts +212 -0
  46. package/src/cli/codegen/index.ts +31 -0
  47. package/src/cli/codegen/language.ts +47 -0
  48. package/src/cli/codegen/languages/typescript.ts +807 -0
  49. package/src/cli/commands/index.ts +5 -0
  50. package/src/cli/commands/install.ts +196 -0
  51. package/src/cli/lib/prompt.ts +29 -0
  52. package/src/cli/logger.ts +10 -0
  53. package/src/cli/storage.ts +297 -0
  54. package/src/core/getJSONSchemaDefaults.ts +74 -0
  55. package/src/core/index.ts +108 -0
  56. package/src/{lib/parseResponse.js → core/parseResponse.ts} +5 -7
  57. package/src/core/prepareAuth.ts +85 -0
  58. package/src/core/prepareParams.ts +338 -0
  59. package/src/{lib/prepareServer.js → core/prepareServer.ts} +13 -12
  60. package/src/fetcher.ts +141 -0
  61. package/src/index.ts +212 -0
  62. package/src/packageInfo.ts +3 -0
  63. package/src/typings.d.ts +3 -0
  64. package/tsconfig.json +24 -0
  65. package/src/cache.js +0 -225
  66. package/src/index.js +0 -177
  67. package/src/lib/getSchema.js +0 -34
  68. package/src/lib/index.js +0 -11
  69. package/src/lib/prepareAuth.js +0 -69
  70. package/src/lib/prepareParams.js +0 -198
package/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright © 2020 ReadMe
1
+ Copyright © 2022 ReadMe
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of
4
4
  this software and associated documentation files (the “Software”), to deal in
package/README.md CHANGED
@@ -1,180 +1,50 @@
1
- # 🚀 api
1
+ <p align="center">
2
+ <img width="400" src="https://raw.githubusercontent.com/readmeio/api/main/docs/images/logo.svg" />
3
+ </p>
2
4
 
3
- [![npm](https://img.shields.io/npm/v/api)](https://npm.im/api) [![Build](https://github.com/readmeio/api/workflows/CI/badge.svg)](https://github.com/readmeio/api)
5
+ <p align="center">
6
+ Magical SDK generation from an OpenAPI definition 🪄
7
+ </p>
4
8
 
5
- Automatic SDK generation from an OpenAPI definition.
9
+ <p align="center">
10
+ <a href="https://npm.im/api"><img src="https://img.shields.io/npm/v/api.svg?style=for-the-badge" alt="NPM Version"></a>
11
+ <a href="https://npm.im/api"><img src="https://img.shields.io/node/v/api.svg?style=for-the-badge" alt="Node Version"></a>
12
+ <a href="https://npm.im/api"><img src="https://img.shields.io/npm/l/api.svg?style=for-the-badge" alt="MIT License"></a>
13
+ <a href="https://github.com/readmeio/api"><img src="https://img.shields.io/github/workflow/status/readmeio/api/CI.svg?style=for-the-badge" alt="Build status"></a>
14
+ </p>
6
15
 
7
- * [Installation](#installation)
8
- * [Usage](#usage)
9
- * [Authentication](#authentication)
10
- * [Parameters and Payloads](#parameters-and-payloads)
11
- * [HTTP requests](#http-requests)
12
- * [Server configurations](#server-configurations)
13
- * [How does it work?](#how-does-it-work)
14
- * [Interested in contributing?](#interested-in-contributing)
15
- * [FAQ](#faq)
16
+ - [Installation](https://api.readme.dev/docs/installation)
17
+ - [Usage](https://api.readme.dev/docs/usage)
18
+ - [Authentication](https://api.readme.dev/docs/authentication)
19
+ - [Parameters and Payloads](https://api.readme.dev/docs/parameters-and-payloads)
20
+ - [HTTP requests](https://api.readme.dev/docs/http-requests)
21
+ - [Server configurations](https://api.readme.dev/docs/server-configurations)
22
+ - [How does it work?](https://api.readme.dev/docs/how-it-works)
23
+ - [FAQ](https://api.readme.dev/docs/faq)
16
24
 
17
- ## Installation
18
- ```
19
- npm install api --save
20
- ```
21
-
22
- ## Usage
23
- Using `api` is as simple as supplying it an OpenAPI and using the SDK as you would any other!
24
-
25
- ```js
26
- const sdk = require('api')('https://raw.githubusercontent.com/readmeio/oas-examples/main/3.0/json/petstore.json');
27
-
28
- sdk.listPets().then(res => {
29
- console.log(`My pets name is ${res[0].name}!`);
30
- });
31
- ```
32
-
33
- The OpenAPI definition is automatically downloaded, cached, and transformed into a chainable [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) Promise that you can use to make API requests.
34
-
35
- ### Authentication
36
- `api` supports API authentication through an `.auth()` method:
37
-
38
- ```js
39
- sdk.auth('myApiToken');
40
- sdk.listPets().then(...);
41
- ```
42
-
43
- With the exception of OpenID, it supports all forms of authentication supported by the OpenAPI specification! Just give `.auth()` your credentials and it'll figure out how to use it according to the API you're using.
44
-
45
- For example:
46
-
47
- * HTTP Basic auth: `sdk.auth('username', 'password')`
48
- * Bearer tokens (HTTP or OAuth 2): `sdk.auth('myBearerToken')`
49
- * API Keys: `sdk.auth('myApiKey')`
50
-
51
- > ℹ️ Note that `sdk.auth()` is not chainable.
52
-
53
- ### Parameters and Payloads
54
- When supplying parameters and/or request body payloads to an API request, you don't need to explicitly define what goes where since the API definition contains all that information. All you need to do is supply either one or two objects:
55
-
56
- * `body`: This will contain all data required for a request body payload for a POST, PUT, etc. request. It can either be an array or an object — whichever you need to use the API operation you're using.
57
- * `metadata`: This is an object where all parameters (path, query, header, cookie) go. Again, don't worry about telling the SDK that a path parameter is for the path, that's all handled for you.
58
-
59
- For example, if you wanted to make a simple GET request:
60
-
61
- ```js
62
- sdk.showPetById({ petId: 1234 }).then(...)
63
- ```
64
-
65
- Since `petId` matches up with the `petId` path parameter, the SDK here will issue a GET request against `/pets/1234`.
66
-
67
- What about a POST request?
68
-
69
- ```js
70
- sdk.createPets({ name: 'Buster' }).then(...)
71
- ```
72
-
73
- Since `name` here would correspond on `createPets` to request body payload, this will issue a POST request against `/pets` to make a new pet named "Buster".
74
-
75
- What about operations that require both? Well you can mix them too!
76
-
77
- ```js
78
- sdk.updatePet({ name: 'Buster 2' }, { petId: 1234 }).then(...)
79
- ```
80
-
81
- Since we've supplied two objects here, the SDK automatically knows that you're supplying both a `body` and `metadata`, and can make a PUT request against `/pets/1234` for you.
82
-
83
- What about a `multipart/form-data` request? That works too, and you don't even have to worry about the fun of multipart boundaries!
25
+ `api` is a library that facilitates creating an SDK from an OpenAPI definition. You can use its codegen offering to create an opinionated SDK for TypeScript or JS (+ TypeScript types).
84
26
 
85
- ```js
86
- sdk.uploadFile({ file: '/path/to/a/file.txt' }).then(...)
27
+ ```sh
28
+ $ npx api install https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.json
87
29
  ```
88
30
 
89
- You can also give it a stream and it'll handle all of the hard work for you.
90
-
91
31
  ```js
92
- sdk.uploadFile({ file: fs.createReadStream('/path/to/a/file.txt') }).then(...)
93
- ```
94
-
95
- ### HTTP requests
96
- If the API you're using doesn't have any documented operation IDs, you can make requests with HTTP verbs instead:
97
-
98
- ```js
99
- sdk.get('/pets/{petId}', { petId: 1234 }).then(...)
100
- ```
101
-
102
- The SDK supports GET, PUT, POST, DELETE, OPTIONS, HEAD, and TRACE requests.
103
-
104
- ### Server configurations
105
- If the API you're using offers alternate server URLs and server variables in its [`servers`](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#serverObject) definition you can supply this to the SDK with `.server()`:
32
+ const SDK = require('@api/petstore');
106
33
 
107
- ```js
108
- sdk.server('https://{region}.api.example.com/{basePath}', {
109
- name: 'eu',
110
- basePath: 'v14',
34
+ const petstore = new SDK();
35
+ petstore.listPets().then(res => {
36
+ console.log(`My pets name is ${res[0].name}!`);
111
37
  });
112
-
113
- sdk.get('/pets').then(...)
114
- ```
115
-
116
- When your request is executed it will be made to `https://eu.api.example.com/v14/pets`. Alternatively if you don't want to deal with URL templates you can opt to pass the full URL in instead:
117
-
118
- ```js
119
- sdk.server('https://eu.api.example.com/v14');
120
- ```
121
-
122
- ## How does it work?
123
- Behind the scenes, `api` will:
124
-
125
- 1. Download the supplied OpenAPI definition, either from a publically accessible URLs or an absolute/relative path.
126
- 2. Dereference the definition so it's easier for us to handle.
127
- 3. Hash the definition and cache it into a directory in `node_modules/.cache/api/`.
128
- 4. Process the definition and instantiate chainable methods for HTTP verbs and operation IDs the API contains via a JS [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy).
129
-
130
- On subsequent requests, `api` will look in its cache, and if the supplied definition exists there, it'll retrieve it from the cache instead of re-retrieving it again.
131
-
132
- ## Interested in contributing?
133
- Welcome! Have a look at [CONTRIBUTING.md](CONTRIBUTING.md).
134
-
135
- ## FAQ
136
- #### Does this support YAML definitions?
137
- Yes! YAML definitions will be automatically converted to JSON before they're cached and loaded as an SDK.
138
-
139
- #### Does this support Swagger 2.0 definitions?
140
- At the moment it does not. If you wish to use an API that has a Swagger 2.0 file, you'll need to first convert it to an OpenAPI 3 definition.
141
-
142
- #### Does this support traditional OAuth 2 flows of creating tokens?
143
- Not yet, unfortunately. For APIs that use OAuth 2, you'll need a fully-qualified token already for `api` to make requests.
144
-
145
- #### Does this support APIs that use multiple forms of authentication on a single request?
146
- Not yet! This is something we're thinking about how to handle, but it's difficult with the simple nature of the `.auth()` method as it currently does not require the user to inform the SDK of what kind of authentication scheme the token they're supplying it should match up against.
147
-
148
- #### Will this work in browsers?
149
- Not at the moment as the library requires some filesystem handling in order to manage its cache state, but it's something we're actively thinking about. If you'd like to help us out in making this compatible with browsers we'd love to help you out on a pull request.
150
-
151
- #### Will this validate my data before it reaches the API?
152
- Not yet! This is something we've got planned down the road.
153
-
154
- #### Does this support OpenAPI definitions that require authentication to download?
155
- Not yet! The URL that you give the module must be publicy accessible. If it isn't, you can download it to your computer/server and then use the absolute path to that file instead.
156
-
157
- ```js
158
- const sdk = require('api')('/path/to/downloaded.json');
159
38
  ```
160
39
 
161
- #### How do I access the Response object (for status and headers)?
162
- By default we parse the response based on the `content-type` header for you. You can disable this by doing the following:
40
+ Or you can use it dynamically (though you won't have fancy TypeScript types):
163
41
 
164
42
  ```js
165
- sdk.config({ parseResponse: false });
166
- ```
167
-
168
- #### Where is the cache stored?
169
-
170
- By default the cache is configured with the [find-cache-dir](https://npm.im/find-cache-dir) library so the cache will be in `node_modules/.cache/api`. If placing this cache within the `node_modules/` directory is a problem for your environment (maybe you use `npm prune`) you can configure this by supplying an additional argument to the SDK instantiator:
171
-
172
- ```js
173
- const sdk = require('api')('https://raw.githubusercontent.com/readmeio/oas-examples/main/3.0/json/petstore.json', {
174
- cacheDir: './path/to/my/custom/cache/dir',
175
- });
43
+ const petstore = require('api')(
44
+ 'https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.json'
45
+ );
176
46
 
177
- sdk.listPets().then(res => {
47
+ petstore.listPets().then(res => {
178
48
  console.log(`My pets name is ${res[0].name}!`);
179
49
  });
180
50
  ```
package/bin/api ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ require('../dist/bin');
package/dist/bin.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (_) try {
41
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ var __importDefault = (this && this.__importDefault) || function (mod) {
62
+ return (mod && mod.__esModule) ? mod : { "default": mod };
63
+ };
64
+ exports.__esModule = true;
65
+ var commander_1 = require("commander");
66
+ var pkg = __importStar(require("./packageInfo"));
67
+ var commands_1 = __importDefault(require("./cli/commands"));
68
+ (function () { return __awaiter(void 0, void 0, void 0, function () {
69
+ var program;
70
+ return __generator(this, function (_a) {
71
+ switch (_a.label) {
72
+ case 0:
73
+ program = new commander_1.Command();
74
+ program.name(pkg.PACKAGE_NAME);
75
+ program.version(pkg.PACKAGE_VERSION);
76
+ /**
77
+ * Instead of using Commander's `executableDir` API for loading in external command files we're
78
+ * programatically doing it like this because it's cleaner for us to let Commander manage option
79
+ * and argument parsing within this file than having each command manage that itself.
80
+ */
81
+ Object.entries(commands_1["default"]).forEach(function (_a) {
82
+ var cmd = _a[1];
83
+ program.addCommand(cmd);
84
+ });
85
+ return [4 /*yield*/, program.parseAsync(process.argv)];
86
+ case 1:
87
+ _a.sent();
88
+ return [2 /*return*/];
89
+ }
90
+ });
91
+ }); })();
@@ -0,0 +1,30 @@
1
+ import type { OASDocument } from 'oas/@types/rmoas.types';
2
+ import 'isomorphic-fetch';
3
+ import Fetcher from './fetcher';
4
+ declare type CacheStore = Record<string, {
5
+ hash: string;
6
+ path?: string;
7
+ original: string | OASDocument;
8
+ title?: string;
9
+ version?: string;
10
+ }>;
11
+ export default class Cache {
12
+ static dir: string;
13
+ static cacheStore: string;
14
+ static specsCache: string;
15
+ uri: string | OASDocument;
16
+ uriHash: string;
17
+ cached: false | CacheStore;
18
+ fetcher: Fetcher;
19
+ constructor(uri: string | OASDocument, cacheDir?: string | false);
20
+ static getCacheHash(file: string | OASDocument): string;
21
+ static setCacheDir(dir?: string | false): void;
22
+ static reset(): Promise<void>;
23
+ static validate(json: any): Promise<import("openapi-types").OpenAPI.Document<{}>>;
24
+ isCached(): boolean;
25
+ getCache(): CacheStore;
26
+ get(): any;
27
+ load(): Promise<OASDocument>;
28
+ save(spec: OASDocument): OASDocument;
29
+ }
30
+ export {};
package/dist/cache.js ADDED
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (_) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ exports.__esModule = true;
42
+ require("isomorphic-fetch");
43
+ var openapi_parser_1 = __importDefault(require("@readme/openapi-parser"));
44
+ var crypto_1 = __importDefault(require("crypto"));
45
+ var find_cache_dir_1 = __importDefault(require("find-cache-dir"));
46
+ var fs_1 = __importDefault(require("fs"));
47
+ var os_1 = __importDefault(require("os"));
48
+ var path_1 = __importDefault(require("path"));
49
+ var make_dir_1 = __importDefault(require("make-dir"));
50
+ var packageInfo_1 = require("./packageInfo");
51
+ var fetcher_1 = __importDefault(require("./fetcher"));
52
+ var Cache = /** @class */ (function () {
53
+ function Cache(uri, cacheDir) {
54
+ if (cacheDir === void 0) { cacheDir = false; }
55
+ Cache.setCacheDir(cacheDir);
56
+ Cache.cacheStore = path_1["default"].join(Cache.dir, 'cache.json');
57
+ Cache.specsCache = path_1["default"].join(Cache.dir, 'specs');
58
+ this.fetcher = new fetcher_1["default"](uri);
59
+ this.uri = this.fetcher.uri;
60
+ this.uriHash = Cache.getCacheHash(this.uri);
61
+ // This should default to false so we have awareness if we've looked at the cache yet.
62
+ this.cached = false;
63
+ }
64
+ Cache.getCacheHash = function (file) {
65
+ var data;
66
+ if (typeof file === 'object') {
67
+ // Under certain unit testing circumstances, we might be supplying the class with a raw JSON
68
+ // object so we'll need to convert it to a string in order to hand it off to the crypto
69
+ // module.
70
+ data = JSON.stringify(file);
71
+ }
72
+ else {
73
+ data = file;
74
+ }
75
+ return crypto_1["default"].createHash('md5').update(data).digest('hex');
76
+ };
77
+ Cache.setCacheDir = function (dir) {
78
+ if (dir) {
79
+ Cache.dir = dir;
80
+ return;
81
+ }
82
+ else if (Cache.dir) {
83
+ // If we already have a cache dir set and aren't explicitly it to something new then we
84
+ // shouldn't overwrite what we've already got.
85
+ return;
86
+ }
87
+ Cache.dir = (0, find_cache_dir_1["default"])({ name: packageInfo_1.PACKAGE_NAME });
88
+ if (typeof Cache.dir === 'undefined') {
89
+ // The `find-cache-dir` module returns `undefined` if the `node_modules/` directory isn't
90
+ // writable, or there's no `package.json` in the root-most directory. If this happens, we can
91
+ // instead adhoc create a cache directory in the users OS temp directory and store our data
92
+ // there.
93
+ //
94
+ // @link https://github.com/avajs/find-cache-dir/issues/29
95
+ Cache.dir = make_dir_1["default"].sync(path_1["default"].join(os_1["default"].tmpdir(), packageInfo_1.PACKAGE_NAME));
96
+ }
97
+ };
98
+ Cache.reset = function () {
99
+ return __awaiter(this, void 0, void 0, function () {
100
+ return __generator(this, function (_a) {
101
+ switch (_a.label) {
102
+ case 0:
103
+ if (!Cache.cacheStore) return [3 /*break*/, 2];
104
+ return [4 /*yield*/, fs_1["default"].promises.rm(Cache.cacheStore)["catch"](function () {
105
+ // no-op
106
+ })];
107
+ case 1:
108
+ _a.sent();
109
+ _a.label = 2;
110
+ case 2:
111
+ if (!Cache.specsCache) return [3 /*break*/, 4];
112
+ return [4 /*yield*/, fs_1["default"].promises.rm(Cache.specsCache, { recursive: true })["catch"](function () {
113
+ // no-op
114
+ })];
115
+ case 3:
116
+ _a.sent();
117
+ _a.label = 4;
118
+ case 4: return [2 /*return*/];
119
+ }
120
+ });
121
+ });
122
+ };
123
+ Cache.validate = function (json) {
124
+ if (json.swagger) {
125
+ throw new Error('Sorry, this module only supports OpenAPI definitions.');
126
+ }
127
+ // The `validate` method handles dereferencing for us.
128
+ return openapi_parser_1["default"].validate(json, {
129
+ dereference: {
130
+ // If circular `$refs` are ignored they'll remain in the API definition as `$ref: String`.
131
+ // This allows us to not only do easy circular reference detection but also stringify and
132
+ // save dereferenced API definitions back into the cache directory.
133
+ circular: 'ignore'
134
+ }
135
+ })["catch"](function (err) {
136
+ if (/is not a valid openapi definition/i.test(err.message)) {
137
+ throw new Error("Sorry, that doesn't look like a valid OpenAPI definition.");
138
+ }
139
+ throw err;
140
+ });
141
+ };
142
+ Cache.prototype.isCached = function () {
143
+ var cache = this.getCache();
144
+ return cache && this.uriHash in cache;
145
+ };
146
+ Cache.prototype.getCache = function () {
147
+ if (typeof this.cached === 'object') {
148
+ return this.cached;
149
+ }
150
+ this.cached = {};
151
+ if (fs_1["default"].existsSync(Cache.cacheStore)) {
152
+ this.cached = JSON.parse(fs_1["default"].readFileSync(Cache.cacheStore, 'utf8'));
153
+ }
154
+ return this.cached;
155
+ };
156
+ Cache.prototype.get = function () {
157
+ // If the class was supplied a raw object, just go ahead and bypass the caching system and
158
+ // return that.
159
+ if (typeof this.uri === 'object') {
160
+ return this.uri;
161
+ }
162
+ if (!this.isCached()) {
163
+ throw new Error("".concat(this.uri, " has not been cached yet and must do so before being retrieved."));
164
+ }
165
+ var cache = this.getCache();
166
+ // Prior to v4.5.0 we were putting a fully resolved path to the API definition in the cache
167
+ // store but if you had specified a custom caching directory and would generate the cache on
168
+ // your system, that filepath would obviously not be the same in other environments. For this
169
+ // reason the `path` was removed from the cache store in favor of storing the `hash` instead.
170
+ //
171
+ // If we still have `path` in the config cache for backwards compatibility we should use it.
172
+ if ('path' in cache[this.uriHash]) {
173
+ return JSON.parse(fs_1["default"].readFileSync(cache[this.uriHash].path, 'utf8'));
174
+ }
175
+ return JSON.parse(fs_1["default"].readFileSync(path_1["default"].join(Cache.specsCache, "".concat(cache[this.uriHash].hash, ".json")), 'utf8'));
176
+ };
177
+ Cache.prototype.load = function () {
178
+ return __awaiter(this, void 0, void 0, function () {
179
+ var _this = this;
180
+ return __generator(this, function (_a) {
181
+ // If the class was supplied a raw object, just go ahead and bypass the caching system and
182
+ // return that.
183
+ if (typeof this.uri === 'object') {
184
+ return [2 /*return*/, this.uri];
185
+ }
186
+ return [2 /*return*/, this.fetcher.load().then(function (spec) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
187
+ return [2 /*return*/, this.save(spec)];
188
+ }); }); })];
189
+ });
190
+ });
191
+ };
192
+ Cache.prototype.save = function (spec) {
193
+ if (!fs_1["default"].existsSync(Cache.dir)) {
194
+ fs_1["default"].mkdirSync(Cache.dir, { recursive: true });
195
+ }
196
+ if (!fs_1["default"].existsSync(Cache.specsCache)) {
197
+ fs_1["default"].mkdirSync(Cache.specsCache, { recursive: true });
198
+ }
199
+ var cache = this.getCache();
200
+ if (!(this.uriHash in cache)) {
201
+ var saved = JSON.stringify(spec, null, 2);
202
+ var fileHash = crypto_1["default"].createHash('md5').update(saved).digest('hex');
203
+ cache[this.uriHash] = {
204
+ hash: fileHash,
205
+ original: this.uri,
206
+ title: 'title' in spec.info ? spec.info.title : undefined,
207
+ version: 'version' in spec.info ? spec.info.version : undefined
208
+ };
209
+ fs_1["default"].writeFileSync(path_1["default"].join(Cache.specsCache, "".concat(fileHash, ".json")), saved);
210
+ fs_1["default"].writeFileSync(Cache.cacheStore, JSON.stringify(cache, null, 2));
211
+ this.cached = cache;
212
+ }
213
+ return spec;
214
+ };
215
+ return Cache;
216
+ }());
217
+ exports["default"] = Cache;
@@ -0,0 +1,4 @@
1
+ import type Oas from 'oas';
2
+ import type CodeGeneratorLanguage from './language';
3
+ export declare type SupportedLanguages = 'js' | 'js-cjs' | 'js-esm' | 'ts';
4
+ export default function codegen(language: SupportedLanguages, spec: Oas, specPath: string, identifier: string): CodeGeneratorLanguage;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ exports.__esModule = true;
6
+ var typescript_1 = __importDefault(require("./languages/typescript"));
7
+ function codegen(language, spec, specPath, identifier) {
8
+ switch (language) {
9
+ case 'js':
10
+ throw new TypeError('An export format of CommonJS or ECMAScript is required for JavaScript compilation.');
11
+ case 'js-cjs':
12
+ case 'js-esm':
13
+ case 'ts':
14
+ return new typescript_1["default"](spec, specPath, identifier, {
15
+ outputJS: ['js-cjs', 'js-esm'].includes(language),
16
+ // TS will always generate with ESM-like exports.
17
+ compilerTarget: language === 'js-cjs' ? 'cjs' : 'esm'
18
+ });
19
+ default:
20
+ throw new TypeError("Unsupported language supplied: ".concat(language));
21
+ }
22
+ }
23
+ exports["default"] = codegen;
@@ -0,0 +1,27 @@
1
+ import type Oas from 'oas';
2
+ import type Storage from '../storage';
3
+ export interface InstallerOptions {
4
+ /**
5
+ * Will initiate a dry run install process. Used for simulating installations within a unit test.
6
+ */
7
+ dryRun?: boolean;
8
+ /**
9
+ * Used for stubbing out the logger that we use within the installation process so it can be
10
+ * easily introspected without having to mock out `console.*`.
11
+ */
12
+ logger?: (msg: string) => void;
13
+ }
14
+ export default abstract class CodeGeneratorLanguage {
15
+ spec: Oas;
16
+ specPath: string;
17
+ identifier: string;
18
+ userAgent: string;
19
+ requiredPackages: Record<string, {
20
+ reason: string;
21
+ url: string;
22
+ }>;
23
+ constructor(spec: Oas, specPath: string, identifier: string);
24
+ abstract generator(): Promise<Record<string, string>>;
25
+ abstract installer(storage: Storage, opts?: InstallerOptions): Promise<void>;
26
+ hasRequiredPackages(): boolean;
27
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ exports.__esModule = true;
3
+ var packageInfo_1 = require("../../packageInfo");
4
+ var CodeGeneratorLanguage = /** @class */ (function () {
5
+ function CodeGeneratorLanguage(spec, specPath, identifier) {
6
+ this.spec = spec;
7
+ this.specPath = specPath;
8
+ // User agents should be contextual to the spec in question and the version of `api` that was
9
+ // used to generate the SDK. For example, this'll look like `petstore/1.0.0 (api/4.2.0)` for
10
+ // a `petstore` spec installed on api@4.2.0.
11
+ var info = spec.getDefinition().info;
12
+ this.userAgent = "".concat(identifier, "/").concat(info.version, " (").concat(packageInfo_1.PACKAGE_NAME, "/").concat(packageInfo_1.PACKAGE_VERSION, ")");
13
+ }
14
+ CodeGeneratorLanguage.prototype.hasRequiredPackages = function () {
15
+ return Boolean(Object.keys(this.requiredPackages));
16
+ };
17
+ return CodeGeneratorLanguage;
18
+ }());
19
+ exports["default"] = CodeGeneratorLanguage;