api 6.1.1 → 7.0.0-alpha.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.
Files changed (69) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +0 -12
  3. package/package.json +14 -32
  4. package/src/bin.ts +1 -1
  5. package/src/{cli/codegen → codegen}/language.ts +3 -2
  6. package/src/{cli/codegen → codegen}/languages/typescript/util.ts +1 -1
  7. package/src/{cli/codegen → codegen}/languages/typescript.ts +31 -32
  8. package/src/{cli/commands → commands}/install.ts +1 -1
  9. package/src/fetcher.ts +4 -5
  10. package/src/packageInfo.ts +1 -1
  11. package/src/{cli/storage.ts → storage.ts} +13 -9
  12. package/tsconfig.json +3 -13
  13. package/dist/bin.d.ts +0 -1
  14. package/dist/bin.js +0 -91
  15. package/dist/cache.d.ts +0 -68
  16. package/dist/cache.js +0 -198
  17. package/dist/cli/codegen/index.d.ts +0 -4
  18. package/dist/cli/codegen/index.js +0 -23
  19. package/dist/cli/codegen/language.d.ts +0 -27
  20. package/dist/cli/codegen/language.js +0 -32
  21. package/dist/cli/codegen/languages/typescript/util.d.ts +0 -20
  22. package/dist/cli/codegen/languages/typescript/util.js +0 -176
  23. package/dist/cli/codegen/languages/typescript.d.ts +0 -111
  24. package/dist/cli/codegen/languages/typescript.js +0 -821
  25. package/dist/cli/commands/index.d.ts +0 -4
  26. package/dist/cli/commands/index.js +0 -9
  27. package/dist/cli/commands/install.d.ts +0 -3
  28. package/dist/cli/commands/install.js +0 -236
  29. package/dist/cli/lib/prompt.d.ts +0 -9
  30. package/dist/cli/lib/prompt.js +0 -81
  31. package/dist/cli/logger.d.ts +0 -1
  32. package/dist/cli/logger.js +0 -16
  33. package/dist/cli/storage.d.ts +0 -105
  34. package/dist/cli/storage.js +0 -277
  35. package/dist/core/errors/fetchError.d.ts +0 -12
  36. package/dist/core/errors/fetchError.js +0 -36
  37. package/dist/core/getJSONSchemaDefaults.d.ts +0 -14
  38. package/dist/core/getJSONSchemaDefaults.js +0 -61
  39. package/dist/core/index.d.ts +0 -40
  40. package/dist/core/index.js +0 -168
  41. package/dist/core/parseResponse.d.ts +0 -6
  42. package/dist/core/parseResponse.js +0 -71
  43. package/dist/core/prepareAuth.d.ts +0 -5
  44. package/dist/core/prepareAuth.js +0 -84
  45. package/dist/core/prepareParams.d.ts +0 -21
  46. package/dist/core/prepareParams.js +0 -425
  47. package/dist/core/prepareServer.d.ts +0 -10
  48. package/dist/core/prepareServer.js +0 -47
  49. package/dist/fetcher.d.ts +0 -54
  50. package/dist/fetcher.js +0 -164
  51. package/dist/index.d.ts +0 -6
  52. package/dist/index.js +0 -259
  53. package/dist/packageInfo.d.ts +0 -2
  54. package/dist/packageInfo.js +0 -6
  55. package/src/.sink.d.ts +0 -1
  56. package/src/cache.ts +0 -193
  57. package/src/core/errors/fetchError.ts +0 -31
  58. package/src/core/getJSONSchemaDefaults.ts +0 -74
  59. package/src/core/index.ts +0 -148
  60. package/src/core/parseResponse.ts +0 -26
  61. package/src/core/prepareAuth.ts +0 -109
  62. package/src/core/prepareParams.ts +0 -415
  63. package/src/core/prepareServer.ts +0 -48
  64. package/src/index.ts +0 -203
  65. package/src/typings.d.ts +0 -2
  66. /package/src/{cli/codegen → codegen}/index.ts +0 -0
  67. /package/src/{cli/commands → commands}/index.ts +0 -0
  68. /package/src/{cli/lib → lib}/prompt.ts +0 -0
  69. /package/src/{cli/logger.ts → logger.ts} +0 -0
@@ -1,415 +0,0 @@
1
- import type { ReadStream } from 'fs';
2
- import type { Operation } from 'oas';
3
- import type { ParameterObject, SchemaObject } from 'oas/dist/rmoas.types';
4
-
5
- import fs from 'fs';
6
- import path from 'path';
7
- import stream from 'stream';
8
-
9
- import caseless from 'caseless';
10
- import DatauriParser from 'datauri/parser';
11
- import datauri from 'datauri/sync';
12
- import getStream from 'get-stream';
13
- import lodashMerge from 'lodash.merge';
14
- import removeUndefinedObjects from 'remove-undefined-objects';
15
-
16
- import getJSONSchemaDefaults from './getJSONSchemaDefaults';
17
-
18
- // These headers are normally only defined by the OpenAPI definition but we allow the user to
19
- // manually supply them in their `metadata` parameter if they wish.
20
- const specialHeaders = ['accept', 'authorization'];
21
-
22
- /**
23
- * Extract all available parameters from an operations Parameter Object into a digestable array
24
- * that we can use to apply to the request.
25
- *
26
- * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject}
27
- * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterObject}
28
- */
29
- function digestParameters(parameters: ParameterObject[]): Record<string, ParameterObject> {
30
- return parameters.reduce((prev, param) => {
31
- if ('$ref' in param || 'allOf' in param || 'anyOf' in param || 'oneOf' in param) {
32
- throw new Error("The OpenAPI document for this operation wasn't dereferenced before processing.");
33
- } else if (param.name in prev) {
34
- throw new Error(
35
- `The operation you are using has the same parameter, ${param.name}, spread across multiple entry points. We unfortunately can't handle this right now.`,
36
- );
37
- }
38
-
39
- return Object.assign(prev, { [param.name]: param });
40
- }, {});
41
- }
42
-
43
- // https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_isempty
44
- function isEmpty(obj: any) {
45
- return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
46
- }
47
-
48
- function isObject(thing: any) {
49
- if (thing instanceof stream.Readable) {
50
- return false;
51
- }
52
-
53
- return typeof thing === 'object' && thing !== null && !Array.isArray(thing);
54
- }
55
-
56
- function isPrimitive(obj: any) {
57
- return obj === null || typeof obj === 'number' || typeof obj === 'string';
58
- }
59
-
60
- function merge(src: any, target: any) {
61
- if (Array.isArray(target)) {
62
- // @todo we need to add support for merging array defaults with array body/metadata arguments
63
- return target;
64
- } else if (!isObject(target)) {
65
- return target;
66
- }
67
-
68
- return lodashMerge(src, target);
69
- }
70
-
71
- /**
72
- * Ingest a file path or readable stream into a common object that we can later use to process it
73
- * into a parameters object for making an API request.
74
- *
75
- */
76
- function processFile(
77
- paramName: string,
78
- file: string | ReadStream,
79
- ): Promise<{ base64: string; buffer: Buffer; filename: string; paramName: string }> {
80
- if (typeof file === 'string') {
81
- // In order to support relative pathed files, we need to attempt to resolve them.
82
- const resolvedFile = path.resolve(file);
83
-
84
- return new Promise((resolve, reject) => {
85
- fs.stat(resolvedFile, async err => {
86
- if (err) {
87
- if (err.code === 'ENOENT') {
88
- // It's less than ideal for us to handle files that don't exist like this but because
89
- // `file` is a string it might actually be the full text contents of the file and not
90
- // actually a path.
91
- //
92
- // We also can't really regex to see if `file` *looks*` like a path because one should be
93
- // able to pass in a relative `owlbert.png` (instead of `./owlbert.png`) and though that
94
- // doesn't *look* like a path, it is one that should still work.
95
- return resolve(undefined);
96
- }
97
-
98
- return reject(err);
99
- }
100
-
101
- const fileMetadata = await datauri(resolvedFile);
102
- const payloadFilename = encodeURIComponent(path.basename(resolvedFile));
103
-
104
- return resolve({
105
- paramName,
106
- base64: fileMetadata.content.replace(';base64', `;name=${payloadFilename};base64`),
107
- filename: payloadFilename,
108
- buffer: fileMetadata.buffer,
109
- });
110
- });
111
- });
112
- } else if (file instanceof stream.Readable) {
113
- return getStream.buffer(file).then(buffer => {
114
- const filePath = file.path as string;
115
- const parser = new DatauriParser();
116
- const base64 = parser.format(filePath, buffer).content;
117
- const payloadFilename = encodeURIComponent(path.basename(filePath));
118
-
119
- return {
120
- paramName,
121
- base64: base64.replace(';base64', `;name=${payloadFilename};base64`),
122
- filename: payloadFilename,
123
- buffer,
124
- };
125
- });
126
- }
127
-
128
- return Promise.reject(
129
- new TypeError(
130
- paramName
131
- ? `The data supplied for the \`${paramName}\` request body parameter is not a file handler that we support.`
132
- : 'The data supplied for the request body payload is not a file handler that we support.',
133
- ),
134
- );
135
- }
136
-
137
- /**
138
- * With potentially supplied body and/or metadata we need to run through them against a given API
139
- * operation to see what's what and prepare any available parameters to be used in an API request
140
- * with `@readme/oas-to-har`.
141
- *
142
- */
143
- export default async function prepareParams(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {
144
- let metadataIntersected = false;
145
- const digestedParameters = digestParameters(operation.getParameters());
146
- const jsonSchema = operation.getParametersAsJSONSchema();
147
-
148
- /**
149
- * It might be common for somebody to run `sdk.findPetsByStatus({ status: 'available' }, {})`, in
150
- * which case we want to filter out the second (metadata) parameter and treat the first parameter
151
- * as the metadata instead. If we don't do this, their supplied `status` metadata will be treated
152
- * as a body parameter, and because there's no `status` body parameter, and no supplied metadata
153
- * (because it's an empty object), the request won't send a payload.
154
- *
155
- * @see {@link https://github.com/readmeio/api/issues/449}
156
- */
157
- // eslint-disable-next-line no-param-reassign
158
- metadata = removeUndefinedObjects(metadata);
159
-
160
- if (!jsonSchema && (body !== undefined || metadata !== undefined)) {
161
- let throwNoParamsError = true;
162
-
163
- // If this operation doesn't have any parameters for us to transform to JSON Schema but they've
164
- // sent us either an `Accept` or `Authorization` header (or both) we should let them do that.
165
- // We should, however, only do this check for the `body` parameter as if they've sent this
166
- // request both `body` and `metadata` we can reject it outright as the operation won't have any
167
- // body data.
168
- if (body !== undefined) {
169
- if (typeof body === 'object' && body !== null && !Array.isArray(body)) {
170
- if (Object.keys(body).length <= 2) {
171
- const bodyParams = caseless(body);
172
-
173
- if (specialHeaders.some(header => bodyParams.has(header))) {
174
- throwNoParamsError = false;
175
- }
176
- }
177
- }
178
- }
179
-
180
- if (throwNoParamsError) {
181
- throw new Error(
182
- "You supplied metadata and/or body data for this operation but it doesn't have any documented parameters or request payloads. If you think this is an error please contact support for the API you're using.",
183
- );
184
- }
185
- }
186
-
187
- const jsonSchemaDefaults = jsonSchema ? getJSONSchemaDefaults(jsonSchema) : {};
188
-
189
- const params: {
190
- body?: any;
191
- cookie?: Record<string, string | number | boolean>;
192
- files?: Record<string, Buffer>;
193
- formData?: any;
194
- header?: Record<string, string | number | boolean>;
195
- path?: Record<string, string | number | boolean>;
196
- query?: Record<string, string | number | boolean>;
197
- server?: {
198
- selected: number;
199
- variables: Record<string, string | number>;
200
- };
201
- } = jsonSchemaDefaults;
202
-
203
- // If a body argument was supplied we need to do a bit of work to see if it's actually a body
204
- // argument or metadata because the library lets you supply either a body, metadata, or body with
205
- // metadata.
206
- if (typeof body !== 'undefined') {
207
- if (Array.isArray(body) || isPrimitive(body)) {
208
- // If the body param is an array or a primitive then we know it's absolutely a body because
209
- // metadata can only ever be undefined or an object.
210
- params.body = merge(params.body, body);
211
- } else if (typeof metadata === 'undefined') {
212
- // No metadata was explicitly provided so we need to analyze the body to determine if it's a
213
- // body or should be actually be treated as metadata.
214
- const headerParams = caseless({});
215
- Object.entries(digestedParameters).forEach(([paramName, param]) => {
216
- // Headers are sent case-insensitive so we need to make sure that we're properly
217
- // matching them when detecting what our incoming payload looks like.
218
- if (param.in === 'header') {
219
- headerParams.set(paramName, '');
220
- }
221
- });
222
-
223
- // `Accept` and `Authorization` headers can't be defined as normal parameters but we should
224
- // always allow the user to supply them if they wish.
225
- specialHeaders.forEach(header => {
226
- if (!headerParams.has(header)) {
227
- headerParams.set(header, '');
228
- }
229
- });
230
-
231
- const intersection = Object.keys(body).filter(value => {
232
- if (Object.keys(digestedParameters).includes(value)) {
233
- return true;
234
- } else if (headerParams.has(value)) {
235
- return true;
236
- }
237
-
238
- return false;
239
- }).length;
240
-
241
- if (intersection && intersection / Object.keys(body).length > 0.25) {
242
- /* eslint-disable no-param-reassign */
243
- // If more than 25% of the body intersects with the parameters that we've got on hand,
244
- // then we should treat it as a metadata object and organize into parameters.
245
- metadataIntersected = true;
246
- metadata = merge(params.body, body) as Record<string, unknown>;
247
- body = undefined;
248
- /* eslint-enable no-param-reassign */
249
- } else {
250
- // For all other cases, we should just treat the supplied body as a body.
251
- params.body = merge(params.body, body);
252
- }
253
- } else {
254
- // Body and metadata were both supplied.
255
- params.body = merge(params.body, body);
256
- }
257
- }
258
-
259
- if (!operation.hasRequestBody()) {
260
- // If this operation doesn't have any documented request body then we shouldn't be sending
261
- // anything.
262
- delete params.body;
263
- } else {
264
- if (!('body' in params)) params.body = {};
265
-
266
- // We need to retrieve the request body for this operation to search for any `binary` format
267
- // data that the user wants to send so we know what we need to prepare for the final API
268
- // request.
269
- const payloadJsonSchema = jsonSchema.find(js => js.type === 'body');
270
- if (payloadJsonSchema) {
271
- if (!params.files) params.files = {};
272
-
273
- const conversions = [];
274
-
275
- // @todo add support for `type: array`, `oneOf` and `anyOf`
276
- if (payloadJsonSchema.schema?.properties) {
277
- Object.entries(payloadJsonSchema.schema?.properties)
278
- .filter(([, schema]: [string, SchemaObject]) => schema?.format === 'binary')
279
- .filter(([prop]) => Object.keys(params.body).includes(prop))
280
- .forEach(([prop]) => {
281
- conversions.push(processFile(prop, params.body[prop]));
282
- });
283
- } else if (payloadJsonSchema.schema?.type === 'string') {
284
- if (payloadJsonSchema.schema?.format === 'binary') {
285
- conversions.push(processFile(undefined, params.body));
286
- }
287
- }
288
-
289
- await Promise.all(conversions)
290
- .then(fileMetadata => fileMetadata.filter(Boolean))
291
- .then(fm => {
292
- fm.forEach(fileMetadata => {
293
- if (!fileMetadata) {
294
- // If we don't have any metadata here it's because the file we have is likely
295
- // the full string content of the file so since we don't have any filenames to
296
- // work with we shouldn't do any additional handling to the `body` or `files`
297
- // parameters.
298
- return;
299
- }
300
-
301
- if (fileMetadata.paramName) {
302
- params.body[fileMetadata.paramName] = fileMetadata.base64;
303
- } else {
304
- params.body = fileMetadata.base64;
305
- }
306
-
307
- params.files[fileMetadata.filename] = fileMetadata.buffer;
308
- });
309
- });
310
- }
311
- }
312
-
313
- // Form data should be placed within `formData` instead of `body` for it to properly get picked
314
- // up by `fetch-har`.
315
- if (operation.isFormUrlEncoded()) {
316
- params.formData = merge(params.formData, params.body);
317
- delete params.body;
318
- }
319
-
320
- // Only spend time trying to organize metadata into parameters if we were able to digest
321
- // parameters out of the operation schema. If we couldn't digest anything, but metadata was
322
- // supplied then we wouldn't know how to send it in the request!
323
- if (typeof metadata !== 'undefined') {
324
- if (!('cookie' in params)) params.cookie = {};
325
- if (!('header' in params)) params.header = {};
326
- if (!('path' in params)) params.path = {};
327
- if (!('query' in params)) params.query = {};
328
-
329
- Object.entries(digestedParameters).forEach(([paramName, param]) => {
330
- let value: any;
331
- let metadataHeaderParam;
332
- if (typeof metadata === 'object' && !isEmpty(metadata)) {
333
- if (paramName in metadata) {
334
- value = metadata[paramName];
335
- metadataHeaderParam = paramName;
336
- } else if (param.in === 'header') {
337
- // Headers are sent case-insensitive so we need to make sure that we're properly
338
- // matching them when detecting what our incoming payload looks like.
339
- metadataHeaderParam = Object.keys(metadata).find(k => k.toLowerCase() === paramName.toLowerCase());
340
- value = metadata[metadataHeaderParam];
341
- }
342
- }
343
-
344
- if (value === undefined) {
345
- return;
346
- }
347
-
348
- /* eslint-disable no-param-reassign */
349
- switch (param.in) {
350
- case 'path':
351
- params.path[paramName] = value;
352
- delete metadata[paramName];
353
- break;
354
- case 'query':
355
- params.query[paramName] = value;
356
- delete metadata[paramName];
357
- break;
358
- case 'header':
359
- params.header[paramName.toLowerCase()] = value;
360
- delete metadata[metadataHeaderParam];
361
- break;
362
- case 'cookie':
363
- params.cookie[paramName] = value;
364
- delete metadata[paramName];
365
- break;
366
- default: // no-op
367
- }
368
- /* eslint-enable no-param-reassign */
369
-
370
- // Because a user might have sent just a metadata object, we want to make sure that we filter
371
- // out anything that they sent that is a parameter from also being sent as part of a form
372
- // data payload for `x-www-form-urlencoded` requests.
373
- if (metadataIntersected && operation.isFormUrlEncoded()) {
374
- if (paramName in params.formData) {
375
- delete params.formData[paramName];
376
- }
377
- }
378
- });
379
-
380
- // If there's any leftover metadata that hasn't been moved into form data for this request we
381
- // need to move it or else it'll get tossed.
382
- if (!isEmpty(metadata)) {
383
- if (typeof metadata === 'object') {
384
- // If the user supplied an `accept` or `authorization` header themselves we should allow it
385
- // through. Normally these headers are automatically handled by `@readme/oas-to-har` but in
386
- // the event that maybe the user wants to return XML for an API that normally returns JSON
387
- // or specify a custom auth header (maybe we can't handle their auth case right) this is the
388
- // only way with this library that they can do that.
389
- specialHeaders.forEach(headerName => {
390
- const headerParam = Object.keys(metadata).find(m => m.toLowerCase() === headerName);
391
- if (headerParam) {
392
- params.header[headerName] = metadata[headerParam] as string;
393
- // eslint-disable-next-line no-param-reassign
394
- delete metadata[headerParam];
395
- }
396
- });
397
- }
398
-
399
- if (operation.isFormUrlEncoded()) {
400
- params.formData = merge(params.formData, metadata);
401
- } else {
402
- // Any other remaining unused metadata will be unused because we don't know where to place
403
- // it in the request.
404
- }
405
- }
406
- }
407
-
408
- ['body', 'cookie', 'files', 'formData', 'header', 'path', 'query'].forEach((type: keyof typeof params) => {
409
- if (type in params && isEmpty(params[type])) {
410
- delete params[type];
411
- }
412
- });
413
-
414
- return params;
415
- }
@@ -1,48 +0,0 @@
1
- import type Oas from 'oas';
2
-
3
- function stripTrailingSlash(url: string) {
4
- if (url[url.length - 1] === '/') {
5
- return url.slice(0, -1);
6
- }
7
-
8
- return url;
9
- }
10
-
11
- /**
12
- * With an SDK server config and an instance of OAS we should extract and prepare the server and
13
- * any server variables to be supplied to `@readme/oas-to-har`.
14
- *
15
- */
16
- export default function prepareServer(spec: Oas, url: string, variables: Record<string, string | number> = {}) {
17
- let serverIdx;
18
- const sanitizedUrl = stripTrailingSlash(url);
19
- (spec.api.servers || []).forEach((server, i) => {
20
- if (server.url === sanitizedUrl) {
21
- serverIdx = i;
22
- }
23
- });
24
-
25
- // If we were able to find the passed in server in the OAS servers, we should use that! If we
26
- // couldn't and server variables were passed in we should try our best to handle that, otherwise
27
- // we should ignore the passed in server and use whever the default from the OAS is.
28
- if (serverIdx) {
29
- return {
30
- selected: serverIdx,
31
- variables,
32
- };
33
- } else if (Object.keys(variables).length) {
34
- // @todo we should run `oas.replaceUrl(url)` and pass that unto `@readme/oas-to-har`
35
- } else {
36
- const server = spec.splitVariables(url);
37
- if (server) {
38
- return {
39
- selected: server.selected,
40
- variables: server.variables,
41
- };
42
- }
43
-
44
- // @todo we should pass `url` directly into `@readme/oas-to-har` as the base URL
45
- }
46
-
47
- return false;
48
- }
package/src/index.ts DELETED
@@ -1,203 +0,0 @@
1
- import type { ConfigOptions } from './core';
2
- import type { Operation } from 'oas';
3
- import type { OASDocument } from 'oas/dist/rmoas.types';
4
-
5
- import Oas from 'oas';
6
-
7
- import Cache from './cache';
8
- import APICore from './core';
9
- import { PACKAGE_NAME, PACKAGE_VERSION } from './packageInfo';
10
-
11
- interface SDKOptions {
12
- cacheDir?: string;
13
- }
14
-
15
- class Sdk {
16
- uri: string | OASDocument;
17
-
18
- userAgent: string;
19
-
20
- cacheDir: string | false;
21
-
22
- constructor(uri: string | OASDocument, opts: SDKOptions = {}) {
23
- this.uri = uri;
24
- this.userAgent = `${PACKAGE_NAME} (node)/${PACKAGE_VERSION}`;
25
-
26
- this.cacheDir = opts.cacheDir ? opts.cacheDir : false;
27
- }
28
-
29
- load() {
30
- const cache = new Cache(this.uri, this.cacheDir);
31
- const userAgent = this.userAgent;
32
-
33
- const core = new APICore();
34
- core.setUserAgent(userAgent);
35
-
36
- let isLoaded = false;
37
- let isCached = cache.isCached();
38
- let sdk = {};
39
-
40
- /**
41
- * Create dynamic accessors for every operation with a defined operation ID. If an operation
42
- * does not have an operation ID it can be accessed by its `.method('/path')` accessor instead.
43
- *
44
- */
45
- function loadOperations(spec: Oas) {
46
- return Object.entries(spec.getPaths())
47
- .map(([, operations]) => Object.values(operations))
48
- .reduce((prev, next) => prev.concat(next), [])
49
- .reduce((prev, next) => {
50
- // `getOperationId()` creates dynamic operation IDs when one isn't available but we need
51
- // to know here if we actually have one present or not. The `camelCase` option here also
52
- // cleans up any `operationId` that we might have into something that can be used as a
53
- // valid JS method.
54
- const originalOperationId = next.getOperationId();
55
- const operationId = next.getOperationId({ camelCase: true });
56
-
57
- const op = {
58
- [operationId]: ((operation: Operation, ...args: unknown[]) => {
59
- return core.fetchOperation(operation, ...args);
60
- }).bind(null, next),
61
- };
62
-
63
- if (operationId !== originalOperationId) {
64
- // If we cleaned up their operation ID into a friendly method accessor (`findPetById`
65
- // versus `find pet by id`) we should still let them use the non-friendly version if
66
- // they want.
67
- //
68
- // This work is to maintain backwards compatibility with `api@4` and does not exist
69
- // within our code generated SDKs -- those only allow the cleaner camelCase
70
- // `operationId` to be used.
71
- op[originalOperationId] = ((operation: Operation, ...args: unknown[]) => {
72
- return core.fetchOperation(operation, ...args);
73
- }).bind(null, next);
74
- }
75
-
76
- return Object.assign(prev, op);
77
- }, {});
78
- }
79
-
80
- async function loadFromCache() {
81
- let cachedSpec;
82
- if (isCached) {
83
- cachedSpec = await cache.get();
84
- } else {
85
- cachedSpec = await cache.load();
86
- isCached = true;
87
- }
88
-
89
- const spec = new Oas(cachedSpec);
90
-
91
- core.setSpec(spec);
92
-
93
- sdk = Object.assign(sdk, loadOperations(spec));
94
- isLoaded = true;
95
- }
96
-
97
- const sdkProxy = {
98
- // @give this a better type than any
99
- get(target: any, method: string) {
100
- // Since auth returns a self-proxy, we **do not** want it to fall through into the async
101
- // function below as when that'll happen, instead of returning a self-proxy, it'll end up
102
- // returning a Promise. When that happens, chaining `sdk.auth().operationId()` will fail.
103
- if (['auth', 'config'].includes(method)) {
104
- // @todo split this up so we have better types for `auth` and `config`
105
- return function authAndConfigHandler(...args: any) {
106
- return target[method].apply(this, args);
107
- };
108
- }
109
-
110
- return async function accessorHandler(...args: unknown[]) {
111
- if (!(method in target)) {
112
- // If this method doesn't exist on the proxy, have we loaded the SDK? If we have, then
113
- // this method isn't valid.
114
- if (isLoaded) {
115
- throw new Error(`Sorry, \`${method}\` does not appear to be a valid operation on this API.`);
116
- }
117
-
118
- await loadFromCache();
119
-
120
- // If after loading the SDK and this method still doesn't exist, then it's not real!
121
- if (!(method in sdk)) {
122
- throw new Error(`Sorry, \`${method}\` does not appear to be a valid operation on this API.`);
123
- }
124
-
125
- // @todo give sdk a better type
126
- return (sdk as any)[method].apply(this, args);
127
- }
128
-
129
- return target[method].apply(this, args);
130
- };
131
- },
132
- };
133
-
134
- sdk = {
135
- /**
136
- * If the API you're using requires authentication you can supply the required credentials
137
- * through this method and the library will magically determine how they should be used
138
- * within your API request.
139
- *
140
- * With the exception of OpenID and MutualTLS, it supports all forms of authentication
141
- * supported by the OpenAPI specification.
142
- *
143
- * @example <caption>HTTP Basic auth</caption>
144
- * sdk.auth('username', 'password');
145
- *
146
- * @example <caption>Bearer tokens (HTTP or OAuth 2)</caption>
147
- * sdk.auth('myBearerToken');
148
- *
149
- * @example <caption>API Keys</caption>
150
- * sdk.auth('myApiKey');
151
- *
152
- * @see {@link https://spec.openapis.org/oas/v3.0.3#fixed-fields-22}
153
- * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-22}
154
- * @param values Your auth credentials for the API. Can specify up to two strings or numbers.
155
- */
156
- auth: (...values: string[] | number[]) => {
157
- core.setAuth(...values);
158
- },
159
-
160
- /**
161
- * Optionally configure various options that the SDK allows.
162
- *
163
- * @param config Object of supported SDK options and toggles.
164
- * @param config.timeout Override the default `fetch` request timeout of 30 seconds (30000ms).
165
- */
166
- config: (config: ConfigOptions) => {
167
- core.setConfig(config);
168
- },
169
-
170
- /**
171
- * If the API you're using offers alternate server URLs, and server variables, you can tell
172
- * the SDK which one to use with this method. To use it you can supply either one of the
173
- * server URLs that are contained within the OpenAPI definition (along with any server
174
- * variables), or you can pass it a fully qualified URL to use (that may or may not exist
175
- * within the OpenAPI definition).
176
- *
177
- * @example <caption>Server URL with server variables</caption>
178
- * sdk.server('https://{region}.api.example.com/{basePath}', {
179
- * name: 'eu',
180
- * basePath: 'v14',
181
- * });
182
- *
183
- * @example <caption>Fully qualified server URL</caption>
184
- * sdk.server('https://eu.api.example.com/v14');
185
- *
186
- * @param url Server URL
187
- * @param variables An object of variables to replace into the server URL.
188
- */
189
- server: (url: string, variables = {}) => {
190
- core.setServer(url, variables);
191
- },
192
- };
193
-
194
- return new Proxy(sdk, sdkProxy);
195
- }
196
- }
197
-
198
- // Why `export` vs `export default`? If we leave this as `export` then TS will transpile it into
199
- // a `module.exports` export so that when folks load this they don't need to load it as
200
- // `require('api').default`.
201
- export = (uri: string | OASDocument, opts: SDKOptions = {}) => {
202
- return new Sdk(uri, opts).load();
203
- };
package/src/typings.d.ts DELETED
@@ -1,2 +0,0 @@
1
- // These libraries don't have any types so we need to let TS know so we can use them.
2
- declare module 'fetch-har';
File without changes
File without changes
File without changes
File without changes