fetch-har 10.0.0 → 11.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,291 +1,260 @@
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;
1
+ 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;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __async = (__this, __arguments, generator) => {
21
+ return new Promise((resolve, reject) => {
22
+ var fulfilled = (value) => {
23
+ try {
24
+ step(generator.next(value));
25
+ } catch (e) {
26
+ reject(e);
27
+ }
10
28
  };
11
- return __assign.apply(this, arguments);
29
+ var rejected = (value) => {
30
+ try {
31
+ step(generator.throw(value));
32
+ } catch (e) {
33
+ reject(e);
34
+ }
35
+ };
36
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
+ step((generator = generator.apply(__this, __arguments)).next());
38
+ });
12
39
  };
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- var data_urls_1 = require("@readme/data-urls");
15
- var readable_stream_1 = require("readable-stream");
16
- if (!globalThis.Blob) {
17
- try {
18
- // eslint-disable-next-line @typescript-eslint/no-var-requires
19
- globalThis.Blob = require('node:buffer').Blob;
20
- }
21
- catch (e) {
22
- throw new Error('The Blob API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/Blob');
23
- }
24
- }
25
- if (!globalThis.File) {
26
- try {
27
- // Node's native `fetch` implementation unfortunately does not make this API global so we need
28
- // to pull it in if we don't have it.
29
- // eslint-disable-next-line @typescript-eslint/no-var-requires
30
- globalThis.File = require('undici').File;
31
- }
32
- catch (e) {
33
- throw new Error('The File API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/File');
34
- }
35
- }
40
+
41
+ // src/index.ts
42
+ import { parse as parseDataUrl } from "@readme/data-urls";
36
43
  function isBrowser() {
37
- return typeof window !== 'undefined' && typeof document !== 'undefined';
44
+ return typeof window !== "undefined" && typeof document !== "undefined";
38
45
  }
39
46
  function isBuffer(value) {
40
- return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);
47
+ return typeof Buffer !== "undefined" && Buffer.isBuffer(value);
41
48
  }
42
49
  function isFile(value) {
43
- if (value instanceof File) {
44
- /**
45
- * The `Blob` polyfill on Node comes back as being an instanceof `File`. Because passing a Blob
46
- * into a File will end up with a corrupted file we want to prevent this.
47
- *
48
- * This object identity crisis does not happen in the browser.
49
- */
50
- return value.constructor.name === 'File';
51
- }
52
- return false;
50
+ if (value instanceof File) {
51
+ return value.constructor.name === "File";
52
+ }
53
+ return false;
53
54
  }
54
55
  function getFileFromSuppliedFiles(filename, files) {
55
- if (filename in files) {
56
- return files[filename];
57
- }
58
- else if (decodeURIComponent(filename) in files) {
59
- return files[decodeURIComponent(filename)];
60
- }
61
- return false;
56
+ if (files && filename in files) {
57
+ return files[filename];
58
+ } else if (files && decodeURIComponent(filename) in files) {
59
+ return files[decodeURIComponent(filename)];
60
+ }
61
+ return false;
62
62
  }
63
- function fetchHAR(har, opts) {
64
- var _a;
65
- if (opts === void 0) { opts = {}; }
63
+ function fetchHAR(_0) {
64
+ return __async(this, arguments, function* (har, opts = {}) {
65
+ var _a, _b, _c, _d, _e;
66
66
  if (!har)
67
- throw new Error('Missing HAR definition');
67
+ throw new Error("Missing HAR definition");
68
68
  if (!har.log || !har.log.entries || !har.log.entries.length)
69
- throw new Error('Missing log.entries array');
70
- var request = har.log.entries[0].request;
71
- var url = request.url;
72
- var querystring = '';
73
- var shouldSetDuplex = false;
74
- var options = __assign(__assign({}, (opts.init ? opts.init : {})), { method: request.method });
69
+ throw new Error("Missing log.entries array");
70
+ if (!globalThis.Blob) {
71
+ try {
72
+ const NodeBlob = (yield import("buffer")).Blob;
73
+ globalThis.Blob = NodeBlob;
74
+ } catch (e) {
75
+ throw new Error(
76
+ "The Blob API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/Blob"
77
+ );
78
+ }
79
+ }
80
+ if (!globalThis.File) {
81
+ try {
82
+ const UndiciFile = (yield import("undici")).File;
83
+ globalThis.File = UndiciFile;
84
+ } catch (e) {
85
+ throw new Error(
86
+ "The File API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/File"
87
+ );
88
+ }
89
+ }
90
+ const { request } = har.log.entries[0];
91
+ const { url } = request;
92
+ let querystring = "";
93
+ let shouldSetDuplex = false;
94
+ const options = __spreadProps(__spreadValues({}, opts.init ? opts.init : {}), {
95
+ method: request.method
96
+ });
75
97
  if (!options.headers) {
76
- options.headers = new Headers();
98
+ options.headers = new Headers();
99
+ } else if (typeof options.headers === "object" && !(options.headers instanceof Headers) && options.headers !== null) {
100
+ options.headers = new Headers(options.headers);
77
101
  }
78
- else if (typeof options.headers === 'object' && !(options.headers instanceof Headers) && options.headers !== null) {
79
- options.headers = new Headers(options.headers);
102
+ const headers = options.headers;
103
+ if ("headers" in request && request.headers.length) {
104
+ request.headers.forEach((header) => {
105
+ try {
106
+ return headers.append(header.name, header.value);
107
+ } catch (err) {
108
+ }
109
+ });
80
110
  }
81
- var headers = options.headers;
82
- if ('headers' in request && request.headers.length) {
83
- // eslint-disable-next-line consistent-return
84
- request.headers.forEach(function (header) {
85
- try {
86
- return headers.append(header.name, header.value);
87
- }
88
- catch (err) {
89
- /**
90
- * `Headers.append()` will throw errors if the header name is not a legal HTTP header name,
91
- * like `X-API-KEY (Header)`. If that happens instead of tossing the error back out, we
92
- * should silently just ignore
93
- * it.
94
- */
95
- }
111
+ if ("cookies" in request && request.cookies.length) {
112
+ if (isBrowser()) {
113
+ request.cookies.forEach((cookie) => {
114
+ document.cookie = `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`;
96
115
  });
116
+ options.credentials = "include";
117
+ } else {
118
+ headers.append(
119
+ "cookie",
120
+ request.cookies.map((cookie) => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`).join("; ")
121
+ );
122
+ }
97
123
  }
98
- if ('cookies' in request && request.cookies.length) {
99
- /**
100
- * As the browser fetch API can't set custom cookies for requests, they instead need to be
101
- * defined on the document and passed into the request via `credentials: include`. Since this
102
- * is a browser-specific quirk, that should only
103
- * happen in browsers!
104
- */
105
- if (isBrowser()) {
106
- request.cookies.forEach(function (cookie) {
107
- document.cookie = "".concat(encodeURIComponent(cookie.name), "=").concat(encodeURIComponent(cookie.value));
108
- });
109
- options.credentials = 'include';
124
+ if ("postData" in request) {
125
+ if (request.postData && "params" in request.postData) {
126
+ if (!("mimeType" in request.postData)) {
127
+ request.postData.mimeType = "application/octet-stream";
110
128
  }
111
- else {
112
- headers.append('cookie', request.cookies
113
- .map(function (cookie) { return "".concat(encodeURIComponent(cookie.name), "=").concat(encodeURIComponent(cookie.value)); })
114
- .join('; '));
115
- }
116
- }
117
- if ('postData' in request) {
118
- if ('params' in request.postData) {
119
- if (!('mimeType' in request.postData)) {
120
- // @ts-expect-error HAR spec requires that `mimeType` is always present but it might not be.
121
- request.postData.mimeType = 'application/octet-stream';
129
+ switch (request.postData.mimeType) {
130
+ case "application/x-www-form-urlencoded":
131
+ headers.set("Content-Type", request.postData.mimeType);
132
+ const encodedParams = new URLSearchParams();
133
+ (_a = request.postData.params) == null ? void 0 : _a.forEach((param) => {
134
+ if (param.value)
135
+ encodedParams.set(param.name, param.value);
136
+ });
137
+ options.body = encodedParams.toString();
138
+ break;
139
+ case "multipart/alternative":
140
+ case "multipart/form-data":
141
+ case "multipart/mixed":
142
+ case "multipart/related":
143
+ if (headers.has("Content-Type")) {
144
+ headers.delete("Content-Type");
122
145
  }
123
- switch (request.postData.mimeType) {
124
- case 'application/x-www-form-urlencoded':
125
- /**
126
- * Since the content we're handling here is to be encoded as
127
- * `application/x-www-form-urlencoded`, this should override any other `Content-Type`
128
- * headers that are present in the HAR. This is how Postman handles this case when
129
- * building code snippets!
130
- *
131
- * @see {@link https://github.com/github/fetch/issues/263#issuecomment-209530977}
132
- */
133
- headers.set('Content-Type', request.postData.mimeType);
134
- var encodedParams_1 = new URLSearchParams();
135
- request.postData.params.forEach(function (param) { return encodedParams_1.set(param.name, param.value); });
136
- options.body = encodedParams_1.toString();
137
- break;
138
- case 'multipart/alternative':
139
- case 'multipart/form-data':
140
- case 'multipart/mixed':
141
- case 'multipart/related':
142
- /**
143
- * If there's a `Content-Type` header set we need to remove it. We're doing this because
144
- * when we pass the form data object into `fetch` that'll set a proper `Content-Type`
145
- * header for this request that also includes the boundary used on the content.
146
- *
147
- * If we don't do this, then consumers won't be able to parse out the payload because
148
- * they won't know what the boundary to split on it.
149
- */
150
- if (headers.has('Content-Type')) {
151
- headers.delete('Content-Type');
146
+ const form = new FormData();
147
+ (_b = request.postData.params) == null ? void 0 : _b.forEach((param) => {
148
+ if ("fileName" in param && param.fileName) {
149
+ if (opts.files) {
150
+ const fileContents = getFileFromSuppliedFiles(param.fileName, opts.files);
151
+ if (fileContents) {
152
+ if (isBuffer(fileContents)) {
153
+ form.append(
154
+ param.name,
155
+ new File([fileContents], param.fileName, {
156
+ type: param.contentType || void 0
157
+ }),
158
+ param.fileName
159
+ );
160
+ return;
161
+ } else if (isFile(fileContents)) {
162
+ form.append(param.name, fileContents, param.fileName);
163
+ return;
152
164
  }
153
- var form_1 = new FormData();
154
- request.postData.params.forEach(function (param) {
155
- if ('fileName' in param) {
156
- if (opts.files) {
157
- var fileContents = getFileFromSuppliedFiles(param.fileName, opts.files);
158
- if (fileContents) {
159
- // If the file we've got available to us is a Buffer then we need to convert it so
160
- // that the FormData API can use it.
161
- if (isBuffer(fileContents)) {
162
- form_1.append(param.name, new File([fileContents], param.fileName, {
163
- type: param.contentType || null,
164
- }), param.fileName);
165
- return;
166
- }
167
- else if (isFile(fileContents)) {
168
- form_1.append(param.name, fileContents, param.fileName);
169
- return;
170
- }
171
- 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.');
172
- }
173
- }
174
- if ('value' in param) {
175
- var paramBlob = void 0;
176
- var parsed = (0, data_urls_1.parse)(param.value);
177
- if (parsed) {
178
- // If we were able to parse out this data URL we don't need to transform its data
179
- // into a buffer for `Blob` because that supports data URLs already.
180
- paramBlob = new Blob([param.value], { type: parsed.contentType || param.contentType || null });
181
- }
182
- else {
183
- paramBlob = new Blob([param.value], { type: param.contentType || null });
184
- }
185
- form_1.append(param.name, paramBlob, param.fileName);
186
- return;
187
- }
188
- 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.");
189
- }
190
- form_1.append(param.name, param.value);
191
- });
192
- options.body = form_1;
193
- break;
194
- default:
195
- var formBody_1 = {};
196
- request.postData.params.map(function (param) {
197
- try {
198
- formBody_1[param.name] = JSON.parse(param.value);
199
- }
200
- catch (e) {
201
- formBody_1[param.name] = param.value;
202
- }
203
- return true;
204
- });
205
- options.body = JSON.stringify(formBody_1);
206
- }
165
+ throw new TypeError(
166
+ "An unknown object has been supplied into the `files` config for use. We only support instances of the File API and Node Buffer objects."
167
+ );
168
+ }
169
+ }
170
+ if ("value" in param && param.value) {
171
+ let paramBlob;
172
+ const parsed = parseDataUrl(param.value);
173
+ if (parsed) {
174
+ paramBlob = new Blob([param.value], { type: parsed.contentType || param.contentType || void 0 });
175
+ } else {
176
+ paramBlob = new Blob([param.value], { type: param.contentType || void 0 });
177
+ }
178
+ form.append(param.name, paramBlob, param.fileName);
179
+ return;
180
+ }
181
+ throw new Error(
182
+ "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."
183
+ );
184
+ }
185
+ if (param.value)
186
+ form.append(param.name, param.value);
187
+ });
188
+ options.body = form;
189
+ break;
190
+ default:
191
+ const formBody = {};
192
+ (_c = request.postData.params) == null ? void 0 : _c.map((param) => {
193
+ try {
194
+ formBody[param.name] = JSON.parse(param.value || "");
195
+ } catch (e) {
196
+ formBody[param.name] = param.value;
197
+ }
198
+ return true;
199
+ });
200
+ options.body = JSON.stringify(formBody);
207
201
  }
208
- else if ((_a = request.postData.text) === null || _a === void 0 ? void 0 : _a.length) {
209
- // If we've got `files` map content present, and this post data content contains a valid data
210
- // URL then we can substitute the payload with that file instead of the using data URL.
211
- if (opts.files) {
212
- var parsed = (0, data_urls_1.parse)(request.postData.text);
213
- if (parsed) {
214
- if ((parsed === null || parsed === void 0 ? void 0 : parsed.name) && parsed.name in opts.files) {
215
- var fileContents = getFileFromSuppliedFiles(parsed.name, opts.files);
216
- if (fileContents) {
217
- if (isBuffer(fileContents)) {
218
- options.body = fileContents;
219
- }
220
- else if (isFile(fileContents)) {
221
- // `Readable.from` isn't available in browsers but the browser `Request` object can
222
- // handle `File` objects just fine without us having to mold it into shape.
223
- if (isBrowser()) {
224
- options.body = fileContents;
225
- }
226
- else {
227
- // @ts-expect-error "Property 'from' does not exist on type 'typeof Readable'." but it does!
228
- options.body = readable_stream_1.Readable.from(fileContents.stream());
229
- shouldSetDuplex = true;
230
- // Supplying a polyfilled `File` stream into `Request.body` doesn't automatically
231
- // add `Content-Length`.
232
- if (!headers.has('content-length')) {
233
- headers.set('content-length', String(fileContents.size));
234
- }
235
- }
236
- }
237
- }
202
+ } else if ((_e = (_d = request.postData) == null ? void 0 : _d.text) == null ? void 0 : _e.length) {
203
+ if (opts.files) {
204
+ const parsed = parseDataUrl(request.postData.text);
205
+ if (parsed) {
206
+ if ((parsed == null ? void 0 : parsed.name) && parsed.name in opts.files) {
207
+ const fileContents = getFileFromSuppliedFiles(parsed.name, opts.files);
208
+ if (fileContents) {
209
+ if (isBuffer(fileContents)) {
210
+ options.body = fileContents;
211
+ } else if (isFile(fileContents)) {
212
+ if (isBrowser()) {
213
+ options.body = fileContents;
214
+ } else {
215
+ options.body = fileContents.stream();
216
+ shouldSetDuplex = true;
217
+ if (!headers.has("content-length")) {
218
+ headers.set("content-length", String(fileContents.size));
238
219
  }
220
+ }
239
221
  }
222
+ }
240
223
  }
241
- if (typeof options.body === 'undefined') {
242
- options.body = request.postData.text;
243
- }
224
+ }
244
225
  }
245
- /**
246
- * The fetch spec, which Node 18+ strictly abides by, now requires that `duplex` be sent with
247
- * requests that have payloads.
248
- *
249
- * As `RequestInit#duplex` isn't supported by any browsers, or even mentioned on MDN, we aren't
250
- * sending it in browser environments. This work is purely to support Node 18+ and `undici`
251
- * environments.
252
- *
253
- * @see {@link https://github.com/nodejs/node/issues/46221}
254
- * @see {@link https://github.com/whatwg/fetch/pull/1457}
255
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request}
256
- */
257
- if (shouldSetDuplex && !isBrowser()) {
258
- options.duplex = 'half';
226
+ if (typeof options.body === "undefined") {
227
+ options.body = request.postData.text;
259
228
  }
229
+ }
230
+ if (shouldSetDuplex && !isBrowser()) {
231
+ options.duplex = "half";
232
+ }
260
233
  }
261
- // We automaticaly assume that the HAR that we have already has query parameters encoded within
262
- // it so we do **not** use the `URLSearchParams` API here for composing the query string.
263
- var requestURL = url;
264
- if ('queryString' in request && request.queryString.length) {
265
- var urlObj = new URL(requestURL);
266
- var queryParams_1 = Array.from(urlObj.searchParams).map(function (_a) {
267
- var k = _a[0], v = _a[1];
268
- return "".concat(k, "=").concat(v);
269
- });
270
- request.queryString.forEach(function (q) {
271
- queryParams_1.push("".concat(q.name, "=").concat(q.value));
272
- });
273
- querystring = queryParams_1.join('&');
274
- // Because anchor hashes before query strings will prevent query strings from being delivered
275
- // we need to pop them off and re-add them after.
276
- if (urlObj.hash) {
277
- var urlWithoutHashes = requestURL.replace(urlObj.hash, '');
278
- requestURL = "".concat(urlWithoutHashes.split('?')[0]).concat(querystring ? "?".concat(querystring) : '');
279
- requestURL += urlObj.hash;
280
- }
281
- else {
282
- requestURL = "".concat(requestURL.split('?')[0]).concat(querystring ? "?".concat(querystring) : '');
283
- }
234
+ let requestURL = url;
235
+ if ("queryString" in request && request.queryString.length) {
236
+ const urlObj = new URL(requestURL);
237
+ const queryParams = Array.from(urlObj.searchParams).map(([k, v]) => `${k}=${v}`);
238
+ request.queryString.forEach((q) => {
239
+ queryParams.push(`${q.name}=${q.value}`);
240
+ });
241
+ querystring = queryParams.join("&");
242
+ if (urlObj.hash) {
243
+ const urlWithoutHashes = requestURL.replace(urlObj.hash, "");
244
+ requestURL = `${urlWithoutHashes.split("?")[0]}${querystring ? `?${querystring}` : ""}`;
245
+ requestURL += urlObj.hash;
246
+ } else {
247
+ requestURL = `${requestURL.split("?")[0]}${querystring ? `?${querystring}` : ""}`;
248
+ }
284
249
  }
285
250
  if (opts.userAgent) {
286
- headers.append('User-Agent', opts.userAgent);
251
+ headers.append("User-Agent", opts.userAgent);
287
252
  }
288
253
  options.headers = headers;
289
254
  return fetch(requestURL, options);
255
+ });
290
256
  }
291
- exports.default = fetchHAR;
257
+ export {
258
+ fetchHAR as default
259
+ };
260
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { FetchHAROptions, RequestInitWithDuplex } from './types.js';\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\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 async function fetchHAR(har: Har, opts: FetchHAROptions = {}): Promise<Response> {\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 if (!globalThis.Blob) {\n try {\n const NodeBlob = (await import('node:buffer')).Blob;\n // @ts-expect-error the types don't match exactly, which is expected!\n globalThis.Blob = NodeBlob;\n } catch (e) {\n throw new Error(\n 'The Blob API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/Blob',\n );\n }\n }\n\n if (!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 const UndiciFile = (await import('undici')).File;\n // @ts-expect-error the types don't match exactly, which is expected!\n globalThis.File = UndiciFile;\n } catch (e) {\n throw new Error(\n 'The File API is required for this library. https://developer.mozilla.org/en-US/docs/Web/API/File',\n );\n }\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,SAAS,oBAAoB;AAQtC,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,mBAAmB,QAAQ,CAAC;AAAA,EAC3C;AAEA,SAAO;AACT;AAEA,SAAO,SAAgC,IAAyD;AAAA,6CAAzD,KAAU,OAAwB,CAAC,GAAsB;AA5ChG;AA6CE,QAAI,CAAC;AAAK,YAAM,IAAI,MAAM,wBAAwB;AAClD,QAAI,CAAC,IAAI,OAAO,CAAC,IAAI,IAAI,WAAW,CAAC,IAAI,IAAI,QAAQ;AAAQ,YAAM,IAAI,MAAM,2BAA2B;AAExG,QAAI,CAAC,WAAW,MAAM;AACpB,UAAI;AACF,cAAM,YAAY,MAAM,OAAO,QAAa,GAAG;AAE/C,mBAAW,OAAO;AAAA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AAAA,IACF;AAEA,QAAI,KAAK,WAAW;AAClB,cAAQ,OAAO,cAAc,KAAK,SAAS;AAAA,IAC7C;AAEA,YAAQ,UAAU;AAElB,WAAO,MAAM,YAAY,OAAO;AAAA,EAClC;AAAA;","names":[]}
package/dist/types.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";//# sourceMappingURL=types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,19 @@
1
+ interface RequestInitWithDuplex extends RequestInit {
2
+ /**
3
+ * `RequestInit#duplex` does not yet exist in the TS `lib.dom.d.ts` definition yet the native
4
+ * fetch implementation in Node 18+, `undici`, requires it for certain POST payloads.
5
+ *
6
+ * @see {@link https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1483}
7
+ * @see {@link https://github.com/nodejs/node/issues/46221}
8
+ * @see {@link https://fetch.spec.whatwg.org/#request-class}
9
+ * @see {@link https://github.com/microsoft/TypeScript/blob/main/lib/lib.dom.d.ts}
10
+ */
11
+ duplex?: 'half';
12
+ }
13
+ interface FetchHAROptions {
14
+ files?: Record<string, Blob | Buffer>;
15
+ init?: RequestInitWithDuplex;
16
+ userAgent?: string;
17
+ }
18
+
19
+ export { FetchHAROptions, RequestInitWithDuplex };
@@ -0,0 +1,19 @@
1
+ interface RequestInitWithDuplex extends RequestInit {
2
+ /**
3
+ * `RequestInit#duplex` does not yet exist in the TS `lib.dom.d.ts` definition yet the native
4
+ * fetch implementation in Node 18+, `undici`, requires it for certain POST payloads.
5
+ *
6
+ * @see {@link https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1483}
7
+ * @see {@link https://github.com/nodejs/node/issues/46221}
8
+ * @see {@link https://fetch.spec.whatwg.org/#request-class}
9
+ * @see {@link https://github.com/microsoft/TypeScript/blob/main/lib/lib.dom.d.ts}
10
+ */
11
+ duplex?: 'half';
12
+ }
13
+ interface FetchHAROptions {
14
+ files?: Record<string, Blob | Buffer>;
15
+ init?: RequestInitWithDuplex;
16
+ userAgent?: string;
17
+ }
18
+
19
+ export { FetchHAROptions, RequestInitWithDuplex };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}