@readme/api-core 7.0.0-alpha.6 → 7.0.0-beta.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/dist/index.js CHANGED
@@ -1,440 +1,17 @@
1
1
  import {
2
2
  FetchError
3
3
  } from "./chunk-L7DN22AA.js";
4
+ import {
5
+ parseResponse,
6
+ prepareAuth,
7
+ prepareParams,
8
+ prepareServer
9
+ } from "./chunk-PWY7T36C.js";
4
10
 
5
11
  // src/index.ts
6
12
  import oasToHar from "@readme/oas-to-har";
7
13
  import fetchHar from "fetch-har";
8
14
  import Oas from "oas";
9
-
10
- // src/lib/getJSONSchemaDefaults.ts
11
- import traverse from "json-schema-traverse";
12
- function getJSONSchemaDefaults(jsonSchemas) {
13
- return jsonSchemas.map(({ type: payloadType, schema: jsonSchema }) => {
14
- const defaults = {};
15
- traverse(
16
- jsonSchema,
17
- (schema, pointer, rootSchema, parentPointer, parentKeyword, parentSchema, indexProperty) => {
18
- if (!pointer.startsWith("/properties/")) {
19
- return;
20
- }
21
- if (Array.isArray(parentSchema?.required) && parentSchema?.required.includes(String(indexProperty))) {
22
- if (schema.type === "object" && indexProperty) {
23
- defaults[indexProperty] = {};
24
- }
25
- let destination = defaults;
26
- if (parentPointer) {
27
- parentPointer.replace(/\/properties/g, "").split("/").forEach((subSchema) => {
28
- if (subSchema === "") {
29
- return;
30
- }
31
- destination = destination?.[subSchema] || {};
32
- });
33
- }
34
- if (schema.default !== void 0) {
35
- if (indexProperty !== void 0) {
36
- destination[indexProperty] = schema.default;
37
- }
38
- }
39
- }
40
- }
41
- );
42
- if (!Object.keys(defaults).length) {
43
- return {};
44
- }
45
- return {
46
- // @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?
47
- [payloadType]: defaults
48
- };
49
- }).reduce((prev, next) => Object.assign(prev, next));
50
- }
51
-
52
- // src/lib/parseResponse.ts
53
- import { matchesMimeType } from "oas/utils";
54
- async function parseResponse(response) {
55
- const contentType = response.headers.get("Content-Type");
56
- const isJSON = contentType && (matchesMimeType.json(contentType) || matchesMimeType.wildcard(contentType));
57
- const responseBody = await response.text();
58
- let data = responseBody;
59
- if (isJSON) {
60
- try {
61
- data = JSON.parse(responseBody);
62
- } catch (e) {
63
- }
64
- }
65
- return {
66
- data,
67
- status: response.status,
68
- headers: response.headers,
69
- res: response
70
- };
71
- }
72
-
73
- // src/lib/prepareAuth.ts
74
- function prepareAuth(authKey, operation) {
75
- if (authKey.length === 0) {
76
- return {};
77
- }
78
- const preparedAuth = {};
79
- const security = operation.getSecurity();
80
- if (security.length === 0) {
81
- return {};
82
- }
83
- if (security.every((s) => Object.keys(s).length > 1)) {
84
- throw new Error(
85
- "Sorry, this operation currently requires multiple forms of authentication which this library doesn't yet support."
86
- );
87
- }
88
- const usableSecurity = security.map((s) => {
89
- return Object.keys(s).length === 1 ? s : false;
90
- }).filter(Boolean);
91
- const usableSecuritySchemes = usableSecurity.map((s) => Object.keys(s)).reduce((prev, next) => prev.concat(next), []);
92
- const preparedSecurity = operation.prepareSecurity();
93
- if (authKey.length >= 2) {
94
- if (!("Basic" in preparedSecurity)) {
95
- throw new Error("Multiple auth tokens were supplied for this endpoint but only a single token is needed.");
96
- }
97
- const schemes2 = preparedSecurity.Basic.filter((s) => usableSecuritySchemes.includes(s._key));
98
- if (!schemes2.length) {
99
- throw new Error(
100
- "Credentials for Basic Authentication were supplied but this operation requires another form of auth in that case, which this library does not yet support. This operation does, however, allow supplying a single auth token."
101
- );
102
- }
103
- const scheme2 = schemes2.shift();
104
- preparedAuth[scheme2._key] = {
105
- user: authKey[0],
106
- pass: authKey.length === 2 ? authKey[1] : ""
107
- };
108
- return preparedAuth;
109
- }
110
- const usableScheme = usableSecuritySchemes[0];
111
- const schemes = Object.entries(preparedSecurity).map(([, ps]) => ps.filter((s) => usableScheme === s._key)).reduce((prev, next) => prev.concat(next), []);
112
- const scheme = schemes.shift();
113
- switch (scheme.type) {
114
- case "http":
115
- if (scheme.scheme === "basic") {
116
- preparedAuth[scheme._key] = {
117
- user: authKey[0],
118
- pass: authKey.length === 2 ? authKey[1] : ""
119
- };
120
- } else if (scheme.scheme === "bearer") {
121
- preparedAuth[scheme._key] = authKey[0];
122
- }
123
- break;
124
- case "oauth2":
125
- preparedAuth[scheme._key] = authKey[0];
126
- break;
127
- case "apiKey":
128
- if (scheme.in === "query" || scheme.in === "header" || scheme.in === "cookie") {
129
- preparedAuth[scheme._key] = authKey[0];
130
- }
131
- break;
132
- default:
133
- throw new Error(
134
- `Sorry, this API currently uses a security scheme, ${scheme.type}, which this library doesn't yet support.`
135
- );
136
- }
137
- return preparedAuth;
138
- }
139
-
140
- // src/lib/prepareParams.ts
141
- import fs from "fs";
142
- import path from "path";
143
- import stream from "stream";
144
- import caseless from "caseless";
145
- import DatauriParser from "datauri/parser.js";
146
- import datauri from "datauri/sync.js";
147
- import getStream from "get-stream";
148
- import lodashMerge from "lodash.merge";
149
- import removeUndefinedObjects from "remove-undefined-objects";
150
- var specialHeaders = ["accept", "authorization"];
151
- function digestParameters(parameters) {
152
- return parameters.reduce((prev, param) => {
153
- if ("$ref" in param || "allOf" in param || "anyOf" in param || "oneOf" in param) {
154
- throw new Error("The OpenAPI document for this operation wasn't dereferenced before processing.");
155
- } else if (param.name in prev) {
156
- throw new Error(
157
- `The operation you are using has the same parameter, ${param.name}, spread across multiple entry points. We unfortunately can't handle this right now.`
158
- );
159
- }
160
- return Object.assign(prev, { [param.name]: param });
161
- }, {});
162
- }
163
- function isEmpty(obj) {
164
- return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
165
- }
166
- function isObject(thing) {
167
- if (thing instanceof stream.Readable) {
168
- return false;
169
- }
170
- return typeof thing === "object" && thing !== null && !Array.isArray(thing);
171
- }
172
- function isPrimitive(obj) {
173
- return obj === null || typeof obj === "number" || typeof obj === "string";
174
- }
175
- function merge(src, target) {
176
- if (Array.isArray(target)) {
177
- return target;
178
- } else if (!isObject(target)) {
179
- return target;
180
- }
181
- return lodashMerge(src, target);
182
- }
183
- function processFile(paramName, file) {
184
- if (typeof file === "string") {
185
- const resolvedFile = path.resolve(file);
186
- return new Promise((resolve, reject) => {
187
- fs.stat(resolvedFile, async (err) => {
188
- if (err) {
189
- if (err.code === "ENOENT") {
190
- return resolve(void 0);
191
- }
192
- return reject(err);
193
- }
194
- const fileMetadata = await datauri(resolvedFile);
195
- const payloadFilename = encodeURIComponent(path.basename(resolvedFile));
196
- return resolve({
197
- paramName,
198
- base64: fileMetadata?.content?.replace(";base64", `;name=${payloadFilename};base64`),
199
- filename: payloadFilename,
200
- buffer: fileMetadata.buffer
201
- });
202
- });
203
- });
204
- } else if (file instanceof stream.Readable) {
205
- return getStream.buffer(file).then((buffer) => {
206
- const filePath = file.path;
207
- const parser = new DatauriParser();
208
- const base64 = parser.format(filePath, buffer).content;
209
- const payloadFilename = encodeURIComponent(path.basename(filePath));
210
- return {
211
- paramName,
212
- base64: base64?.replace(";base64", `;name=${payloadFilename};base64`),
213
- filename: payloadFilename,
214
- buffer
215
- };
216
- });
217
- }
218
- return Promise.reject(
219
- new TypeError(
220
- paramName ? `The data supplied for the \`${paramName}\` request body parameter is not a file handler that we support.` : "The data supplied for the request body payload is not a file handler that we support."
221
- )
222
- );
223
- }
224
- async function prepareParams(operation, body, metadata) {
225
- let metadataIntersected = false;
226
- const digestedParameters = digestParameters(operation.getParameters());
227
- const jsonSchema = operation.getParametersAsJSONSchema();
228
- metadata = removeUndefinedObjects(metadata);
229
- if (!jsonSchema && (body !== void 0 || metadata !== void 0)) {
230
- let throwNoParamsError = true;
231
- if (body !== void 0) {
232
- if (typeof body === "object" && body !== null && !Array.isArray(body)) {
233
- if (Object.keys(body).length <= 2) {
234
- const bodyParams = caseless(body);
235
- if (specialHeaders.some((header) => bodyParams.has(header))) {
236
- throwNoParamsError = false;
237
- }
238
- }
239
- }
240
- }
241
- if (throwNoParamsError) {
242
- throw new Error(
243
- "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."
244
- );
245
- }
246
- }
247
- const jsonSchemaDefaults = jsonSchema ? getJSONSchemaDefaults(jsonSchema) : {};
248
- const params = jsonSchemaDefaults;
249
- if (typeof body !== "undefined") {
250
- if (Array.isArray(body) || isPrimitive(body)) {
251
- params.body = merge(params.body, body);
252
- } else if (typeof metadata === "undefined") {
253
- const headerParams = caseless({});
254
- Object.entries(digestedParameters).forEach(([paramName, param]) => {
255
- if (param.in === "header") {
256
- headerParams.set(paramName, "");
257
- }
258
- });
259
- specialHeaders.forEach((header) => {
260
- if (!headerParams.has(header)) {
261
- headerParams.set(header, "");
262
- }
263
- });
264
- const intersection = Object.keys(body).filter((value) => {
265
- if (Object.keys(digestedParameters).includes(value)) {
266
- return true;
267
- } else if (headerParams.has(value)) {
268
- return true;
269
- }
270
- return false;
271
- }).length;
272
- if (intersection && intersection / Object.keys(body).length > 0.25) {
273
- metadataIntersected = true;
274
- metadata = merge(params.body, body);
275
- body = void 0;
276
- } else {
277
- params.body = merge(params.body, body);
278
- }
279
- } else {
280
- params.body = merge(params.body, body);
281
- }
282
- }
283
- if (!operation.hasRequestBody()) {
284
- delete params.body;
285
- } else {
286
- if (!("body" in params))
287
- params.body = {};
288
- const payloadJsonSchema = jsonSchema.find((js) => js.type === "body");
289
- if (payloadJsonSchema) {
290
- if (!params.files)
291
- params.files = {};
292
- const conversions = [];
293
- if (payloadJsonSchema.schema?.properties) {
294
- Object.entries(payloadJsonSchema.schema?.properties).filter(([, schema]) => schema?.format === "binary").filter(([prop]) => Object.keys(params.body).includes(prop)).forEach(([prop]) => {
295
- conversions.push(processFile(prop, params.body[prop]));
296
- });
297
- } else if (payloadJsonSchema.schema?.type === "string") {
298
- if (payloadJsonSchema.schema?.format === "binary") {
299
- conversions.push(processFile(void 0, params.body));
300
- }
301
- }
302
- await Promise.all(conversions).then((fileMetadata) => fileMetadata.filter(Boolean)).then((fm) => {
303
- fm.forEach((fileMetadata) => {
304
- if (!fileMetadata) {
305
- return;
306
- }
307
- if (fileMetadata.paramName) {
308
- params.body[fileMetadata.paramName] = fileMetadata.base64;
309
- } else {
310
- params.body = fileMetadata.base64;
311
- }
312
- if (fileMetadata.buffer && params?.files) {
313
- params.files[fileMetadata.filename] = fileMetadata.buffer;
314
- }
315
- });
316
- });
317
- }
318
- }
319
- if (operation.isFormUrlEncoded()) {
320
- params.formData = merge(params.formData, params.body);
321
- delete params.body;
322
- }
323
- if (typeof metadata !== "undefined") {
324
- if (!("cookie" in params))
325
- params.cookie = {};
326
- if (!("header" in params))
327
- params.header = {};
328
- if (!("path" in params))
329
- params.path = {};
330
- if (!("query" in params))
331
- params.query = {};
332
- Object.entries(digestedParameters).forEach(([paramName, param]) => {
333
- let value;
334
- let metadataHeaderParam;
335
- if (typeof metadata === "object" && !isEmpty(metadata)) {
336
- if (paramName in metadata) {
337
- value = metadata[paramName];
338
- metadataHeaderParam = paramName;
339
- } else if (param.in === "header") {
340
- metadataHeaderParam = Object.keys(metadata).find((k) => k.toLowerCase() === paramName.toLowerCase()) || "";
341
- value = metadata[metadataHeaderParam];
342
- }
343
- }
344
- if (value === void 0) {
345
- return;
346
- }
347
- switch (param.in) {
348
- case "path":
349
- params.path[paramName] = value;
350
- if (metadata?.[paramName])
351
- delete metadata[paramName];
352
- break;
353
- case "query":
354
- params.query[paramName] = value;
355
- if (metadata?.[paramName])
356
- delete metadata[paramName];
357
- break;
358
- case "header":
359
- params.header[paramName.toLowerCase()] = value;
360
- if (metadataHeaderParam && metadata?.[metadataHeaderParam])
361
- delete metadata[metadataHeaderParam];
362
- break;
363
- case "cookie":
364
- params.cookie[paramName] = value;
365
- if (metadata?.[paramName])
366
- delete metadata[paramName];
367
- break;
368
- default:
369
- }
370
- if (metadataIntersected && operation.isFormUrlEncoded()) {
371
- if (paramName in params.formData) {
372
- delete params.formData[paramName];
373
- }
374
- }
375
- });
376
- if (!isEmpty(metadata)) {
377
- if (typeof metadata === "object") {
378
- specialHeaders.forEach((headerName) => {
379
- const headerParam = Object.keys(metadata || {}).find((m) => m.toLowerCase() === headerName);
380
- if (headerParam) {
381
- if (typeof metadata === "object") {
382
- if (typeof params.header === "object") {
383
- params.header[headerName] = metadata[headerParam];
384
- }
385
- delete metadata[headerParam];
386
- }
387
- }
388
- });
389
- }
390
- if (operation.isFormUrlEncoded()) {
391
- params.formData = merge(params.formData, metadata);
392
- } else {
393
- }
394
- }
395
- }
396
- ["body", "cookie", "files", "formData", "header", "path", "query"].forEach((type) => {
397
- if (type in params && isEmpty(params[type])) {
398
- delete params[type];
399
- }
400
- });
401
- return params;
402
- }
403
-
404
- // src/lib/prepareServer.ts
405
- function stripTrailingSlash(url) {
406
- if (url[url.length - 1] === "/") {
407
- return url.slice(0, -1);
408
- }
409
- return url;
410
- }
411
- function prepareServer(spec, url, variables = {}) {
412
- let serverIdx;
413
- const sanitizedUrl = stripTrailingSlash(url);
414
- (spec.api.servers || []).forEach((server, i) => {
415
- if (server.url === sanitizedUrl) {
416
- serverIdx = i;
417
- }
418
- });
419
- if (serverIdx) {
420
- return {
421
- selected: serverIdx,
422
- variables
423
- };
424
- } else if (Object.keys(variables).length) {
425
- } else {
426
- const server = spec.splitVariables(url);
427
- if (server) {
428
- return {
429
- selected: server.selected,
430
- variables: server.variables
431
- };
432
- }
433
- }
434
- return false;
435
- }
436
-
437
- // src/index.ts
438
15
  var APICore = class {
439
16
  spec;
440
17
  auth = [];
@@ -466,8 +43,8 @@ var APICore = class {
466
43
  this.server = { url, variables };
467
44
  return this;
468
45
  }
469
- async fetch(path2, method, body, metadata) {
470
- const operation = this.spec.operation(path2, method);
46
+ async fetch(path, method, body, metadata) {
47
+ const operation = this.spec.operation(path, method);
471
48
  return this.fetchOperation(operation, body, metadata);
472
49
  }
473
50
  async fetchOperation(operation, body, metadata) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/lib/getJSONSchemaDefaults.ts","../src/lib/parseResponse.ts","../src/lib/prepareAuth.ts","../src/lib/prepareParams.ts","../src/lib/prepareServer.ts"],"sourcesContent":["import type { Har } from 'har-format';\nimport type Operation from 'oas/operation';\nimport type { HttpMethods, OASDocument } from 'oas/rmoas.types';\n\nimport oasToHar from '@readme/oas-to-har';\nimport fetchHar from 'fetch-har';\nimport Oas from 'oas';\n\nimport FetchError from './errors/fetchError.js';\nimport { parseResponse, prepareAuth, prepareParams, prepareServer } from './lib/index.js';\n\nexport interface ConfigOptions {\n /**\n * Override the default `fetch` request timeout of 30 seconds. This number should be represented\n * in milliseconds.\n */\n timeout?: number;\n}\n\nexport interface FetchResponse<HTTPStatus, Data> {\n data: Data;\n headers: Headers;\n res: Response;\n status: HTTPStatus;\n}\n\n// https://stackoverflow.com/a/39495173\ntype Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N\n ? Acc[number]\n : Enumerate<N, [...Acc, Acc['length']]>;\n\nexport type HTTPMethodRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;\n\nexport default class APICore {\n spec!: Oas;\n\n private auth: (number | string)[] = [];\n\n private server:\n | false\n | {\n url: string;\n variables?: Record<string, string | number>;\n } = false;\n\n private config: ConfigOptions = {};\n\n private userAgent!: string;\n\n constructor(definition?: Record<string, unknown> | OASDocument, userAgent?: string) {\n if (definition) this.spec = Oas.init(definition);\n if (userAgent) this.userAgent = userAgent;\n }\n\n setSpec(spec: Oas) {\n this.spec = spec;\n }\n\n setConfig(config: ConfigOptions) {\n this.config = config;\n return this;\n }\n\n setUserAgent(userAgent: string) {\n this.userAgent = userAgent;\n return this;\n }\n\n setAuth(...values: string[] | number[]) {\n this.auth = values;\n return this;\n }\n\n setServer(url: string, variables: Record<string, string | number> = {}) {\n this.server = { url, variables };\n return this;\n }\n\n async fetch<HTTPStatus extends number = number>(\n path: string,\n method: HttpMethods,\n body?: unknown,\n metadata?: Record<string, unknown>,\n ) {\n const operation = this.spec.operation(path, method);\n\n return this.fetchOperation<HTTPStatus>(operation, body, metadata);\n }\n\n async fetchOperation<HTTPStatus extends number = number>(\n operation: Operation,\n body?: unknown,\n metadata?: Record<string, unknown>,\n ) {\n return prepareParams(operation, body, metadata).then(params => {\n const data = { ...params };\n\n // If `sdk.server()` has been issued data then we need to do some extra work to figure out\n // how to use that supplied server, and also handle any server variables that were sent\n // alongside it.\n if (this.server) {\n const preparedServer = prepareServer(this.spec, this.server.url, this.server.variables);\n if (preparedServer) {\n data.server = preparedServer;\n }\n }\n\n // @ts-expect-error `this.auth` typing is off. FIXME\n const har = oasToHar(this.spec, operation, data, prepareAuth(this.auth, operation));\n\n let timeoutSignal: NodeJS.Timeout;\n const init: RequestInit = {};\n if (this.config.timeout) {\n const controller = new AbortController();\n timeoutSignal = setTimeout(() => controller.abort(), this.config.timeout);\n init.signal = controller.signal;\n }\n\n return fetchHar(har as Har, {\n files: data.files || {},\n init,\n userAgent: this.userAgent,\n })\n .then(async (res: Response) => {\n const parsed = await parseResponse<HTTPStatus>(res);\n\n if (res.status >= 400 && res.status <= 599) {\n throw new FetchError<typeof parsed.status, typeof parsed.data>(\n parsed.status,\n parsed.data,\n parsed.headers,\n parsed.res,\n );\n }\n\n return parsed;\n })\n .finally(() => {\n if (this.config.timeout) {\n clearTimeout(timeoutSignal);\n }\n });\n });\n }\n}\n","import type { SchemaWrapper } from 'oas/operation/get-parameters-as-json-schema';\nimport type { SchemaObject } from 'oas/rmoas.types';\n\nimport traverse from 'json-schema-traverse';\n\n/**\n * Run through a JSON Schema object and compose up an object containing default data for any schema\n * property that is required and also has a defined default.\n *\n * Code partially adapted from the `json-schema-default` package but modified to only return\n * defaults of required properties.\n *\n * @todo This is a good candidate to be moved into a core `oas` library method.\n * @see {@link https://github.com/mdornseif/json-schema-default}\n */\nexport default function getJSONSchemaDefaults(jsonSchemas: SchemaWrapper[]) {\n return jsonSchemas\n .map(({ type: payloadType, schema: jsonSchema }) => {\n const defaults: Record<string, unknown> = {};\n traverse(\n jsonSchema,\n (\n schema: SchemaObject,\n pointer: string,\n rootSchema: SchemaObject,\n parentPointer?: string,\n parentKeyword?: string,\n parentSchema?: SchemaObject,\n indexProperty?: string | number,\n ) => {\n if (!pointer.startsWith('/properties/')) {\n return;\n }\n\n if (Array.isArray(parentSchema?.required) && parentSchema?.required.includes(String(indexProperty))) {\n if (schema.type === 'object' && indexProperty) {\n defaults[indexProperty] = {};\n }\n\n let destination = defaults;\n if (parentPointer) {\n // To map nested objects correct we need to pick apart the parent pointer.\n parentPointer\n .replace(/\\/properties/g, '')\n .split('/')\n .forEach((subSchema: string) => {\n if (subSchema === '') {\n return;\n }\n\n destination = (destination?.[subSchema] as Record<string, unknown>) || {};\n });\n }\n\n if (schema.default !== undefined) {\n if (indexProperty !== undefined) {\n destination[indexProperty] = schema.default;\n }\n }\n }\n },\n );\n\n if (!Object.keys(defaults).length) {\n return {};\n }\n\n return {\n // @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?\n [payloadType]: defaults,\n };\n })\n .reduce((prev, next) => Object.assign(prev, next));\n}\n","import { matchesMimeType } from 'oas/utils';\n\nexport default async function parseResponse<HTTPStatus extends number = number>(response: Response) {\n const contentType = response.headers.get('Content-Type');\n const isJSON = contentType && (matchesMimeType.json(contentType) || matchesMimeType.wildcard(contentType));\n\n const responseBody = await response.text();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let data: any = responseBody;\n if (isJSON) {\n try {\n data = JSON.parse(responseBody);\n } catch (e) {\n // If our JSON parsing failed then we can just return plaintext instead.\n }\n }\n\n return {\n data,\n status: response.status as HTTPStatus,\n headers: response.headers,\n res: response,\n };\n}\n","/* eslint-disable no-underscore-dangle */\nimport type Operation from 'oas/operation';\nimport type { KeyedSecuritySchemeObject } from 'oas/rmoas.types';\n\nexport default function prepareAuth(authKey: (number | string)[], operation: Operation) {\n if (authKey.length === 0) {\n return {};\n }\n\n const preparedAuth: Record<\n string,\n | string\n | number\n | {\n pass: string | number;\n user: string | number;\n }\n > = {};\n\n const security = operation.getSecurity();\n if (security.length === 0) {\n // If there's no auth configured on this operation, don't prepare anything (even if it was\n // supplied by the user).\n return {};\n }\n\n // Does this operation require multiple forms of auth?\n if (security.every(s => Object.keys(s).length > 1)) {\n throw new Error(\n \"Sorry, this operation currently requires multiple forms of authentication which this library doesn't yet support.\",\n );\n }\n\n // Since we can only handle single auth security configurations, let's pull those out. This code\n // is a bit opaque but `security` here may look like `[{ basic: [] }, { oauth2: [], basic: []}]`\n // and are filtering it down to only single-auth requirements of `[{ basic: [] }]`.\n const usableSecurity = security\n .map(s => {\n return Object.keys(s).length === 1 ? s : false;\n })\n .filter(Boolean);\n\n const usableSecuritySchemes = usableSecurity.map(s => Object.keys(s)).reduce((prev, next) => prev.concat(next), []);\n const preparedSecurity = operation.prepareSecurity();\n\n // If we have two auth tokens present let's look for Basic Auth in their configuration.\n if (authKey.length >= 2) {\n // If this operation doesn't support HTTP Basic auth but we have two tokens, that's a paddlin.\n if (!('Basic' in preparedSecurity)) {\n throw new Error('Multiple auth tokens were supplied for this endpoint but only a single token is needed.');\n }\n\n // If we have two auth keys for Basic Auth but Basic isn't a usable security scheme (maybe it's\n // part of an AND or auth configuration -- which we don't support) then we need to error out.\n const schemes = preparedSecurity.Basic.filter(s => usableSecuritySchemes.includes(s._key));\n if (!schemes.length) {\n throw new Error(\n 'Credentials for Basic Authentication were supplied but this operation requires another form of auth in that case, which this library does not yet support. This operation does, however, allow supplying a single auth token.',\n );\n }\n\n const scheme = schemes.shift() as KeyedSecuritySchemeObject;\n preparedAuth[scheme._key] = {\n user: authKey[0],\n pass: authKey.length === 2 ? authKey[1] : '',\n };\n\n return preparedAuth;\n }\n\n // If we know we don't need to use HTTP Basic auth because we have a username+password then we\n // can pick the first usable security scheme available and try to use that. This might not always\n // be the auth scheme that the user wants, but we don't have any other way for the user to tell\n // us what they want with the current `sdk.auth()` API.\n const usableScheme = usableSecuritySchemes[0];\n const schemes = Object.entries(preparedSecurity)\n .map(([, ps]) => ps.filter(s => usableScheme === s._key))\n .reduce((prev, next) => prev.concat(next), []);\n\n const scheme = schemes.shift() as KeyedSecuritySchemeObject;\n switch (scheme.type) {\n case 'http':\n if (scheme.scheme === 'basic') {\n preparedAuth[scheme._key] = {\n user: authKey[0],\n pass: authKey.length === 2 ? authKey[1] : '',\n };\n } else if (scheme.scheme === 'bearer') {\n preparedAuth[scheme._key] = authKey[0];\n }\n break;\n\n case 'oauth2':\n preparedAuth[scheme._key] = authKey[0];\n break;\n\n case 'apiKey':\n if (scheme.in === 'query' || scheme.in === 'header' || scheme.in === 'cookie') {\n preparedAuth[scheme._key] = authKey[0];\n }\n break;\n\n default:\n throw new Error(\n `Sorry, this API currently uses a security scheme, ${scheme.type}, which this library doesn't yet support.`,\n );\n }\n\n return preparedAuth;\n}\n","import type { ReadStream } from 'node:fs';\nimport type Operation from 'oas/operation';\nimport type { ParameterObject, SchemaObject } from 'oas/rmoas.types';\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport stream from 'node:stream';\n\nimport caseless from 'caseless';\nimport DatauriParser from 'datauri/parser.js';\nimport datauri from 'datauri/sync.js';\nimport getStream from 'get-stream';\nimport lodashMerge from 'lodash.merge';\nimport removeUndefinedObjects from 'remove-undefined-objects';\n\nimport getJSONSchemaDefaults from './getJSONSchemaDefaults.js';\n\n// These headers are normally only defined by the OpenAPI definition but we allow the user to\n// manually supply them in their `metadata` parameter if they wish.\nconst specialHeaders = ['accept', 'authorization'];\n\n/**\n * Extract all available parameters from an operations Parameter Object into a digestable array\n * that we can use to apply to the request.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterObject}\n */\nfunction digestParameters(parameters: ParameterObject[]): Record<string, ParameterObject> {\n return parameters.reduce((prev, param) => {\n if ('$ref' in param || 'allOf' in param || 'anyOf' in param || 'oneOf' in param) {\n throw new Error(\"The OpenAPI document for this operation wasn't dereferenced before processing.\");\n } else if (param.name in prev) {\n throw new Error(\n `The operation you are using has the same parameter, ${param.name}, spread across multiple entry points. We unfortunately can't handle this right now.`,\n );\n }\n\n return Object.assign(prev, { [param.name]: param });\n }, {});\n}\n\n// https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_isempty\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isEmpty(obj: any) {\n return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;\n}\n\nfunction isObject(thing: unknown) {\n if (thing instanceof stream.Readable) {\n return false;\n }\n\n return typeof thing === 'object' && thing !== null && !Array.isArray(thing);\n}\n\nfunction isPrimitive(obj: unknown) {\n return obj === null || typeof obj === 'number' || typeof obj === 'string';\n}\n\nfunction merge(src: unknown, target: unknown) {\n if (Array.isArray(target)) {\n // @todo we need to add support for merging array defaults with array body/metadata arguments\n return target;\n } else if (!isObject(target)) {\n return target;\n }\n\n return lodashMerge(src, target);\n}\n\n/**\n * Ingest a file path or readable stream into a common object that we can later use to process it\n * into a parameters object for making an API request.\n *\n */\nfunction processFile(\n paramName: string | undefined,\n file: string | ReadStream,\n): Promise<{ base64?: string; buffer?: Buffer; filename: string; paramName?: string } | undefined> {\n if (typeof file === 'string') {\n // In order to support relative pathed files, we need to attempt to resolve them.\n const resolvedFile = path.resolve(file);\n\n return new Promise((resolve, reject) => {\n fs.stat(resolvedFile, async err => {\n if (err) {\n if (err.code === 'ENOENT') {\n // It's less than ideal for us to handle files that don't exist like this but because\n // `file` is a string it might actually be the full text contents of the file and not\n // actually a path.\n //\n // We also can't really regex to see if `file` *looks*` like a path because one should be\n // able to pass in a relative `owlbert.png` (instead of `./owlbert.png`) and though that\n // doesn't *look* like a path, it is one that should still work.\n return resolve(undefined);\n }\n\n return reject(err);\n }\n\n const fileMetadata = await datauri(resolvedFile);\n const payloadFilename = encodeURIComponent(path.basename(resolvedFile));\n\n return resolve({\n paramName,\n base64: fileMetadata?.content?.replace(';base64', `;name=${payloadFilename};base64`),\n filename: payloadFilename,\n buffer: fileMetadata.buffer,\n });\n });\n });\n } else if (file instanceof stream.Readable) {\n return getStream.buffer(file).then(buffer => {\n const filePath = file.path as string;\n const parser = new DatauriParser();\n const base64 = parser.format(filePath, buffer).content;\n const payloadFilename = encodeURIComponent(path.basename(filePath));\n\n return {\n paramName,\n base64: base64?.replace(';base64', `;name=${payloadFilename};base64`),\n filename: payloadFilename,\n buffer,\n };\n });\n }\n\n return Promise.reject(\n new TypeError(\n paramName\n ? `The data supplied for the \\`${paramName}\\` request body parameter is not a file handler that we support.`\n : 'The data supplied for the request body payload is not a file handler that we support.',\n ),\n );\n}\n\n/**\n * With potentially supplied body and/or metadata we need to run through them against a given API\n * operation to see what's what and prepare any available parameters to be used in an API request\n * with `@readme/oas-to-har`.\n *\n */\nexport default async function prepareParams(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {\n let metadataIntersected = false;\n const digestedParameters = digestParameters(operation.getParameters());\n const jsonSchema = operation.getParametersAsJSONSchema();\n\n /**\n * It might be common for somebody to run `sdk.findPetsByStatus({ status: 'available' }, {})`, in\n * which case we want to filter out the second (metadata) parameter and treat the first parameter\n * as the metadata instead. If we don't do this, their supplied `status` metadata will be treated\n * as a body parameter, and because there's no `status` body parameter, and no supplied metadata\n * (because it's an empty object), the request won't send a payload.\n *\n * @see {@link https://github.com/readmeio/api/issues/449}\n */\n // eslint-disable-next-line no-param-reassign\n metadata = removeUndefinedObjects(metadata);\n\n if (!jsonSchema && (body !== undefined || metadata !== undefined)) {\n let throwNoParamsError = true;\n\n // If this operation doesn't have any parameters for us to transform to JSON Schema but they've\n // sent us either an `Accept` or `Authorization` header (or both) we should let them do that.\n // We should, however, only do this check for the `body` parameter as if they've sent this\n // request both `body` and `metadata` we can reject it outright as the operation won't have any\n // body data.\n if (body !== undefined) {\n if (typeof body === 'object' && body !== null && !Array.isArray(body)) {\n if (Object.keys(body).length <= 2) {\n const bodyParams = caseless(body);\n\n if (specialHeaders.some(header => bodyParams.has(header))) {\n throwNoParamsError = false;\n }\n }\n }\n }\n\n if (throwNoParamsError) {\n throw new Error(\n \"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.\",\n );\n }\n }\n\n const jsonSchemaDefaults = jsonSchema ? getJSONSchemaDefaults(jsonSchema) : {};\n\n const params: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body?: any;\n cookie?: Record<string, string | number | boolean>;\n files?: Record<string, Buffer>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n formData?: any;\n header?: Record<string, string | number | boolean>;\n path?: Record<string, string | number | boolean>;\n query?: Record<string, string | number | boolean>;\n server?: {\n selected: number;\n variables: Record<string, string | number>;\n };\n } = jsonSchemaDefaults;\n\n // If a body argument was supplied we need to do a bit of work to see if it's actually a body\n // argument or metadata because the library lets you supply either a body, metadata, or body with\n // metadata.\n if (typeof body !== 'undefined') {\n if (Array.isArray(body) || isPrimitive(body)) {\n // If the body param is an array or a primitive then we know it's absolutely a body because\n // metadata can only ever be undefined or an object.\n params.body = merge(params.body, body);\n } else if (typeof metadata === 'undefined') {\n // No metadata was explicitly provided so we need to analyze the body to determine if it's a\n // body or should be actually be treated as metadata.\n const headerParams = caseless({});\n Object.entries(digestedParameters).forEach(([paramName, param]) => {\n // Headers are sent case-insensitive so we need to make sure that we're properly\n // matching them when detecting what our incoming payload looks like.\n if (param.in === 'header') {\n headerParams.set(paramName, '');\n }\n });\n\n // `Accept` and `Authorization` headers can't be defined as normal parameters but we should\n // always allow the user to supply them if they wish.\n specialHeaders.forEach(header => {\n if (!headerParams.has(header)) {\n headerParams.set(header, '');\n }\n });\n\n const intersection = Object.keys(body as NonNullable<unknown>).filter(value => {\n if (Object.keys(digestedParameters).includes(value)) {\n return true;\n } else if (headerParams.has(value)) {\n return true;\n }\n\n return false;\n }).length;\n\n // If more than 25% of the body intersects with the parameters that we've got on hand, then\n // we should treat it as a metadata object and organize into parameters.\n if (intersection && intersection / Object.keys(body as NonNullable<unknown>).length > 0.25) {\n /* eslint-disable no-param-reassign */\n metadataIntersected = true;\n metadata = merge(params.body, body) as Record<string, unknown>;\n body = undefined;\n /* eslint-enable no-param-reassign */\n } else {\n // For all other cases, we should just treat the supplied body as a body.\n params.body = merge(params.body, body);\n }\n } else {\n // Body and metadata were both supplied.\n params.body = merge(params.body, body);\n }\n }\n\n if (!operation.hasRequestBody()) {\n // If this operation doesn't have any documented request body then we shouldn't be sending\n // anything.\n delete params.body;\n } else {\n if (!('body' in params)) params.body = {};\n\n // We need to retrieve the request body for this operation to search for any `binary` format\n // data that the user wants to send so we know what we need to prepare for the final API\n // request.\n const payloadJsonSchema = jsonSchema.find(js => js.type === 'body');\n if (payloadJsonSchema) {\n if (!params.files) params.files = {};\n\n const conversions = [];\n\n // @todo add support for `type: array`, `oneOf` and `anyOf`\n if (payloadJsonSchema.schema?.properties) {\n Object.entries(payloadJsonSchema.schema?.properties)\n .filter(([, schema]: [string, SchemaObject]) => schema?.format === 'binary')\n .filter(([prop]) => Object.keys(params.body).includes(prop))\n .forEach(([prop]) => {\n conversions.push(processFile(prop, params.body[prop]));\n });\n } else if (payloadJsonSchema.schema?.type === 'string') {\n if (payloadJsonSchema.schema?.format === 'binary') {\n conversions.push(processFile(undefined, params.body));\n }\n }\n\n await Promise.all(conversions)\n .then(fileMetadata => fileMetadata.filter(Boolean))\n .then(fm => {\n fm.forEach(fileMetadata => {\n if (!fileMetadata) {\n // If we don't have any metadata here it's because the file we have is likely\n // the full string content of the file so since we don't have any filenames to\n // work with we shouldn't do any additional handling to the `body` or `files`\n // parameters.\n return;\n }\n\n if (fileMetadata.paramName) {\n params.body[fileMetadata.paramName] = fileMetadata.base64;\n } else {\n params.body = fileMetadata.base64;\n }\n\n if (fileMetadata.buffer && params?.files) {\n params.files[fileMetadata.filename] = fileMetadata.buffer;\n }\n });\n });\n }\n }\n\n // Form data should be placed within `formData` instead of `body` for it to properly get picked\n // up by `fetch-har`.\n if (operation.isFormUrlEncoded()) {\n params.formData = merge(params.formData, params.body);\n delete params.body;\n }\n\n // Only spend time trying to organize metadata into parameters if we were able to digest\n // parameters out of the operation schema. If we couldn't digest anything, but metadata was\n // supplied then we wouldn't know how to send it in the request!\n if (typeof metadata !== 'undefined') {\n if (!('cookie' in params)) params.cookie = {};\n if (!('header' in params)) params.header = {};\n if (!('path' in params)) params.path = {};\n if (!('query' in params)) params.query = {};\n\n Object.entries(digestedParameters).forEach(([paramName, param]) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let value: any;\n let metadataHeaderParam;\n if (typeof metadata === 'object' && !isEmpty(metadata)) {\n if (paramName in metadata) {\n value = metadata[paramName];\n metadataHeaderParam = paramName;\n } else if (param.in === 'header') {\n // Headers are sent case-insensitive so we need to make sure that we're properly\n // matching them when detecting what our incoming payload looks like.\n metadataHeaderParam = Object.keys(metadata).find(k => k.toLowerCase() === paramName.toLowerCase()) || '';\n value = metadata[metadataHeaderParam];\n }\n }\n\n if (value === undefined) {\n return;\n }\n\n /* eslint-disable no-param-reassign */\n switch (param.in) {\n case 'path':\n (params.path as NonNullable<typeof params.path>)[paramName] = value;\n if (metadata?.[paramName]) delete metadata[paramName];\n break;\n case 'query':\n (params.query as NonNullable<typeof params.query>)[paramName] = value;\n if (metadata?.[paramName]) delete metadata[paramName];\n break;\n case 'header':\n (params.header as NonNullable<typeof params.header>)[paramName.toLowerCase()] = value;\n if (metadataHeaderParam && metadata?.[metadataHeaderParam]) delete metadata[metadataHeaderParam];\n break;\n case 'cookie':\n (params.cookie as NonNullable<typeof params.cookie>)[paramName] = value;\n if (metadata?.[paramName]) delete metadata[paramName];\n break;\n default: // no-op\n }\n /* eslint-enable no-param-reassign */\n\n // Because a user might have sent just a metadata object, we want to make sure that we filter\n // out anything that they sent that is a parameter from also being sent as part of a form\n // data payload for `x-www-form-urlencoded` requests.\n if (metadataIntersected && operation.isFormUrlEncoded()) {\n if (paramName in params.formData) {\n delete params.formData[paramName];\n }\n }\n });\n\n // If there's any leftover metadata that hasn't been moved into form data for this request we\n // need to move it or else it'll get tossed.\n if (!isEmpty(metadata)) {\n if (typeof metadata === 'object') {\n // If the user supplied an `accept` or `authorization` header themselves we should allow it\n // through. Normally these headers are automatically handled by `@readme/oas-to-har` but in\n // the event that maybe the user wants to return XML for an API that normally returns JSON\n // or specify a custom auth header (maybe we can't handle their auth case right) this is the\n // only way with this library that they can do that.\n specialHeaders.forEach(headerName => {\n const headerParam = Object.keys(metadata || {}).find(m => m.toLowerCase() === headerName);\n if (headerParam) {\n // this if-statement below is a typeguard\n if (typeof metadata === 'object') {\n // this if-statement below is a typeguard\n if (typeof params.header === 'object') {\n params.header[headerName] = metadata[headerParam] as string;\n }\n // eslint-disable-next-line no-param-reassign\n delete metadata[headerParam];\n }\n }\n });\n }\n\n if (operation.isFormUrlEncoded()) {\n params.formData = merge(params.formData, metadata);\n } else {\n // Any other remaining unused metadata will be unused because we don't know where to place\n // it in the request.\n }\n }\n }\n\n (['body', 'cookie', 'files', 'formData', 'header', 'path', 'query'] as const).forEach((type: keyof typeof params) => {\n if (type in params && isEmpty(params[type])) {\n delete params[type];\n }\n });\n\n return params;\n}\n","import type Oas from 'oas';\n\nfunction stripTrailingSlash(url: string) {\n if (url[url.length - 1] === '/') {\n return url.slice(0, -1);\n }\n\n return url;\n}\n\n/**\n * With an SDK server config and an instance of OAS we should extract and prepare the server and\n * any server variables to be supplied to `@readme/oas-to-har`.\n *\n */\nexport default function prepareServer(spec: Oas, url: string, variables: Record<string, string | number> = {}) {\n let serverIdx;\n const sanitizedUrl = stripTrailingSlash(url);\n (spec.api.servers || []).forEach((server, i) => {\n if (server.url === sanitizedUrl) {\n serverIdx = i;\n }\n });\n\n // If we were able to find the passed in server in the OAS servers, we should use that! If we\n // couldn't and server variables were passed in we should try our best to handle that, otherwise\n // we should ignore the passed in server and use whever the default from the OAS is.\n if (serverIdx) {\n return {\n selected: serverIdx,\n variables,\n };\n } else if (Object.keys(variables).length) {\n // @todo we should run `oas.replaceUrl(url)` and pass that unto `@readme/oas-to-har`\n } else {\n const server = spec.splitVariables(url);\n if (server) {\n return {\n selected: server.selected,\n variables: server.variables,\n };\n }\n\n // @todo we should pass `url` directly into `@readme/oas-to-har` as the base URL\n }\n\n return false;\n}\n"],"mappings":";;;;;AAIA,OAAO,cAAc;AACrB,OAAO,cAAc;AACrB,OAAO,SAAS;;;ACHhB,OAAO,cAAc;AAYN,SAAR,sBAAuC,aAA8B;AAC1E,SAAO,YACJ,IAAI,CAAC,EAAE,MAAM,aAAa,QAAQ,WAAW,MAAM;AAClD,UAAM,WAAoC,CAAC;AAC3C;AAAA,MACE;AAAA,MACA,CACE,QACA,SACA,YACA,eACA,eACA,cACA,kBACG;AACH,YAAI,CAAC,QAAQ,WAAW,cAAc,GAAG;AACvC;AAAA,QACF;AAEA,YAAI,MAAM,QAAQ,cAAc,QAAQ,KAAK,cAAc,SAAS,SAAS,OAAO,aAAa,CAAC,GAAG;AACnG,cAAI,OAAO,SAAS,YAAY,eAAe;AAC7C,qBAAS,aAAa,IAAI,CAAC;AAAA,UAC7B;AAEA,cAAI,cAAc;AAClB,cAAI,eAAe;AAEjB,0BACG,QAAQ,iBAAiB,EAAE,EAC3B,MAAM,GAAG,EACT,QAAQ,CAAC,cAAsB;AAC9B,kBAAI,cAAc,IAAI;AACpB;AAAA,cACF;AAEA,4BAAe,cAAc,SAAS,KAAiC,CAAC;AAAA,YAC1E,CAAC;AAAA,UACL;AAEA,cAAI,OAAO,YAAY,QAAW;AAChC,gBAAI,kBAAkB,QAAW;AAC/B,0BAAY,aAAa,IAAI,OAAO;AAAA,YACtC;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,QAAI,CAAC,OAAO,KAAK,QAAQ,EAAE,QAAQ;AACjC,aAAO,CAAC;AAAA,IACV;AAEA,WAAO;AAAA;AAAA,MAEL,CAAC,WAAW,GAAG;AAAA,IACjB;AAAA,EACF,CAAC,EACA,OAAO,CAAC,MAAM,SAAS,OAAO,OAAO,MAAM,IAAI,CAAC;AACrD;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Y,KAAK,KAAK,UAAUA,OAAM,MAAM;AAElD,WAAO,KAAK,eAA2B,WAAW,MAAM,QAAQ;AAAA,EAClE;AAAA,EAEA,MAAM,eACJ,WACA,MACA,UACA;AACA,WAAO,cAAc,WAAW,MAAM,QAAQ,EAAE,KAAK,YAAU;AAC7D,YAAM,OAAO,EAAE,GAAG,OAAO;AAKzB,UAAI,KAAK,QAAQ;AACf,cAAM,iBAAiB,cAAc,KAAK,MAAM,KAAK,OAAO,KAAK,KAAK,OAAO,SAAS;AACtF,YAAI,gBAAgB;AAClB,eAAK,SAAS;AAAA,QAChB;AAAA,MACF;AAGA,YAAM,MAAM,SAAS,KAAK,MAAM,WAAW,MAAM,YAAY,KAAK,MAAM,SAAS,CAAC;AAElF,UAAI;AACJ,YAAM,OAAoB,CAAC;AAC3B,UAAI,KAAK,OAAO,SAAS;AACvB,cAAM,aAAa,IAAI,gBAAgB;AACvC,wBAAgB,WAAW,MAAM,WAAW,MAAM,GAAG,KAAK,OAAO,OAAO;AACxE,aAAK,SAAS,WAAW;AAAA,MAC3B;AAEA,aAAO,SAAS,KAAY;AAAA,QAC1B,OAAO,KAAK,SAAS,CAAC;AAAA,QACtB;AAAA,QACA,WAAW,KAAK;AAAA,MAClB,CAAC,EACE,KAAK,OAAO,QAAkB;AAC7B,cAAM,SAAS,MAAM,cAA0B,GAAG;AAElD,YAAI,IAAI,UAAU,OAAO,IAAI,UAAU,KAAK;AAC1C,gBAAM,IAAI;AAAA,YACR,OAAO;AAAA,YACP,OAAO;AAAA,YACP,OAAO;AAAA,YACP,OAAO;AAAA,UACT;AAAA,QACF;AAEA,eAAO;AAAA,MACT,CAAC,EACA,QAAQ,MAAM;AACb,YAAI,KAAK,OAAO,SAAS;AACvB,uBAAa,aAAa;AAAA,QAC5B;AAAA,MACF,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AACF;","names":["schemes","scheme","path"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Har } from 'har-format';\nimport type Operation from 'oas/operation';\nimport type { HttpMethods, OASDocument } from 'oas/rmoas.types';\n\nimport oasToHar from '@readme/oas-to-har';\nimport fetchHar from 'fetch-har';\nimport Oas from 'oas';\n\nimport FetchError from './errors/fetchError.js';\nimport { parseResponse, prepareAuth, prepareParams, prepareServer } from './lib/index.js';\n\nexport interface ConfigOptions {\n /**\n * Override the default `fetch` request timeout of 30 seconds. This number should be represented\n * in milliseconds.\n */\n timeout?: number;\n}\n\nexport interface FetchResponse<HTTPStatus, Data> {\n data: Data;\n headers: Headers;\n res: Response;\n status: HTTPStatus;\n}\n\n// https://stackoverflow.com/a/39495173\ntype Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N\n ? Acc[number]\n : Enumerate<N, [...Acc, Acc['length']]>;\n\nexport type HTTPMethodRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;\n\nexport default class APICore {\n spec!: Oas;\n\n private auth: (number | string)[] = [];\n\n private server:\n | false\n | {\n url: string;\n variables?: Record<string, string | number>;\n } = false;\n\n private config: ConfigOptions = {};\n\n private userAgent!: string;\n\n constructor(definition?: Record<string, unknown> | OASDocument, userAgent?: string) {\n if (definition) this.spec = Oas.init(definition);\n if (userAgent) this.userAgent = userAgent;\n }\n\n setSpec(spec: Oas) {\n this.spec = spec;\n }\n\n setConfig(config: ConfigOptions) {\n this.config = config;\n return this;\n }\n\n setUserAgent(userAgent: string) {\n this.userAgent = userAgent;\n return this;\n }\n\n setAuth(...values: string[] | number[]) {\n this.auth = values;\n return this;\n }\n\n setServer(url: string, variables: Record<string, string | number> = {}) {\n this.server = { url, variables };\n return this;\n }\n\n async fetch<HTTPStatus extends number = number>(\n path: string,\n method: HttpMethods,\n body?: unknown,\n metadata?: Record<string, unknown>,\n ) {\n const operation = this.spec.operation(path, method);\n\n return this.fetchOperation<HTTPStatus>(operation, body, metadata);\n }\n\n async fetchOperation<HTTPStatus extends number = number>(\n operation: Operation,\n body?: unknown,\n metadata?: Record<string, unknown>,\n ) {\n return prepareParams(operation, body, metadata).then(params => {\n const data = { ...params };\n\n // If `sdk.server()` has been issued data then we need to do some extra work to figure out\n // how to use that supplied server, and also handle any server variables that were sent\n // alongside it.\n if (this.server) {\n const preparedServer = prepareServer(this.spec, this.server.url, this.server.variables);\n if (preparedServer) {\n data.server = preparedServer;\n }\n }\n\n // @ts-expect-error `this.auth` typing is off. FIXME\n const har = oasToHar(this.spec, operation, data, prepareAuth(this.auth, operation));\n\n let timeoutSignal: NodeJS.Timeout;\n const init: RequestInit = {};\n if (this.config.timeout) {\n const controller = new AbortController();\n timeoutSignal = setTimeout(() => controller.abort(), this.config.timeout);\n init.signal = controller.signal;\n }\n\n return fetchHar(har as Har, {\n files: data.files || {},\n init,\n userAgent: this.userAgent,\n })\n .then(async (res: Response) => {\n const parsed = await parseResponse<HTTPStatus>(res);\n\n if (res.status >= 400 && res.status <= 599) {\n throw new FetchError<typeof parsed.status, typeof parsed.data>(\n parsed.status,\n parsed.data,\n parsed.headers,\n parsed.res,\n );\n }\n\n return parsed;\n })\n .finally(() => {\n if (this.config.timeout) {\n clearTimeout(timeoutSignal);\n }\n });\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAIA,OAAO,cAAc;AACrB,OAAO,cAAc;AACrB,OAAO,SAAS;AA2BhB,IAAqB,UAArB,MAA6B;AAAA,EAC3B;AAAA,EAEQ,OAA4B,CAAC;AAAA,EAE7B,SAKA;AAAA,EAEA,SAAwB,CAAC;AAAA,EAEzB;AAAA,EAER,YAAY,YAAoD,WAAoB;AAClF,QAAI;AAAY,WAAK,OAAO,IAAI,KAAK,UAAU;AAC/C,QAAI;AAAW,WAAK,YAAY;AAAA,EAClC;AAAA,EAEA,QAAQ,MAAW;AACjB,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,UAAU,QAAuB;AAC/B,SAAK,SAAS;AACd,WAAO;AAAA,EACT;AAAA,EAEA,aAAa,WAAmB;AAC9B,SAAK,YAAY;AACjB,WAAO;AAAA,EACT;AAAA,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,MACT,CAAC,EACA,QAAQ,MAAM;AACb,YAAI,KAAK,OAAO,SAAS;AACvB,uBAAa,aAAa;AAAA,QAC5B;AAAA,MACF,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -0,0 +1,15 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+ var _chunkTOMHUGQAcjs = require('../chunk-TOMHUGQA.cjs');
8
+
9
+
10
+
11
+
12
+
13
+
14
+ exports.getJSONSchemaDefaults = _chunkTOMHUGQAcjs.getJSONSchemaDefaults; exports.parseResponse = _chunkTOMHUGQAcjs.parseResponse; exports.prepareAuth = _chunkTOMHUGQAcjs.prepareAuth; exports.prepareParams = _chunkTOMHUGQAcjs.prepareParams; exports.prepareServer = _chunkTOMHUGQAcjs.prepareServer;
15
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,62 @@
1
+ export { FromSchema } from 'json-schema-to-ts';
2
+ import { SchemaWrapper } from 'oas/operation/get-parameters-as-json-schema';
3
+ import Operation from 'oas/operation';
4
+ import Oas from 'oas';
5
+
6
+ /**
7
+ * Run through a JSON Schema object and compose up an object containing default data for any schema
8
+ * property that is required and also has a defined default.
9
+ *
10
+ * Code partially adapted from the `json-schema-default` package but modified to only return
11
+ * defaults of required properties.
12
+ *
13
+ * @todo This is a good candidate to be moved into a core `oas` library method.
14
+ * @see {@link https://github.com/mdornseif/json-schema-default}
15
+ */
16
+ declare function getJSONSchemaDefaults(jsonSchemas: SchemaWrapper[]): {
17
+ [x: string]: Record<string, unknown>;
18
+ };
19
+
20
+ declare function parseResponse<HTTPStatus extends number = number>(response: Response): Promise<{
21
+ data: any;
22
+ status: HTTPStatus;
23
+ headers: Headers;
24
+ res: Response;
25
+ }>;
26
+
27
+ declare function prepareAuth(authKey: (number | string)[], operation: Operation): Record<string, string | number | {
28
+ pass: string | number;
29
+ user: string | number;
30
+ }>;
31
+
32
+ /**
33
+ * With potentially supplied body and/or metadata we need to run through them against a given API
34
+ * operation to see what's what and prepare any available parameters to be used in an API request
35
+ * with `@readme/oas-to-har`.
36
+ *
37
+ */
38
+ declare function prepareParams(operation: Operation, body?: unknown, metadata?: Record<string, unknown>): Promise<{
39
+ body?: any;
40
+ cookie?: Record<string, string | number | boolean> | undefined;
41
+ files?: Record<string, Buffer> | undefined;
42
+ formData?: any;
43
+ header?: Record<string, string | number | boolean> | undefined;
44
+ path?: Record<string, string | number | boolean> | undefined;
45
+ query?: Record<string, string | number | boolean> | undefined;
46
+ server?: {
47
+ selected: number;
48
+ variables: Record<string, string | number>;
49
+ } | undefined;
50
+ }>;
51
+
52
+ /**
53
+ * With an SDK server config and an instance of OAS we should extract and prepare the server and
54
+ * any server variables to be supplied to `@readme/oas-to-har`.
55
+ *
56
+ */
57
+ declare function prepareServer(spec: Oas, url: string, variables?: Record<string, string | number>): false | {
58
+ selected: number;
59
+ variables: Record<string, string | number>;
60
+ };
61
+
62
+ export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };