fetch-har 9.0.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,367 +1,240 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
12
18
  };
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- var data_urls_1 = require("@readme/data-urls");
15
- var readable_stream_1 = require("readable-stream");
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
21
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
22
+ }) : x)(function(x) {
23
+ if (typeof require !== "undefined")
24
+ return require.apply(this, arguments);
25
+ throw Error('Dynamic require of "' + x + '" is not supported');
26
+ });
27
+
28
+ // src/index.ts
29
+ var _dataurls = require('@readme/data-urls');
16
30
  if (!globalThis.Blob) {
17
- try {
18
- // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-extraneous-dependencies
19
- globalThis.Blob = require('formdata-node').Blob;
20
- }
21
- catch (e) {
22
- throw new Error('Since you do not have the Blob API available in this environment you must install the optional `formdata-node` dependency.');
23
- }
31
+ try {
32
+ globalThis.Blob = __require("buffer").Blob;
33
+ } catch (e) {
34
+ throw new Error("The Blob API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/Blob");
35
+ }
24
36
  }
25
37
  if (!globalThis.File) {
26
- try {
27
- // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-extraneous-dependencies
28
- globalThis.File = require('formdata-node').File;
29
- }
30
- catch (e) {
31
- throw new Error('Since you do not have the File API available in this environment you must install the optional `formdata-node` dependency.');
32
- }
33
- }
34
- if (!globalThis.FormData) {
35
- try {
36
- // eslint-disable-next-line @typescript-eslint/no-var-requires, import/no-extraneous-dependencies
37
- globalThis.FormData = require('formdata-node').FormData;
38
- }
39
- catch (e) {
40
- throw new Error('Since you do not have the FormData API available in this environment you must install the optional `formdata-node` dependency.');
41
- }
38
+ try {
39
+ globalThis.File = __require("undici").File;
40
+ } catch (e) {
41
+ throw new Error("The File API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/File");
42
+ }
42
43
  }
43
44
  function isBrowser() {
44
- return typeof window !== 'undefined' && typeof document !== 'undefined';
45
+ return typeof window !== "undefined" && typeof document !== "undefined";
45
46
  }
46
47
  function isBuffer(value) {
47
- return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);
48
+ return typeof Buffer !== "undefined" && Buffer.isBuffer(value);
48
49
  }
49
50
  function isFile(value) {
50
- if (value instanceof File) {
51
- /**
52
- * The `Blob` polyfill on Node comes back as being an instanceof `File`. Because passing a Blob
53
- * into a File will end up with a corrupted file we want to prevent this.
54
- *
55
- * This object identity crisis does not happen in the browser.
56
- */
57
- return value.constructor.name === 'File';
58
- }
59
- return false;
60
- }
61
- /**
62
- * @license MIT
63
- * @see {@link https://github.com/octet-stream/form-data-encoder/blob/master/lib/util/isFunction.ts}
64
- */
65
- function isFunction(value) {
66
- return typeof value === 'function';
67
- }
68
- /**
69
- * We're using this library in here instead of loading it from `form-data-encoder` because that
70
- * uses lookbehind regex in its main encoder that Safari doesn't support so it throws a fatal page
71
- * exception.
72
- *
73
- * @license MIT
74
- * @see {@link https://github.com/octet-stream/form-data-encoder/blob/master/lib/util/isFormData.ts}
75
- */
76
- function isFormData(value) {
77
- return (value &&
78
- isFunction(value.constructor) &&
79
- value[Symbol.toStringTag] === 'FormData' &&
80
- isFunction(value.append) &&
81
- isFunction(value.getAll) &&
82
- isFunction(value.entries) &&
83
- isFunction(value[Symbol.iterator]));
51
+ if (value instanceof File) {
52
+ return value.constructor.name === "File";
53
+ }
54
+ return false;
84
55
  }
85
56
  function getFileFromSuppliedFiles(filename, files) {
86
- if (filename in files) {
87
- return files[filename];
88
- }
89
- else if (decodeURIComponent(filename) in files) {
90
- return files[decodeURIComponent(filename)];
91
- }
92
- return false;
57
+ if (files && filename in files) {
58
+ return files[filename];
59
+ } else if (files && decodeURIComponent(filename) in files) {
60
+ return files[decodeURIComponent(filename)];
61
+ }
62
+ return false;
93
63
  }
94
- function fetchHAR(har, opts) {
95
- var _a;
96
- if (opts === void 0) { opts = {}; }
97
- if (!har)
98
- throw new Error('Missing HAR definition');
99
- if (!har.log || !har.log.entries || !har.log.entries.length)
100
- throw new Error('Missing log.entries array');
101
- var request = har.log.entries[0].request;
102
- var url = request.url;
103
- var querystring = '';
104
- var shouldSetDuplex = false;
105
- var options = __assign(__assign({}, (opts.init ? opts.init : {})), { method: request.method });
106
- if (!options.headers) {
107
- options.headers = new Headers();
108
- }
109
- else if (typeof options.headers === 'object' && !(options.headers instanceof Headers) && options.headers !== null) {
110
- options.headers = new Headers(options.headers);
111
- }
112
- var headers = options.headers;
113
- if ('headers' in request && request.headers.length) {
114
- // eslint-disable-next-line consistent-return
115
- request.headers.forEach(function (header) {
116
- try {
117
- return headers.append(header.name, header.value);
118
- }
119
- catch (err) {
120
- /**
121
- * `Headers.append()` will throw errors if the header name is not a legal HTTP header name,
122
- * like `X-API-KEY (Header)`. If that happens instead of tossing the error back out, we
123
- * should silently just ignore
124
- * it.
125
- */
126
- }
127
- });
128
- }
129
- if ('cookies' in request && request.cookies.length) {
130
- /**
131
- * As the browser fetch API can't set custom cookies for requests, they instead need to be
132
- * defined on the document and passed into the request via `credentials: include`. Since this
133
- * is a browser-specific quirk, that should only
134
- * happen in browsers!
135
- */
136
- if (isBrowser()) {
137
- request.cookies.forEach(function (cookie) {
138
- document.cookie = "".concat(encodeURIComponent(cookie.name), "=").concat(encodeURIComponent(cookie.value));
139
- });
140
- options.credentials = 'include';
141
- }
142
- else {
143
- headers.append('cookie', request.cookies
144
- .map(function (cookie) { return "".concat(encodeURIComponent(cookie.name), "=").concat(encodeURIComponent(cookie.value)); })
145
- .join('; '));
146
- }
147
- }
148
- if ('postData' in request) {
149
- if ('params' in request.postData) {
150
- if (!('mimeType' in request.postData)) {
151
- // @ts-expect-error HAR spec requires that `mimeType` is always present but it might not be.
152
- request.postData.mimeType = 'application/octet-stream';
153
- }
154
- switch (request.postData.mimeType) {
155
- case 'application/x-www-form-urlencoded':
156
- /**
157
- * Since the content we're handling here is to be encoded as
158
- * `application/x-www-form-urlencoded`, this should override any other `Content-Type`
159
- * headers that are present in the HAR. This is how Postman handles this case when
160
- * building code snippets!
161
- *
162
- * @see {@link https://github.com/github/fetch/issues/263#issuecomment-209530977}
163
- */
164
- headers.set('Content-Type', request.postData.mimeType);
165
- var encodedParams_1 = new URLSearchParams();
166
- request.postData.params.forEach(function (param) { return encodedParams_1.set(param.name, param.value); });
167
- options.body = encodedParams_1.toString();
168
- break;
169
- case 'multipart/alternative':
170
- case 'multipart/form-data':
171
- case 'multipart/mixed':
172
- case 'multipart/related':
173
- /**
174
- * If there's a `Content-Type` header set we need to remove it. We're doing this because
175
- * when we pass the form data object into `fetch` that'll set a proper `Content-Type`
176
- * header for this request that also includes the boundary used on the content.
177
- *
178
- * If we don't do this, then consumers won't be able to parse out the payload because
179
- * they won't know what the boundary to split on it.
180
- */
181
- if (headers.has('Content-Type')) {
182
- headers.delete('Content-Type');
183
- }
184
- var form_1 = new FormData();
185
- if (!isFormData(form_1)) {
186
- /**
187
- * The `form-data` NPM module returns one of two things: a native `FormData` API or its
188
- * own polyfill. Unfortunately this polyfill does not support the full API of the native
189
- * FormData object so when you load `form-data` within a browser environment you'll
190
- * have two major differences in API:
191
- *
192
- * - The `.append()` API in `form-data` requires that the third argument is an object
193
- * containing various, undocumented, options. In the browser, `.append()`'s third
194
- * argument should only be present when the second is a `Blob` or `USVString`, and
195
- * when it is present, it should be a filename string.
196
- * - `form-data` does not expose an `.entries()` API, so the only way to retrieve data
197
- * out of it for construction of boundary-separated payload content is to use its
198
- * `.pipe()` API. Since the browser doesn't have this API, you'll be unable to
199
- * retrieve data out of it.
200
- *
201
- * Now since the native `FormData` API is iterable, and has the `.entries()` iterator,
202
- * we can easily detect if we have a native copy of the FormData API. It's for all of
203
- * these reasons that we're opting to hard crash here because supporting this
204
- * non-compliant API is more trouble than its worth.
205
- *
206
- * @see {@link https://github.com/form-data/form-data/issues/124}
207
- */
208
- throw new Error("We've detected you're using a non-spec compliant FormData library. We recommend polyfilling FormData with https://npm.im/formdata-node");
209
- }
210
- request.postData.params.forEach(function (param) {
211
- if ('fileName' in param) {
212
- if (opts.files) {
213
- var fileContents = getFileFromSuppliedFiles(param.fileName, opts.files);
214
- if (fileContents) {
215
- // If the file we've got available to us is a Buffer then we need to convert it so
216
- // that the FormData API can use it.
217
- if (isBuffer(fileContents)) {
218
- form_1.append(param.name, new File([fileContents], param.fileName, {
219
- type: param.contentType || null,
220
- }), param.fileName);
221
- return;
222
- }
223
- else if (isFile(fileContents)) {
224
- form_1.append(param.name, fileContents, param.fileName);
225
- return;
226
- }
227
- throw new TypeError('An unknown object has been supplied into the `files` config for use. We only support instances of the File API and Node Buffer objects.');
228
- }
229
- }
230
- if ('value' in param) {
231
- var paramBlob = void 0;
232
- var parsed = (0, data_urls_1.parse)(param.value);
233
- if (parsed) {
234
- // If we were able to parse out this data URL we don't need to transform its data
235
- // into a buffer for `Blob` because that supports data URLs already.
236
- paramBlob = new Blob([param.value], { type: parsed.contentType || param.contentType || null });
237
- }
238
- else {
239
- paramBlob = new Blob([param.value], { type: param.contentType || null });
240
- }
241
- form_1.append(param.name, paramBlob, param.fileName);
242
- return;
243
- }
244
- throw new Error("The supplied HAR has a postData parameter with `fileName`, but neither `value` content within the HAR or any file buffers were supplied with the `files` option. Since this library doesn't have access to the filesystem, it can't fetch that file.");
245
- }
246
- form_1.append(param.name, param.value);
247
- });
248
- /**
249
- * If a the `fetch` polyfill that's being used here doesn't have spec-compliant handling
250
- * for the `FormData` API (like `node-fetch@2`), then you should pass in a handler (like
251
- * the `form-data-encoder` library) to transform its contents into something that can be
252
- * used with the `Request` object.
253
- *
254
- * @see {@link https://www.npmjs.com/package/formdata-node}
255
- */
256
- if (opts.multipartEncoder) {
257
- // eslint-disable-next-line new-cap
258
- var encoder_1 = new opts.multipartEncoder(form_1);
259
- Object.keys(encoder_1.headers).forEach(function (header) {
260
- headers.set(header, encoder_1.headers[header]);
261
- });
262
- // @ts-expect-error "Property 'from' does not exist on type 'typeof Readable'." but it does!
263
- options.body = readable_stream_1.Readable.from(encoder_1);
264
- shouldSetDuplex = true;
265
- }
266
- else {
267
- options.body = form_1;
268
- }
269
- break;
270
- default:
271
- var formBody_1 = {};
272
- request.postData.params.map(function (param) {
273
- try {
274
- formBody_1[param.name] = JSON.parse(param.value);
275
- }
276
- catch (e) {
277
- formBody_1[param.name] = param.value;
278
- }
279
- return true;
280
- });
281
- options.body = JSON.stringify(formBody_1);
282
- }
283
- }
284
- else if ((_a = request.postData.text) === null || _a === void 0 ? void 0 : _a.length) {
285
- // If we've got `files` map content present, and this post data content contains a valid data
286
- // URL then we can substitute the payload with that file instead of the using data URL.
287
- if (opts.files) {
288
- var parsed = (0, data_urls_1.parse)(request.postData.text);
64
+ function fetchHAR(har, opts = {}) {
65
+ var _a, _b, _c, _d, _e;
66
+ if (!har)
67
+ throw new Error("Missing HAR definition");
68
+ if (!har.log || !har.log.entries || !har.log.entries.length)
69
+ throw new Error("Missing log.entries array");
70
+ const { request } = har.log.entries[0];
71
+ const { url } = request;
72
+ let querystring = "";
73
+ let shouldSetDuplex = false;
74
+ const options = __spreadProps(__spreadValues({}, opts.init ? opts.init : {}), {
75
+ method: request.method
76
+ });
77
+ if (!options.headers) {
78
+ options.headers = new Headers();
79
+ } else if (typeof options.headers === "object" && !(options.headers instanceof Headers) && options.headers !== null) {
80
+ options.headers = new Headers(options.headers);
81
+ }
82
+ const headers = options.headers;
83
+ if ("headers" in request && request.headers.length) {
84
+ request.headers.forEach((header) => {
85
+ try {
86
+ return headers.append(header.name, header.value);
87
+ } catch (err) {
88
+ }
89
+ });
90
+ }
91
+ if ("cookies" in request && request.cookies.length) {
92
+ if (isBrowser()) {
93
+ request.cookies.forEach((cookie) => {
94
+ document.cookie = `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`;
95
+ });
96
+ options.credentials = "include";
97
+ } else {
98
+ headers.append(
99
+ "cookie",
100
+ request.cookies.map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`).join("; ")
101
+ );
102
+ }
103
+ }
104
+ if ("postData" in request) {
105
+ if (request.postData && "params" in request.postData) {
106
+ if (!("mimeType" in request.postData)) {
107
+ request.postData.mimeType = "application/octet-stream";
108
+ }
109
+ switch (request.postData.mimeType) {
110
+ case "application/x-www-form-urlencoded":
111
+ headers.set("Content-Type", request.postData.mimeType);
112
+ const encodedParams = new URLSearchParams();
113
+ (_a = request.postData.params) == null ? void 0 : _a.forEach((param) => {
114
+ if (param.value)
115
+ encodedParams.set(param.name, param.value);
116
+ });
117
+ options.body = encodedParams.toString();
118
+ break;
119
+ case "multipart/alternative":
120
+ case "multipart/form-data":
121
+ case "multipart/mixed":
122
+ case "multipart/related":
123
+ if (headers.has("Content-Type")) {
124
+ headers.delete("Content-Type");
125
+ }
126
+ const form = new FormData();
127
+ (_b = request.postData.params) == null ? void 0 : _b.forEach((param) => {
128
+ if ("fileName" in param && param.fileName) {
129
+ if (opts.files) {
130
+ const fileContents = getFileFromSuppliedFiles(param.fileName, opts.files);
131
+ if (fileContents) {
132
+ if (isBuffer(fileContents)) {
133
+ form.append(
134
+ param.name,
135
+ new File([fileContents], param.fileName, {
136
+ type: param.contentType || void 0
137
+ }),
138
+ param.fileName
139
+ );
140
+ return;
141
+ } else if (isFile(fileContents)) {
142
+ form.append(param.name, fileContents, param.fileName);
143
+ return;
144
+ }
145
+ throw new TypeError(
146
+ "An unknown object has been supplied into the `files` config for use. We only support instances of the File API and Node Buffer objects."
147
+ );
148
+ }
149
+ }
150
+ if ("value" in param && param.value) {
151
+ let paramBlob;
152
+ const parsed = _dataurls.parse.call(void 0, param.value);
289
153
  if (parsed) {
290
- if ((parsed === null || parsed === void 0 ? void 0 : parsed.name) && parsed.name in opts.files) {
291
- var fileContents = getFileFromSuppliedFiles(parsed.name, opts.files);
292
- if (fileContents) {
293
- if (isBuffer(fileContents)) {
294
- options.body = fileContents;
295
- }
296
- else if (isFile(fileContents)) {
297
- // `Readable.from` isn't available in browsers but the browser `Request` object can
298
- // handle `File` objects just fine without us having to mold it into shape.
299
- if (isBrowser()) {
300
- options.body = fileContents;
301
- }
302
- else {
303
- // @ts-expect-error "Property 'from' does not exist on type 'typeof Readable'." but it does!
304
- options.body = readable_stream_1.Readable.from(fileContents.stream());
305
- shouldSetDuplex = true;
306
- // Supplying a polyfilled `File` stream into `Request.body` doesn't automatically
307
- // add `Content-Length`.
308
- if (!headers.has('content-length')) {
309
- headers.set('content-length', String(fileContents.size));
310
- }
311
- }
312
- }
313
- }
314
- }
154
+ paramBlob = new Blob([param.value], { type: parsed.contentType || param.contentType || void 0 });
155
+ } else {
156
+ paramBlob = new Blob([param.value], { type: param.contentType || void 0 });
315
157
  }
158
+ form.append(param.name, paramBlob, param.fileName);
159
+ return;
160
+ }
161
+ throw new Error(
162
+ "The supplied HAR has a postData parameter with `fileName`, but neither `value` content within the HAR or any file buffers were supplied with the `files` option. Since this library doesn't have access to the filesystem, it can't fetch that file."
163
+ );
316
164
  }
317
- if (typeof options.body === 'undefined') {
318
- options.body = request.postData.text;
165
+ if (param.value)
166
+ form.append(param.name, param.value);
167
+ });
168
+ options.body = form;
169
+ break;
170
+ default:
171
+ const formBody = {};
172
+ (_c = request.postData.params) == null ? void 0 : _c.map((param) => {
173
+ try {
174
+ formBody[param.name] = JSON.parse(param.value || "");
175
+ } catch (e) {
176
+ formBody[param.name] = param.value;
319
177
  }
178
+ return true;
179
+ });
180
+ options.body = JSON.stringify(formBody);
181
+ }
182
+ } else if ((_e = (_d = request.postData) == null ? void 0 : _d.text) == null ? void 0 : _e.length) {
183
+ if (opts.files) {
184
+ const parsed = _dataurls.parse.call(void 0, request.postData.text);
185
+ if (parsed) {
186
+ if ((parsed == null ? void 0 : parsed.name) && parsed.name in opts.files) {
187
+ const fileContents = getFileFromSuppliedFiles(parsed.name, opts.files);
188
+ if (fileContents) {
189
+ if (isBuffer(fileContents)) {
190
+ options.body = fileContents;
191
+ } else if (isFile(fileContents)) {
192
+ if (isBrowser()) {
193
+ options.body = fileContents;
194
+ } else {
195
+ options.body = fileContents.stream();
196
+ shouldSetDuplex = true;
197
+ if (!headers.has("content-length")) {
198
+ headers.set("content-length", String(fileContents.size));
199
+ }
200
+ }
201
+ }
202
+ }
203
+ }
320
204
  }
321
- /**
322
- * The fetch spec, which Node 18+ strictly abides by, now requires that `duplex` be sent with
323
- * requests that have payloads.
324
- *
325
- * As `RequestInit#duplex` isn't supported by any browsers, or even mentioned on MDN, we aren't
326
- * sending it in browser environments. This work is purely to support Node 18+ and `undici`
327
- * environments.
328
- *
329
- * @see {@link https://github.com/nodejs/node/issues/46221}
330
- * @see {@link https://github.com/whatwg/fetch/pull/1457}
331
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request}
332
- */
333
- if (shouldSetDuplex && !isBrowser()) {
334
- options.duplex = 'half';
335
- }
336
- }
337
- // We automaticaly assume that the HAR that we have already has query parameters encoded within
338
- // it so we do **not** use the `URLSearchParams` API here for composing the query string.
339
- var requestURL = url;
340
- if ('queryString' in request && request.queryString.length) {
341
- var urlObj = new URL(requestURL);
342
- var queryParams_1 = Array.from(urlObj.searchParams).map(function (_a) {
343
- var k = _a[0], v = _a[1];
344
- return "".concat(k, "=").concat(v);
345
- });
346
- request.queryString.forEach(function (q) {
347
- queryParams_1.push("".concat(q.name, "=").concat(q.value));
348
- });
349
- querystring = queryParams_1.join('&');
350
- // Because anchor hashes before query strings will prevent query strings from being delivered
351
- // we need to pop them off and re-add them after.
352
- if (urlObj.hash) {
353
- var urlWithoutHashes = requestURL.replace(urlObj.hash, '');
354
- requestURL = "".concat(urlWithoutHashes.split('?')[0]).concat(querystring ? "?".concat(querystring) : '');
355
- requestURL += urlObj.hash;
356
- }
357
- else {
358
- requestURL = "".concat(requestURL.split('?')[0]).concat(querystring ? "?".concat(querystring) : '');
359
- }
360
- }
361
- if (opts.userAgent) {
362
- headers.append('User-Agent', opts.userAgent);
363
- }
364
- options.headers = headers;
365
- return fetch(requestURL, options);
205
+ }
206
+ if (typeof options.body === "undefined") {
207
+ options.body = request.postData.text;
208
+ }
209
+ }
210
+ if (shouldSetDuplex && !isBrowser()) {
211
+ options.duplex = "half";
212
+ }
213
+ }
214
+ let requestURL = url;
215
+ if ("queryString" in request && request.queryString.length) {
216
+ const urlObj = new URL(requestURL);
217
+ const queryParams = Array.from(urlObj.searchParams).map(([k, v]) => `${k}=${v}`);
218
+ request.queryString.forEach((q) => {
219
+ queryParams.push(`${q.name}=${q.value}`);
220
+ });
221
+ querystring = queryParams.join("&");
222
+ if (urlObj.hash) {
223
+ const urlWithoutHashes = requestURL.replace(urlObj.hash, "");
224
+ requestURL = `${urlWithoutHashes.split("?")[0]}${querystring ? `?${querystring}` : ""}`;
225
+ requestURL += urlObj.hash;
226
+ } else {
227
+ requestURL = `${requestURL.split("?")[0]}${querystring ? `?${querystring}` : ""}`;
228
+ }
229
+ }
230
+ if (opts.userAgent) {
231
+ headers.append("User-Agent", opts.userAgent);
232
+ }
233
+ options.headers = headers;
234
+ return fetch(requestURL, options);
366
235
  }
236
+
237
+
367
238
  exports.default = fetchHAR;
239
+
240
+ module.exports = exports.default//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,SAAS,oBAAoB;AAEtC,IAAI,CAAC,WAAW,MAAM;AACpB,MAAI;AAEF,eAAW,OAAO,UAAQ,QAAa,EAAE;AAAA,EAC3C,SAAS,GAAG;AACV,UAAM,IAAI,MAAM,kGAAkG;AAAA,EACpH;AACF;AAEA,IAAI,CAAC,WAAW,MAAM;AACpB,MAAI;AAIF,eAAW,OAAO,UAAQ,QAAQ,EAAE;AAAA,EACtC,SAAS,GAAG;AACV,UAAM,IAAI,MAAM,kGAAkG;AAAA,EACpH;AACF;AAQA,SAAS,YAAY;AACnB,SAAO,OAAO,WAAW,eAAe,OAAO,aAAa;AAC9D;AAEA,SAAS,SAAS,OAAY;AAC5B,SAAO,OAAO,WAAW,eAAe,OAAO,SAAS,KAAK;AAC/D;AAEA,SAAS,OAAO,OAAY;AAC1B,MAAI,iBAAiB,MAAM;AAOzB,WAAO,MAAM,YAAY,SAAS;AAAA,EACpC;AAEA,SAAO;AACT;AAEA,SAAS,yBAAyB,UAAkB,OAAiC;AACnF,MAAI,SAAS,YAAY,OAAO;AAC9B,WAAO,MAAM,QAAQ;AAAA,EACvB,WAAW,SAAS,mBAAmB,QAAQ,KAAK,OAAO;AACzD,WAAO,MAAM,mB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AI,KAAK,WAAW;AAClB,YAAQ,OAAO,cAAc,KAAK,SAAS;AAAA,EAC7C;AAEA,UAAQ,UAAU;AAElB,SAAO,MAAM,YAAY,OAAO;AAClC","sourcesContent":["import type { FetchHAROptions, RequestInitWithDuplex } from './types';\nimport type { DataURL as npmDataURL } from '@readme/data-urls';\nimport type { Har } from 'har-format';\n\nimport { parse as parseDataUrl } from '@readme/data-urls';\n\nif (!globalThis.Blob) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n globalThis.Blob = require('node:buffer').Blob;\n } catch (e) {\n throw new Error('The Blob API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/Blob');\n }\n}\n\nif (!globalThis.File) {\n try {\n // Node's native `fetch` implementation unfortunately does not make this API global so we need\n // to pull it in if we don't have it.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n globalThis.File = require('undici').File;\n } catch (e) {\n throw new Error('The File API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/File');\n }\n}\n\ntype DataURL = npmDataURL & {\n // `parse-data-url` doesn't explicitly support `name` in data URLs but if it's there it'll be\n // returned back to us.\n name?: string;\n};\n\nfunction isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nfunction isBuffer(value: any) {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);\n}\n\nfunction isFile(value: any) {\n if (value instanceof File) {\n /**\n * The `Blob` polyfill on Node comes back as being an instanceof `File`. Because passing a Blob\n * into a File will end up with a corrupted file we want to prevent this.\n *\n * This object identity crisis does not happen in the browser.\n */\n return value.constructor.name === 'File';\n }\n\n return false;\n}\n\nfunction getFileFromSuppliedFiles(filename: string, files: FetchHAROptions['files']) {\n if (files && filename in files) {\n return files[filename];\n } else if (files && decodeURIComponent(filename) in files) {\n return files[decodeURIComponent(filename)];\n }\n\n return false;\n}\n\nexport default function fetchHAR(har: Har, opts: FetchHAROptions = {}) {\n if (!har) throw new Error('Missing HAR definition');\n if (!har.log || !har.log.entries || !har.log.entries.length) throw new Error('Missing log.entries array');\n\n const { request } = har.log.entries[0];\n const { url } = request;\n let querystring = '';\n let shouldSetDuplex = false;\n\n const options: RequestInitWithDuplex = {\n // If we have custom options for the `Request` API we need to add them in here now before we\n // fill it in with everything we need from the HAR.\n ...(opts.init ? opts.init : {}),\n method: request.method,\n };\n\n if (!options.headers) {\n options.headers = new Headers();\n } else if (typeof options.headers === 'object' && !(options.headers instanceof Headers) && options.headers !== null) {\n options.headers = new Headers(options.headers);\n }\n\n const headers = options.headers as Headers;\n if ('headers' in request && request.headers.length) {\n // eslint-disable-next-line consistent-return\n request.headers.forEach(header => {\n try {\n return headers.append(header.name, header.value);\n } catch (err) {\n /**\n * `Headers.append()` will throw errors if the header name is not a legal HTTP header name,\n * like `X-API-KEY (Header)`. If that happens instead of tossing the error back out, we\n * should silently just ignore\n * it.\n */\n }\n });\n }\n\n if ('cookies' in request && request.cookies.length) {\n /**\n * As the browser fetch API can't set custom cookies for requests, they instead need to be\n * defined on the document and passed into the request via `credentials: include`. Since this\n * is a browser-specific quirk, that should only\n * happen in browsers!\n */\n if (isBrowser()) {\n request.cookies.forEach(cookie => {\n document.cookie = `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`;\n });\n\n options.credentials = 'include';\n } else {\n headers.append(\n 'cookie',\n request.cookies\n .map(cookie => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`)\n .join('; '),\n );\n }\n }\n\n if ('postData' in request) {\n if (request.postData && 'params' in request.postData) {\n if (!('mimeType' in request.postData)) {\n // @ts-expect-error HAR spec requires that `mimeType` is always present but it might not be.\n request.postData.mimeType = 'application/octet-stream';\n }\n\n switch (request.postData.mimeType) {\n case 'application/x-www-form-urlencoded':\n /**\n * Since the content we're handling here is to be encoded as\n * `application/x-www-form-urlencoded`, this should override any other `Content-Type`\n * headers that are present in the HAR. This is how Postman handles this case when\n * building code snippets!\n *\n * @see {@link https://github.com/github/fetch/issues/263#issuecomment-209530977}\n */\n headers.set('Content-Type', request.postData.mimeType);\n\n const encodedParams = new URLSearchParams();\n request.postData.params?.forEach(param => {\n if (param.value) encodedParams.set(param.name, param.value);\n });\n\n options.body = encodedParams.toString();\n break;\n\n case 'multipart/alternative':\n case 'multipart/form-data':\n case 'multipart/mixed':\n case 'multipart/related':\n /**\n * If there's a `Content-Type` header set we need to remove it. We're doing this because\n * when we pass the form data object into `fetch` that'll set a proper `Content-Type`\n * header for this request that also includes the boundary used on the content.\n *\n * If we don't do this, then consumers won't be able to parse out the payload because\n * they won't know what the boundary to split on it.\n */\n if (headers.has('Content-Type')) {\n headers.delete('Content-Type');\n }\n\n const form = new FormData();\n\n request.postData.params?.forEach(param => {\n if ('fileName' in param && param.fileName) {\n if (opts.files) {\n const fileContents = getFileFromSuppliedFiles(param.fileName, opts.files);\n if (fileContents) {\n // If the file we've got available to us is a Buffer then we need to convert it so\n // that the FormData API can use it.\n if (isBuffer(fileContents)) {\n form.append(\n param.name,\n new File([fileContents], param.fileName, {\n type: param.contentType || undefined,\n }),\n param.fileName,\n );\n\n return;\n } else if (isFile(fileContents)) {\n form.append(param.name, fileContents as Blob, param.fileName);\n return;\n }\n\n throw new TypeError(\n 'An unknown object has been supplied into the `files` config for use. We only support instances of the File API and Node Buffer objects.',\n );\n }\n }\n\n if ('value' in param && param.value) {\n let paramBlob;\n const parsed = parseDataUrl(param.value);\n if (parsed) {\n // If we were able to parse out this data URL we don't need to transform its data\n // into a buffer for `Blob` because that supports data URLs already.\n paramBlob = new Blob([param.value], { type: parsed.contentType || param.contentType || undefined });\n } else {\n paramBlob = new Blob([param.value], { type: param.contentType || undefined });\n }\n\n form.append(param.name, paramBlob, param.fileName);\n return;\n }\n\n throw new Error(\n \"The supplied HAR has a postData parameter with `fileName`, but neither `value` content within the HAR or any file buffers were supplied with the `files` option. Since this library doesn't have access to the filesystem, it can't fetch that file.\",\n );\n }\n\n if (param.value) form.append(param.name, param.value);\n });\n\n options.body = form;\n break;\n\n default:\n const formBody: Record<string, unknown> = {};\n request.postData.params?.map(param => {\n try {\n formBody[param.name] = JSON.parse(param.value || '');\n } catch (e) {\n formBody[param.name] = param.value;\n }\n\n return true;\n });\n\n options.body = JSON.stringify(formBody);\n }\n } else if (request.postData?.text?.length) {\n // If we've got `files` map content present, and this post data content contains a valid data\n // URL then we can substitute the payload with that file instead of the using data URL.\n if (opts.files) {\n const parsed = parseDataUrl(request.postData.text) as DataURL;\n if (parsed) {\n if (parsed?.name && parsed.name in opts.files) {\n const fileContents = getFileFromSuppliedFiles(parsed.name, opts.files);\n if (fileContents) {\n if (isBuffer(fileContents)) {\n options.body = fileContents;\n } else if (isFile(fileContents)) {\n // `Readable.from` isn't available in browsers but the browser `Request` object can\n // handle `File` objects just fine without us having to mold it into shape.\n if (isBrowser()) {\n options.body = fileContents;\n } else {\n options.body = (fileContents as File).stream();\n shouldSetDuplex = true;\n\n // Supplying a polyfilled `File` stream into `Request.body` doesn't automatically\n // add `Content-Length`.\n if (!headers.has('content-length')) {\n headers.set('content-length', String((fileContents as File).size));\n }\n }\n }\n }\n }\n }\n }\n\n if (typeof options.body === 'undefined') {\n options.body = request.postData.text;\n }\n }\n\n /**\n * The fetch spec, which Node 18+ strictly abides by, now requires that `duplex` be sent with\n * requests that have payloads.\n *\n * As `RequestInit#duplex` isn't supported by any browsers, or even mentioned on MDN, we aren't\n * sending it in browser environments. This work is purely to support Node 18+ and `undici`\n * environments.\n *\n * @see {@link https://github.com/nodejs/node/issues/46221}\n * @see {@link https://github.com/whatwg/fetch/pull/1457}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request}\n */\n if (shouldSetDuplex && !isBrowser()) {\n options.duplex = 'half';\n }\n }\n\n // We automaticaly assume that the HAR that we have already has query parameters encoded within\n // it so we do **not** use the `URLSearchParams` API here for composing the query string.\n let requestURL = url;\n if ('queryString' in request && request.queryString.length) {\n const urlObj = new URL(requestURL);\n\n const queryParams = Array.from(urlObj.searchParams).map(([k, v]) => `${k}=${v}`);\n request.queryString.forEach(q => {\n queryParams.push(`${q.name}=${q.value}`);\n });\n\n querystring = queryParams.join('&');\n\n // Because anchor hashes before query strings will prevent query strings from being delivered\n // we need to pop them off and re-add them after.\n if (urlObj.hash) {\n const urlWithoutHashes = requestURL.replace(urlObj.hash, '');\n requestURL = `${urlWithoutHashes.split('?')[0]}${querystring ? `?${querystring}` : ''}`;\n requestURL += urlObj.hash;\n } else {\n requestURL = `${requestURL.split('?')[0]}${querystring ? `?${querystring}` : ''}`;\n }\n }\n\n if (opts.userAgent) {\n headers.append('User-Agent', opts.userAgent);\n }\n\n options.headers = headers;\n\n return fetch(requestURL, options);\n}\n"]}