index.js
8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
'use strict';
const EventEmitter = require('events');
const http = require('http');
const https = require('https');
const PassThrough = require('stream').PassThrough;
const urlLib = require('url');
const querystring = require('querystring');
const duplexer3 = require('duplexer3');
const isStream = require('is-stream');
const getStream = require('get-stream');
const timedOut = require('timed-out');
const urlParseLax = require('url-parse-lax');
const lowercaseKeys = require('lowercase-keys');
const isRedirect = require('is-redirect');
const unzipResponse = require('unzip-response');
const createErrorClass = require('create-error-class');
const isRetryAllowed = require('is-retry-allowed');
const Buffer = require('safe-buffer').Buffer;
const pkg = require('./package');
function requestAsEventEmitter(opts) {
opts = opts || {};
const ee = new EventEmitter();
const requestUrl = opts.href || urlLib.resolve(urlLib.format(opts), opts.path);
let redirectCount = 0;
let retryCount = 0;
let redirectUrl;
const get = opts => {
const fn = opts.protocol === 'https:' ? https : http;
const req = fn.request(opts, res => {
const statusCode = res.statusCode;
if (isRedirect(statusCode) && opts.followRedirect && 'location' in res.headers && (opts.method === 'GET' || opts.method === 'HEAD')) {
res.resume();
if (++redirectCount > 10) {
ee.emit('error', new got.MaxRedirectsError(statusCode, opts), null, res);
return;
}
const bufferString = Buffer.from(res.headers.location, 'binary').toString();
redirectUrl = urlLib.resolve(urlLib.format(opts), bufferString);
const redirectOpts = Object.assign({}, opts, urlLib.parse(redirectUrl));
ee.emit('redirect', res, redirectOpts);
get(redirectOpts);
return;
}
setImmediate(() => {
const response = typeof unzipResponse === 'function' && req.method !== 'HEAD' ? unzipResponse(res) : res;
response.url = redirectUrl || requestUrl;
response.requestUrl = requestUrl;
ee.emit('response', response);
});
});
req.once('error', err => {
const backoff = opts.retries(++retryCount, err);
if (backoff) {
setTimeout(get, backoff, opts);
return;
}
ee.emit('error', new got.RequestError(err, opts));
});
if (opts.gotTimeout) {
timedOut(req, opts.gotTimeout);
}
setImmediate(() => {
ee.emit('request', req);
});
};
get(opts);
return ee;
}
function asPromise(opts) {
return new Promise((resolve, reject) => {
const ee = requestAsEventEmitter(opts);
ee.on('request', req => {
if (isStream(opts.body)) {
opts.body.pipe(req);
opts.body = undefined;
return;
}
req.end(opts.body);
});
ee.on('response', res => {
const stream = opts.encoding === null ? getStream.buffer(res) : getStream(res, opts);
stream
.catch(err => reject(new got.ReadError(err, opts)))
.then(data => {
const statusCode = res.statusCode;
const limitStatusCode = opts.followRedirect ? 299 : 399;
res.body = data;
if (opts.json && res.body) {
try {
res.body = JSON.parse(res.body);
} catch (e) {
throw new got.ParseError(e, statusCode, opts, data);
}
}
if (statusCode < 200 || statusCode > limitStatusCode) {
throw new got.HTTPError(statusCode, opts);
}
resolve(res);
})
.catch(err => {
Object.defineProperty(err, 'response', {value: res});
reject(err);
});
});
ee.on('error', reject);
});
}
function asStream(opts) {
const input = new PassThrough();
const output = new PassThrough();
const proxy = duplexer3(input, output);
if (opts.json) {
throw new Error('got can not be used as stream when options.json is used');
}
if (opts.body) {
proxy.write = () => {
throw new Error('got\'s stream is not writable when options.body is used');
};
}
const ee = requestAsEventEmitter(opts);
ee.on('request', req => {
proxy.emit('request', req);
if (isStream(opts.body)) {
opts.body.pipe(req);
return;
}
if (opts.body) {
req.end(opts.body);
return;
}
if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') {
input.pipe(req);
return;
}
req.end();
});
ee.on('response', res => {
const statusCode = res.statusCode;
res.pipe(output);
if (statusCode < 200 || statusCode > 299) {
proxy.emit('error', new got.HTTPError(statusCode, opts), null, res);
return;
}
proxy.emit('response', res);
});
ee.on('redirect', proxy.emit.bind(proxy, 'redirect'));
ee.on('error', proxy.emit.bind(proxy, 'error'));
return proxy;
}
function normalizeArguments(url, opts) {
if (typeof url !== 'string' && typeof url !== 'object') {
throw new Error(`Parameter \`url\` must be a string or object, not ${typeof url}`);
}
if (typeof url === 'string') {
url = url.replace(/^unix:/, 'http://$&');
url = urlParseLax(url);
if (url.auth) {
throw new Error('Basic authentication must be done with auth option');
}
}
opts = Object.assign(
{
protocol: 'http:',
path: '',
retries: 5
},
url,
opts
);
opts.headers = Object.assign({
'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`,
'accept-encoding': 'gzip,deflate'
}, lowercaseKeys(opts.headers));
const query = opts.query;
if (query) {
if (typeof query !== 'string') {
opts.query = querystring.stringify(query);
}
opts.path = `${opts.path.split('?')[0]}?${opts.query}`;
delete opts.query;
}
if (opts.json && opts.headers.accept === undefined) {
opts.headers.accept = 'application/json';
}
let body = opts.body;
if (body) {
if (typeof body !== 'string' && !(body !== null && typeof body === 'object')) {
throw new Error('options.body must be a ReadableStream, string, Buffer or plain Object');
}
opts.method = opts.method || 'POST';
if (isStream(body) && typeof body.getBoundary === 'function') {
// Special case for https://github.com/form-data/form-data
opts.headers['content-type'] = opts.headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`;
} else if (body !== null && typeof body === 'object' && !Buffer.isBuffer(body) && !isStream(body)) {
opts.headers['content-type'] = opts.headers['content-type'] || 'application/x-www-form-urlencoded';
body = opts.body = querystring.stringify(body);
}
if (opts.headers['content-length'] === undefined && opts.headers['transfer-encoding'] === undefined && !isStream(body)) {
const length = typeof body === 'string' ? Buffer.byteLength(body) : body.length;
opts.headers['content-length'] = length;
}
}
opts.method = (opts.method || 'GET').toUpperCase();
if (opts.hostname === 'unix') {
const matches = /(.+):(.+)/.exec(opts.path);
if (matches) {
opts.socketPath = matches[1];
opts.path = matches[2];
opts.host = null;
}
}
if (typeof opts.retries !== 'function') {
const retries = opts.retries;
opts.retries = (iter, err) => {
if (iter > retries || !isRetryAllowed(err)) {
return 0;
}
const noise = Math.random() * 100;
return ((1 << iter) * 1000) + noise;
};
}
if (opts.followRedirect === undefined) {
opts.followRedirect = true;
}
if (opts.timeout) {
opts.gotTimeout = opts.timeout;
delete opts.timeout;
}
return opts;
}
function got(url, opts) {
try {
return asPromise(normalizeArguments(url, opts));
} catch (err) {
return Promise.reject(err);
}
}
const helpers = [
'get',
'post',
'put',
'patch',
'head',
'delete'
];
helpers.forEach(el => {
got[el] = (url, opts) => got(url, Object.assign({}, opts, {method: el}));
});
got.stream = (url, opts) => asStream(normalizeArguments(url, opts));
for (const el of helpers) {
got.stream[el] = (url, opts) => got.stream(url, Object.assign({}, opts, {method: el}));
}
function stdError(error, opts) {
if (error.code !== undefined) {
this.code = error.code;
}
Object.assign(this, {
message: error.message,
host: opts.host,
hostname: opts.hostname,
method: opts.method,
path: opts.path
});
}
got.RequestError = createErrorClass('RequestError', stdError);
got.ReadError = createErrorClass('ReadError', stdError);
got.ParseError = createErrorClass('ParseError', function (e, statusCode, opts, data) {
stdError.call(this, e, opts);
this.statusCode = statusCode;
this.statusMessage = http.STATUS_CODES[this.statusCode];
this.message = `${e.message} in "${urlLib.format(opts)}": \n${data.slice(0, 77)}...`;
});
got.HTTPError = createErrorClass('HTTPError', function (statusCode, opts) {
stdError.call(this, {}, opts);
this.statusCode = statusCode;
this.statusMessage = http.STATUS_CODES[this.statusCode];
this.message = `Response code ${this.statusCode} (${this.statusMessage})`;
});
got.MaxRedirectsError = createErrorClass('MaxRedirectsError', function (statusCode, opts) {
stdError.call(this, {}, opts);
this.statusCode = statusCode;
this.statusMessage = http.STATUS_CODES[this.statusCode];
this.message = 'Redirected 10 times. Aborting.';
});
module.exports = got;