@readme/oas-to-har 39.0.1 → 40.0.1

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,1324 +1,1168 @@
1
- import {
2
- configureSecurity
3
- } from "./chunk-JWXX5N4N.js";
4
-
5
- // src/index.ts
6
- import { parse as parseDataUrl } from "@readme/data-urls";
1
+ import configureSecurity from "./lib/configure-security.js";
2
+ import { parse } from "@readme/data-urls";
7
3
  import { HEADERS, PROXY_ENABLED } from "oas/extensions";
8
4
  import { Operation } from "oas/operation";
9
- import { isRef as isRef2 } from "oas/types";
10
- import { dereferenceRef as dereferenceRef2, jsonSchemaTypes, matchesMimeType as matchesMimeType2 } from "oas/utils";
5
+ import { isRef } from "oas/types";
6
+ import { dereferenceRef, dereferenceRefDeep, getParameterContentType, jsonSchemaTypes, matchesMimeType } from "oas/utils";
11
7
  import removeUndefinedObjects from "remove-undefined-objects";
8
+ import qs from "qs";
12
9
 
13
10
  // src/lib/lodash.ts
11
+ /**
12
+ * A janky, poorly typed replacement for `lodash.get`.
13
+ *
14
+ * @see {@link https://youmightnotneed.com/lodash#get}
15
+ */
14
16
  function get(object, path) {
15
- if (!path) return void 0;
16
- const pathArray = String(path).match(/([^[.\]])+/g);
17
- const result = pathArray?.reduce((prevObj, key) => prevObj?.[key], object);
18
- return result;
17
+ if (!path) return void 0;
18
+ return String(path).match(/([^[.\]])+/g)?.reduce((prevObj, key) => prevObj?.[key], object);
19
19
  }
20
+ /**
21
+ * A janky, poorly typed replacement for `lodash.set`.
22
+ *
23
+ * @see {@link https://youmightnotneed.com/lodash#set}
24
+ */
20
25
  function set(object, path, value) {
21
- const pathArray = Array.isArray(path) ? path : String(path).match(/([^[.\]])+/g);
22
- return pathArray?.reduce((acc, key, i) => {
23
- if (acc[key] === void 0) {
24
- acc[key] = {};
25
- }
26
- if (i === pathArray.length - 1) {
27
- acc[key] = value;
28
- }
29
- return acc[key];
30
- }, object);
26
+ const pathArray = Array.isArray(path) ? path : String(path).match(/([^[.\]])+/g);
27
+ return pathArray?.reduce((acc, key, i) => {
28
+ if (acc[key] === void 0) acc[key] = {};
29
+ if (i === pathArray.length - 1) acc[key] = value;
30
+ return acc[key];
31
+ }, object);
31
32
  }
32
33
 
33
- // src/lib/style-formatting/index.ts
34
- import { matchesMimeType } from "oas/utils";
35
- import qs from "qs";
36
-
37
34
  // src/lib/utils.ts
38
- import { isRef } from "oas/types";
39
- import { dereferenceRef, dereferenceRefDeep, getParameterContentType as getParameterContentTypeUtil } from "oas/utils";
35
+ /**
36
+ * Determine if a schema `type` is, or contains, a specific discriminator.
37
+ *
38
+ */
40
39
  function hasSchemaType(schema, discriminator) {
41
- if (Array.isArray(schema.type)) {
42
- return schema.type.includes(discriminator);
43
- }
44
- return schema.type === discriminator;
40
+ if (Array.isArray(schema.type)) return schema.type.includes(discriminator);
41
+ return schema.type === discriminator;
45
42
  }
43
+ /**
44
+ * When we only have a schema fragment (no request payload), peel a single top-level polymorphic
45
+ * schema to its first branch so we can enumerate its properties.
46
+ *
47
+ */
46
48
  function unwrapFirstPolymorphicBranch(obj) {
47
- if (obj.oneOf && Array.isArray(obj.oneOf) && obj.oneOf.length) {
48
- return unwrapFirstPolymorphicBranch(obj.oneOf[0]);
49
- }
50
- if (obj.anyOf && Array.isArray(obj.anyOf) && obj.anyOf.length) {
51
- return unwrapFirstPolymorphicBranch(obj.anyOf[0]);
52
- }
53
- return obj;
49
+ if (obj.oneOf && Array.isArray(obj.oneOf) && obj.oneOf.length) return unwrapFirstPolymorphicBranch(obj.oneOf[0]);
50
+ if (obj.anyOf && Array.isArray(obj.anyOf) && obj.anyOf.length) return unwrapFirstPolymorphicBranch(obj.anyOf[0]);
51
+ return obj;
54
52
  }
55
53
  function getSubschemas(schema, api, opts, seenRefs = /* @__PURE__ */ new Set()) {
56
- let subSchemaDataSize = 0;
57
- if (opts.parentIsArray) {
58
- const parentData = get(opts.payload, opts.parentKey || "");
59
- if (parentData === void 0 || !Array.isArray(parentData)) {
60
- return false;
61
- }
62
- subSchemaDataSize = parentData.length;
63
- }
64
- let subschemas = [];
65
- if (subSchemaDataSize > 0) {
66
- for (let idx = 0; idx < subSchemaDataSize; idx += 1) {
67
- const foundSubschemas = getSubschemas(
68
- schema,
69
- api,
70
- {
71
- ...opts,
72
- parentIsArray: false,
73
- parentKey: opts.parentKey ? [opts.parentKey, idx].join(".") : String(idx)
74
- },
75
- seenRefs
76
- );
77
- if (foundSubschemas) {
78
- subschemas = subschemas.concat(foundSubschemas);
79
- }
80
- }
81
- } else {
82
- let resolvedSchema = schema;
83
- if (schema && isRef(schema)) {
84
- if (seenRefs.has(schema.$ref)) {
85
- return subschemas;
86
- }
87
- seenRefs.add(schema.$ref);
88
- resolvedSchema = dereferenceRef(schema, api);
89
- if (!resolvedSchema || isRef(resolvedSchema)) {
90
- return subschemas;
91
- }
92
- }
93
- const baseKey = opts.parentKey ?? "";
94
- if (resolvedSchema.properties && typeof resolvedSchema.properties === "object") {
95
- for (const [propName, propSchema] of Object.entries(resolvedSchema.properties)) {
96
- if (propSchema && typeof propSchema === "object") {
97
- let resolved;
98
- if (isRef(propSchema)) {
99
- if (seenRefs.has(propSchema.$ref)) {
100
- continue;
101
- }
102
- seenRefs.add(propSchema.$ref);
103
- resolved = dereferenceRef(propSchema, api);
104
- } else {
105
- resolved = propSchema;
106
- }
107
- if (resolved && !isRef(resolved)) {
108
- subschemas.push({
109
- key: baseKey ? [baseKey, propName].join(".") : propName,
110
- schema: resolved
111
- });
112
- }
113
- }
114
- }
115
- }
116
- if (!("properties" in resolvedSchema) && typeof resolvedSchema === "object" && !("type" in resolvedSchema && resolvedSchema.type !== "object")) {
117
- for (const [propName, propSchema] of Object.entries(resolvedSchema)) {
118
- if (propSchema && (Array.isArray(propSchema) || typeof propSchema === "object" && propSchema !== null)) {
119
- const raw = unwrapFirstPolymorphicBranch(propSchema);
120
- const resolved = isRef(raw) ? dereferenceRef(raw, api) : raw;
121
- const toPush = resolved && !isRef(resolved) ? resolved : raw;
122
- if (toPush && typeof toPush === "object") {
123
- subschemas.push({
124
- key: baseKey ? [baseKey, propName].join(".") : propName,
125
- schema: toPush
126
- });
127
- }
128
- }
129
- }
130
- }
131
- if ("items" in resolvedSchema && resolvedSchema.items !== void 0 && resolvedSchema.items !== true) {
132
- const itemsSchema = resolvedSchema.items;
133
- let resolved;
134
- if (isRef(itemsSchema)) {
135
- if (!seenRefs.has(itemsSchema.$ref)) {
136
- seenRefs.add(itemsSchema.$ref);
137
- resolved = dereferenceRef(itemsSchema, api);
138
- }
139
- } else {
140
- resolved = itemsSchema;
141
- }
142
- if (resolved && !isRef(resolved)) {
143
- subschemas.push({
144
- key: baseKey,
145
- schema: resolved,
146
- parentIsArray: true
147
- });
148
- }
149
- }
150
- }
151
- return subschemas;
54
+ let subSchemaDataSize = 0;
55
+ if (opts.parentIsArray) {
56
+ const parentData = get(opts.payload, opts.parentKey || "");
57
+ if (parentData === void 0 || !Array.isArray(parentData)) return false;
58
+ subSchemaDataSize = parentData.length;
59
+ }
60
+ let subschemas = [];
61
+ if (subSchemaDataSize > 0) for (let idx = 0; idx < subSchemaDataSize; idx += 1) {
62
+ const foundSubschemas = getSubschemas(schema, api, {
63
+ ...opts,
64
+ parentIsArray: false,
65
+ parentKey: opts.parentKey ? [opts.parentKey, idx].join(".") : String(idx)
66
+ }, seenRefs);
67
+ if (foundSubschemas) subschemas = subschemas.concat(foundSubschemas);
68
+ }
69
+ else {
70
+ let resolvedSchema = schema;
71
+ if (schema && isRef(schema)) {
72
+ if (seenRefs.has(schema.$ref)) return subschemas;
73
+ seenRefs.add(schema.$ref);
74
+ resolvedSchema = dereferenceRef(schema, api);
75
+ if (!resolvedSchema || isRef(resolvedSchema)) return subschemas;
76
+ }
77
+ const baseKey = opts.parentKey ?? "";
78
+ if (resolvedSchema.properties && typeof resolvedSchema.properties === "object") {
79
+ for (const [propName, propSchema] of Object.entries(resolvedSchema.properties)) if (propSchema && typeof propSchema === "object") {
80
+ let resolved;
81
+ if (isRef(propSchema)) {
82
+ if (seenRefs.has(propSchema.$ref)) continue;
83
+ seenRefs.add(propSchema.$ref);
84
+ resolved = dereferenceRef(propSchema, api);
85
+ } else resolved = propSchema;
86
+ if (resolved && !isRef(resolved)) subschemas.push({
87
+ key: baseKey ? [baseKey, propName].join(".") : propName,
88
+ schema: resolved
89
+ });
90
+ }
91
+ }
92
+ if (!("properties" in resolvedSchema) && typeof resolvedSchema === "object" && !("type" in resolvedSchema && resolvedSchema.type !== "object")) {
93
+ for (const [propName, propSchema] of Object.entries(resolvedSchema)) if (propSchema && (Array.isArray(propSchema) || typeof propSchema === "object" && propSchema !== null)) {
94
+ const raw = unwrapFirstPolymorphicBranch(propSchema);
95
+ const resolved = isRef(raw) ? dereferenceRef(raw, api) : raw;
96
+ const toPush = resolved && !isRef(resolved) ? resolved : raw;
97
+ if (toPush && typeof toPush === "object") subschemas.push({
98
+ key: baseKey ? [baseKey, propName].join(".") : propName,
99
+ schema: toPush
100
+ });
101
+ }
102
+ }
103
+ if ("items" in resolvedSchema && resolvedSchema.items !== void 0 && resolvedSchema.items !== true) {
104
+ const itemsSchema = resolvedSchema.items;
105
+ let resolved;
106
+ if (isRef(itemsSchema)) {
107
+ if (!seenRefs.has(itemsSchema.$ref)) {
108
+ seenRefs.add(itemsSchema.$ref);
109
+ resolved = dereferenceRef(itemsSchema, api);
110
+ }
111
+ } else resolved = itemsSchema;
112
+ if (resolved && !isRef(resolved)) subschemas.push({
113
+ key: baseKey,
114
+ schema: resolved,
115
+ parentIsArray: true
116
+ });
117
+ }
118
+ }
119
+ return subschemas;
152
120
  }
121
+ /**
122
+ * With a supplied JSON Schema object, spider through it for any schemas that may contain specific
123
+ * kind of `format` that also happen to be within the current `requestBody` payload that we're
124
+ * creating a HAR representation for.
125
+ *
126
+ */
153
127
  function getTypedFormatsInSchema(format, schema, api, opts, seenRefs = /* @__PURE__ */ new Set()) {
154
- try {
155
- if (schema?.format === format) {
156
- if (opts.parentIsArray) {
157
- const parentData = get(opts.payload, opts.parentKey || "");
158
- if (parentData !== void 0 && Array.isArray(parentData)) {
159
- return Object.keys(parentData).map((pdk) => {
160
- const currentKey = [opts.parentKey, pdk].join(".");
161
- if (get(opts.payload, currentKey) !== void 0) {
162
- return currentKey;
163
- }
164
- return false;
165
- }).filter(Boolean);
166
- }
167
- } else if (opts.parentKey && get(opts.payload, opts.parentKey) !== void 0) {
168
- return opts.parentKey;
169
- } else if (!opts.parentKey && opts.payload !== void 0) {
170
- return true;
171
- }
172
- return false;
173
- }
174
- const subschemas = getSubschemas(schema, api, opts, seenRefs);
175
- if (!subschemas) {
176
- return false;
177
- }
178
- return subschemas.flatMap(({ key, schema: subschema, parentIsArray: entryIsArray }) => {
179
- if (isRef(subschema)) {
180
- const resolved = dereferenceRef(subschema, api);
181
- if (resolved && !isRef(resolved)) {
182
- return resolved;
183
- }
184
- return false;
185
- }
186
- return getTypedFormatsInSchema(
187
- format,
188
- subschema,
189
- api,
190
- {
191
- payload: opts.payload,
192
- parentKey: key,
193
- parentIsArray: entryIsArray
194
- },
195
- seenRefs
196
- );
197
- }).filter(Boolean);
198
- } catch {
199
- return [];
200
- }
128
+ try {
129
+ if (schema?.format === format) {
130
+ if (opts.parentIsArray) {
131
+ const parentData = get(opts.payload, opts.parentKey || "");
132
+ if (parentData !== void 0 && Array.isArray(parentData)) return Object.keys(parentData).map((pdk) => {
133
+ const currentKey = [opts.parentKey, pdk].join(".");
134
+ if (get(opts.payload, currentKey) !== void 0) return currentKey;
135
+ return false;
136
+ }).filter(Boolean);
137
+ } else if (opts.parentKey && get(opts.payload, opts.parentKey) !== void 0) return opts.parentKey;
138
+ else if (!opts.parentKey && opts.payload !== void 0) return true;
139
+ return false;
140
+ }
141
+ const subschemas = getSubschemas(schema, api, opts, seenRefs);
142
+ if (!subschemas) return false;
143
+ return subschemas.flatMap(({ key, schema: subschema, parentIsArray: entryIsArray }) => {
144
+ if (isRef(subschema)) {
145
+ const resolved = dereferenceRef(subschema, api);
146
+ if (resolved && !isRef(resolved)) return resolved;
147
+ return false;
148
+ }
149
+ return getTypedFormatsInSchema(format, subschema, api, {
150
+ payload: opts.payload,
151
+ parentKey: key,
152
+ parentIsArray: entryIsArray
153
+ }, seenRefs);
154
+ }).filter(Boolean);
155
+ } catch {
156
+ return [];
157
+ }
201
158
  }
202
- function getParameterContentType(param) {
203
- if (!("content" in param) || typeof param.content !== "object" || !param.content) {
204
- return null;
205
- }
206
- const contentKeys = Object.keys(param.content);
207
- if (contentKeys.length < 1) {
208
- return null;
209
- }
210
- return getParameterContentTypeUtil(contentKeys) || null;
159
+ /**
160
+ * Extract content type from a parameter's `content` field.
161
+ * According to OAS spec, when `content` is present, `style` and `explode` are ignored.
162
+ * We prioritize `application/json` and other JSON-like content types over other content types.
163
+ * Note: this is just a safe guard. In OAS parser, we enforce that there is exactly one content type.
164
+ *
165
+ * @param param - The parameter object
166
+ * @returns The content type, or `null` if no content is present
167
+ */
168
+ function getParameterContentType$1(param) {
169
+ if (!param.content) return null;
170
+ const contentKeys = Object.keys(param.content);
171
+ if (contentKeys.length < 1) return null;
172
+ return getParameterContentType(contentKeys) || null;
211
173
  }
174
+ /**
175
+ * Extract schema from a parameter's `content` field.
176
+ *
177
+ * @param param - The parameter object
178
+ * @param contentType - The content type
179
+ * @returns The schema, or `null` if no schema is present
180
+ */
212
181
  function getParameterContentSchema(param, contentType, api) {
213
- if (!("content" in param) || typeof param.content !== "object" || !param.content) {
214
- return null;
215
- }
216
- const mediaTypeObject = param.content[contentType];
217
- if (typeof mediaTypeObject === "object" && mediaTypeObject && "schema" in mediaTypeObject && mediaTypeObject.schema) {
218
- const schema = isRef(mediaTypeObject.schema) ? dereferenceRef(mediaTypeObject.schema, api) : mediaTypeObject.schema;
219
- if (!schema || isRef(schema)) {
220
- return null;
221
- }
222
- return schema;
223
- }
224
- return null;
182
+ if (!param.content) return null;
183
+ const mediaTypeObject = param.content[contentType];
184
+ if (typeof mediaTypeObject === "object" && mediaTypeObject && "schema" in mediaTypeObject && mediaTypeObject.schema) {
185
+ const schema = isRef(mediaTypeObject.schema) ? dereferenceRef(mediaTypeObject.schema, api) : mediaTypeObject.schema;
186
+ if (!schema || isRef(schema)) return null;
187
+ return schema;
188
+ }
189
+ return null;
225
190
  }
191
+ /**
192
+ * Recursively parse string values that are valid JSON.
193
+ *
194
+ * This is used when we're dealing with objects that have nested `format: json` descriptors.
195
+ */
226
196
  function parseJSONStrings(obj) {
227
- if (typeof obj === "string") {
228
- try {
229
- const p = JSON.parse(obj);
230
- return typeof p === "object" && p !== null ? parseJSONStrings(p) : p;
231
- } catch {
232
- return obj;
233
- }
234
- }
235
- if (Array.isArray(obj)) {
236
- return obj.map(parseJSONStrings);
237
- }
238
- if (obj !== null && typeof obj === "object") {
239
- const out = {};
240
- for (const [k, v] of Object.entries(obj)) {
241
- out[k] = parseJSONStrings(v);
242
- }
243
- return out;
244
- }
245
- return obj;
197
+ if (typeof obj === "string") try {
198
+ const p = JSON.parse(obj);
199
+ return typeof p === "object" && p !== null ? parseJSONStrings(p) : p;
200
+ } catch {
201
+ return obj;
202
+ }
203
+ if (Array.isArray(obj)) return obj.map(parseJSONStrings);
204
+ if (obj !== null && typeof obj === "object") {
205
+ const out = {};
206
+ for (const [k, v] of Object.entries(obj)) out[k] = parseJSONStrings(v);
207
+ return out;
208
+ }
209
+ return obj;
246
210
  }
211
+ /**
212
+ * Like {@link parseJSONStrings} but only parses string values that are clearly JSON objects or
213
+ * arrays (after trim, starts with `{` or `[`). Used for payload keys that are not declared on the
214
+ * schema's `properties` map so numerical strings are not coerced into numbers.
215
+ */
247
216
  function parseJSONStringsObjectContainersOnly(obj) {
248
- if (typeof obj === "string") {
249
- const trimmed = obj.trim();
250
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
251
- try {
252
- const parsed = JSON.parse(obj);
253
- return parseJSONStringsObjectContainersOnly(parsed);
254
- } catch {
255
- return obj;
256
- }
257
- }
258
- return obj;
259
- }
260
- if (Array.isArray(obj)) {
261
- return obj.map(parseJSONStringsObjectContainersOnly);
262
- }
263
- if (obj !== null && typeof obj === "object") {
264
- const out = {};
265
- for (const [k, v] of Object.entries(obj)) {
266
- out[k] = parseJSONStringsObjectContainersOnly(v);
267
- }
268
- return out;
269
- }
270
- return obj;
217
+ if (typeof obj === "string") {
218
+ const trimmed = obj.trim();
219
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
220
+ return parseJSONStringsObjectContainersOnly(JSON.parse(obj));
221
+ } catch {
222
+ return obj;
223
+ }
224
+ return obj;
225
+ }
226
+ if (Array.isArray(obj)) return obj.map(parseJSONStringsObjectContainersOnly);
227
+ if (obj !== null && typeof obj === "object") {
228
+ const out = {};
229
+ for (const [k, v] of Object.entries(obj)) out[k] = parseJSONStringsObjectContainersOnly(v);
230
+ return out;
231
+ }
232
+ return obj;
271
233
  }
272
234
  function getAdditionalPropertiesSchema(schema) {
273
- return schema.additionalProperties && typeof schema.additionalProperties === "object" ? schema.additionalProperties : void 0;
235
+ return schema.additionalProperties && typeof schema.additionalProperties === "object" ? schema.additionalProperties : void 0;
274
236
  }
275
237
  function mergePropertiesFromAllOf(allOf, api, seenRefs) {
276
- const merged = {};
277
- let found = false;
278
- for (const branch of allOf) {
279
- const collected = collectSchemaObjectProperties(branch, api, new Set(seenRefs));
280
- if (collected) {
281
- found = true;
282
- Object.assign(merged, collected);
283
- }
284
- }
285
- return found ? merged : void 0;
238
+ const merged = {};
239
+ let found = false;
240
+ for (const branch of allOf) {
241
+ const collected = collectSchemaObjectProperties(branch, api, new Set(seenRefs));
242
+ if (collected) {
243
+ found = true;
244
+ Object.assign(merged, collected);
245
+ }
246
+ }
247
+ return found ? merged : void 0;
286
248
  }
287
249
  function collectSchemaObjectProperties(schema, api, seenRefs) {
288
- let node = schema;
289
- if (isRef(node)) {
290
- if (seenRefs.has(node.$ref)) {
291
- return void 0;
292
- }
293
- seenRefs.add(node.$ref);
294
- const deref = dereferenceRef(node, api);
295
- if (!deref || isRef(deref)) {
296
- return void 0;
297
- }
298
- node = deref;
299
- }
300
- const safe = unwrapFirstPolymorphicBranch(node);
301
- if (isRef(safe)) {
302
- return collectSchemaObjectProperties(safe, api, seenRefs);
303
- }
304
- node = safe;
305
- if (node) {
306
- if ("allOf" in node && Array.isArray(node.allOf) && node.allOf.length) {
307
- return mergePropertiesFromAllOf(node.allOf, api, seenRefs);
308
- }
309
- if (node.properties && typeof node.properties === "object") {
310
- return node.properties;
311
- }
312
- }
313
- return void 0;
250
+ let node = schema;
251
+ if (isRef(node)) {
252
+ if (seenRefs.has(node.$ref)) return;
253
+ seenRefs.add(node.$ref);
254
+ const deref = dereferenceRef(node, api);
255
+ if (!deref || isRef(deref)) return;
256
+ node = deref;
257
+ }
258
+ const safe = unwrapFirstPolymorphicBranch(node);
259
+ if (isRef(safe)) return collectSchemaObjectProperties(safe, api, seenRefs);
260
+ node = safe;
261
+ if (node) {
262
+ if ("allOf" in node && Array.isArray(node.allOf) && node.allOf.length) return mergePropertiesFromAllOf(node.allOf, api, seenRefs);
263
+ if (node.properties && typeof node.properties === "object") return node.properties;
264
+ }
314
265
  }
315
266
  function getPayloadPropertyKeys(payload) {
316
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
317
- return [];
318
- }
319
- return Object.keys(payload).filter(
320
- (k) => typeof payload[k] !== "undefined"
321
- );
267
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return [];
268
+ return Object.keys(payload).filter((k) => typeof payload[k] !== "undefined");
322
269
  }
323
270
  function getPolymorphicSchema(node) {
324
- return node.oneOf && Array.isArray(node.oneOf) && node.oneOf.length ? node.oneOf : node.anyOf && Array.isArray(node.anyOf) && node.anyOf.length ? node.anyOf : null;
271
+ return node.oneOf && Array.isArray(node.oneOf) && node.oneOf.length ? node.oneOf : node.anyOf && Array.isArray(node.anyOf) && node.anyOf.length ? node.anyOf : null;
325
272
  }
273
+ /**
274
+ * Choose a single branch from a polymorphic schema that best matches the payload we have.
275
+ *
276
+ * A branch matches when every non-`undefined` payload key exists on that branch's merged object
277
+ * properties. If we have no payload, or no branches match, we use the first branch.
278
+ *
279
+ * When several branches match the one with the fewest declared properties wins, which would get us
280
+ * as close to a best match as possible, however having more data in our payload would give us more
281
+ * insight into which branch is what the user wants.
282
+ */
326
283
  function pickPolymorphicBranch(alternatives, keys, api) {
327
- if (!keys.length) {
328
- return alternatives[0];
329
- }
330
- const scored = alternatives.map((branch, idx) => {
331
- const props = collectSchemaObjectProperties(branch, api, /* @__PURE__ */ new Set());
332
- const allMatch = Boolean(props && keys.every((k) => Object.prototype.hasOwnProperty.call(props, k)));
333
- const propCount = props ? Object.keys(props).length : Number.POSITIVE_INFINITY;
334
- return { idx, branch, allMatch, propCount };
335
- });
336
- const matches = scored.filter((entry) => entry.allMatch);
337
- if (matches.length === 1) return matches[0].branch;
338
- if (matches.length > 1) {
339
- matches.sort((a, b) => a.propCount - b.propCount || a.idx - b.idx);
340
- return matches[0].branch;
341
- }
342
- return scored[0].branch;
284
+ if (!keys.length) return alternatives[0];
285
+ const scored = alternatives.map((branch, idx) => {
286
+ const props = collectSchemaObjectProperties(branch, api, /* @__PURE__ */ new Set());
287
+ return {
288
+ idx,
289
+ branch,
290
+ allMatch: Boolean(props && keys.every((k) => Object.prototype.hasOwnProperty.call(props, k))),
291
+ propCount: props ? Object.keys(props).length : Number.POSITIVE_INFINITY
292
+ };
293
+ });
294
+ const matches = scored.filter((entry) => entry.allMatch);
295
+ if (matches.length === 1) return matches[0].branch;
296
+ if (matches.length > 1) {
297
+ matches.sort((a, b) => a.propCount - b.propCount || a.idx - b.idx);
298
+ return matches[0].branch;
299
+ }
300
+ return scored[0].branch;
343
301
  }
302
+ /**
303
+ * Resolve a request-body JSON Schema against a concrete payload.
304
+ *
305
+ */
344
306
  function getSafeRequestBody(schema, payload, api) {
345
- let resolved = dereferenceRefDeep(schema, api);
346
- const keys = getPayloadPropertyKeys(payload);
347
- for (let alternatives = getPolymorphicSchema(resolved); alternatives != null; alternatives = getPolymorphicSchema(resolved)) {
348
- resolved = pickPolymorphicBranch(alternatives, keys, api);
349
- }
350
- if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
351
- const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, /* @__PURE__ */ new Set());
352
- if (fromAllOf && Object.keys(fromAllOf).length) {
353
- const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
354
- resolved = {
355
- ...resolved,
356
- type: "object",
357
- properties: { ...fromAllOf, ...existing }
358
- };
359
- }
360
- }
361
- return resolved;
307
+ let resolved = dereferenceRefDeep(schema, api);
308
+ const keys = getPayloadPropertyKeys(payload);
309
+ for (let alternatives = getPolymorphicSchema(resolved); alternatives != null; alternatives = getPolymorphicSchema(resolved)) resolved = pickPolymorphicBranch(alternatives, keys, api);
310
+ if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
311
+ const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, /* @__PURE__ */ new Set());
312
+ if (fromAllOf && Object.keys(fromAllOf).length) {
313
+ const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
314
+ resolved = {
315
+ ...resolved,
316
+ type: "object",
317
+ properties: {
318
+ ...fromAllOf,
319
+ ...existing
320
+ }
321
+ };
322
+ }
323
+ }
324
+ return resolved;
362
325
  }
326
+ /**
327
+ * Recursively runs through a schema, parsing any values that have `format: json` attached and
328
+ * deserializing them into their JSON representations.
329
+ *
330
+ * @see {@link parseJSONStrings}
331
+ */
363
332
  function parseJSONStringsInBodyWithSchema(obj, schema, api, seenRefs = /* @__PURE__ */ new Set()) {
364
- if (schema === void 0) return parseJSONStrings(obj);
365
- let resolved = schema;
366
- if (isRef(schema)) {
367
- if (seenRefs.has(schema.$ref)) {
368
- return parseJSONStrings(obj);
369
- }
370
- seenRefs.add(schema.$ref);
371
- const deref = dereferenceRef(schema, api);
372
- if (!deref || isRef(deref)) {
373
- return parseJSONStrings(obj);
374
- }
375
- resolved = deref;
376
- }
377
- const safe = getSafeRequestBody(resolved, obj, api);
378
- if (isRef(safe)) {
379
- return parseJSONStringsInBodyWithSchema(obj, safe, api, seenRefs);
380
- }
381
- resolved = safe;
382
- if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
383
- const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, new Set(seenRefs));
384
- if (fromAllOf && Object.keys(fromAllOf).length) {
385
- const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
386
- resolved = {
387
- ...resolved,
388
- type: "object",
389
- properties: { ...fromAllOf, ...existing }
390
- };
391
- }
392
- }
393
- if (typeof obj === "string") {
394
- if (hasSchemaType(resolved, "string") && resolved.format !== "json") {
395
- return obj;
396
- }
397
- return parseJSONStrings(obj);
398
- }
399
- if (Array.isArray(obj)) {
400
- let items = resolved.items;
401
- if (items && typeof items === "object" && isRef(items)) {
402
- if (seenRefs.has(items.$ref)) {
403
- return obj.map((item) => parseJSONStrings(item));
404
- }
405
- seenRefs.add(items.$ref);
406
- const derefItems = dereferenceRef(items, api);
407
- items = derefItems && !isRef(derefItems) ? derefItems : void 0;
408
- }
409
- return obj.map((item) => parseJSONStringsInBodyWithSchema(item, items, api, new Set(seenRefs)));
410
- }
411
- if (obj !== null && typeof obj === "object") {
412
- const additionalPropertiesSchema = getAdditionalPropertiesSchema(resolved);
413
- if (!resolved.properties || typeof resolved.properties !== "object") {
414
- if (additionalPropertiesSchema) {
415
- const out2 = {};
416
- for (const [k, v] of Object.entries(obj)) {
417
- out2[k] = parseJSONStringsInBodyWithSchema(v, additionalPropertiesSchema, api, new Set(seenRefs));
418
- }
419
- return out2;
420
- }
421
- return parseJSONStrings(obj);
422
- }
423
- const out = {};
424
- for (const [k, v] of Object.entries(obj)) {
425
- const propSchema = resolved.properties[k];
426
- const schemaForValue = propSchema ?? additionalPropertiesSchema;
427
- out[k] = schemaForValue !== void 0 ? parseJSONStringsInBodyWithSchema(v, schemaForValue, api, new Set(seenRefs)) : parseJSONStringsObjectContainersOnly(v);
428
- }
429
- return out;
430
- }
431
- return obj;
333
+ if (schema === void 0) return parseJSONStrings(obj);
334
+ let resolved = schema;
335
+ if (isRef(schema)) {
336
+ if (seenRefs.has(schema.$ref)) return parseJSONStrings(obj);
337
+ seenRefs.add(schema.$ref);
338
+ const deref = dereferenceRef(schema, api);
339
+ if (!deref || isRef(deref)) return parseJSONStrings(obj);
340
+ resolved = deref;
341
+ }
342
+ const safe = getSafeRequestBody(resolved, obj, api);
343
+ if (isRef(safe)) return parseJSONStringsInBodyWithSchema(obj, safe, api, seenRefs);
344
+ resolved = safe;
345
+ if ("allOf" in resolved && Array.isArray(resolved.allOf) && resolved.allOf.length) {
346
+ const fromAllOf = mergePropertiesFromAllOf(resolved.allOf, api, new Set(seenRefs));
347
+ if (fromAllOf && Object.keys(fromAllOf).length) {
348
+ const existing = resolved.properties && typeof resolved.properties === "object" && resolved.properties !== null ? resolved.properties : {};
349
+ resolved = {
350
+ ...resolved,
351
+ type: "object",
352
+ properties: {
353
+ ...fromAllOf,
354
+ ...existing
355
+ }
356
+ };
357
+ }
358
+ }
359
+ if (typeof obj === "string") {
360
+ if (hasSchemaType(resolved, "string") && resolved.format !== "json") return obj;
361
+ return parseJSONStrings(obj);
362
+ }
363
+ if (Array.isArray(obj)) {
364
+ let items = resolved.items;
365
+ if (items && typeof items === "object" && isRef(items)) {
366
+ if (seenRefs.has(items.$ref)) return obj.map((item) => parseJSONStrings(item));
367
+ seenRefs.add(items.$ref);
368
+ const derefItems = dereferenceRef(items, api);
369
+ items = derefItems && !isRef(derefItems) ? derefItems : void 0;
370
+ }
371
+ return obj.map((item) => parseJSONStringsInBodyWithSchema(item, items, api, new Set(seenRefs)));
372
+ }
373
+ if (obj !== null && typeof obj === "object") {
374
+ const additionalPropertiesSchema = getAdditionalPropertiesSchema(resolved);
375
+ if (!resolved.properties || typeof resolved.properties !== "object") {
376
+ if (additionalPropertiesSchema) {
377
+ const out = {};
378
+ for (const [k, v] of Object.entries(obj)) out[k] = parseJSONStringsInBodyWithSchema(v, additionalPropertiesSchema, api, new Set(seenRefs));
379
+ return out;
380
+ }
381
+ return parseJSONStrings(obj);
382
+ }
383
+ const out = {};
384
+ for (const [k, v] of Object.entries(obj)) {
385
+ const schemaForValue = resolved.properties[k] ?? additionalPropertiesSchema;
386
+ out[k] = schemaForValue !== void 0 ? parseJSONStringsInBodyWithSchema(v, schemaForValue, api, new Set(seenRefs)) : parseJSONStringsObjectContainersOnly(v);
387
+ }
388
+ return out;
389
+ }
390
+ return obj;
432
391
  }
433
392
 
434
393
  // src/lib/style-formatting/style-serializer.ts
435
- var isRfc3986Reserved = (char) => ":/?#[]@!$&'()*+,;=".indexOf(char) > -1;
436
- var isRfc3986Unreserved = (char) => /^[a-z0-9\-._~]+$/i.test(char);
394
+ /**
395
+ * This file has been extracted and modified from `swagger-client`.
396
+ *
397
+ * @license Apache 2.0
398
+ * @link https://npm.im/swagger-client
399
+ * @link https://github.com/swagger-api/swagger-js/blob/master/src/execute/oas3/style-serializer.js
400
+ */
401
+ const isRfc3986Reserved = (char) => ":/?#[]@!$&'()*+,;=".indexOf(char) > -1;
402
+ const isRfc3986Unreserved = (char) => /^[a-z0-9\-._~]+$/i.test(char);
437
403
  function isURIEncoded(value) {
438
- try {
439
- return decodeURIComponent(value) !== value;
440
- } catch {
441
- return false;
442
- }
404
+ try {
405
+ return decodeURIComponent(value) !== value;
406
+ } catch {
407
+ return false;
408
+ }
443
409
  }
444
410
  function isObject(value) {
445
- return typeof value === "object" && value !== null;
411
+ return typeof value === "object" && value !== null;
446
412
  }
447
- function encodeDisallowedCharacters(str, {
448
- escape,
449
- returnIfEncoded = false,
450
- isAllowedReserved
451
- } = {}, parse) {
452
- if (typeof str === "number") {
453
- str = str.toString();
454
- }
455
- if (returnIfEncoded) {
456
- if (isURIEncoded(str)) {
457
- return str;
458
- }
459
- }
460
- if (typeof str !== "string" || !str.length) {
461
- return str;
462
- }
463
- if (!escape) {
464
- return str;
465
- }
466
- if (parse) {
467
- return JSON.parse(str);
468
- }
469
- return [...str].map((char) => {
470
- if (isRfc3986Unreserved(char)) {
471
- return char;
472
- }
473
- if (isRfc3986Reserved(char) && (escape === "unsafe" || isAllowedReserved)) {
474
- return char;
475
- }
476
- const encoder = new TextEncoder();
477
- const encoded = Array.from(encoder.encode(char)).map((byte) => `0${byte.toString(16).toUpperCase()}`.slice(-2)).map((encodedByte) => `%${encodedByte}`).join("");
478
- return encoded;
479
- }).join("");
413
+ function encodeDisallowedCharacters(str, { escape, returnIfEncoded = false, isAllowedReserved } = {}, parse) {
414
+ if (typeof str === "number") str = str.toString();
415
+ if (returnIfEncoded) {
416
+ if (isURIEncoded(str)) return str;
417
+ }
418
+ if (typeof str !== "string" || !str.length) return str;
419
+ if (!escape) return str;
420
+ if (parse) return JSON.parse(str);
421
+ return [...str].map((char) => {
422
+ if (isRfc3986Unreserved(char)) return char;
423
+ if (isRfc3986Reserved(char) && (escape === "unsafe" || isAllowedReserved)) return char;
424
+ const encoder = new TextEncoder();
425
+ return Array.from(encoder.encode(char)).map((byte) => `0${byte.toString(16).toUpperCase()}`.slice(-2)).map((encodedByte) => `%${encodedByte}`).join("");
426
+ }).join("");
480
427
  }
481
428
  function stylize(config) {
482
- const { value } = config;
483
- if (Array.isArray(value)) {
484
- return encodeArray(config);
485
- }
486
- if (isObject(value)) {
487
- return encodeObject(config);
488
- }
489
- return encodePrimitive(config);
429
+ const { value } = config;
430
+ if (Array.isArray(value)) return encodeArray(config);
431
+ if (isObject(value)) return encodeObject(config);
432
+ return encodePrimitive(config);
490
433
  }
491
- function encodeArray({
492
- location,
493
- key,
494
- value,
495
- style,
496
- explode,
497
- escape,
498
- isAllowedReserved = false
499
- }) {
500
- const valueEncoder = (str) => {
501
- if (str === null) {
502
- return "null";
503
- }
504
- const result = encodeDisallowedCharacters(str, {
505
- escape,
506
- returnIfEncoded: location === "query",
507
- isAllowedReserved
508
- });
509
- return result;
510
- };
511
- switch (style) {
512
- /**
513
- * @example <caption>`style: simple`</caption>
514
- * `["blue","black","brown"]` → `blue,black,brown`
515
- */
516
- case "simple":
517
- return value.map((val) => valueEncoder(val)).join(",");
518
- /**
519
- * @example <caption>`style: label`</caption>
520
- * `["blue","black","brown"]` → `.blue.black.brown`
521
- */
522
- case "label":
523
- return `.${value.map((val) => valueEncoder(val)).join(".")}`;
524
- /**
525
- * @example <caption>`style: matrix` + `explode: true`</caption>
526
- * `["blue","black","brown"]` → `;color=blue;color=black;color=brown`
527
- *
528
- * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
529
- * `["blue","black","brown"]` → `;color=blue,black,brown `
530
- */
531
- case "matrix":
532
- return value.map((val) => valueEncoder(val)).reduce((prev, curr) => {
533
- if (!prev || explode) {
534
- return `${prev || ""};${key}=${curr}`;
535
- }
536
- return `${prev},${curr}`;
537
- }, "");
538
- /**
539
- * @example <caption>`style: form` + `explode: true`</caption>
540
- * `["blue","black","brown"]` → `color=blue&color=black&color=brown`
541
- *
542
- * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
543
- * `["blue","black","brown"]` → `color=blue,black,brown`
544
- */
545
- case "form":
546
- return value.map((val) => valueEncoder(val)).join(explode ? `&${key}=` : ",");
547
- /**
548
- * @example <caption>`style: spaceDelimited`</caption>
549
- * `["blue","black","brown"]` → `blue%20black%20brown`
550
- */
551
- case "spaceDelimited":
552
- return value.map((val) => valueEncoder(val)).join(` ${explode ? `${key}=` : ""}`);
553
- /**
554
- * @example <caption>`style: pipeDelimited`</caption>
555
- * `["blue","black","brown"]` → `blue|black|brown`
556
- */
557
- case "pipeDelimited":
558
- return value.map((val) => valueEncoder(val)).join(`|${explode ? `${key}=` : ""}`);
559
- default:
560
- }
434
+ /**
435
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#style-examples}
436
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#style-examples}
437
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#style-examples}
438
+ */
439
+ function encodeArray({ location, key, value, style, explode, escape, isAllowedReserved = false }) {
440
+ const valueEncoder = (str) => {
441
+ if (str === null) return "null";
442
+ return encodeDisallowedCharacters(str, {
443
+ escape,
444
+ returnIfEncoded: location === "query",
445
+ isAllowedReserved
446
+ });
447
+ };
448
+ switch (style) {
449
+ /**
450
+ * @example <caption>`style: simple`</caption>
451
+ * `["blue","black","brown"]` → `blue,black,brown`
452
+ */
453
+ case "simple": return value.map((val) => valueEncoder(val)).join(",");
454
+ /**
455
+ * @example <caption>`style: label`</caption>
456
+ * `["blue","black","brown"]` → `.blue.black.brown`
457
+ */
458
+ case "label": return `.${value.map((val) => valueEncoder(val)).join(".")}`;
459
+ /**
460
+ * @example <caption>`style: matrix` + `explode: true`</caption>
461
+ * `["blue","black","brown"]` → `;color=blue;color=black;color=brown`
462
+ *
463
+ * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
464
+ * `["blue","black","brown"]` → `;color=blue,black,brown `
465
+ */
466
+ case "matrix": return value.map((val) => valueEncoder(val)).reduce((prev, curr) => {
467
+ if (!prev || explode) return `${prev || ""};${key}=${curr}`;
468
+ return `${prev},${curr}`;
469
+ }, "");
470
+ /**
471
+ * @example <caption>`style: form` + `explode: true`</caption>
472
+ * `["blue","black","brown"]` → `color=blue&color=black&color=brown`
473
+ *
474
+ * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
475
+ * `["blue","black","brown"]` → `color=blue,black,brown`
476
+ */
477
+ case "form": return value.map((val) => valueEncoder(val)).join(explode ? `&${key}=` : ",");
478
+ /**
479
+ * @example <caption>`style: spaceDelimited`</caption>
480
+ * `["blue","black","brown"]` → `blue%20black%20brown`
481
+ */
482
+ case "spaceDelimited": return value.map((val) => valueEncoder(val)).join(` ${explode ? `${key}=` : ""}`);
483
+ /**
484
+ * @example <caption>`style: pipeDelimited`</caption>
485
+ * `["blue","black","brown"]` → `blue|black|brown`
486
+ */
487
+ case "pipeDelimited": return value.map((val) => valueEncoder(val)).join(`|${explode ? `${key}=` : ""}`);
488
+ }
561
489
  }
490
+ /**
491
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#style-examples}
492
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#style-examples}
493
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#style-examples}
494
+ */
562
495
  function encodeObject({ location, key, value, style, explode, escape, isAllowedReserved = false }) {
563
- const valueEncoder = (str) => encodeDisallowedCharacters(str, {
564
- escape,
565
- returnIfEncoded: location === "query",
566
- isAllowedReserved
567
- });
568
- const valueKeys = Object.keys(value);
569
- switch (style) {
570
- /**
571
- * @example <caption>`style: simple` + `explode: true`</caption>
572
- * `{ "R": 100, "G": 200, "B": 150 }` → `R=100,G=200,B=150`
573
- *
574
- * @example <caption>`style: simple` + `explode: false` (the default behavior)</caption>
575
- * `{ "R": 100, "G": 200, "B": 150 }` → `R,100,G,200,B,150`
576
- */
577
- case "simple":
578
- return valueKeys.reduce((prev, curr) => {
579
- const val = valueEncoder(value[curr]);
580
- const middleChar = explode ? "=" : ",";
581
- const prefix = prev ? `${prev},` : "";
582
- return `${prefix}${curr}${middleChar}${val}`;
583
- }, "");
584
- /**
585
- * @example <caption>`style: label` + `explode: true`</caption>
586
- * `{ "R": 100, "G": 200, "B": 150 }` → `.R=100.G=200.B=150`
587
- *
588
- * @example <caption>`style: label` + `explode: false` (the default behavior)</caption>
589
- * `{ "R": 100, "G": 200, "B": 150 }` → `.R.100.G.200.B.150`
590
- */
591
- case "label":
592
- return valueKeys.reduce((prev, curr) => {
593
- const val = valueEncoder(value[curr]);
594
- const middleChar = explode ? "=" : ".";
595
- const prefix = prev ? `${prev}.` : ".";
596
- return `${prefix}${curr}${middleChar}${val}`;
597
- }, "");
598
- /**
599
- * @example <caption>`style: matrix` + `explode: true`</caption>
600
- * `{ "R": 100, "G": 200, "B": 150 }` → `;R=100;G=200;B=150`
601
- *
602
- * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
603
- * `{ "R": 100, "G": 200, "B": 150 }` → `;color=R,100,G,200,B,150`
604
- */
605
- case "matrix":
606
- if (explode) {
607
- return valueKeys.reduce((prev, curr) => {
608
- const val = valueEncoder(value[curr]);
609
- const prefix = prev ? `${prev};` : ";";
610
- return `${prefix}${curr}=${val}`;
611
- }, "");
612
- }
613
- return valueKeys.reduce((prev, curr) => {
614
- const val = valueEncoder(value[curr]);
615
- const prefix = prev ? `${prev},` : `;${key}=`;
616
- return `${prefix}${curr},${val}`;
617
- }, "");
618
- /**
619
- * @example <caption>`style: form` + `explode: true`</caption>
620
- * `{ "R": 100, "G": 200, "B": 150 }` → `R=100&G=200&B=150`
621
- *
622
- * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
623
- * `{ "R": 100, "G": 200, "B": 150 }` → `color=R,100,G,200,B,150`
624
- */
625
- case "form":
626
- return valueKeys.reduce((prev, curr) => {
627
- const val = valueEncoder(value[curr]);
628
- const prefix = prev ? `${prev}${explode ? "&" : ","}` : "";
629
- const separator = explode ? "=" : ",";
630
- return `${prefix}${curr}${separator}${val}`;
631
- }, "");
632
- /**
633
- * @example <caption>`style: spaceDelimited`</caption>
634
- * `{ "R": 100, "G": 200, "B": 150 }` → `R%20100%20G%20200%20B%20150`
635
- */
636
- case "spaceDelimited":
637
- return valueKeys.reduce((prev, curr) => {
638
- const val = valueEncoder(value[curr]);
639
- const prefix = prev ? `${prev} ` : "";
640
- return `${prefix}${curr} ${val}`;
641
- }, "");
642
- /**
643
- * @example <caption>`style: pipeDelimited`</caption>
644
- * `{ "R": 100, "G": 200, "B": 150 }` → `R|100|G|200|B|150`
645
- */
646
- case "pipeDelimited":
647
- return valueKeys.reduce((prev, curr) => {
648
- const val = valueEncoder(value[curr]);
649
- const prefix = prev ? `${prev}|` : "";
650
- return `${prefix}${curr}|${val}`;
651
- }, "");
652
- /**
653
- * @example <caption>`style: deepObject`</caption>
654
- * `{ "R": 100, "G": 200, "B": 150 }` → `color[R]=100&color[G]=200&color[B]=150`
655
- */
656
- case "deepObject":
657
- return valueKeys.reduce((curr) => {
658
- const val = valueEncoder(value[curr]);
659
- return `${val}`;
660
- }, "");
661
- default:
662
- }
496
+ const valueEncoder = (str) => encodeDisallowedCharacters(str, {
497
+ escape,
498
+ returnIfEncoded: location === "query",
499
+ isAllowedReserved
500
+ });
501
+ const valueKeys = Object.keys(value);
502
+ switch (style) {
503
+ /**
504
+ * @example <caption>`style: simple` + `explode: true`</caption>
505
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R=100,G=200,B=150`
506
+ *
507
+ * @example <caption>`style: simple` + `explode: false` (the default behavior)</caption>
508
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R,100,G,200,B,150`
509
+ */
510
+ case "simple": return valueKeys.reduce((prev, curr) => {
511
+ const val = valueEncoder(value[curr]);
512
+ const middleChar = explode ? "=" : ",";
513
+ return `${prev ? `${prev},` : ""}${curr}${middleChar}${val}`;
514
+ }, "");
515
+ /**
516
+ * @example <caption>`style: label` + `explode: true`</caption>
517
+ * `{ "R": 100, "G": 200, "B": 150 }` → `.R=100.G=200.B=150`
518
+ *
519
+ * @example <caption>`style: label` + `explode: false` (the default behavior)</caption>
520
+ * `{ "R": 100, "G": 200, "B": 150 }` → `.R.100.G.200.B.150`
521
+ */
522
+ case "label": return valueKeys.reduce((prev, curr) => {
523
+ const val = valueEncoder(value[curr]);
524
+ const middleChar = explode ? "=" : ".";
525
+ return `${prev ? `${prev}.` : "."}${curr}${middleChar}${val}`;
526
+ }, "");
527
+ /**
528
+ * @example <caption>`style: matrix` + `explode: true`</caption>
529
+ * `{ "R": 100, "G": 200, "B": 150 }` → `;R=100;G=200;B=150`
530
+ *
531
+ * @example <caption>`style: matrix` + `explode: false` (the default behavior)</caption>
532
+ * `{ "R": 100, "G": 200, "B": 150 }` → `;color=R,100,G,200,B,150`
533
+ */
534
+ case "matrix":
535
+ if (explode) return valueKeys.reduce((prev, curr) => {
536
+ const val = valueEncoder(value[curr]);
537
+ return `${prev ? `${prev};` : ";"}${curr}=${val}`;
538
+ }, "");
539
+ return valueKeys.reduce((prev, curr) => {
540
+ const val = valueEncoder(value[curr]);
541
+ return `${prev ? `${prev},` : `;${key}=`}${curr},${val}`;
542
+ }, "");
543
+ /**
544
+ * @example <caption>`style: form` + `explode: true`</caption>
545
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R=100&G=200&B=150`
546
+ *
547
+ * @example <caption>`style: form` + `explode: false` (the default behavior)</caption>
548
+ * `{ "R": 100, "G": 200, "B": 150 }` → `color=R,100,G,200,B,150`
549
+ */
550
+ case "form": return valueKeys.reduce((prev, curr) => {
551
+ const val = valueEncoder(value[curr]);
552
+ return `${prev ? `${prev}${explode ? "&" : ","}` : ""}${curr}${explode ? "=" : ","}${val}`;
553
+ }, "");
554
+ /**
555
+ * @example <caption>`style: spaceDelimited`</caption>
556
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R%20100%20G%20200%20B%20150`
557
+ */
558
+ case "spaceDelimited": return valueKeys.reduce((prev, curr) => {
559
+ const val = valueEncoder(value[curr]);
560
+ return `${prev ? `${prev} ` : ""}${curr} ${val}`;
561
+ }, "");
562
+ /**
563
+ * @example <caption>`style: pipeDelimited`</caption>
564
+ * `{ "R": 100, "G": 200, "B": 150 }` → `R|100|G|200|B|150`
565
+ */
566
+ case "pipeDelimited": return valueKeys.reduce((prev, curr) => {
567
+ const val = valueEncoder(value[curr]);
568
+ return `${prev ? `${prev}|` : ""}${curr}|${val}`;
569
+ }, "");
570
+ /**
571
+ * @example <caption>`style: deepObject`</caption>
572
+ * `{ "R": 100, "G": 200, "B": 150 }` → `color[R]=100&color[G]=200&color[B]=150`
573
+ */
574
+ case "deepObject": return valueKeys.reduce((curr) => {
575
+ return `${valueEncoder(value[curr])}`;
576
+ }, "");
577
+ }
663
578
  }
579
+ /**
580
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#style-examples}
581
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#style-examples}
582
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#style-examples}
583
+ */
664
584
  function encodePrimitive({ location, key, value, style, escape, isAllowedReserved = false }) {
665
- const valueEncoder = (str) => encodeDisallowedCharacters(str, {
666
- escape,
667
- returnIfEncoded: location === "query" || location === "body",
668
- isAllowedReserved
669
- });
670
- switch (style) {
671
- /**
672
- * @example <caption>`style: simple`</caption>
673
- * `blue` → `blue`
674
- */
675
- case "simple":
676
- return valueEncoder(value);
677
- /**
678
- * @example <caption>`style: label`</caption>
679
- * `blue` → `.blue`
680
- */
681
- case "label":
682
- return `.${valueEncoder(value)}`;
683
- /**
684
- * @example <caption>`style: matrix`</caption>
685
- * `blue` → `;color=blue`
686
- */
687
- case "matrix":
688
- if (value === "") {
689
- return `;${key}`;
690
- }
691
- return `;${key}=${valueEncoder(value)}`;
692
- /**
693
- * @example <caption>`style: form`</caption>
694
- * `blue` → `color=blue`
695
- */
696
- case "form":
697
- return valueEncoder(value);
698
- /**
699
- * @example <caption>`style: deepObject`</caption>
700
- * `blue` → n/a
701
- */
702
- case "deepObject":
703
- return valueEncoder(value);
704
- default:
705
- }
585
+ const valueEncoder = (str) => encodeDisallowedCharacters(str, {
586
+ escape,
587
+ returnIfEncoded: location === "query" || location === "body",
588
+ isAllowedReserved
589
+ });
590
+ switch (style) {
591
+ /**
592
+ * @example <caption>`style: simple`</caption>
593
+ * `blue` → `blue`
594
+ */
595
+ case "simple": return valueEncoder(value);
596
+ /**
597
+ * @example <caption>`style: label`</caption>
598
+ * `blue` → `.blue`
599
+ */
600
+ case "label": return `.${valueEncoder(value)}`;
601
+ /**
602
+ * @example <caption>`style: matrix`</caption>
603
+ * `blue` → `;color=blue`
604
+ */
605
+ case "matrix":
606
+ if (value === "") return `;${key}`;
607
+ return `;${key}=${valueEncoder(value)}`;
608
+ /**
609
+ * @example <caption>`style: form`</caption>
610
+ * `blue` → `color=blue`
611
+ */
612
+ case "form": return valueEncoder(value);
613
+ /**
614
+ * @example <caption>`style: deepObject`</caption>
615
+ * `blue` → n/a
616
+ */
617
+ case "deepObject": return valueEncoder(value);
618
+ }
706
619
  }
707
620
 
708
621
  // src/lib/style-formatting/index.ts
709
622
  function shouldNotStyleEmptyValues(parameter) {
710
- return ["simple", "spaceDelimited", "pipeDelimited", "deepObject"].includes(parameter.style || "");
623
+ return [
624
+ "simple",
625
+ "spaceDelimited",
626
+ "pipeDelimited",
627
+ "deepObject"
628
+ ].includes(parameter.style || "");
711
629
  }
712
630
  function shouldNotStyleReservedHeader(parameter) {
713
- return ["accept", "authorization", "content-type"].includes(parameter.name.toLowerCase());
631
+ return [
632
+ "accept",
633
+ "authorization",
634
+ "content-type"
635
+ ].includes(parameter.name.toLowerCase());
714
636
  }
637
+ /**
638
+ * Note: This isn't necessarily part of the spec. Behavior for the value 'undefined' is, well,
639
+ * undefined. This code makes our system look better. If we wanted to be more accurate, we might
640
+ * want to remove this, restore the un-fixed behavior for undefined and have our UI pass in empty
641
+ * string instead of undefined.
642
+ */
715
643
  function removeUndefinedForPath(value) {
716
- let finalValue = value;
717
- if (typeof finalValue === "undefined") {
718
- return "";
719
- }
720
- if (Array.isArray(finalValue)) {
721
- finalValue = finalValue.filter((val) => val === void 0 ? "" : val);
722
- if (finalValue.length === 0) {
723
- finalValue = "";
724
- }
725
- }
726
- if (typeof finalValue === "object") {
727
- Object.keys(finalValue).forEach((key) => {
728
- finalValue[key] = finalValue[key] === void 0 ? "" : finalValue[key];
729
- });
730
- }
731
- return finalValue;
644
+ let finalValue = value;
645
+ if (typeof finalValue === "undefined") return "";
646
+ if (Array.isArray(finalValue)) {
647
+ finalValue = finalValue.filter((val) => val !== void 0);
648
+ if (finalValue.length === 0) finalValue = "";
649
+ }
650
+ if (typeof finalValue === "object") Object.keys(finalValue).forEach((key) => {
651
+ finalValue[key] = finalValue[key] === void 0 ? "" : finalValue[key];
652
+ });
653
+ return finalValue;
732
654
  }
733
655
  function stylizeValue(value, parameter) {
734
- let finalValue = value;
735
- if (shouldNotStyleEmptyValues(parameter) && (typeof finalValue === "undefined" || finalValue === "")) {
736
- if (parameter.in === "path") {
737
- return "";
738
- }
739
- return;
740
- }
741
- if (parameter.in === "path") {
742
- finalValue = removeUndefinedForPath(finalValue);
743
- }
744
- if (parameter.in === "header" && shouldNotStyleReservedHeader(parameter)) {
745
- return value;
746
- }
747
- if (parameter.content && (parameter.in === "query" || parameter.in === "header")) {
748
- const contentType = getParameterContentType(parameter);
749
- if (!contentType) {
750
- return;
751
- }
752
- let serialized;
753
- if (matchesMimeType.json(contentType)) {
754
- serialized = JSON.stringify(value);
755
- } else {
756
- serialized = String(value);
757
- }
758
- return parameter.in === "query" ? encodeURIComponent(serialized) : serialized;
759
- }
760
- let style = parameter.style;
761
- if (!style) {
762
- if (parameter.in === "query") {
763
- style = "form";
764
- } else if (parameter.in === "path") {
765
- style = "simple";
766
- } else if (parameter.in === "header") {
767
- style = "simple";
768
- } else if (parameter.in === "cookie") {
769
- style = "form";
770
- }
771
- }
772
- let explode = parameter.explode;
773
- if (explode === void 0 && style === "form") {
774
- explode = true;
775
- }
776
- return stylize({
777
- location: parameter.in,
778
- value: finalValue,
779
- key: parameter.name,
780
- style,
781
- explode,
782
- /**
783
- * @todo this parameter is optional to stylize. It defaults to false, and can accept falsy, truthy, or "unsafe".
784
- * I do not know if it is correct for query to use this. See style-serializer for more info
785
- */
786
- escape: true,
787
- ...parameter.in === "query" ? { isAllowedReserved: parameter.allowReserved || false } : {}
788
- });
656
+ let finalValue = value;
657
+ if (shouldNotStyleEmptyValues(parameter) && (typeof finalValue === "undefined" || finalValue === "")) {
658
+ if (parameter.in === "path") return "";
659
+ return;
660
+ }
661
+ if (parameter.in === "path") finalValue = removeUndefinedForPath(finalValue);
662
+ /**
663
+ * Eventhough `accept`, `authorization`, and `content-type` headers can be defined as parameters,
664
+ * they should be completely ignored when it comes to serialization.
665
+ *
666
+ * > If `in` is "header" and the `name` field is "Accept", "Content-Type" or "Authorization", the
667
+ * > parameter definition SHALL be ignored.
668
+ *
669
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#fixed-fields-10}
670
+ */
671
+ if (parameter.in === "header" && shouldNotStyleReservedHeader(parameter)) return value;
672
+ /**
673
+ * If content is present, we should use the content type to format the value. We also ignore the style and explode settings.
674
+ *
675
+ * @see {@link https://swagger.io/docs/specification/v3_0/describing-parameters/#schema-vs-content}
676
+ */
677
+ if (parameter.content && (parameter.in === "query" || parameter.in === "header")) {
678
+ const contentType = getParameterContentType$1(parameter);
679
+ if (!contentType) return;
680
+ /**
681
+ * @todo Handle other content types
682
+ */
683
+ let serialized;
684
+ if (matchesMimeType.json(contentType)) serialized = JSON.stringify(value);
685
+ else serialized = String(value);
686
+ return parameter.in === "query" ? encodeURIComponent(serialized) : serialized;
687
+ }
688
+ /**
689
+ * All parameter types have a default `style` format so if they don't have one prescribed we
690
+ * should still conform to what the spec defines.
691
+ *
692
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#parameterStyle}
693
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#parameterStyle}
694
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#parameter-style}
695
+ */
696
+ let style = parameter.style;
697
+ if (!style) {
698
+ if (parameter.in === "query") style = "form";
699
+ else if (parameter.in === "path") style = "simple";
700
+ else if (parameter.in === "header") style = "simple";
701
+ else if (parameter.in === "cookie") style = "form";
702
+ }
703
+ let explode = parameter.explode;
704
+ if (explode === void 0 && style === "form")
705
+ /**
706
+ * Per the spec if no `explode` is present but `style` is `form` then `explode` should default to `true`.
707
+ *
708
+ * @see {@link https://spec.openapis.org/oas/v3.0.0.html#parameterExplode}
709
+ * @see {@link https://spec.openapis.org/oas/v3.1.0.html#parameterExplode}
710
+ * @see {@link https://spec.openapis.org/oas/v3.2.0.html#parameter-explode}
711
+ */
712
+ explode = true;
713
+ return stylize({
714
+ location: parameter.in,
715
+ value: finalValue,
716
+ key: parameter.name,
717
+ style,
718
+ explode,
719
+ /**
720
+ * @todo this parameter is optional to stylize. It defaults to false, and can accept falsy, truthy, or "unsafe".
721
+ * I do not know if it is correct for query to use this. See style-serializer for more info
722
+ */
723
+ escape: true,
724
+ ...parameter.in === "query" ? { isAllowedReserved: parameter.allowReserved || false } : {}
725
+ });
789
726
  }
790
727
  function handleDeepObject(value, parameter) {
791
- return qs.stringify(value, {
792
- encoder(str, defaultEncoder, charset, type) {
793
- if (type === "key") {
794
- const prefixedKey = str.split(/[[\]]/g).filter(Boolean).map((k) => `[${k}]`).join("");
795
- return `${parameter.name}${prefixedKey}`;
796
- } else if (type === "value") {
797
- return stylizeValue(str, parameter);
798
- }
799
- }
800
- }).split("&").map((item) => {
801
- const split = item.split("=");
802
- return {
803
- label: split[0],
804
- // `qs` will coerce null values into being `undefined` string but we want to preserve them.
805
- value: split[1] === "undefined" ? null : split[1]
806
- };
807
- });
728
+ return qs.stringify(value, { encoder(str, defaultEncoder, charset, type) {
729
+ if (type === "key") {
730
+ const prefixedKey = str.split(/[[\]]/g).filter(Boolean).map((k) => `[${k}]`).join("");
731
+ return `${parameter.name}${prefixedKey}`;
732
+ } else if (type === "value") return stylizeValue(str, parameter);
733
+ } }).split("&").map((item) => {
734
+ const split = item.split("=");
735
+ return {
736
+ label: split[0],
737
+ value: split[1] === "undefined" ? null : split[1]
738
+ };
739
+ });
808
740
  }
809
741
  function handleExplode(value, parameter) {
810
- if (Array.isArray(value) && parameter.schema?.type === "array" && parameter.style === "deepObject") {
811
- const newObj = {};
812
- const deepObjs = handleDeepObject(value, parameter);
813
- deepObjs.forEach((obj) => {
814
- newObj[obj.label] = obj.value;
815
- });
816
- return newObj;
817
- }
818
- if (Array.isArray(value)) {
819
- return value.map((val) => {
820
- return stylizeValue(val, parameter);
821
- });
822
- }
823
- if (typeof value === "object" && value !== null) {
824
- const newObj = {};
825
- Object.keys(value).forEach((key) => {
826
- if (parameter.style === "deepObject") {
827
- const deepObjs = handleDeepObject(value, parameter);
828
- deepObjs.forEach((obj) => {
829
- newObj[obj.label] = obj.value;
830
- });
831
- } else {
832
- newObj[key] = stylizeValue(value[key], parameter);
833
- }
834
- });
835
- return newObj;
836
- }
837
- return stylizeValue(value, parameter);
742
+ if (Array.isArray(value) && parameter.schema && typeof parameter.schema === "object" && !isRef(parameter.schema) && parameter.schema.type === "array" && parameter.style === "deepObject") {
743
+ const newObj = {};
744
+ handleDeepObject(value, parameter).forEach((obj) => {
745
+ newObj[obj.label] = obj.value;
746
+ });
747
+ return newObj;
748
+ }
749
+ if (Array.isArray(value)) return value.map((val) => {
750
+ return stylizeValue(val, parameter);
751
+ });
752
+ if (typeof value === "object" && value !== null) {
753
+ const newObj = {};
754
+ Object.keys(value).forEach((key) => {
755
+ if (parameter.style === "deepObject") handleDeepObject(value, parameter).forEach((obj) => {
756
+ newObj[obj.label] = obj.value;
757
+ });
758
+ else newObj[key] = stylizeValue(value[key], parameter);
759
+ });
760
+ return newObj;
761
+ }
762
+ return stylizeValue(value, parameter);
838
763
  }
839
764
  function shouldExplode(parameter) {
840
- return (parameter.explode || parameter.explode !== false && parameter.style === "form" || // style: deepObject && explode: false doesn't exist so explode it always
841
- // https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples
842
- parameter.style === "deepObject") && // header and path doesn't explode into separate parameters like query and cookie do
843
- parameter.in !== "header" && parameter.in !== "path" && !parameter.content;
765
+ return (parameter.explode || parameter.explode !== false && parameter.style === "form" || parameter.style === "deepObject") && parameter.in !== "header" && parameter.in !== "path" && !parameter.content;
844
766
  }
845
767
  function formatStyle(value, parameter) {
846
- if (!parameter.content && parameter.style === "deepObject" && (!value || typeof value !== "object" || parameter.explode === false)) {
847
- return void 0;
848
- }
849
- if (shouldExplode(parameter)) {
850
- return handleExplode(value, parameter);
851
- }
852
- return stylizeValue(value, parameter);
768
+ if (!parameter.content && parameter.style === "deepObject" && (!value || typeof value !== "object" || parameter.explode === false)) return;
769
+ if (shouldExplode(parameter)) return handleExplode(value, parameter);
770
+ return stylizeValue(value, parameter);
853
771
  }
854
772
 
855
773
  // src/index.ts
774
+ /**
775
+ * Retrieves the value for a given parameter out of the bucket of values for its `in` type (e.g.
776
+ * `values.header`).
777
+ *
778
+ * HTTP header names are case-insensitive, but incoming header values (e.g. as normalized by
779
+ * `api/core`) are often lowercased while the OAS document defining the header parameter may use
780
+ * any casing (e.g. `X-Customer-Code`). So for headers we fall back to a case-insensitive lookup
781
+ * if there wasn't an exact match on the parameter name.
782
+ */
856
783
  function getParamValue(values, param, type) {
857
- const bucket = values[type];
858
- if (bucket && typeof bucket === "object" && !(param.name in bucket) && type === "header") {
859
- const matchedKey = Object.keys(bucket).find((key) => key.toLowerCase() === param.name.toLowerCase());
860
- if (matchedKey !== void 0) {
861
- return bucket[matchedKey];
862
- }
863
- }
864
- return bucket?.[param.name];
784
+ const bucket = values[type];
785
+ if (bucket && typeof bucket === "object" && !(param.name in bucket) && type === "header") {
786
+ const matchedKey = Object.keys(bucket).find((key) => key.toLowerCase() === param.name.toLowerCase());
787
+ if (matchedKey !== void 0) return bucket[matchedKey];
788
+ }
789
+ return bucket?.[param.name];
865
790
  }
866
791
  function formatter(values, param, type, onlyIfExists = false, api) {
867
- if (param.style) {
868
- const value2 = getParamValue(values, param, type);
869
- return formatStyle(value2, param);
870
- }
871
- let value;
872
- if (typeof getParamValue(values, param, type) !== "undefined") {
873
- value = getParamValue(values, param, type);
874
- } else if (onlyIfExists && !param.required) {
875
- value = void 0;
876
- } else if (param.required && param.schema) {
877
- const schema = isRef2(param.schema) ? dereferenceRef2(param.schema, api) : param.schema;
878
- if (schema && !isRef2(schema) && schema.default) {
879
- value = schema.default;
880
- } else if (param.content) {
881
- const contentType = getParameterContentType(param);
882
- const contentSchema = contentType ? getParameterContentSchema(param, contentType, api) : null;
883
- value = contentSchema?.default;
884
- }
885
- } else if (param.required && param.content) {
886
- const contentType = getParameterContentType(param);
887
- const schema = contentType ? getParameterContentSchema(param, contentType, api) : null;
888
- value = schema?.default;
889
- }
890
- if (value === void 0 && type === "path") {
891
- return param.name;
892
- }
893
- if (param.schema && !isRef2(param.schema) && param.schema.type === "array" && param.schema.items && !isRef2(param.schema.items) && param.schema.items.format === "binary") {
894
- if (Array.isArray(value)) {
895
- return value;
896
- }
897
- return JSON.stringify(value);
898
- }
899
- if (value !== void 0) {
900
- if (type === "query" || type === "header" && param.content) {
901
- return formatStyle(value, param);
902
- }
903
- return value;
904
- }
792
+ if (param.style) {
793
+ const value = getParamValue(values, param, type);
794
+ return formatStyle(value, param);
795
+ }
796
+ let value;
797
+ if (typeof getParamValue(values, param, type) !== "undefined") value = getParamValue(values, param, type);
798
+ else if (onlyIfExists && !param.required) value = void 0;
799
+ else if (param.required && param.schema && typeof param.schema === "object") {
800
+ const schema = isRef(param.schema) ? dereferenceRef(param.schema, api) : param.schema;
801
+ if (schema && typeof schema === "object" && !isRef(schema) && schema.default) value = schema.default;
802
+ else if (param.content) {
803
+ const contentType = getParameterContentType$1(param);
804
+ value = (contentType ? getParameterContentSchema(param, contentType, api) : null)?.default;
805
+ }
806
+ } else if (param.required && param.content) {
807
+ const contentType = getParameterContentType$1(param);
808
+ value = (contentType ? getParameterContentSchema(param, contentType, api) : null)?.default;
809
+ }
810
+ if (value === void 0 && type === "path") return param.name;
811
+ if (param.schema && typeof param.schema === "object" && !isRef(param.schema) && param.schema.type === "array" && param.schema.items && typeof param.schema.items === "object" && !Array.isArray(param.schema.items) && !isRef(param.schema.items) && param.schema.items.format === "binary") {
812
+ if (Array.isArray(value)) return value;
813
+ return JSON.stringify(value);
814
+ }
815
+ if (value !== void 0) {
816
+ if (type === "query" || type === "header" && (param.content || typeof value === "object" && value !== null)) return formatStyle(value, param);
817
+ return value;
818
+ }
905
819
  }
906
820
  function multipartBodyToFormatterParams(payload, oasMediaTypeObject, schema) {
907
- const encoding = oasMediaTypeObject.encoding;
908
- if (typeof payload === "object" && payload !== null) {
909
- return Object.keys(payload).map((key) => {
910
- if (!schema.properties?.[key]) {
911
- return false;
912
- }
913
- const paramEncoding = encoding ? encoding[key] : void 0;
914
- const propertySchema = schema.properties[key];
915
- const isObjectSchema = typeof propertySchema === "object" && propertySchema !== null && !isRef2(propertySchema);
916
- const hasObjectType = isObjectSchema && // OAS 3.1 uses JSON Schema union types, so object schemas can appear as
917
- // `type: ['object', 'null']` or another union that includes `object`.
918
- (Array.isArray(propertySchema.type) ? propertySchema.type.includes("object") : propertySchema.type === "object");
919
- const hasObjectProperties = isObjectSchema && typeof propertySchema.properties === "object" && propertySchema.properties !== null;
920
- const shouldDefaultNestedMultipartObject = !paramEncoding && (hasObjectType || hasObjectProperties);
921
- return {
922
- name: key,
923
- // Preserve nested multipart object paths as form fields unless the spec supplies explicit
924
- // encoding for this property.
925
- style: paramEncoding ? paramEncoding.style : shouldDefaultNestedMultipartObject ? "deepObject" : void 0,
926
- explode: paramEncoding ? paramEncoding.explode : shouldDefaultNestedMultipartObject ? true : void 0,
927
- required: schema.required && typeof schema.required === "boolean" && Boolean(schema.required) || Array.isArray(schema.required) && schema.required.includes(key),
928
- schema: schema.properties[key],
929
- in: "body"
930
- };
931
- }).filter(Boolean);
932
- }
933
- return [];
821
+ const encoding = oasMediaTypeObject.encoding;
822
+ if (typeof payload === "object" && payload !== null) return Object.keys(payload).map((key) => {
823
+ if (!schema.properties?.[key]) return false;
824
+ const paramEncoding = encoding ? encoding[key] : void 0;
825
+ const propertySchema = schema.properties[key];
826
+ const isObjectSchema = typeof propertySchema === "object" && propertySchema !== null && !isRef(propertySchema);
827
+ const hasObjectType = isObjectSchema && (Array.isArray(propertySchema.type) ? propertySchema.type.includes("object") : propertySchema.type === "object");
828
+ const hasObjectProperties = isObjectSchema && typeof propertySchema.properties === "object" && propertySchema.properties !== null;
829
+ const shouldDefaultNestedMultipartObject = !paramEncoding && (hasObjectType || hasObjectProperties);
830
+ return {
831
+ name: key,
832
+ style: paramEncoding ? paramEncoding.style : shouldDefaultNestedMultipartObject ? "deepObject" : void 0,
833
+ explode: paramEncoding ? paramEncoding.explode : shouldDefaultNestedMultipartObject ? true : void 0,
834
+ required: schema.required && typeof schema.required === "boolean" && Boolean(schema.required) || Array.isArray(schema.required) && schema.required.includes(key),
835
+ schema: schema.properties[key],
836
+ in: "body"
837
+ };
838
+ }).filter(Boolean);
839
+ return [];
934
840
  }
935
- var defaultFormDataTypes = Object.keys(jsonSchemaTypes).reduce((prev, curr) => {
936
- return Object.assign(prev, { [curr]: {} });
841
+ const defaultFormDataTypes = Object.keys(jsonSchemaTypes).reduce((prev, curr) => {
842
+ return Object.assign(prev, { [curr]: {} });
937
843
  }, {});
938
844
  function getResponseContentType(content) {
939
- const types = Object.keys(content) || [];
940
- if (types?.length) {
941
- const jsonType = types.find((t) => matchesMimeType2.json(t));
942
- if (jsonType) {
943
- return jsonType;
944
- }
945
- return types[0];
946
- }
947
- return "application/json";
845
+ const types = Object.keys(content) || [];
846
+ if (types?.length) {
847
+ const jsonType = types.find((t) => matchesMimeType.json(t));
848
+ if (jsonType) return jsonType;
849
+ return types[0];
850
+ }
851
+ return "application/json";
948
852
  }
949
853
  function isPrimitive(val) {
950
- return typeof val === "string" || typeof val === "number" || typeof val === "boolean";
854
+ return typeof val === "string" || typeof val === "number" || typeof val === "boolean";
951
855
  }
952
856
  function stringify(json) {
953
- return JSON.stringify(
954
- removeUndefinedObjects(typeof json.RAW_BODY !== "undefined" ? json.RAW_BODY : json, {
955
- preserveNullishArrays: true,
956
- preserveEmptyArray: true,
957
- preserveEmptyObject: {
958
- arrayItem: false,
959
- objectProperty: true,
960
- root: true
961
- }
962
- })
963
- );
857
+ return JSON.stringify(removeUndefinedObjects(typeof json.RAW_BODY !== "undefined" ? json.RAW_BODY : json, {
858
+ preserveNullishArrays: true,
859
+ preserveEmptyArray: true,
860
+ preserveEmptyObject: {
861
+ arrayItem: false,
862
+ objectProperty: true,
863
+ root: true
864
+ }
865
+ }));
964
866
  }
965
867
  function stringifyParameter(param) {
966
- if (param === null || isPrimitive(param)) {
967
- return String(param);
968
- } else if (Array.isArray(param) && param.every(isPrimitive)) {
969
- return String(param);
970
- }
971
- return JSON.stringify(param);
868
+ if (param === null || isPrimitive(param)) return String(param);
869
+ else if (Array.isArray(param) && param.every(isPrimitive)) return String(param);
870
+ return JSON.stringify(param);
972
871
  }
973
872
  function appendHarValue(harParam, name, value, addtlData = {}) {
974
- if (typeof value === "undefined") return;
975
- if (Array.isArray(value)) {
976
- value.forEach((singleValue) => {
977
- appendHarValue(harParam, name, singleValue);
978
- });
979
- } else if (typeof value === "object" && value !== null) {
980
- Object.keys(value).forEach((key) => {
981
- appendHarValue(harParam, key, value[key]);
982
- });
983
- } else {
984
- harParam.push({
985
- ...addtlData,
986
- name,
987
- value: String(value)
988
- });
989
- }
873
+ if (typeof value === "undefined") return;
874
+ if (Array.isArray(value)) value.forEach((singleValue) => {
875
+ appendHarValue(harParam, name, singleValue);
876
+ });
877
+ else if (typeof value === "object" && value !== null) Object.keys(value).forEach((key) => {
878
+ appendHarValue(harParam, key, value[key]);
879
+ });
880
+ else harParam.push({
881
+ ...addtlData,
882
+ name,
883
+ value: String(value)
884
+ });
990
885
  }
991
886
  function encodeBodyForHAR(body) {
992
- if (isPrimitive(body)) {
993
- return body;
994
- } else if (typeof body === "object" && body !== null && !Array.isArray(body) && typeof body.RAW_BODY !== "undefined") {
995
- if (isPrimitive(body.RAW_BODY)) {
996
- return body.RAW_BODY;
997
- }
998
- return stringify(body.RAW_BODY);
999
- }
1000
- return stringify(body);
887
+ if (isPrimitive(body)) return body;
888
+ else if (typeof body === "object" && body !== null && !Array.isArray(body) && typeof body.RAW_BODY !== "undefined") {
889
+ if (isPrimitive(body.RAW_BODY)) return body.RAW_BODY;
890
+ return stringify(body.RAW_BODY);
891
+ }
892
+ return stringify(body);
1001
893
  }
1002
894
  function oasToHar(oas, operationSchema, values = {}, auth = {}, opts = { proxyUrl: "" }) {
1003
- let operation;
1004
- if (!operationSchema || typeof operationSchema.getParameters !== "function") {
1005
- operation = new Operation(
1006
- oas,
1007
- operationSchema?.path || "",
1008
- operationSchema?.method || "",
1009
- operationSchema || { path: "", method: "" }
1010
- );
1011
- } else {
1012
- operation = operationSchema;
1013
- }
1014
- const apiDefinition = oas.getDefinition();
1015
- const formData = {
1016
- ...defaultFormDataTypes,
1017
- ...values
1018
- };
1019
- const shouldSerializeBody = Object.prototype.hasOwnProperty.call(values, "body") && values.body !== void 0;
1020
- if (!formData.server) {
1021
- formData.server = {
1022
- selected: 0,
1023
- variables: operation.defaultVariables(0)
1024
- };
1025
- }
1026
- formData.server.variables = {
1027
- ...operation.defaultVariables(formData.server.selected),
1028
- ...formData.server.variables ? formData.server.variables : {}
1029
- };
1030
- const har = {
1031
- cookies: [],
1032
- headers: [],
1033
- headersSize: 0,
1034
- queryString: [],
1035
- // @ts-expect-error This is fine because we're fleshing `postData` out further down.
1036
- postData: {},
1037
- bodySize: 0,
1038
- method: operation.method.toUpperCase(),
1039
- url: `${operation.url(formData.server.selected, formData.server.variables)}${operation.path}`.replace(
1040
- /\s/g,
1041
- "%20"
1042
- ),
1043
- httpVersion: "HTTP/1.1"
1044
- };
1045
- if (opts.proxyUrl) {
1046
- if (oas.getExtension(PROXY_ENABLED, operation)) {
1047
- har.url = `${opts.proxyUrl}/${har.url}`;
1048
- }
1049
- }
1050
- const parameters = operation.getParameters();
1051
- har.url = har.url.replace(/{([-_a-zA-Z0-9[\]]+)}/g, (full, key) => {
1052
- if (!operation || !parameters) return key;
1053
- const parameter = parameters.find((param) => param.name === key) || { name: key };
1054
- if (!("style" in parameter) || !parameter.style) {
1055
- return encodeURIComponent(formatter(formData, parameter, "path", false, oas.api));
1056
- }
1057
- return formatter(formData, parameter, "path", false, oas.api);
1058
- });
1059
- const queryStrings = parameters?.filter((param) => param.in === "query");
1060
- if (queryStrings?.length) {
1061
- queryStrings.forEach((queryString) => {
1062
- const value = formatter(formData, queryString, "query", true, oas.api);
1063
- appendHarValue(har.queryString, queryString.name, value);
1064
- });
1065
- }
1066
- const cookies = parameters?.filter((param) => param.in === "cookie");
1067
- if (cookies?.length) {
1068
- cookies.forEach((cookie) => {
1069
- const value = formatter(formData, cookie, "cookie", true, oas.api);
1070
- appendHarValue(har.cookies, cookie.name, value);
1071
- });
1072
- }
1073
- if (operation.schema.responses) {
1074
- Object.keys(operation.schema.responses).some((statusCode) => {
1075
- const response = operation.getResponseByStatusCode(statusCode);
1076
- if (!response) return false;
1077
- const content = response.content;
1078
- if (!content) return false;
1079
- if (Object.keys(formData.header || {}).find((h) => h.toLowerCase() === "accept")) return true;
1080
- har.headers.push({
1081
- name: "accept",
1082
- value: getResponseContentType(content)
1083
- });
1084
- return true;
1085
- });
1086
- }
1087
- let hasContentType = false;
1088
- let contentType = operation.getContentType();
1089
- const headers = parameters?.filter((param) => param.in === "header");
1090
- if (headers?.length) {
1091
- headers.forEach((header) => {
1092
- const value = formatter(formData, header, "header", true, oas.api);
1093
- if (typeof value === "undefined") return;
1094
- if (header.name.toLowerCase() === "content-type") {
1095
- hasContentType = true;
1096
- contentType = String(value);
1097
- }
1098
- appendHarValue(har.headers, header.name, value);
1099
- });
1100
- }
1101
- const userDefinedHeaders = oas.getExtension(HEADERS, operation);
1102
- if (userDefinedHeaders) {
1103
- userDefinedHeaders.forEach((header) => {
1104
- if (typeof header.key === "string" && header.key.toLowerCase() === "content-type") {
1105
- hasContentType = true;
1106
- contentType = String(header.value);
1107
- }
1108
- har.headers.push({
1109
- name: String(header.key),
1110
- value: String(header.value)
1111
- });
1112
- });
1113
- }
1114
- if (formData.header) {
1115
- const contentTypeFormHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "content-type");
1116
- if (contentTypeFormHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "content-type")) {
1117
- hasContentType = true;
1118
- contentType = String(formData.header[contentTypeFormHeader]);
1119
- har.headers.push({
1120
- name: "content-type",
1121
- value: contentType
1122
- });
1123
- }
1124
- const acceptHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "accept");
1125
- if (acceptHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "accept")) {
1126
- har.headers.push({
1127
- name: "accept",
1128
- value: String(formData.header[acceptHeader])
1129
- });
1130
- }
1131
- const authorizationHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "authorization");
1132
- if (authorizationHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "authorization")) {
1133
- har.headers.push({
1134
- name: "authorization",
1135
- value: String(formData.header[authorizationHeader])
1136
- });
1137
- }
1138
- }
1139
- let requestBody;
1140
- if (operation.hasRequestBody()) {
1141
- const isFormUrlEncoded = matchesMimeType2.formUrlEncoded(contentType);
1142
- const matchesRequestBodyType = (payload) => {
1143
- return payload.type === (isFormUrlEncoded ? "formData" : "body");
1144
- };
1145
- requestBody = operation.getParametersAsJSONSchema({ contentType })?.find(matchesRequestBodyType);
1146
- }
1147
- if (requestBody?.schema && Object.keys(requestBody.schema).length) {
1148
- const requestBodySchema = requestBody.schema;
1149
- const isFormUrlEncoded = matchesMimeType2.formUrlEncoded(contentType);
1150
- if (isFormUrlEncoded) {
1151
- if (Object.keys(formData.formData || {}).length) {
1152
- const cleanFormData = removeUndefinedObjects(formData.formData, { preserveNullishArrays: true });
1153
- if (cleanFormData !== void 0) {
1154
- const postData = { params: [], mimeType: "application/x-www-form-urlencoded" };
1155
- Object.keys(cleanFormData).forEach((name) => {
1156
- postData.params.push({
1157
- name,
1158
- value: stringifyParameter(cleanFormData[name])
1159
- });
1160
- });
1161
- har.postData = postData;
1162
- }
1163
- }
1164
- } else if (shouldSerializeBody) {
1165
- const isMultipart = matchesMimeType2.multipart(contentType);
1166
- const isJSON = matchesMimeType2.json(contentType);
1167
- if (isMultipart || isJSON) {
1168
- try {
1169
- let cleanBody = removeUndefinedObjects(formData.body, {
1170
- preserveNullishArrays: true,
1171
- preserveEmptyArray: true,
1172
- preserveEmptyObject: {
1173
- arrayItem: false,
1174
- objectProperty: true,
1175
- root: true
1176
- }
1177
- });
1178
- if (isMultipart) {
1179
- har.postData = { params: [], mimeType: "multipart/form-data" };
1180
- const safeBodySchema = getSafeRequestBody(requestBodySchema, formData.body, operation.api);
1181
- const binaryTypes = Object.keys(safeBodySchema.properties ?? {}).filter((key) => {
1182
- if (!safeBodySchema.properties?.[key] || typeof safeBodySchema.properties[key] !== "object" || safeBodySchema.properties[key] === null) {
1183
- return false;
1184
- }
1185
- const propData = safeBodySchema.properties[key];
1186
- if (propData.format === "binary") {
1187
- return true;
1188
- } else if (propData.type === "array" && propData.items && typeof propData.items === "object" && propData.items !== null && propData.items.format === "binary") {
1189
- return true;
1190
- }
1191
- return false;
1192
- });
1193
- if (cleanBody !== void 0) {
1194
- let multipartParams = [];
1195
- const multipartContent = operation.getRequestBody(contentType);
1196
- if (multipartContent) {
1197
- multipartParams = multipartBodyToFormatterParams(
1198
- formData.body,
1199
- multipartContent.mediaTypeObject,
1200
- safeBodySchema
1201
- );
1202
- }
1203
- if (multipartParams.length) {
1204
- Object.keys(cleanBody).forEach((name) => {
1205
- const param = multipartParams.find((multipartParam) => multipartParam.name === name);
1206
- if (param) {
1207
- const addtlData = {};
1208
- let value = formatter(formData, param, "body", true, oas.api);
1209
- if (!Array.isArray(value)) {
1210
- value = [value];
1211
- }
1212
- value.forEach((val) => {
1213
- if (binaryTypes.includes(name)) {
1214
- const parsed = parseDataUrl(val);
1215
- if (parsed) {
1216
- addtlData.fileName = "name" in parsed ? parsed.name : "unknown";
1217
- if ("contentType" in parsed) {
1218
- addtlData.contentType = parsed.contentType;
1219
- }
1220
- }
1221
- }
1222
- appendHarValue(har.postData?.params || [], name, val, addtlData);
1223
- });
1224
- }
1225
- });
1226
- }
1227
- }
1228
- } else {
1229
- har.postData = { mimeType: contentType, text: "" };
1230
- if (hasSchemaType(requestBody.schema, "string") || hasSchemaType(requestBody.schema, "integer") || hasSchemaType(requestBody.schema, "number") || hasSchemaType(requestBody.schema, "boolean")) {
1231
- har.postData.text = JSON.stringify(JSON.parse(cleanBody));
1232
- } else {
1233
- const jsonTypes = getTypedFormatsInSchema("json", requestBodySchema, operation.api, {
1234
- payload: cleanBody
1235
- });
1236
- if (Array.isArray(jsonTypes) && jsonTypes.length) {
1237
- try {
1238
- jsonTypes.forEach((prop) => {
1239
- try {
1240
- set(cleanBody, String(prop), JSON.parse(get(cleanBody, String(prop))));
1241
- } catch {
1242
- }
1243
- });
1244
- if (typeof cleanBody.RAW_BODY !== "undefined") {
1245
- cleanBody = cleanBody.RAW_BODY;
1246
- }
1247
- har.postData.text = JSON.stringify(cleanBody);
1248
- } catch {
1249
- har.postData.text = stringify(formData.body);
1250
- }
1251
- } else {
1252
- try {
1253
- const parsed = parseJSONStringsInBodyWithSchema(cleanBody, requestBodySchema, operation.api);
1254
- if (typeof parsed?.RAW_BODY !== "undefined") {
1255
- har.postData.text = isPrimitive(parsed.RAW_BODY) ? String(parsed.RAW_BODY) : stringify(parsed.RAW_BODY);
1256
- } else {
1257
- har.postData.text = JSON.stringify(parsed);
1258
- }
1259
- } catch {
1260
- har.postData.text = encodeBodyForHAR(formData.body);
1261
- }
1262
- }
1263
- }
1264
- }
1265
- } catch {
1266
- har.postData = { mimeType: contentType, text: stringify(formData.body) };
1267
- }
1268
- } else {
1269
- har.postData = { mimeType: contentType, text: encodeBodyForHAR(formData.body) };
1270
- }
1271
- }
1272
- }
1273
- if ((har.postData?.text || requestBody?.schema && Object.keys(requestBody.schema).length) && !hasContentType) {
1274
- har.headers.push({
1275
- name: "content-type",
1276
- value: contentType
1277
- });
1278
- }
1279
- const securityRequirements = operation.getSecurity();
1280
- if (securityRequirements?.length) {
1281
- securityRequirements.forEach((schemes) => {
1282
- Object.keys(schemes).forEach((security) => {
1283
- const securityValue = configureSecurity(apiDefinition, auth, security);
1284
- if (!securityValue) {
1285
- return;
1286
- }
1287
- if (securityValue.value.name === "authorization") {
1288
- if (har[securityValue.type].find((v) => v.name === securityValue.value.name)) {
1289
- return;
1290
- }
1291
- }
1292
- if (har[securityValue.type].find(
1293
- (v) => v.name === securityValue.value.name && v.value === securityValue.value.value
1294
- )) {
1295
- return;
1296
- }
1297
- har[securityValue.type].push(securityValue.value);
1298
- });
1299
- });
1300
- }
1301
- if (Object.keys(har.postData || {}).length === 0) {
1302
- delete har.postData;
1303
- }
1304
- return {
1305
- log: {
1306
- entries: [
1307
- {
1308
- request: har
1309
- }
1310
- ]
1311
- }
1312
- };
895
+ let operation;
896
+ if (!operationSchema || typeof operationSchema.getParameters !== "function")
897
+ /**
898
+ * If `operationSchema` was supplied as a plain object instead of an instance of `Operation`
899
+ * then we should create a new instance of it. We're doing it with a check on `getParameters`
900
+ * instead of checking `instanceof Operation` because JS is very weird when it comes to
901
+ * checking `instanceof` against classes. One instance of `Operation` may not always match up
902
+ * with another if they're being loaded between two different libraries.
903
+ *
904
+ * It's weird. This is easier.
905
+ */
906
+ operation = new Operation(oas, operationSchema?.path || "", operationSchema?.method || "", operationSchema || {
907
+ path: "",
908
+ method: ""
909
+ });
910
+ else operation = operationSchema;
911
+ const apiDefinition = oas.getDefinition();
912
+ const formData = {
913
+ ...defaultFormDataTypes,
914
+ ...values
915
+ };
916
+ const shouldSerializeBody = Object.prototype.hasOwnProperty.call(values, "body") && values.body !== void 0;
917
+ if (!formData.server) formData.server = {
918
+ selected: 0,
919
+ variables: operation.defaultVariables(0)
920
+ };
921
+ formData.server.variables = {
922
+ ...operation.defaultVariables(formData.server.selected),
923
+ ...formData.server.variables ? formData.server.variables : {}
924
+ };
925
+ const har = {
926
+ cookies: [],
927
+ headers: [],
928
+ headersSize: 0,
929
+ queryString: [],
930
+ postData: {},
931
+ bodySize: 0,
932
+ method: operation.method.toUpperCase(),
933
+ url: `${operation.url(formData.server.selected, formData.server.variables)}${operation.path}`.replace(/\s/g, "%20"),
934
+ httpVersion: "HTTP/1.1"
935
+ };
936
+ if (opts.proxyUrl) {
937
+ if (oas.getExtension(PROXY_ENABLED, operation)) har.url = `${opts.proxyUrl}/${har.url}`;
938
+ }
939
+ const parameters = operation.getParameters();
940
+ har.url = har.url.replace(/{([-_a-zA-Z0-9[\]]+)}/g, (full, key) => {
941
+ if (!operation || !parameters) return key;
942
+ const parameter = parameters.find((param) => param.name === key) || { name: key };
943
+ if (!parameter.style) return encodeURIComponent(formatter(formData, parameter, "path", false, oas.api));
944
+ return formatter(formData, parameter, "path", false, oas.api);
945
+ });
946
+ const queryStrings = parameters?.filter((param) => param.in === "query");
947
+ if (queryStrings?.length) queryStrings.forEach((queryString) => {
948
+ const value = formatter(formData, queryString, "query", true, oas.api);
949
+ appendHarValue(har.queryString, queryString.name, value);
950
+ });
951
+ const cookies = parameters?.filter((param) => param.in === "cookie");
952
+ if (cookies?.length) cookies.forEach((cookie) => {
953
+ const value = formatter(formData, cookie, "cookie", true, oas.api);
954
+ appendHarValue(har.cookies, cookie.name, value);
955
+ });
956
+ if (operation.schema.responses) Object.keys(operation.schema.responses).some((statusCode) => {
957
+ const response = operation.getResponseByStatusCode(statusCode);
958
+ if (!response) return false;
959
+ const content = response.content;
960
+ if (!content) return false;
961
+ if (Object.keys(formData.header || {}).find((h) => h.toLowerCase() === "accept")) return true;
962
+ har.headers.push({
963
+ name: "accept",
964
+ value: getResponseContentType(content)
965
+ });
966
+ return true;
967
+ });
968
+ let hasContentType = false;
969
+ let contentType = operation.getContentType();
970
+ const headers = parameters?.filter((param) => param.in === "header");
971
+ if (headers?.length) headers.forEach((header) => {
972
+ const value = formatter(formData, header, "header", true, oas.api);
973
+ if (typeof value === "undefined") return;
974
+ if (header.name.toLowerCase() === "content-type") {
975
+ hasContentType = true;
976
+ contentType = String(value);
977
+ }
978
+ appendHarValue(har.headers, header.name, value);
979
+ });
980
+ const userDefinedHeaders = oas.getExtension(HEADERS, operation);
981
+ if (userDefinedHeaders) userDefinedHeaders.forEach((header) => {
982
+ if (typeof header.key === "string" && header.key.toLowerCase() === "content-type") {
983
+ hasContentType = true;
984
+ contentType = String(header.value);
985
+ }
986
+ har.headers.push({
987
+ name: String(header.key),
988
+ value: String(header.value)
989
+ });
990
+ });
991
+ if (formData.header) {
992
+ const contentTypeFormHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "content-type");
993
+ if (contentTypeFormHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "content-type")) {
994
+ hasContentType = true;
995
+ contentType = String(formData.header[contentTypeFormHeader]);
996
+ har.headers.push({
997
+ name: "content-type",
998
+ value: contentType
999
+ });
1000
+ }
1001
+ const acceptHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "accept");
1002
+ if (acceptHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "accept")) har.headers.push({
1003
+ name: "accept",
1004
+ value: String(formData.header[acceptHeader])
1005
+ });
1006
+ const authorizationHeader = Object.keys(formData.header).find((h) => h.toLowerCase() === "authorization");
1007
+ if (authorizationHeader && !har.headers.find((hdr) => hdr.name.toLowerCase() === "authorization")) har.headers.push({
1008
+ name: "authorization",
1009
+ value: String(formData.header[authorizationHeader])
1010
+ });
1011
+ }
1012
+ let requestBody;
1013
+ if (operation.hasRequestBody()) {
1014
+ const isFormUrlEncoded = matchesMimeType.formUrlEncoded(contentType);
1015
+ const matchesRequestBodyType = (payload) => {
1016
+ return payload.type === (isFormUrlEncoded ? "formData" : "body");
1017
+ };
1018
+ requestBody = operation.getParametersAsJSONSchema({ contentType })?.find(matchesRequestBodyType);
1019
+ }
1020
+ if (requestBody?.schema && Object.keys(requestBody.schema).length) {
1021
+ const requestBodySchema = requestBody.schema;
1022
+ if (matchesMimeType.formUrlEncoded(contentType)) {
1023
+ if (Object.keys(formData.formData || {}).length) {
1024
+ const cleanFormData = removeUndefinedObjects(formData.formData, { preserveNullishArrays: true });
1025
+ if (cleanFormData !== void 0) {
1026
+ const postData = {
1027
+ params: [],
1028
+ mimeType: "application/x-www-form-urlencoded"
1029
+ };
1030
+ Object.keys(cleanFormData).forEach((name) => {
1031
+ postData.params.push({
1032
+ name,
1033
+ value: stringifyParameter(cleanFormData[name])
1034
+ });
1035
+ });
1036
+ har.postData = postData;
1037
+ }
1038
+ }
1039
+ } else if (shouldSerializeBody) {
1040
+ const isMultipart = matchesMimeType.multipart(contentType);
1041
+ const isJSON = matchesMimeType.json(contentType);
1042
+ if (isMultipart || isJSON) try {
1043
+ let cleanBody = removeUndefinedObjects(formData.body, {
1044
+ preserveNullishArrays: true,
1045
+ preserveEmptyArray: true,
1046
+ preserveEmptyObject: {
1047
+ arrayItem: false,
1048
+ objectProperty: true,
1049
+ root: true
1050
+ }
1051
+ });
1052
+ if (isMultipart) {
1053
+ har.postData = {
1054
+ params: [],
1055
+ mimeType: "multipart/form-data"
1056
+ };
1057
+ const safeBodySchema = getSafeRequestBody(requestBodySchema, formData.body, operation.api);
1058
+ /**
1059
+ * Discover all `{ type: string, format: binary }` properties, or arrays containing the
1060
+ * same, within the request body. If there are any, then that means that we're dealing
1061
+ * with a `multipart/form-data` request and need to treat the payload as
1062
+ * `postData.params` and supply filenames and content types for the files (if they're
1063
+ * available).
1064
+ *
1065
+ * @todo It'd be nice to replace this with `getTypedFormatsInSchema` instead.
1066
+ * @example `{ type: string, format: binary }`
1067
+ * @example `{ type: array, items: { type: string, format: binary } }`
1068
+ */
1069
+ const binaryTypes = Object.keys(safeBodySchema.properties ?? {}).filter((key) => {
1070
+ if (!safeBodySchema.properties?.[key] || typeof safeBodySchema.properties[key] !== "object" || safeBodySchema.properties[key] === null) return false;
1071
+ const propData = safeBodySchema.properties[key];
1072
+ if (propData.format === "binary") return true;
1073
+ else if (propData.type === "array" && propData.items && typeof propData.items === "object" && propData.items !== null && propData.items.format === "binary") return true;
1074
+ return false;
1075
+ });
1076
+ if (cleanBody !== void 0) {
1077
+ let multipartParams = [];
1078
+ const multipartContent = operation.getRequestBody(contentType);
1079
+ if (multipartContent) multipartParams = multipartBodyToFormatterParams(formData.body, multipartContent.mediaTypeObject, safeBodySchema);
1080
+ if (multipartParams.length) Object.keys(cleanBody).forEach((name) => {
1081
+ const param = multipartParams.find((multipartParam) => multipartParam.name === name);
1082
+ if (param) {
1083
+ const addtlData = {};
1084
+ let value = formatter(formData, param, "body", true, oas.api);
1085
+ if (!Array.isArray(value)) value = [value];
1086
+ value.forEach((val) => {
1087
+ if (binaryTypes.includes(name)) {
1088
+ const parsed = parse(val);
1089
+ if (parsed) {
1090
+ addtlData.fileName = "name" in parsed ? parsed.name : "unknown";
1091
+ if ("contentType" in parsed) addtlData.contentType = parsed.contentType;
1092
+ }
1093
+ }
1094
+ appendHarValue(har.postData?.params || [], name, val, addtlData);
1095
+ });
1096
+ }
1097
+ });
1098
+ }
1099
+ } else {
1100
+ har.postData = {
1101
+ mimeType: contentType,
1102
+ text: ""
1103
+ };
1104
+ if (hasSchemaType(requestBody.schema, "string") || hasSchemaType(requestBody.schema, "integer") || hasSchemaType(requestBody.schema, "number") || hasSchemaType(requestBody.schema, "boolean")) har.postData.text = JSON.stringify(JSON.parse(cleanBody));
1105
+ else {
1106
+ /**
1107
+ * Handle formatted JSON objects that have properties that accept arbitrary JSON.
1108
+ *
1109
+ * Find all `{ type: string, format: json }` properties in the schema because we need
1110
+ * to manually `JSON.parse` them before submit, otherwise they'll be escaped instead
1111
+ * of actual objects. We also only want values that the user has entered, so we drop
1112
+ * any `undefined` `cleanBody` keys.
1113
+ */
1114
+ const jsonTypes = getTypedFormatsInSchema("json", requestBodySchema, operation.api, { payload: cleanBody });
1115
+ if (Array.isArray(jsonTypes) && jsonTypes.length) try {
1116
+ jsonTypes.forEach((prop) => {
1117
+ try {
1118
+ set(cleanBody, String(prop), JSON.parse(get(cleanBody, String(prop))));
1119
+ } catch {}
1120
+ });
1121
+ if (typeof cleanBody.RAW_BODY !== "undefined") cleanBody = cleanBody.RAW_BODY;
1122
+ har.postData.text = JSON.stringify(cleanBody);
1123
+ } catch {
1124
+ har.postData.text = stringify(formData.body);
1125
+ }
1126
+ else try {
1127
+ const parsed = parseJSONStringsInBodyWithSchema(cleanBody, requestBodySchema, operation.api);
1128
+ if (typeof parsed?.RAW_BODY !== "undefined") har.postData.text = isPrimitive(parsed.RAW_BODY) ? String(parsed.RAW_BODY) : stringify(parsed.RAW_BODY);
1129
+ else har.postData.text = JSON.stringify(parsed);
1130
+ } catch {
1131
+ har.postData.text = encodeBodyForHAR(formData.body);
1132
+ }
1133
+ }
1134
+ }
1135
+ } catch {
1136
+ har.postData = {
1137
+ mimeType: contentType,
1138
+ text: stringify(formData.body)
1139
+ };
1140
+ }
1141
+ else har.postData = {
1142
+ mimeType: contentType,
1143
+ text: encodeBodyForHAR(formData.body)
1144
+ };
1145
+ }
1146
+ }
1147
+ if ((har.postData?.text || requestBody?.schema && Object.keys(requestBody.schema).length) && !hasContentType) har.headers.push({
1148
+ name: "content-type",
1149
+ value: contentType
1150
+ });
1151
+ const securityRequirements = operation.getSecurity();
1152
+ if (securityRequirements?.length) securityRequirements.forEach((schemes) => {
1153
+ Object.keys(schemes).forEach((security) => {
1154
+ const securityValue = configureSecurity(apiDefinition, auth, security);
1155
+ if (!securityValue) return;
1156
+ if (securityValue.value.name === "authorization") {
1157
+ if (har[securityValue.type].find((v) => v.name === securityValue.value.name)) return;
1158
+ }
1159
+ if (har[securityValue.type].find((v) => v.name === securityValue.value.name && v.value === securityValue.value.value)) return;
1160
+ har[securityValue.type].push(securityValue.value);
1161
+ });
1162
+ });
1163
+ if (Object.keys(har.postData || {}).length === 0) delete har.postData;
1164
+ return { log: { entries: [{ request: har }] } };
1313
1165
  }
1314
- export {
1315
- oasToHar as default
1316
- };
1317
- /**
1318
- * This file has been extracted and modified from `swagger-client`.
1319
- *
1320
- * @license Apache 2.0
1321
- * @link https://npm.im/swagger-client
1322
- * @link https://github.com/swagger-api/swagger-js/blob/master/src/execute/oas3/style-serializer.js
1323
- */
1166
+
1167
+ export { oasToHar as default };
1324
1168
  //# sourceMappingURL=index.js.map