got 10.5.7 → 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.
Files changed (60) hide show
  1. package/dist/source/{calculate-retry-delay.d.ts → as-promise/calculate-retry-delay.d.ts} +0 -0
  2. package/dist/source/{calculate-retry-delay.js → as-promise/calculate-retry-delay.js} +6 -7
  3. package/dist/source/as-promise/core.d.ts +13 -0
  4. package/dist/source/as-promise/core.js +124 -0
  5. package/dist/source/as-promise/create-rejection.d.ts +2 -0
  6. package/dist/source/as-promise/create-rejection.js +30 -0
  7. package/dist/source/as-promise/index.d.ts +5 -0
  8. package/dist/source/as-promise/index.js +203 -0
  9. package/dist/source/as-promise/types.d.ts +77 -0
  10. package/dist/source/as-promise/types.js +27 -0
  11. package/dist/source/core/index.d.ts +272 -0
  12. package/dist/source/core/index.js +1091 -0
  13. package/dist/source/{utils → core/utils}/get-body-size.d.ts +0 -0
  14. package/dist/source/{utils → core/utils}/get-body-size.js +0 -0
  15. package/dist/source/core/utils/is-form-data.d.ts +8 -0
  16. package/dist/source/{utils → core/utils}/is-form-data.js +0 -0
  17. package/dist/source/core/utils/options-to-url.d.ts +15 -0
  18. package/dist/source/{utils → core/utils}/options-to-url.js +5 -34
  19. package/dist/source/core/utils/proxy-events.d.ts +3 -0
  20. package/dist/source/core/utils/proxy-events.js +17 -0
  21. package/dist/source/{utils → core/utils}/timed-out.d.ts +0 -0
  22. package/dist/source/{utils → core/utils}/timed-out.js +2 -5
  23. package/dist/source/{utils → core/utils}/unhandle.d.ts +1 -1
  24. package/dist/source/{utils → core/utils}/unhandle.js +0 -0
  25. package/dist/source/{utils → core/utils}/url-to-options.d.ts +0 -0
  26. package/dist/source/{utils → core/utils}/url-to-options.js +0 -0
  27. package/dist/source/core/utils/weakable-map.d.ts +8 -0
  28. package/dist/source/core/utils/weakable-map.js +29 -0
  29. package/dist/source/create.d.ts +3 -79
  30. package/dist/source/create.js +83 -39
  31. package/dist/source/index.d.ts +3 -6
  32. package/dist/source/index.js +13 -19
  33. package/dist/source/types.d.ts +84 -198
  34. package/dist/source/types.js +0 -1
  35. package/package.json +41 -37
  36. package/readme.md +211 -97
  37. package/dist/source/as-promise.d.ts +0 -3
  38. package/dist/source/as-promise.js +0 -152
  39. package/dist/source/as-stream.d.ts +0 -7
  40. package/dist/source/as-stream.js +0 -121
  41. package/dist/source/errors.d.ts +0 -41
  42. package/dist/source/errors.js +0 -103
  43. package/dist/source/get-response.d.ts +0 -6
  44. package/dist/source/get-response.js +0 -25
  45. package/dist/source/known-hook-events.d.ts +0 -88
  46. package/dist/source/known-hook-events.js +0 -11
  47. package/dist/source/normalize-arguments.d.ts +0 -19
  48. package/dist/source/normalize-arguments.js +0 -436
  49. package/dist/source/progress.d.ts +0 -4
  50. package/dist/source/progress.js +0 -40
  51. package/dist/source/request-as-event-emitter.d.ts +0 -12
  52. package/dist/source/request-as-event-emitter.js +0 -284
  53. package/dist/source/utils/dynamic-require.d.ts +0 -3
  54. package/dist/source/utils/dynamic-require.js +0 -4
  55. package/dist/source/utils/is-form-data.d.ts +0 -3
  56. package/dist/source/utils/merge.d.ts +0 -6
  57. package/dist/source/utils/merge.js +0 -35
  58. package/dist/source/utils/options-to-url.d.ts +0 -19
  59. package/dist/source/utils/supports-brotli.d.ts +0 -2
  60. package/dist/source/utils/supports-brotli.js +0 -4
@@ -1,436 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const url_1 = require("url");
4
- const util_1 = require("util");
5
- const CacheableRequest = require("cacheable-request");
6
- const http = require("http");
7
- const https = require("https");
8
- const lowercaseKeys = require("lowercase-keys");
9
- const toReadableStream = require("to-readable-stream");
10
- const is_1 = require("@sindresorhus/is");
11
- const cacheable_lookup_1 = require("cacheable-lookup");
12
- const errors_1 = require("./errors");
13
- const known_hook_events_1 = require("./known-hook-events");
14
- const dynamic_require_1 = require("./utils/dynamic-require");
15
- const get_body_size_1 = require("./utils/get-body-size");
16
- const is_form_data_1 = require("./utils/is-form-data");
17
- const merge_1 = require("./utils/merge");
18
- const options_to_url_1 = require("./utils/options-to-url");
19
- const supports_brotli_1 = require("./utils/supports-brotli");
20
- const types_1 = require("./types");
21
- const nonEnumerableProperties = [
22
- 'context',
23
- 'body',
24
- 'json',
25
- 'form'
26
- ];
27
- const isAgentByProtocol = (agent) => is_1.default.object(agent);
28
- // TODO: `preNormalizeArguments` should merge `options` & `defaults`
29
- exports.preNormalizeArguments = (options, defaults) => {
30
- var _a, _b, _c, _d, _e, _f;
31
- // `options.headers`
32
- if (is_1.default.undefined(options.headers)) {
33
- options.headers = {};
34
- }
35
- else {
36
- options.headers = lowercaseKeys(options.headers);
37
- }
38
- for (const [key, value] of Object.entries(options.headers)) {
39
- if (is_1.default.null_(value)) {
40
- throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
41
- }
42
- }
43
- // `options.prefixUrl`
44
- if (is_1.default.urlInstance(options.prefixUrl) || is_1.default.string(options.prefixUrl)) {
45
- options.prefixUrl = options.prefixUrl.toString();
46
- if (options.prefixUrl.length !== 0 && !options.prefixUrl.endsWith('/')) {
47
- options.prefixUrl += '/';
48
- }
49
- }
50
- else {
51
- options.prefixUrl = defaults ? defaults.prefixUrl : '';
52
- }
53
- // `options.hooks`
54
- if (is_1.default.undefined(options.hooks)) {
55
- options.hooks = {};
56
- }
57
- if (is_1.default.object(options.hooks)) {
58
- for (const event of known_hook_events_1.default) {
59
- if (Reflect.has(options.hooks, event)) {
60
- if (!is_1.default.array(options.hooks[event])) {
61
- throw new TypeError(`Parameter \`${event}\` must be an Array, not ${is_1.default(options.hooks[event])}`);
62
- }
63
- }
64
- else {
65
- options.hooks[event] = [];
66
- }
67
- }
68
- }
69
- else {
70
- throw new TypeError(`Parameter \`hooks\` must be an Object, not ${is_1.default(options.hooks)}`);
71
- }
72
- if (defaults) {
73
- for (const event of known_hook_events_1.default) {
74
- if (!(Reflect.has(options.hooks, event) && is_1.default.undefined(options.hooks[event]))) {
75
- // @ts-ignore Union type array is not assignable to union array type
76
- options.hooks[event] = [
77
- ...defaults.hooks[event],
78
- ...options.hooks[event]
79
- ];
80
- }
81
- }
82
- }
83
- // `options.timeout`
84
- if (is_1.default.number(options.timeout)) {
85
- options.timeout = { request: options.timeout };
86
- }
87
- else if (!is_1.default.object(options.timeout)) {
88
- options.timeout = {};
89
- }
90
- // `options.retry`
91
- const { retry } = options;
92
- if (defaults) {
93
- options.retry = { ...defaults.retry };
94
- }
95
- else {
96
- options.retry = {
97
- calculateDelay: retryObject => retryObject.computedValue,
98
- limit: 0,
99
- methods: [],
100
- statusCodes: [],
101
- errorCodes: [],
102
- maxRetryAfter: undefined
103
- };
104
- }
105
- if (is_1.default.object(retry)) {
106
- options.retry = {
107
- ...options.retry,
108
- ...retry
109
- };
110
- }
111
- else if (is_1.default.number(retry)) {
112
- options.retry.limit = retry;
113
- }
114
- if (options.retry.maxRetryAfter === undefined) {
115
- options.retry.maxRetryAfter = Math.min(...[options.timeout.request, options.timeout.connect].filter((n) => !is_1.default.nullOrUndefined(n)));
116
- }
117
- options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))];
118
- options.retry.statusCodes = [...new Set(options.retry.statusCodes)];
119
- options.retry.errorCodes = [...new Set(options.retry.errorCodes)];
120
- // `options.dnsCache`
121
- if (options.dnsCache && !(options.dnsCache instanceof cacheable_lookup_1.default)) {
122
- options.dnsCache = new cacheable_lookup_1.default({ cacheAdapter: options.dnsCache });
123
- }
124
- // `options.method`
125
- if (is_1.default.string(options.method)) {
126
- options.method = options.method.toUpperCase();
127
- }
128
- else {
129
- options.method = (_b = (_a = defaults) === null || _a === void 0 ? void 0 : _a.method, (_b !== null && _b !== void 0 ? _b : 'GET'));
130
- }
131
- // Better memory management, so we don't have to generate a new object every time
132
- if (options.cache) {
133
- options.cacheableRequest = new CacheableRequest(
134
- // @ts-ignore Cannot properly type a function with multiple definitions yet
135
- (requestOptions, handler) => requestOptions[types_1.requestSymbol](requestOptions, handler), options.cache);
136
- }
137
- // `options.cookieJar`
138
- if (is_1.default.object(options.cookieJar)) {
139
- let { setCookie, getCookieString } = options.cookieJar;
140
- // Horrible `tough-cookie` check
141
- if (setCookie.length === 4 && getCookieString.length === 0) {
142
- if (!Reflect.has(setCookie, util_1.promisify.custom)) {
143
- // @ts-ignore TS is dumb - it says `setCookie` is `never`.
144
- setCookie = util_1.promisify(setCookie.bind(options.cookieJar));
145
- getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar));
146
- }
147
- }
148
- else if (setCookie.length !== 2) {
149
- throw new TypeError('`options.cookieJar.setCookie` needs to be an async function with 2 arguments');
150
- }
151
- else if (getCookieString.length !== 1) {
152
- throw new TypeError('`options.cookieJar.getCookieString` needs to be an async function with 1 argument');
153
- }
154
- options.cookieJar = { setCookie, getCookieString };
155
- }
156
- // `options.encoding`
157
- if (is_1.default.null_(options.encoding)) {
158
- throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
159
- }
160
- // `options.maxRedirects`
161
- if (!Reflect.has(options, 'maxRedirects') && !(defaults && Reflect.has(defaults, 'maxRedirects'))) {
162
- options.maxRedirects = 0;
163
- }
164
- // Merge defaults
165
- if (defaults) {
166
- options = merge_1.default({}, defaults, options);
167
- }
168
- // `options._pagination`
169
- if (is_1.default.object(options._pagination)) {
170
- const { _pagination: pagination } = options;
171
- if (!is_1.default.function_(pagination.transform)) {
172
- throw new TypeError('`options._pagination.transform` must be implemented');
173
- }
174
- if (!is_1.default.function_(pagination.shouldContinue)) {
175
- throw new TypeError('`options._pagination.shouldContinue` must be implemented');
176
- }
177
- if (!is_1.default.function_(pagination.filter)) {
178
- throw new TypeError('`options._pagination.filter` must be implemented');
179
- }
180
- if (!is_1.default.function_(pagination.paginate)) {
181
- throw new TypeError('`options._pagination.paginate` must be implemented');
182
- }
183
- }
184
- // Other values
185
- options.decompress = Boolean(options.decompress);
186
- options.isStream = Boolean(options.isStream);
187
- options.throwHttpErrors = Boolean(options.throwHttpErrors);
188
- options.ignoreInvalidCookies = Boolean(options.ignoreInvalidCookies);
189
- options.cache = (_c = options.cache, (_c !== null && _c !== void 0 ? _c : false));
190
- options.responseType = (_d = options.responseType, (_d !== null && _d !== void 0 ? _d : 'text'));
191
- options.resolveBodyOnly = Boolean(options.resolveBodyOnly);
192
- options.followRedirect = Boolean(options.followRedirect);
193
- options.dnsCache = (_e = options.dnsCache, (_e !== null && _e !== void 0 ? _e : false));
194
- options.useElectronNet = Boolean(options.useElectronNet);
195
- options.methodRewriting = Boolean(options.methodRewriting);
196
- options.context = (_f = options.context, (_f !== null && _f !== void 0 ? _f : {}));
197
- return options;
198
- };
199
- exports.mergeOptions = (...sources) => {
200
- let mergedOptions = exports.preNormalizeArguments({});
201
- // Non enumerable properties shall not be merged
202
- const properties = {};
203
- for (const source of sources) {
204
- mergedOptions = exports.preNormalizeArguments(merge_1.default({}, source), mergedOptions);
205
- for (const name of nonEnumerableProperties) {
206
- if (!Reflect.has(source, name)) {
207
- continue;
208
- }
209
- properties[name] = {
210
- writable: true,
211
- configurable: true,
212
- enumerable: false,
213
- value: source[name]
214
- };
215
- }
216
- }
217
- Object.defineProperties(mergedOptions, properties);
218
- return mergedOptions;
219
- };
220
- exports.normalizeArguments = (url, options, defaults) => {
221
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
222
- // Merge options
223
- if (typeof url === 'undefined') {
224
- throw new TypeError('Missing `url` argument');
225
- }
226
- const runInitHooks = (hooks, options) => {
227
- if (hooks && options) {
228
- for (const hook of hooks) {
229
- const result = hook(options);
230
- if (is_1.default.promise(result)) {
231
- throw new TypeError('The `init` hook must be a synchronous function');
232
- }
233
- }
234
- }
235
- };
236
- const hasUrl = is_1.default.urlInstance(url) || is_1.default.string(url);
237
- if (hasUrl) {
238
- if (options) {
239
- if (Reflect.has(options, 'url')) {
240
- throw new TypeError('The `url` option cannot be used if the input is a valid URL.');
241
- }
242
- }
243
- else {
244
- options = {};
245
- }
246
- // @ts-ignore URL is not URL
247
- options.url = url;
248
- runInitHooks((_a = defaults) === null || _a === void 0 ? void 0 : _a.options.hooks.init, options);
249
- runInitHooks((_b = options.hooks) === null || _b === void 0 ? void 0 : _b.init, options);
250
- }
251
- else if (Reflect.has(url, 'resolve')) {
252
- throw new Error('The legacy `url.Url` is deprecated. Use `URL` instead.');
253
- }
254
- else {
255
- runInitHooks((_c = defaults) === null || _c === void 0 ? void 0 : _c.options.hooks.init, url);
256
- runInitHooks((_d = url.hooks) === null || _d === void 0 ? void 0 : _d.init, url);
257
- if (options) {
258
- runInitHooks((_e = defaults) === null || _e === void 0 ? void 0 : _e.options.hooks.init, options);
259
- runInitHooks((_f = options.hooks) === null || _f === void 0 ? void 0 : _f.init, options);
260
- }
261
- }
262
- if (hasUrl) {
263
- options = exports.mergeOptions((_h = (_g = defaults) === null || _g === void 0 ? void 0 : _g.options, (_h !== null && _h !== void 0 ? _h : {})), (options !== null && options !== void 0 ? options : {}));
264
- }
265
- else {
266
- options = exports.mergeOptions((_k = (_j = defaults) === null || _j === void 0 ? void 0 : _j.options, (_k !== null && _k !== void 0 ? _k : {})), url, (options !== null && options !== void 0 ? options : {}));
267
- }
268
- // Normalize URL
269
- // TODO: drop `optionsToUrl` in Got 12
270
- if (is_1.default.string(options.url)) {
271
- options.url = options.prefixUrl + options.url;
272
- options.url = options.url.replace(/^unix:/, 'http://$&');
273
- if (options.searchParams || options.search) {
274
- options.url = options.url.split('?')[0];
275
- }
276
- // @ts-ignore URL is not URL
277
- options.url = options_to_url_1.default({
278
- origin: options.url,
279
- ...options
280
- });
281
- }
282
- else if (!is_1.default.urlInstance(options.url)) {
283
- // @ts-ignore URL is not URL
284
- options.url = options_to_url_1.default({ origin: options.prefixUrl, ...options });
285
- }
286
- const normalizedOptions = options;
287
- // Make it possible to change `options.prefixUrl`
288
- let prefixUrl = options.prefixUrl;
289
- Object.defineProperty(normalizedOptions, 'prefixUrl', {
290
- set: (value) => {
291
- if (!normalizedOptions.url.href.startsWith(value)) {
292
- throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${normalizedOptions.url.href}`);
293
- }
294
- normalizedOptions.url = new url_1.URL(value + normalizedOptions.url.href.slice(prefixUrl.length));
295
- prefixUrl = value;
296
- },
297
- get: () => prefixUrl
298
- });
299
- // Make it possible to remove default headers
300
- for (const [key, value] of Object.entries(normalizedOptions.headers)) {
301
- if (is_1.default.undefined(value)) {
302
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
303
- delete normalizedOptions.headers[key];
304
- }
305
- }
306
- return normalizedOptions;
307
- };
308
- const withoutBody = new Set(['GET', 'HEAD']);
309
- exports.normalizeRequestArguments = async (options) => {
310
- var _a, _b, _c;
311
- options = exports.mergeOptions(options);
312
- // Serialize body
313
- const { headers } = options;
314
- const hasNoContentType = is_1.default.undefined(headers['content-type']);
315
- {
316
- // TODO: these checks should be moved to `preNormalizeArguments`
317
- const isForm = !is_1.default.undefined(options.form);
318
- const isJson = !is_1.default.undefined(options.json);
319
- const isBody = !is_1.default.undefined(options.body);
320
- if ((isBody || isForm || isJson) && withoutBody.has(options.method)) {
321
- throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
322
- }
323
- if ([isBody, isForm, isJson].filter(isTrue => isTrue).length > 1) {
324
- throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');
325
- }
326
- if (isBody &&
327
- !is_1.default.nodeStream(options.body) &&
328
- !is_1.default.string(options.body) &&
329
- !is_1.default.buffer(options.body) &&
330
- !(is_1.default.object(options.body) && is_form_data_1.default(options.body))) {
331
- throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');
332
- }
333
- if (isForm && !is_1.default.object(options.form)) {
334
- throw new TypeError('The `form` option must be an Object');
335
- }
336
- }
337
- if (options.body) {
338
- // Special case for https://github.com/form-data/form-data
339
- if (is_1.default.object(options.body) && is_form_data_1.default(options.body) && hasNoContentType) {
340
- headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
341
- }
342
- }
343
- else if (options.form) {
344
- if (hasNoContentType) {
345
- headers['content-type'] = 'application/x-www-form-urlencoded';
346
- }
347
- options.body = (new url_1.URLSearchParams(options.form)).toString();
348
- }
349
- else if (options.json) {
350
- if (hasNoContentType) {
351
- headers['content-type'] = 'application/json';
352
- }
353
- options.body = JSON.stringify(options.json);
354
- }
355
- const uploadBodySize = await get_body_size_1.default(options);
356
- if (!is_1.default.nodeStream(options.body)) {
357
- options.body = toReadableStream(options.body);
358
- }
359
- // See https://tools.ietf.org/html/rfc7230#section-3.3.2
360
- // A user agent SHOULD send a Content-Length in a request message when
361
- // no Transfer-Encoding is sent and the request method defines a meaning
362
- // for an enclosed payload body. For example, a Content-Length header
363
- // field is normally sent in a POST request even when the value is 0
364
- // (indicating an empty payload body). A user agent SHOULD NOT send a
365
- // Content-Length header field when the request message does not contain
366
- // a payload body and the method semantics do not anticipate such a
367
- // body.
368
- if (is_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) {
369
- if ((options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH' || options.method === 'DELETE') &&
370
- !is_1.default.undefined(uploadBodySize)) {
371
- // @ts-ignore We assign if it is undefined, so this IS correct
372
- headers['content-length'] = String(uploadBodySize);
373
- }
374
- }
375
- if (!options.isStream && options.responseType === 'json' && is_1.default.undefined(headers.accept)) {
376
- headers.accept = 'application/json';
377
- }
378
- if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) {
379
- headers['accept-encoding'] = supports_brotli_1.default ? 'gzip, deflate, br' : 'gzip, deflate';
380
- }
381
- // Validate URL
382
- if (options.url.protocol !== 'http:' && options.url.protocol !== 'https:') {
383
- throw new errors_1.UnsupportedProtocolError(options);
384
- }
385
- decodeURI(options.url.toString());
386
- // Normalize request function
387
- if (is_1.default.function_(options.request)) {
388
- options[types_1.requestSymbol] = options.request;
389
- delete options.request;
390
- }
391
- else {
392
- options[types_1.requestSymbol] = options.url.protocol === 'https:' ? https.request : http.request;
393
- }
394
- // UNIX sockets
395
- if (options.url.hostname === 'unix') {
396
- const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(options.url.pathname);
397
- if ((_a = matches) === null || _a === void 0 ? void 0 : _a.groups) {
398
- const { socketPath, path } = matches.groups;
399
- options = {
400
- ...options,
401
- socketPath,
402
- path,
403
- host: ''
404
- };
405
- }
406
- }
407
- if (isAgentByProtocol(options.agent)) {
408
- options.agent = (_b = options.agent[options.url.protocol.slice(0, -1)], (_b !== null && _b !== void 0 ? _b : options.agent));
409
- }
410
- if (options.dnsCache) {
411
- options.lookup = options.dnsCache.lookup;
412
- }
413
- /* istanbul ignore next: electron.net is broken */
414
- // No point in typing process.versions correctly, as
415
- // `process.version.electron` is used only once, right here.
416
- if (options.useElectronNet && process.versions.electron) {
417
- const electron = dynamic_require_1.default(module, 'electron'); // Trick webpack
418
- options.request = util_1.deprecate((_c = electron.net.request, (_c !== null && _c !== void 0 ? _c : electron.remote.net.request)), 'Electron support has been deprecated and will be removed in Got 11.\n' +
419
- 'See https://github.com/sindresorhus/got/issues/899 for further information.', 'GOT_ELECTRON');
420
- }
421
- // Got's `timeout` is an object, http's `timeout` is a number, so they're not compatible.
422
- delete options.timeout;
423
- // Set cookies
424
- if (options.cookieJar) {
425
- const cookieString = await options.cookieJar.getCookieString(options.url.toString());
426
- if (is_1.default.nonEmptyString(cookieString)) {
427
- options.headers.cookie = cookieString;
428
- }
429
- else {
430
- delete options.headers.cookie;
431
- }
432
- }
433
- // `http-cache-semantics` checks this
434
- delete options.url;
435
- return options;
436
- };
@@ -1,4 +0,0 @@
1
- /// <reference types="node" />
2
- import EventEmitter = require('events');
3
- import { Transform as TransformStream } from 'stream';
4
- export declare function createProgressStream(name: 'downloadProgress' | 'uploadProgress', emitter: EventEmitter, totalBytes?: number | string): TransformStream;
@@ -1,40 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const stream_1 = require("stream");
4
- const is_1 = require("@sindresorhus/is");
5
- function createProgressStream(name, emitter, totalBytes) {
6
- let transformedBytes = 0;
7
- if (is_1.default.string(totalBytes)) {
8
- totalBytes = Number(totalBytes);
9
- }
10
- const progressStream = new stream_1.Transform({
11
- transform(chunk, _encoding, callback) {
12
- transformedBytes += chunk.length;
13
- const percent = totalBytes ? transformedBytes / totalBytes : 0;
14
- // Let `flush()` be responsible for emitting the last event
15
- if (percent < 1) {
16
- emitter.emit(name, {
17
- percent,
18
- transferred: transformedBytes,
19
- total: totalBytes
20
- });
21
- }
22
- callback(undefined, chunk);
23
- },
24
- flush(callback) {
25
- emitter.emit(name, {
26
- percent: 1,
27
- transferred: transformedBytes,
28
- total: totalBytes
29
- });
30
- callback();
31
- }
32
- });
33
- emitter.emit(name, {
34
- percent: 0,
35
- transferred: 0,
36
- total: totalBytes
37
- });
38
- return progressStream;
39
- }
40
- exports.createProgressStream = createProgressStream;
@@ -1,12 +0,0 @@
1
- /// <reference types="node" />
2
- import EventEmitter = require('events');
3
- import { ProxyStream } from './as-stream';
4
- import { RequestError, TimeoutError } from './errors';
5
- import { NormalizedOptions } from './types';
6
- export interface RequestAsEventEmitter extends EventEmitter {
7
- retry: (error: TimeoutError | RequestError) => boolean;
8
- abort: () => void;
9
- }
10
- declare const _default: (options: NormalizedOptions) => RequestAsEventEmitter;
11
- export default _default;
12
- export declare const proxyEvents: (proxy: EventEmitter | ProxyStream<unknown>, emitter: RequestAsEventEmitter) => void;