id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
300 | async function outputInterface(entry: Interface, currentNamespace: INamespace | undefined) {
let output = '';
if (entry.export) {
output += 'export ';
}
if (isInterfaceProperties(entry)) {
const extendList = entry.extends.map(extend => extend.name + stringifyGenerics(extend.generics)).join(', ');
output += 'interface ' + entry.name + stringifyGenerics(entry.generics, true, stringifySimpleTypes);
if (extendList) {
output += ` extends ${extendList}`;
}
output += '{' + EOL;
for (const property of entry.properties) {
const comment = await property.comment();
if (comment) {
output += comment + EOL;
}
const type = isAliasProperty(property) ? property.alias : property.type;
const value = `${stringifyTypes([type], currentNamespace, false)} | undefined`;
output += `${JSON.stringify(property.name)}?: ${value};`;
output += EOL;
}
output += '}';
} else {
output += 'type ' + entry.name + stringifyGenerics(entry.generics, true, stringifySimpleTypes) + ' = ';
const name = entry.fallbacks.name + stringifyGenerics(entry.generics, false, stringifySimpleTypes);
output += `Fallback<${name}>`;
}
return output;
} | type Interface = IInterfaceProperties | IInterfaceFallback; |
301 | function outputDeclaration(entry: IDeclaration, currentNamespace: INamespace | undefined) {
let output = '';
if (entry.export) {
output += 'export ';
}
output += `type ${
entry.name + stringifyGenerics(entry.generics, entry.export, stringifySimpleTypes)
} = ${stringifyTypes(entry.types, currentNamespace, true)}`;
return output;
} | interface IDeclaration {
name: string;
export: boolean;
types: DeclarableType[];
generics: IGenerics[];
namespace: INamespace | undefined;
} |
302 | (dataTypes: IDataTypeDictionary) => Promise<TReturn> | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
303 | async function resolveDataTypes(
dictionary: IDataTypeDictionary,
types: TypeType[],
minTypesInDataTypes: number,
resolver: (
dataTypes: IDataTypeDictionary,
dataType: IDataType,
min: number,
) => Promise<ResolvedType[]> = simpleDataTypeResolver,
): Promise<ResolvedType[]> {
const resolvedDataTypes: ResolvedType[] = [];
for (const type of types) {
switch (type.type) {
case Type.DataType: {
const resolvedDataType = await resolver(dictionary, type, minTypesInDataTypes);
if (resolvedDataType.length >= minTypesInDataTypes) {
// Dissolve data type if it's too small
const dataType = createDataType(dictionary, type.name, resolvedDataType);
if (!hasType(resolvedDataTypes, dataType)) {
resolvedDataTypes.push(dataType);
}
} else {
for (const resolvedType of resolvedDataType) {
if (!hasType(resolvedDataTypes, resolvedType)) {
resolvedDataTypes.push(resolvedType);
}
}
}
break;
}
case Type.PropertyReference: {
const resolvedProperty = await resolver(dictionary, type, minTypesInDataTypes);
// Dissolve property references completely
for (const resolvedType of resolvedProperty) {
if (!hasType(resolvedDataTypes, resolvedType)) {
resolvedDataTypes.push(resolvedType);
}
}
break;
}
default:
if (!hasType(resolvedDataTypes, type)) {
resolvedDataTypes.push(type);
}
}
}
return resolvedDataTypes;
} | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
304 | async function resolveDataTypes(
dictionary: IDataTypeDictionary,
types: TypeType[],
minTypesInDataTypes: number,
resolver: (
dataTypes: IDataTypeDictionary,
dataType: IDataType,
min: number,
) => Promise<ResolvedType[]> = simpleDataTypeResolver,
): Promise<ResolvedType[]> {
const resolvedDataTypes: ResolvedType[] = [];
for (const type of types) {
switch (type.type) {
case Type.DataType: {
const resolvedDataType = await resolver(dictionary, type, minTypesInDataTypes);
if (resolvedDataType.length >= minTypesInDataTypes) {
// Dissolve data type if it's too small
const dataType = createDataType(dictionary, type.name, resolvedDataType);
if (!hasType(resolvedDataTypes, dataType)) {
resolvedDataTypes.push(dataType);
}
} else {
for (const resolvedType of resolvedDataType) {
if (!hasType(resolvedDataTypes, resolvedType)) {
resolvedDataTypes.push(resolvedType);
}
}
}
break;
}
case Type.PropertyReference: {
const resolvedProperty = await resolver(dictionary, type, minTypesInDataTypes);
// Dissolve property references completely
for (const resolvedType of resolvedProperty) {
if (!hasType(resolvedDataTypes, resolvedType)) {
resolvedDataTypes.push(resolvedType);
}
}
break;
}
default:
if (!hasType(resolvedDataTypes, type)) {
resolvedDataTypes.push(type);
}
}
}
return resolvedDataTypes;
} | interface IDataType<TTypeKind = Type.DataType | Type.PropertyReference> {
type: TTypeKind;
name: string;
} |
305 | (
dataTypes: IDataTypeDictionary,
dataType: IDataType,
min: number,
) => Promise<ResolvedType[]> | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
306 | (
dataTypes: IDataTypeDictionary,
dataType: IDataType,
min: number,
) => Promise<ResolvedType[]> | interface IDataType<TTypeKind = Type.DataType | Type.PropertyReference> {
type: TTypeKind;
name: string;
} |
307 | async function simpleDataTypeResolver(
dictionary: IDataTypeDictionary,
dataType: IDataType,
minTypesInDataTypes: number,
): Promise<ResolvedType[]> {
const syntax = await getSyntax(dataType.name);
return syntax
? resolveDataTypes(dictionary, typer(parse(syntax)), minTypesInDataTypes, simpleDataTypeResolver)
: [{ type: Type.String }];
} | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
308 | async function simpleDataTypeResolver(
dictionary: IDataTypeDictionary,
dataType: IDataType,
minTypesInDataTypes: number,
): Promise<ResolvedType[]> {
const syntax = await getSyntax(dataType.name);
return syntax
? resolveDataTypes(dictionary, typer(parse(syntax)), minTypesInDataTypes, simpleDataTypeResolver)
: [{ type: Type.String }];
} | interface IDataType<TTypeKind = Type.DataType | Type.PropertyReference> {
type: TTypeKind;
name: string;
} |
309 | (
dictionary: IDataTypeDictionary,
dataType: IDataType,
min: number,
) => Promise<ResolvedType[]> | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
310 | (
dictionary: IDataTypeDictionary,
dataType: IDataType,
min: number,
) => Promise<ResolvedType[]> | interface IDataType<TTypeKind = Type.DataType | Type.PropertyReference> {
type: TTypeKind;
name: string;
} |
311 | function createDataType(dictionary: IDataTypeDictionary, name: string, types: ResolvedType[], index = 0): DataType {
const realName = name + (index > 0 ? index + 1 : '');
// Rename in case of conflict
if (realName in dictionary) {
const existingDataType = dictionary[realName];
for (const type of types) {
if (!hasType(existingDataType, type)) {
return createDataType(dictionary, name, types, index + 1);
}
}
for (const type of existingDataType) {
if (!hasType(types, type)) {
return createDataType(dictionary, name, types, index + 1);
}
}
}
dictionary[realName] = types;
return {
type: Type.DataType,
name: realName,
};
} | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
312 | async function getAtRules(dataTypeDictionary: IDataTypeDictionary, minTypesInDataTypes: number) {
const literals: IStringLiteral[] = [];
const rules: { [name: string]: IAtRuleDescriptors } = {};
for (const atName in atRules) {
const atRule = atRules[atName];
// Without the `@`
const name = atName.slice(1);
literals.push({
type: Type.StringLiteral,
literal: atName,
});
if ('descriptors' in atRule) {
const descriptors: IAtRuleDescriptors = {};
const compatibilityData = await getAtRuleData(name);
let hasSupportedProperties = false;
for (const descriptor in atRule.descriptors) {
let entities = parse(atRule.descriptors[descriptor].syntax);
let properties = [descriptor];
if (compatibilityData && descriptor in compatibilityData) {
const compats = getCompats(compatibilityData[descriptor]);
if (compats.every(compat => !isAddedBySome(compat))) {
// The property needs to be added by some browsers
continue;
}
entities = compatSyntax(compatibilityData, entities);
properties = properties.concat(
...compats.map(compat =>
// We mix current and obsolete for now
compatNames(compat, descriptor)
.concat(compatNames(compat, descriptor, true))
.filter(property => !(property in atRule.descriptors)),
),
);
}
const types = await resolveDataTypes(dataTypeDictionary, typer(entities), minTypesInDataTypes);
for (const property of properties) {
hasSupportedProperties = true;
descriptors[property] = {
name: descriptor,
types,
};
}
}
if (hasSupportedProperties) {
rules[name] = descriptors;
}
}
}
return {
literals,
rules,
};
} | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
313 | async function getGlobals(
dataTypeDictionary: IDataTypeDictionary,
minTypesInDataTypes: number,
): Promise<ResolvedType[]> {
const dataTypes = await resolveDataTypes(
dataTypeDictionary,
typer(compatSyntax(await getGlobalCompatibilityData(), parse(await getPropertySyntax(ALL)))),
minTypesInDataTypes,
);
return dataTypes;
} | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
314 | async function getHtmlProperties(dataTypeDictionary: IDataTypeDictionary, minTypesInDataTypes: number) {
const propertiesMap = await getProperties();
const allPropertyData = await getPropertyData(ALL);
let getAllComment = async () => {
const comment = await composeCommentBlock(allPropertyData, propertiesMap[ALL]);
getAllComment = () => Promise.resolve(comment);
return comment;
};
htmlPropertiesMap[ALL] = {
name: 'all',
vendor: false,
shorthand: true,
obsolete: false,
comment: () => getAllComment(),
types: [],
};
function filterMissingProperties(names: string[]) {
// Filter only those which isn't defined in MDN data
return names.filter(name => !(name in propertiesMap));
}
for (const originalName in propertiesMap) {
if (IGNORES.includes(originalName)) {
continue;
}
const data = propertiesMap[originalName];
// Default values
let entities = parse(await getPropertySyntax(originalName));
let currentNames: string[] = [originalName];
let obsoleteNames: string[] = [];
let deprecated = isDeprecated(data);
const compatibilityData = await getPropertyData(originalName);
if (compatibilityData) {
const compats = getCompats(compatibilityData);
if (compats.every(compat => !isAddedBySome(compat))) {
// The property needs to be added by some browsers
continue;
}
entities = compatSyntax(compatibilityData, entities);
currentNames = currentNames.concat(
...compats.map(compat => filterMissingProperties(compatNames(compat, originalName))),
);
obsoleteNames = obsoleteNames.concat(
...compats.map(compat => filterMissingProperties(compatNames(compat, originalName, true))),
);
deprecated = compats.every(compat => isDeprecated(data, compat));
}
if (deprecated) {
// Move all property names to obsolete
obsoleteNames = obsoleteNames.concat(currentNames);
currentNames = [];
}
const types = await resolveDataTypes(
dataTypeDictionary,
typer(entities),
minTypesInDataTypes,
createPropertyDataTypeResolver(compatibilityData),
);
// Remove duplicates
for (const name of new Set(currentNames)) {
const vendor = isVendorProperty(name);
let getComment = () => {
const comment = composeCommentBlock(compatibilityData, data, vendor);
getComment = () => comment;
return comment;
};
htmlPropertiesMap[name] = mergeRecurrent(name, {
name: originalName,
vendor,
shorthand: data.shorthand,
obsolete: false,
comment: () => getComment(),
types,
});
}
// Remove duplicates
for (const name of new Set(obsoleteNames)) {
const vendor = isVendorProperty(name);
let getComment = () => {
const comment = composeCommentBlock(compatibilityData, data, vendor, true);
getComment = () => comment;
return comment;
};
htmlPropertiesMap[name] = mergeRecurrent(name, {
name: originalName,
vendor,
shorthand: data.shorthand,
obsolete: true,
comment: () => getComment(),
types,
});
}
}
return htmlPropertiesMap;
} | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
315 | async function getSvgProperties(dataTypeDictionary: IDataTypeDictionary, minTypesInDataTypes: number) {
for (const name in rawSvgProperties) {
const compatibilityData = await getPropertyData(name);
const syntax = rawSvgProperties[name].syntax;
if (syntax) {
svgPropertiesMap[name] = {
name,
vendor: false,
shorthand: false,
obsolete: false,
comment: () => Promise.resolve(undefined),
types: await resolveDataTypes(
dataTypeDictionary,
typer(parse(syntax)),
minTypesInDataTypes,
createPropertyDataTypeResolver(compatibilityData),
),
};
}
}
return svgPropertiesMap;
} | interface IDataTypeDictionary {
[key: string]: ResolvedType[];
} |
316 | (type: SimpleType) => string | type SimpleType = Exclude<DeclarableType, IAlias>; |
317 | (type: IAlias) => string | interface IAlias {
type: Type.Alias;
name: string;
generics: IGenerics[];
namespace: INamespace | undefined;
} |
318 | (type: DeclarableType) => string | type DeclarableType = TypeType<IAlias> | IArray; |
319 | (type: IAlias, currentNamespace: INamespace | undefined) => string | interface IAlias {
type: Type.Alias;
name: string;
generics: IGenerics[];
namespace: INamespace | undefined;
} |
320 | (type: DeclarableType) => {
switch (type.type) {
case Type.String:
return 'string';
case Type.Number:
return 'number';
case Type.StringLiteral:
return JSON.stringify(type.literal);
case Type.NumericLiteral:
return type.literal;
case Type.Array:
return `Array<${stringifyType(type.of)}>`;
case Type.Alias: {
return createTypeAliasName(type, currentNamespace) + stringifyGenerics(type.generics);
}
case Type.Length:
return lengthGeneric.name;
case Type.Time:
return timeGeneric.name;
}
} | type DeclarableType = TypeType<IAlias> | IArray; |
321 | function message(error: IError) {
const {
loc: {
start: { line, column },
},
descr,
} = error.message[0];
return `${line}:${column} - ${descr}`;
} | interface IError {
kind: string;
level: string;
suppressions: any[];
extra: IExtra[];
message: IMessage[];
} |
322 | (server: ExtendedHttpTestServer, clock: GlobalClock): {emitter: EventEmitter; promise: Promise<unknown>} => {
const emitter = new EventEmitter();
const promise = new Promise<void>((resolve, reject) => {
server.all('/abort', async (request, response) => {
emitter.emit('connection');
request.once('aborted', resolve);
response.once('finish', reject.bind(null, new Error('Request finished instead of aborting.')));
try {
await pEvent(request, 'end');
} catch {
// Node.js 15.0.0 throws AND emits `aborted`
}
response.end();
});
server.get('/redirect', (_request, response) => {
response.writeHead(302, {
location: `${server.url}/abort`,
});
response.end();
emitter.emit('sentRedirect');
clock.tick(3000);
resolve();
});
});
return {emitter, promise};
} | type ExtendedHttpTestServer = {
http: http.Server;
url: string;
port: number;
hostname: string;
close: () => Promise<any>;
} & Express; |
323 | (server: ExtendedHttpTestServer, clock: GlobalClock): {emitter: EventEmitter; promise: Promise<unknown>} => {
const emitter = new EventEmitter();
const promise = new Promise<void>((resolve, reject) => {
server.all('/abort', async (request, response) => {
emitter.emit('connection');
request.once('aborted', resolve);
response.once('finish', reject.bind(null, new Error('Request finished instead of aborting.')));
try {
await pEvent(request, 'end');
} catch {
// Node.js 15.0.0 throws AND emits `aborted`
}
response.end();
});
server.get('/redirect', (_request, response) => {
response.writeHead(302, {
location: `${server.url}/abort`,
});
response.end();
emitter.emit('sentRedirect');
clock.tick(3000);
resolve();
});
});
return {emitter, promise};
} | type GlobalClock = any; |
324 | (clock?: GlobalClock): Handler => (_request, response) => {
response.writeHead(200, {
'transfer-encoding': 'chunked',
});
response.flushHeaders();
stream.pipeline(
slowDataStream(clock),
response,
() => {
response.end();
},
);
} | type GlobalClock = any; |
325 | (error: Error) => {
if (controller.signal.aborted) {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
326 | (error: Error) => {
if (controller.signal.aborted) {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
327 | (error: Error) => {
if (error.message === 'This operation was aborted.') {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
328 | (error: Error) => {
if (error.message === 'This operation was aborted.') {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
329 | (options: OptionsInit) => {
options.headers = {
foo: 'bar',
};
} | type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
}; |
330 | (event: Progress) => events.push(event) | type Progress = {
percent: number;
transferred: number;
total?: number;
}; |
331 | (event: Progress) => {
events.push(event);
void promise.off('uploadProgress', listener);
} | type Progress = {
percent: number;
transferred: number;
total?: number;
}; |
332 | (server: ExtendedHttpTestServer, clock: GlobalClock): {emitter: EventEmitter; promise: Promise<unknown>} => {
const emitter = new EventEmitter();
const promise = new Promise<void>((resolve, reject) => {
server.all('/abort', async (request, response) => {
emitter.emit('connection');
request.once('aborted', resolve);
response.once('finish', reject.bind(null, new Error('Request finished instead of aborting.')));
try {
await pEvent(request, 'end');
} catch {
// Node.js 15.0.0 throws AND emits `aborted`
}
response.end();
});
server.get('/redirect', (_request, response) => {
response.writeHead(302, {
location: `${server.url}/abort`,
});
response.end();
emitter.emit('sentRedirect');
clock.tick(3000);
resolve();
});
});
return {emitter, promise};
} | type ExtendedHttpTestServer = {
http: http.Server;
url: string;
port: number;
hostname: string;
close: () => Promise<any>;
} & Express; |
333 | (server: ExtendedHttpTestServer, clock: GlobalClock): {emitter: EventEmitter; promise: Promise<unknown>} => {
const emitter = new EventEmitter();
const promise = new Promise<void>((resolve, reject) => {
server.all('/abort', async (request, response) => {
emitter.emit('connection');
request.once('aborted', resolve);
response.once('finish', reject.bind(null, new Error('Request finished instead of aborting.')));
try {
await pEvent(request, 'end');
} catch {
// Node.js 15.0.0 throws AND emits `aborted`
}
response.end();
});
server.get('/redirect', (_request, response) => {
response.writeHead(302, {
location: `${server.url}/abort`,
});
response.end();
emitter.emit('sentRedirect');
clock.tick(3000);
resolve();
});
});
return {emitter, promise};
} | type GlobalClock = any; |
334 | (clock?: GlobalClock): Handler => (_request, response) => {
response.writeHead(200, {
'transfer-encoding': 'chunked',
});
response.flushHeaders();
stream.pipeline(
slowDataStream(clock),
response,
() => {
response.end();
},
);
} | type GlobalClock = any; |
335 | (error: Error) => {
if (p.isCanceled) {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
336 | (error: Error) => {
if (p.isCanceled) {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
337 | (error: Error) => {
if (error instanceof CancelError) {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
338 | (error: Error) => {
if (error instanceof CancelError) {
return;
}
throw error;
} | type Error = NodeJS.ErrnoException; |
339 | (instance: Got): BeforeRequestHook[] => instance.defaults.options.hooks.beforeRequest | type Got = {
/**
Sets `options.isStream` to `true`.
Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
- request
- response
- redirect
- uploadProgress
- downloadProgress
- error
*/
stream: GotStream;
/**
Returns an async iterator.
See pagination.options for more pagination options.
@example
```
import got from 'got';
const countLimit = 10;
const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
pagination: {countLimit}
});
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
for await (const commitData of pagination) {
console.log(commitData.commit.message);
}
```
*/
paginate: GotPaginate;
/**
The Got defaults used in that instance.
*/
defaults: InstanceDefaults;
/**
Configure a new `got` instance with default `options`.
The `options` are merged with the parent instance's `defaults.options` using `got.mergeOptions`.
You can access the resolved options with the `.defaults` property on the instance.
Additionally, `got.extend()` accepts two properties from the `defaults` object: `mutableDefaults` and `handlers`.
It is also possible to merges many instances into a single one:
- options are merged using `got.mergeOptions()` (including hooks),
- handlers are stored in an array (you can access them through `instance.defaults.handlers`).
@example
```
import got from 'got';
const client = got.extend({
prefixUrl: 'https://example.com',
headers: {
'x-unicorn': 'rainbow'
}
});
client.get('demo');
// HTTP Request =>
// GET /demo HTTP/1.1
// Host: example.com
// x-unicorn: rainbow
```
*/
extend: (...instancesOrOptions: Array<Got | ExtendOptions>) => Got;
} & Record<HTTPAlias, GotRequestFunction> & GotRequestFunction; |
340 | (clock: GlobalClock): Handler => (request, response) => {
request.resume();
request.on('end', () => {
clock.tick(requestDelay);
response.end('OK');
});
} | type GlobalClock = any; |
341 | (clock?: GlobalClock): Handler => (_request, response) => {
response.writeHead(200, {
'transfer-encoding': 'chunked',
});
response.flushHeaders();
setImmediate(async () => {
await pStreamPipeline(slowDataStream(clock), response);
});
} | type GlobalClock = any; |
342 | (server: ExtendedHttpTestServer, count: number, {relative} = {relative: false}): void => {
server.get('/', (request, response) => {
// eslint-disable-next-line unicorn/prevent-abbreviations
const searchParams = new URLSearchParams(request.url.split('?')[1]);
const page = Number(searchParams.get('page')) || 1;
if (page < count) {
response.setHeader('link', `<${relative ? '' : server.url}/?page=${page + 1}>; rel="next"`);
}
response.end(`[${page <= count ? page : ''}]`);
});
} | type ExtendedHttpTestServer = {
http: http.Server;
url: string;
port: number;
hostname: string;
close: () => Promise<any>;
} & Express; |
343 | (request: ClientRequest) => {
t.true(request instanceof ClientRequest);
} | interface ClientRequest {
[reentry]?: boolean;
} |
344 | (response: Response) => {
t.true(response instanceof IncomingMessage);
t.false(response.readable);
t.is(response.statusCode, 200);
t.true(response.ip === '127.0.0.1' || response.ip === '::1');
} | type Response<T = unknown> = {
/**
The result of the request.
*/
body: T;
/**
The raw result of the request.
*/
rawBody: Buffer;
} & PlainResponse; |
345 | (retryStream?: Request) => {
const stream = retryStream ?? got.stream('');
globalRetryCount = stream.retryCount;
if (writeStream) {
writeStream.destroy();
}
writeStream = new PassThroughStream();
stream.pipe(writeStream);
stream.once('retry', (_retryCount, _error, createRetryStream) => {
fn(createRetryStream());
});
stream.once('error', reject);
stream.once('end', () => {
resolve(writeStream);
});
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUrls: URL[];
retryCount: number;
declare private _requestOptions: NativeRequestOptions;
private _stopRetry: () => void;
private _downloadedSize: number;
private _uploadedSize: number;
private _stopReading: boolean;
private readonly _pipedServerResponses: Set<ServerResponse>;
private _request?: ClientRequest;
private _responseSize?: number;
private _bodySize?: number;
private _unproxyEvents: () => void;
private _isFromCache?: boolean;
private _cannotHaveBody: boolean;
private _triggerRead: boolean;
declare private _jobs: Array<() => void>;
private _cancelTimeouts: () => void;
private readonly _removeListeners: () => void;
private _nativeResponse?: IncomingMessageWithTimings;
private _flushed: boolean;
private _aborted: boolean;
// We need this because `this._request` if `undefined` when using cache
private _requestInitialized: boolean;
constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
}
async flush() {
if (this._flushed) {
return;
}
this._flushed = true;
try {
await this._finalizeBody();
if (this.destroyed) {
return;
}
await this._makeRequest();
if (this.destroyed) {
this._request?.destroy();
return;
}
// Queued writes etc.
for (const job of this._jobs) {
job();
}
// Prevent memory leak
this._jobs.length = 0;
this._requestInitialized = true;
} catch (error: any) {
this._beforeError(error);
}
}
_beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
}
override _read(): void {
this._triggerRead = true;
const {response} = this;
if (response && !this._stopReading) {
// We cannot put this in the `if` above
// because `.read()` also triggers the `end` event
if (response.readableLength) {
this._triggerRead = false;
}
let data;
while ((data = response.read()) !== null) {
this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands
const progress = this.downloadProgress;
if (progress.percent < 1) {
this.emit('downloadProgress', progress);
}
this.push(data);
}
}
}
override _write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const write = (): void => {
this._writeRequest(chunk, encoding, callback);
};
if (this._requestInitialized) {
write();
} else {
this._jobs.push(write);
}
}
override _final(callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const endRequest = (): void => {
// We need to check if `this._request` is present,
// because it isn't when we use cache.
if (!this._request || this._request.destroyed) {
callback();
return;
}
this._request.end((error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The request has been destroyed before `_final` finished.
// See https://github.com/nodejs/node/issues/39356
if ((this._request as any)._writableState?.errored) {
return;
}
if (!error) {
this._bodySize = this._uploadedSize;
this.emit('uploadProgress', this.uploadProgress);
this._request!.emit('upload-complete');
}
callback(error);
});
};
if (this._requestInitialized) {
endRequest();
} else {
this._jobs.push(endRequest);
}
}
override _destroy(error: Error | null, callback: (error: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
this._stopReading = true;
this.flush = async () => {};
// Prevent further retries
this._stopRetry();
this._cancelTimeouts();
this._removeListeners();
if (this.options) {
const {body} = this.options;
if (is.nodeStream(body)) {
body.destroy();
}
}
if (this._request) {
this._request.destroy();
}
if (error !== null && !is.undefined(error) && !(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
callback(error);
}
override pipe<T extends NodeJS.WritableStream>(destination: T, options?: {end?: boolean}): T {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.add(destination);
}
return super.pipe(destination, options);
}
override unpipe<T extends NodeJS.WritableStream>(destination: T): this {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.delete(destination);
}
super.unpipe(destination);
return this;
}
private async _finalizeBody(): Promise<void> {
const {options} = this;
const {headers} = options;
const isForm = !is.undefined(options.form);
// eslint-disable-next-line @typescript-eslint/naming-convention
const isJSON = !is.undefined(options.json);
const isBody = !is.undefined(options.body);
const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);
this._cannotHaveBody = cannotHaveBody;
if (isForm || isJSON || isBody) {
if (cannotHaveBody) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
// Serialize body
const noContentType = !is.string(headers['content-type']);
if (isBody) {
// Body is spec-compliant FormData
if (isFormDataLike(options.body)) {
const encoder = new FormDataEncoder(options.body);
if (noContentType) {
headers['content-type'] = encoder.headers['Content-Type'];
}
if ('Content-Length' in encoder.headers) {
headers['content-length'] = encoder.headers['Content-Length'];
}
options.body = encoder.encode();
}
// Special case for https://github.com/form-data/form-data
if (isFormData(options.body) && noContentType) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
} else if (isForm) {
if (noContentType) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
const {form} = options;
options.form = undefined;
options.body = (new URLSearchParams(form as Record<string, string>)).toString();
} else {
if (noContentType) {
headers['content-type'] = 'application/json';
}
const {json} = options;
options.json = undefined;
options.body = options.stringifyJson(json);
}
const uploadBodySize = await getBodySize(options.body, options.headers);
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body. For example, a Content-Length header
// field is normally sent in a POST request even when the value is 0
// (indicating an empty payload body). A user agent SHOULD NOT send a
// Content-Length header field when the request message does not contain
// a payload body and the method semantics do not anticipate such a
// body.
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is.undefined(uploadBodySize)) {
headers['content-length'] = String(uploadBodySize);
}
}
if (options.responseType === 'json' && !('accept' in options.headers)) {
options.headers.accept = 'application/json';
}
this._bodySize = Number(headers['content-length']) || undefined;
}
private async _onResponseBase(response: IncomingMessageWithTimings): Promise<void> {
// This will be called e.g. when using cache so we need to check if this request has been aborted.
if (this.isAborted) {
return;
}
const {options} = this;
const {url} = options;
this._nativeResponse = response;
if (options.decompress) {
response = decompressResponse(response);
}
const statusCode = response.statusCode!;
const typedResponse = response as PlainResponse;
typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];
typedResponse.url = options.url!.toString();
typedResponse.requestUrl = this.requestUrl!;
typedResponse.redirectUrls = this.redirectUrls;
typedResponse.request = this;
typedResponse.isFromCache = (this._nativeResponse as any).fromCache ?? false;
typedResponse.ip = this.ip;
typedResponse.retryCount = this.retryCount;
typedResponse.ok = isResponseOk(typedResponse);
this._isFromCache = typedResponse.isFromCache;
this._responseSize = Number(response.headers['content-length']) || undefined;
this.response = typedResponse;
response.once('end', () => {
this._responseSize = this._downloadedSize;
this.emit('downloadProgress', this.downloadProgress);
});
response.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
});
response.once('aborted', () => {
this._aborted = true;
this._beforeError(new ReadError({
name: 'Error',
message: 'The server aborted pending request',
code: 'ECONNRESET',
}, this));
});
this.emit('downloadProgress', this.downloadProgress);
const rawCookies = response.headers['set-cookie'];
if (is.object(options.cookieJar) && rawCookies) {
let promises: Array<Promise<unknown>> = rawCookies.map(async (rawCookie: string) => (options.cookieJar as PromiseCookieJar).setCookie(rawCookie, url!.toString()));
if (options.ignoreInvalidCookies) {
promises = promises.map(async promise => {
try {
await promise;
} catch {}
});
}
try {
await Promise.all(promises);
} catch (error: any) {
this._beforeError(error);
return;
}
}
// The above is running a promise, therefore we need to check if this request has been aborted yet again.
if (this.isAborted) {
return;
}
if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
// We're being redirected, we don't care about the response.
// It'd be best to abort the request, but we can't because
// we would have to sacrifice the TCP connection. We don't want that.
response.resume();
this._cancelTimeouts();
this._unproxyEvents();
if (this.redirectUrls.length >= options.maxRedirects) {
this._beforeError(new MaxRedirectsError(this));
return;
}
this._request = undefined;
const updatedOptions = new Options(undefined, undefined, this.options);
const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
const canRewrite = statusCode !== 307 && statusCode !== 308;
const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
if (serverRequestedGet || userRequestedGet) {
updatedOptions.method = 'GET';
updatedOptions.body = undefined;
updatedOptions.json = undefined;
updatedOptions.form = undefined;
delete updatedOptions.headers['content-length'];
}
try {
// We need this in order to support UTF-8
const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
const redirectUrl = new URL(redirectBuffer, url);
if (!isUnixSocketURL(url as URL) && isUnixSocketURL(redirectUrl)) {
this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
return;
}
// Redirecting to a different site, clear sensitive data.
if (redirectUrl.hostname !== (url as URL).hostname || redirectUrl.port !== (url as URL).port) {
if ('host' in updatedOptions.headers) {
delete updatedOptions.headers.host;
}
if ('cookie' in updatedOptions.headers) {
delete updatedOptions.headers.cookie;
}
if ('authorization' in updatedOptions.headers) {
delete updatedOptions.headers.authorization;
}
if (updatedOptions.username || updatedOptions.password) {
updatedOptions.username = '';
updatedOptions.password = '';
}
} else {
redirectUrl.username = updatedOptions.username;
redirectUrl.password = updatedOptions.password;
}
this.redirectUrls.push(redirectUrl);
updatedOptions.prefixUrl = '';
updatedOptions.url = redirectUrl;
for (const hook of updatedOptions.hooks.beforeRedirect) {
// eslint-disable-next-line no-await-in-loop
await hook(updatedOptions, typedResponse);
}
this.emit('redirect', updatedOptions, typedResponse);
this.options = updatedOptions;
await this._makeRequest();
} catch (error: any) {
this._beforeError(error);
return;
}
return;
}
// `HTTPError`s always have `error.response.body` defined.
// Therefore we cannot retry if `options.throwHttpErrors` is false.
// On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
// but that wouldn't be possible since the body would be already read in `error.response.body`.
if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
this._beforeError(new HTTPError(typedResponse));
return;
}
response.on('readable', () => {
if (this._triggerRead) {
this._read();
}
});
this.on('resume', () => {
response.resume();
});
this.on('pause', () => {
response.pause();
});
response.once('end', () => {
this.push(null);
});
if (this._noPipe) {
const success = await this._setRawBody();
if (success) {
this.emit('response', response);
}
return;
}
this.emit('response', response);
for (const destination of this._pipedServerResponses) {
if (destination.headersSent) {
continue;
}
// eslint-disable-next-line guard-for-in
for (const key in response.headers) {
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
const value = response.headers[key];
if (isAllowed) {
destination.setHeader(key, value!);
}
}
destination.statusCode = statusCode;
}
}
private async _setRawBody(from: Readable = this): Promise<boolean> {
if (from.readableEnded) {
return false;
}
try {
// Errors are emitted via the `error` event
const rawBody = await getBuffer(from);
// On retry Request is destroyed with no error, therefore the above will successfully resolve.
// So in order to check if this was really successfull, we need to check if it has been properly ended.
if (!this.isAborted) {
this.response!.rawBody = rawBody;
return true;
}
} catch {}
return false;
}
private async _onResponse(response: IncomingMessageWithTimings): Promise<void> {
try {
await this._onResponseBase(response);
} catch (error: any) {
/* istanbul ignore next: better safe than sorry */
this._beforeError(error);
}
}
private _onRequest(request: ClientRequest): void {
const {options} = this;
const {timeout, url} = options;
timer(request);
if (this.options.http2) {
// Unset stream timeout, as the `timeout` option was used only for connection timeout.
request.setTimeout(0);
}
this._cancelTimeouts = timedOut(request, timeout, url as URL);
const responseEventName = options.cache ? 'cacheableResponse' : 'response';
request.once(responseEventName, (response: IncomingMessageWithTimings) => {
void this._onResponse(response);
});
request.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
});
this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
this._request = request;
this.emit('uploadProgress', this.uploadProgress);
this._sendBody();
this.emit('request', request);
}
private async _asyncWrite(chunk: any): Promise<void> {
return new Promise((resolve, reject) => {
super.write(chunk, error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
private _sendBody() {
// Send body
const {body} = this.options;
const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this;
if (is.nodeStream(body)) {
body.pipe(currentRequest);
} else if (is.generator(body) || is.asyncGenerator(body)) {
(async () => {
try {
for await (const chunk of body) {
await this._asyncWrite(chunk);
}
super.end();
} catch (error: any) {
this._beforeError(error);
}
})();
} else if (!is.undefined(body)) {
this._writeRequest(body, undefined, () => {});
currentRequest.end();
} else if (this._cannotHaveBody || this._noPipe) {
currentRequest.end();
}
}
private _prepareCache(cache: string | StorageAdapter) {
if (!cacheableStore.has(cache)) {
const cacheableRequest = new CacheableRequest(
((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
const result = (requestOptions as any)._request(requestOptions, handler);
// TODO: remove this when `cacheable-request` supports async request functions.
if (is.promise(result)) {
// We only need to implement the error handler in order to support HTTP2 caching.
// The result will be a promise anyway.
// @ts-expect-error ignore
// eslint-disable-next-line @typescript-eslint/promise-function-async
result.once = (event: string, handler: (reason: unknown) => void) => {
if (event === 'error') {
(async () => {
try {
await result;
} catch (error) {
handler(error);
}
})();
} else if (event === 'abort') {
// The empty catch is needed here in case when
// it rejects before it's `await`ed in `_makeRequest`.
(async () => {
try {
const request = (await result) as ClientRequest;
request.once('abort', handler);
} catch {}
})();
} else {
/* istanbul ignore next: safety check */
throw new Error(`Unknown HTTP2 promise event: ${event}`);
}
return result;
};
}
return result;
}) as typeof http.request,
cache as StorageAdapter,
);
cacheableStore.set(cache, cacheableRequest.request());
}
}
private async _createCacheableRequest(url: URL, options: RequestOptions): Promise<ClientRequest | ResponseLike> {
return new Promise<ClientRequest | ResponseLike>((resolve, reject) => {
// TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed
Object.assign(options, urlToOptions(url));
let request: ClientRequest | Promise<ClientRequest>;
// TODO: Fix `cacheable-response`. This is ugly.
const cacheRequest = cacheableStore.get((options as any).cache)!(options as CacheableOptions, async (response: any) => {
response._readableState.autoDestroy = false;
if (request) {
const fix = () => {
if (response.req) {
response.complete = response.req.res.complete;
}
};
response.prependOnceListener('end', fix);
fix();
(await request).emit('cacheableResponse', response);
}
resolve(response);
});
cacheRequest.once('error', reject);
cacheRequest.once('request', async (requestOrPromise: ClientRequest | Promise<ClientRequest>) => {
request = requestOrPromise;
resolve(request);
});
});
}
private async _makeRequest(): Promise<void> {
const {options} = this;
const {headers, username, password} = options;
const cookieJar = options.cookieJar as PromiseCookieJar | undefined;
for (const key in headers) {
if (is.undefined(headers[key])) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete headers[key];
} else if (is.null_(headers[key])) {
throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
}
}
if (options.decompress && is.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';
}
if (username || password) {
const credentials = Buffer.from(`${username}:${password}`).toString('base64');
headers.authorization = `Basic ${credentials}`;
}
// Set cookies
if (cookieJar) {
const cookieString: string = await cookieJar.getCookieString(options.url!.toString());
if (is.nonEmptyString(cookieString)) {
headers.cookie = cookieString;
}
}
// Reset `prefixUrl`
options.prefixUrl = '';
let request: ReturnType<Options['getRequestFunction']> | undefined;
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
const result = await hook(options);
if (!is.undefined(result)) {
// @ts-expect-error Skip the type mismatch to support abstract responses
request = () => result;
break;
}
}
if (!request) {
request = options.getRequestFunction();
}
const url = options.url as URL;
this._requestOptions = options.createNativeRequestOptions() as NativeRequestOptions;
if (options.cache) {
(this._requestOptions as any)._request = request;
(this._requestOptions as any).cache = options.cache;
(this._requestOptions as any).body = options.body;
this._prepareCache(options.cache as StorageAdapter);
}
// Cache support
const fn = options.cache ? this._createCacheableRequest : request;
try {
// We can't do `await fn(...)`,
// because stream `error` event can be emitted before `Promise.resolve()`.
let requestOrResponse = fn!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
// Fallback
if (is.undefined(requestOrResponse)) {
requestOrResponse = options.getFallbackRequestFunction()!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
}
if (isClientRequest(requestOrResponse!)) {
this._onRequest(requestOrResponse);
} else if (this.writable) {
this.once('finish', () => {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
});
this._sendBody();
} else {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
}
} catch (error) {
if (error instanceof CacheableCacheError) {
throw new CacheError(error, this);
}
throw error;
}
}
private async _error(error: RequestError): Promise<void> {
try {
if (error instanceof HTTPError && !this.options.throwHttpErrors) {
// This branch can be reached only when using the Promise API
// Skip calling the hooks on purpose.
// See https://github.com/sindresorhus/got/issues/2103
} else {
for (const hook of this.options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
} catch (error_: any) {
error = new RequestError(error_.message, error_, this);
}
this.destroy(error);
}
private _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
if (!this._request || this._request.destroyed) {
// Probably the `ClientRequest` instance will throw
return;
}
this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && !this._request!.destroyed) {
this._uploadedSize += Buffer.byteLength(chunk, encoding);
const progress = this.uploadProgress;
if (progress.percent < 1) {
this.emit('uploadProgress', progress);
}
}
callback(error);
});
}
/**
The remote IP address.
*/
get ip(): string | undefined {
return this.socket?.remoteAddress;
}
/**
Indicates whether the request has been aborted or not.
*/
get isAborted(): boolean {
return this._aborted;
}
get socket(): Socket | undefined {
return this._request?.socket ?? undefined;
}
/**
Progress event for downloading (receiving a response).
*/
get downloadProgress(): Progress {
let percent;
if (this._responseSize) {
percent = this._downloadedSize / this._responseSize;
} else if (this._responseSize === this._downloadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._downloadedSize,
total: this._responseSize,
};
}
/**
Progress event for uploading (sending a request).
*/
get uploadProgress(): Progress {
let percent;
if (this._bodySize) {
percent = this._uploadedSize / this._bodySize;
} else if (this._bodySize === this._uploadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._uploadedSize,
total: this._bodySize,
};
}
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
get timings(): Timings | undefined {
return (this._request as ClientRequestWithTimings)?.timings;
}
/**
Whether the response was retrieved from the cache.
*/
get isFromCache(): boolean | undefined {
return this._isFromCache;
}
get reusedSocket(): boolean | undefined {
return this._request?.reusedSocket;
}
} |
346 | (retryStream?: Request) => {
const stream = retryStream ?? got.stream('');
globalRetryCount = stream.retryCount;
stream.resume();
stream.once('retry', (_retryCount, _error, createRetryStream) => {
fn(createRetryStream());
});
stream.once('data', () => {
stream.destroy(new Error('data event has been emitted'));
});
stream.once('error', reject);
stream.once('end', resolve);
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUrls: URL[];
retryCount: number;
declare private _requestOptions: NativeRequestOptions;
private _stopRetry: () => void;
private _downloadedSize: number;
private _uploadedSize: number;
private _stopReading: boolean;
private readonly _pipedServerResponses: Set<ServerResponse>;
private _request?: ClientRequest;
private _responseSize?: number;
private _bodySize?: number;
private _unproxyEvents: () => void;
private _isFromCache?: boolean;
private _cannotHaveBody: boolean;
private _triggerRead: boolean;
declare private _jobs: Array<() => void>;
private _cancelTimeouts: () => void;
private readonly _removeListeners: () => void;
private _nativeResponse?: IncomingMessageWithTimings;
private _flushed: boolean;
private _aborted: boolean;
// We need this because `this._request` if `undefined` when using cache
private _requestInitialized: boolean;
constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
}
async flush() {
if (this._flushed) {
return;
}
this._flushed = true;
try {
await this._finalizeBody();
if (this.destroyed) {
return;
}
await this._makeRequest();
if (this.destroyed) {
this._request?.destroy();
return;
}
// Queued writes etc.
for (const job of this._jobs) {
job();
}
// Prevent memory leak
this._jobs.length = 0;
this._requestInitialized = true;
} catch (error: any) {
this._beforeError(error);
}
}
_beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
}
override _read(): void {
this._triggerRead = true;
const {response} = this;
if (response && !this._stopReading) {
// We cannot put this in the `if` above
// because `.read()` also triggers the `end` event
if (response.readableLength) {
this._triggerRead = false;
}
let data;
while ((data = response.read()) !== null) {
this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands
const progress = this.downloadProgress;
if (progress.percent < 1) {
this.emit('downloadProgress', progress);
}
this.push(data);
}
}
}
override _write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const write = (): void => {
this._writeRequest(chunk, encoding, callback);
};
if (this._requestInitialized) {
write();
} else {
this._jobs.push(write);
}
}
override _final(callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const endRequest = (): void => {
// We need to check if `this._request` is present,
// because it isn't when we use cache.
if (!this._request || this._request.destroyed) {
callback();
return;
}
this._request.end((error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The request has been destroyed before `_final` finished.
// See https://github.com/nodejs/node/issues/39356
if ((this._request as any)._writableState?.errored) {
return;
}
if (!error) {
this._bodySize = this._uploadedSize;
this.emit('uploadProgress', this.uploadProgress);
this._request!.emit('upload-complete');
}
callback(error);
});
};
if (this._requestInitialized) {
endRequest();
} else {
this._jobs.push(endRequest);
}
}
override _destroy(error: Error | null, callback: (error: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
this._stopReading = true;
this.flush = async () => {};
// Prevent further retries
this._stopRetry();
this._cancelTimeouts();
this._removeListeners();
if (this.options) {
const {body} = this.options;
if (is.nodeStream(body)) {
body.destroy();
}
}
if (this._request) {
this._request.destroy();
}
if (error !== null && !is.undefined(error) && !(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
callback(error);
}
override pipe<T extends NodeJS.WritableStream>(destination: T, options?: {end?: boolean}): T {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.add(destination);
}
return super.pipe(destination, options);
}
override unpipe<T extends NodeJS.WritableStream>(destination: T): this {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.delete(destination);
}
super.unpipe(destination);
return this;
}
private async _finalizeBody(): Promise<void> {
const {options} = this;
const {headers} = options;
const isForm = !is.undefined(options.form);
// eslint-disable-next-line @typescript-eslint/naming-convention
const isJSON = !is.undefined(options.json);
const isBody = !is.undefined(options.body);
const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);
this._cannotHaveBody = cannotHaveBody;
if (isForm || isJSON || isBody) {
if (cannotHaveBody) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
// Serialize body
const noContentType = !is.string(headers['content-type']);
if (isBody) {
// Body is spec-compliant FormData
if (isFormDataLike(options.body)) {
const encoder = new FormDataEncoder(options.body);
if (noContentType) {
headers['content-type'] = encoder.headers['Content-Type'];
}
if ('Content-Length' in encoder.headers) {
headers['content-length'] = encoder.headers['Content-Length'];
}
options.body = encoder.encode();
}
// Special case for https://github.com/form-data/form-data
if (isFormData(options.body) && noContentType) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
} else if (isForm) {
if (noContentType) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
const {form} = options;
options.form = undefined;
options.body = (new URLSearchParams(form as Record<string, string>)).toString();
} else {
if (noContentType) {
headers['content-type'] = 'application/json';
}
const {json} = options;
options.json = undefined;
options.body = options.stringifyJson(json);
}
const uploadBodySize = await getBodySize(options.body, options.headers);
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body. For example, a Content-Length header
// field is normally sent in a POST request even when the value is 0
// (indicating an empty payload body). A user agent SHOULD NOT send a
// Content-Length header field when the request message does not contain
// a payload body and the method semantics do not anticipate such a
// body.
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is.undefined(uploadBodySize)) {
headers['content-length'] = String(uploadBodySize);
}
}
if (options.responseType === 'json' && !('accept' in options.headers)) {
options.headers.accept = 'application/json';
}
this._bodySize = Number(headers['content-length']) || undefined;
}
private async _onResponseBase(response: IncomingMessageWithTimings): Promise<void> {
// This will be called e.g. when using cache so we need to check if this request has been aborted.
if (this.isAborted) {
return;
}
const {options} = this;
const {url} = options;
this._nativeResponse = response;
if (options.decompress) {
response = decompressResponse(response);
}
const statusCode = response.statusCode!;
const typedResponse = response as PlainResponse;
typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];
typedResponse.url = options.url!.toString();
typedResponse.requestUrl = this.requestUrl!;
typedResponse.redirectUrls = this.redirectUrls;
typedResponse.request = this;
typedResponse.isFromCache = (this._nativeResponse as any).fromCache ?? false;
typedResponse.ip = this.ip;
typedResponse.retryCount = this.retryCount;
typedResponse.ok = isResponseOk(typedResponse);
this._isFromCache = typedResponse.isFromCache;
this._responseSize = Number(response.headers['content-length']) || undefined;
this.response = typedResponse;
response.once('end', () => {
this._responseSize = this._downloadedSize;
this.emit('downloadProgress', this.downloadProgress);
});
response.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
});
response.once('aborted', () => {
this._aborted = true;
this._beforeError(new ReadError({
name: 'Error',
message: 'The server aborted pending request',
code: 'ECONNRESET',
}, this));
});
this.emit('downloadProgress', this.downloadProgress);
const rawCookies = response.headers['set-cookie'];
if (is.object(options.cookieJar) && rawCookies) {
let promises: Array<Promise<unknown>> = rawCookies.map(async (rawCookie: string) => (options.cookieJar as PromiseCookieJar).setCookie(rawCookie, url!.toString()));
if (options.ignoreInvalidCookies) {
promises = promises.map(async promise => {
try {
await promise;
} catch {}
});
}
try {
await Promise.all(promises);
} catch (error: any) {
this._beforeError(error);
return;
}
}
// The above is running a promise, therefore we need to check if this request has been aborted yet again.
if (this.isAborted) {
return;
}
if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
// We're being redirected, we don't care about the response.
// It'd be best to abort the request, but we can't because
// we would have to sacrifice the TCP connection. We don't want that.
response.resume();
this._cancelTimeouts();
this._unproxyEvents();
if (this.redirectUrls.length >= options.maxRedirects) {
this._beforeError(new MaxRedirectsError(this));
return;
}
this._request = undefined;
const updatedOptions = new Options(undefined, undefined, this.options);
const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
const canRewrite = statusCode !== 307 && statusCode !== 308;
const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
if (serverRequestedGet || userRequestedGet) {
updatedOptions.method = 'GET';
updatedOptions.body = undefined;
updatedOptions.json = undefined;
updatedOptions.form = undefined;
delete updatedOptions.headers['content-length'];
}
try {
// We need this in order to support UTF-8
const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
const redirectUrl = new URL(redirectBuffer, url);
if (!isUnixSocketURL(url as URL) && isUnixSocketURL(redirectUrl)) {
this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
return;
}
// Redirecting to a different site, clear sensitive data.
if (redirectUrl.hostname !== (url as URL).hostname || redirectUrl.port !== (url as URL).port) {
if ('host' in updatedOptions.headers) {
delete updatedOptions.headers.host;
}
if ('cookie' in updatedOptions.headers) {
delete updatedOptions.headers.cookie;
}
if ('authorization' in updatedOptions.headers) {
delete updatedOptions.headers.authorization;
}
if (updatedOptions.username || updatedOptions.password) {
updatedOptions.username = '';
updatedOptions.password = '';
}
} else {
redirectUrl.username = updatedOptions.username;
redirectUrl.password = updatedOptions.password;
}
this.redirectUrls.push(redirectUrl);
updatedOptions.prefixUrl = '';
updatedOptions.url = redirectUrl;
for (const hook of updatedOptions.hooks.beforeRedirect) {
// eslint-disable-next-line no-await-in-loop
await hook(updatedOptions, typedResponse);
}
this.emit('redirect', updatedOptions, typedResponse);
this.options = updatedOptions;
await this._makeRequest();
} catch (error: any) {
this._beforeError(error);
return;
}
return;
}
// `HTTPError`s always have `error.response.body` defined.
// Therefore we cannot retry if `options.throwHttpErrors` is false.
// On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
// but that wouldn't be possible since the body would be already read in `error.response.body`.
if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
this._beforeError(new HTTPError(typedResponse));
return;
}
response.on('readable', () => {
if (this._triggerRead) {
this._read();
}
});
this.on('resume', () => {
response.resume();
});
this.on('pause', () => {
response.pause();
});
response.once('end', () => {
this.push(null);
});
if (this._noPipe) {
const success = await this._setRawBody();
if (success) {
this.emit('response', response);
}
return;
}
this.emit('response', response);
for (const destination of this._pipedServerResponses) {
if (destination.headersSent) {
continue;
}
// eslint-disable-next-line guard-for-in
for (const key in response.headers) {
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
const value = response.headers[key];
if (isAllowed) {
destination.setHeader(key, value!);
}
}
destination.statusCode = statusCode;
}
}
private async _setRawBody(from: Readable = this): Promise<boolean> {
if (from.readableEnded) {
return false;
}
try {
// Errors are emitted via the `error` event
const rawBody = await getBuffer(from);
// On retry Request is destroyed with no error, therefore the above will successfully resolve.
// So in order to check if this was really successfull, we need to check if it has been properly ended.
if (!this.isAborted) {
this.response!.rawBody = rawBody;
return true;
}
} catch {}
return false;
}
private async _onResponse(response: IncomingMessageWithTimings): Promise<void> {
try {
await this._onResponseBase(response);
} catch (error: any) {
/* istanbul ignore next: better safe than sorry */
this._beforeError(error);
}
}
private _onRequest(request: ClientRequest): void {
const {options} = this;
const {timeout, url} = options;
timer(request);
if (this.options.http2) {
// Unset stream timeout, as the `timeout` option was used only for connection timeout.
request.setTimeout(0);
}
this._cancelTimeouts = timedOut(request, timeout, url as URL);
const responseEventName = options.cache ? 'cacheableResponse' : 'response';
request.once(responseEventName, (response: IncomingMessageWithTimings) => {
void this._onResponse(response);
});
request.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
});
this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
this._request = request;
this.emit('uploadProgress', this.uploadProgress);
this._sendBody();
this.emit('request', request);
}
private async _asyncWrite(chunk: any): Promise<void> {
return new Promise((resolve, reject) => {
super.write(chunk, error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
private _sendBody() {
// Send body
const {body} = this.options;
const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this;
if (is.nodeStream(body)) {
body.pipe(currentRequest);
} else if (is.generator(body) || is.asyncGenerator(body)) {
(async () => {
try {
for await (const chunk of body) {
await this._asyncWrite(chunk);
}
super.end();
} catch (error: any) {
this._beforeError(error);
}
})();
} else if (!is.undefined(body)) {
this._writeRequest(body, undefined, () => {});
currentRequest.end();
} else if (this._cannotHaveBody || this._noPipe) {
currentRequest.end();
}
}
private _prepareCache(cache: string | StorageAdapter) {
if (!cacheableStore.has(cache)) {
const cacheableRequest = new CacheableRequest(
((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
const result = (requestOptions as any)._request(requestOptions, handler);
// TODO: remove this when `cacheable-request` supports async request functions.
if (is.promise(result)) {
// We only need to implement the error handler in order to support HTTP2 caching.
// The result will be a promise anyway.
// @ts-expect-error ignore
// eslint-disable-next-line @typescript-eslint/promise-function-async
result.once = (event: string, handler: (reason: unknown) => void) => {
if (event === 'error') {
(async () => {
try {
await result;
} catch (error) {
handler(error);
}
})();
} else if (event === 'abort') {
// The empty catch is needed here in case when
// it rejects before it's `await`ed in `_makeRequest`.
(async () => {
try {
const request = (await result) as ClientRequest;
request.once('abort', handler);
} catch {}
})();
} else {
/* istanbul ignore next: safety check */
throw new Error(`Unknown HTTP2 promise event: ${event}`);
}
return result;
};
}
return result;
}) as typeof http.request,
cache as StorageAdapter,
);
cacheableStore.set(cache, cacheableRequest.request());
}
}
private async _createCacheableRequest(url: URL, options: RequestOptions): Promise<ClientRequest | ResponseLike> {
return new Promise<ClientRequest | ResponseLike>((resolve, reject) => {
// TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed
Object.assign(options, urlToOptions(url));
let request: ClientRequest | Promise<ClientRequest>;
// TODO: Fix `cacheable-response`. This is ugly.
const cacheRequest = cacheableStore.get((options as any).cache)!(options as CacheableOptions, async (response: any) => {
response._readableState.autoDestroy = false;
if (request) {
const fix = () => {
if (response.req) {
response.complete = response.req.res.complete;
}
};
response.prependOnceListener('end', fix);
fix();
(await request).emit('cacheableResponse', response);
}
resolve(response);
});
cacheRequest.once('error', reject);
cacheRequest.once('request', async (requestOrPromise: ClientRequest | Promise<ClientRequest>) => {
request = requestOrPromise;
resolve(request);
});
});
}
private async _makeRequest(): Promise<void> {
const {options} = this;
const {headers, username, password} = options;
const cookieJar = options.cookieJar as PromiseCookieJar | undefined;
for (const key in headers) {
if (is.undefined(headers[key])) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete headers[key];
} else if (is.null_(headers[key])) {
throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
}
}
if (options.decompress && is.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';
}
if (username || password) {
const credentials = Buffer.from(`${username}:${password}`).toString('base64');
headers.authorization = `Basic ${credentials}`;
}
// Set cookies
if (cookieJar) {
const cookieString: string = await cookieJar.getCookieString(options.url!.toString());
if (is.nonEmptyString(cookieString)) {
headers.cookie = cookieString;
}
}
// Reset `prefixUrl`
options.prefixUrl = '';
let request: ReturnType<Options['getRequestFunction']> | undefined;
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
const result = await hook(options);
if (!is.undefined(result)) {
// @ts-expect-error Skip the type mismatch to support abstract responses
request = () => result;
break;
}
}
if (!request) {
request = options.getRequestFunction();
}
const url = options.url as URL;
this._requestOptions = options.createNativeRequestOptions() as NativeRequestOptions;
if (options.cache) {
(this._requestOptions as any)._request = request;
(this._requestOptions as any).cache = options.cache;
(this._requestOptions as any).body = options.body;
this._prepareCache(options.cache as StorageAdapter);
}
// Cache support
const fn = options.cache ? this._createCacheableRequest : request;
try {
// We can't do `await fn(...)`,
// because stream `error` event can be emitted before `Promise.resolve()`.
let requestOrResponse = fn!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
// Fallback
if (is.undefined(requestOrResponse)) {
requestOrResponse = options.getFallbackRequestFunction()!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
}
if (isClientRequest(requestOrResponse!)) {
this._onRequest(requestOrResponse);
} else if (this.writable) {
this.once('finish', () => {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
});
this._sendBody();
} else {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
}
} catch (error) {
if (error instanceof CacheableCacheError) {
throw new CacheError(error, this);
}
throw error;
}
}
private async _error(error: RequestError): Promise<void> {
try {
if (error instanceof HTTPError && !this.options.throwHttpErrors) {
// This branch can be reached only when using the Promise API
// Skip calling the hooks on purpose.
// See https://github.com/sindresorhus/got/issues/2103
} else {
for (const hook of this.options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
} catch (error_: any) {
error = new RequestError(error_.message, error_, this);
}
this.destroy(error);
}
private _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
if (!this._request || this._request.destroyed) {
// Probably the `ClientRequest` instance will throw
return;
}
this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && !this._request!.destroyed) {
this._uploadedSize += Buffer.byteLength(chunk, encoding);
const progress = this.uploadProgress;
if (progress.percent < 1) {
this.emit('uploadProgress', progress);
}
}
callback(error);
});
}
/**
The remote IP address.
*/
get ip(): string | undefined {
return this.socket?.remoteAddress;
}
/**
Indicates whether the request has been aborted or not.
*/
get isAborted(): boolean {
return this._aborted;
}
get socket(): Socket | undefined {
return this._request?.socket ?? undefined;
}
/**
Progress event for downloading (receiving a response).
*/
get downloadProgress(): Progress {
let percent;
if (this._responseSize) {
percent = this._downloadedSize / this._responseSize;
} else if (this._responseSize === this._downloadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._downloadedSize,
total: this._responseSize,
};
}
/**
Progress event for uploading (sending a request).
*/
get uploadProgress(): Progress {
let percent;
if (this._bodySize) {
percent = this._uploadedSize / this._bodySize;
} else if (this._bodySize === this._uploadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._uploadedSize,
total: this._bodySize,
};
}
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
get timings(): Timings | undefined {
return (this._request as ClientRequestWithTimings)?.timings;
}
/**
Whether the response was retrieved from the cache.
*/
get isFromCache(): boolean | undefined {
return this._isFromCache;
}
get reusedSocket(): boolean | undefined {
return this._request?.reusedSocket;
}
} |
347 | async (options: HttpServerOptions = {}): Promise<ExtendedHttpTestServer> => {
const server = express() as ExtendedHttpTestServer;
server.http = http.createServer(server);
server.set('etag', false);
if (options.bodyParser !== false) {
server.use(bodyParser.json({limit: '1mb', type: 'application/json', ...options.bodyParser}));
server.use(bodyParser.text({limit: '1mb', type: 'text/plain', ...options.bodyParser}));
server.use(bodyParser.urlencoded({limit: '1mb', type: 'application/x-www-form-urlencoded', extended: true, ...options.bodyParser}));
server.use(bodyParser.raw({limit: '1mb', type: 'application/octet-stream', ...options.bodyParser}));
}
await pify(server.http.listen.bind(server.http))();
server.port = (server.http.address() as net.AddressInfo).port;
server.url = `http://localhost:${(server.port)}`;
server.hostname = 'localhost';
server.close = async () => pify(server.http.close.bind(server.http))();
return server;
} | type HttpServerOptions = {
bodyParser?: NextFunction | false;
}; |
348 | (t: ExecutionContext, server: ExtendedHttpTestServer, got: Got, clock: GlobalClock) => Promise<void> | void | type Got = {
/**
Sets `options.isStream` to `true`.
Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
- request
- response
- redirect
- uploadProgress
- downloadProgress
- error
*/
stream: GotStream;
/**
Returns an async iterator.
See pagination.options for more pagination options.
@example
```
import got from 'got';
const countLimit = 10;
const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
pagination: {countLimit}
});
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
for await (const commitData of pagination) {
console.log(commitData.commit.message);
}
```
*/
paginate: GotPaginate;
/**
The Got defaults used in that instance.
*/
defaults: InstanceDefaults;
/**
Configure a new `got` instance with default `options`.
The `options` are merged with the parent instance's `defaults.options` using `got.mergeOptions`.
You can access the resolved options with the `.defaults` property on the instance.
Additionally, `got.extend()` accepts two properties from the `defaults` object: `mutableDefaults` and `handlers`.
It is also possible to merges many instances into a single one:
- options are merged using `got.mergeOptions()` (including hooks),
- handlers are stored in an array (you can access them through `instance.defaults.handlers`).
@example
```
import got from 'got';
const client = got.extend({
prefixUrl: 'https://example.com',
headers: {
'x-unicorn': 'rainbow'
}
});
client.get('demo');
// HTTP Request =>
// GET /demo HTTP/1.1
// Host: example.com
// x-unicorn: rainbow
```
*/
extend: (...instancesOrOptions: Array<Got | ExtendOptions>) => Got;
} & Record<HTTPAlias, GotRequestFunction> & GotRequestFunction; |
349 | (t: ExecutionContext, server: ExtendedHttpTestServer, got: Got, clock: GlobalClock) => Promise<void> | void | type ExtendedHttpTestServer = {
http: http.Server;
url: string;
port: number;
hostname: string;
close: () => Promise<any>;
} & Express; |
350 | (t: ExecutionContext, server: ExtendedHttpTestServer, got: Got, clock: GlobalClock) => Promise<void> | void | type GlobalClock = any; |
351 | (t: ExecutionContext, server: ExtendedHttpsTestServer, got: Got, fakeTimer?: GlobalClock) => Promise<void> | void | type Got = {
/**
Sets `options.isStream` to `true`.
Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
- request
- response
- redirect
- uploadProgress
- downloadProgress
- error
*/
stream: GotStream;
/**
Returns an async iterator.
See pagination.options for more pagination options.
@example
```
import got from 'got';
const countLimit = 10;
const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
pagination: {countLimit}
});
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
for await (const commitData of pagination) {
console.log(commitData.commit.message);
}
```
*/
paginate: GotPaginate;
/**
The Got defaults used in that instance.
*/
defaults: InstanceDefaults;
/**
Configure a new `got` instance with default `options`.
The `options` are merged with the parent instance's `defaults.options` using `got.mergeOptions`.
You can access the resolved options with the `.defaults` property on the instance.
Additionally, `got.extend()` accepts two properties from the `defaults` object: `mutableDefaults` and `handlers`.
It is also possible to merges many instances into a single one:
- options are merged using `got.mergeOptions()` (including hooks),
- handlers are stored in an array (you can access them through `instance.defaults.handlers`).
@example
```
import got from 'got';
const client = got.extend({
prefixUrl: 'https://example.com',
headers: {
'x-unicorn': 'rainbow'
}
});
client.get('demo');
// HTTP Request =>
// GET /demo HTTP/1.1
// Host: example.com
// x-unicorn: rainbow
```
*/
extend: (...instancesOrOptions: Array<Got | ExtendOptions>) => Got;
} & Record<HTTPAlias, GotRequestFunction> & GotRequestFunction; |
352 | (t: ExecutionContext, server: ExtendedHttpsTestServer, got: Got, fakeTimer?: GlobalClock) => Promise<void> | void | type ExtendedHttpsTestServer = {
https: https.Server;
caKey: Buffer;
caCert: Buffer;
url: string;
port: number;
close: () => Promise<any>;
} & express.Express; |
353 | (t: ExecutionContext, server: ExtendedHttpsTestServer, got: Got, fakeTimer?: GlobalClock) => Promise<void> | void | type GlobalClock = any; |
354 | (t: ExecutionContext, server: ExtendedHttpServer) => Promise<void> | void | type ExtendedHttpServer = {
socketPath: string;
} & Server; |
355 | (options?: HttpsServerOptions, installFakeTimer = false): Macro<[RunTestWithHttpsServer]> => ({
async exec(t, run) {
const fakeTimer = installFakeTimer ? FakeTimers.install() as GlobalClock : undefined;
const server = await createHttpsTestServer(options);
const preparedGot = got.extend({
context: {
avaTest: t.title,
},
handlers: [
(options, next) => {
const result = next(options);
fakeTimer?.tick(0);
// @ts-expect-error FIXME: Incompatible union type signatures
result.on('response', () => {
fakeTimer?.tick(0);
});
return result;
},
],
prefixUrl: server.url,
https: {
certificateAuthority: (server as any).caCert,
rejectUnauthorized: true,
},
});
try {
await run(t, server, preparedGot, fakeTimer);
} finally {
await server.close();
}
if (installFakeTimer) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
(fakeTimer as InstalledClock).uninstall();
}
},
}) | type HttpsServerOptions = {
commonName?: string;
days?: number;
ciphers?: SecureContextOptions['ciphers'];
honorCipherOrder?: SecureContextOptions['honorCipherOrder'];
minVersion?: SecureContextOptions['minVersion'];
maxVersion?: SecureContextOptions['maxVersion'];
}; |
356 | async (options: HttpsServerOptions = {}): Promise<ExtendedHttpsTestServer> => {
const createCsr = pify(pem.createCSR as CreateCsr);
const createCertificate = pify(pem.createCertificate as CreateCertificate);
const caCsrResult = await createCsr({commonName: 'authority'});
const caResult = await createCertificate({
csr: caCsrResult.csr,
clientKey: caCsrResult.clientKey,
selfSigned: true,
});
const caKey = caResult.clientKey;
const caCert = caResult.certificate;
const serverCsrResult = await createCsr({commonName: options.commonName ?? 'localhost'});
const serverResult = await createCertificate({
csr: serverCsrResult.csr,
clientKey: serverCsrResult.clientKey,
serviceKey: caKey,
serviceCertificate: caCert,
days: options.days ?? 365,
});
const serverKey = serverResult.clientKey;
const serverCert = serverResult.certificate;
const server = express() as ExtendedHttpsTestServer;
server.https = https.createServer(
{
key: serverKey,
cert: serverCert,
ca: caCert,
requestCert: true,
rejectUnauthorized: false, // This should be checked by the test
ciphers: options.ciphers,
honorCipherOrder: options.honorCipherOrder,
minVersion: options.minVersion,
maxVersion: options.maxVersion,
},
server,
);
server.set('etag', false);
await pify(server.https.listen.bind(server.https))();
server.caKey = caKey as any;
server.caCert = caCert;
server.port = (server.https.address() as net.AddressInfo).port;
server.url = `https://localhost:${(server.port)}`;
server.close = async () => pify(server.https.close.bind(server.https))();
return server;
} | type HttpsServerOptions = {
commonName?: string;
days?: number;
ciphers?: SecureContextOptions['ciphers'];
honorCipherOrder?: SecureContextOptions['honorCipherOrder'];
minVersion?: SecureContextOptions['minVersion'];
maxVersion?: SecureContextOptions['maxVersion'];
}; |
357 | (error: Error) => {
if (error) {
throw error;
}
deferred.resolve();
} | type Error = NodeJS.ErrnoException; |
358 | (error: Error) => {
if (error) {
throw error;
}
deferred.resolve();
} | type Error = NodeJS.ErrnoException; |
359 | <T extends GotReturn>(options: Options, next: (options: Options) => T) => T | Promise<T> | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.undefined], input);
assert.any([is.object, is.undefined], options);
assert.any([is.object, is.undefined], defaults);
if (input instanceof Options || options instanceof Options) {
throw new TypeError('The defaults must be passed as the third argument');
}
this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals);
this._init = [...(defaults?._init ?? [])];
this._merging = false;
this._unixOptions = undefined;
// This rule allows `finally` to be considered more important.
// Meaning no matter the error thrown in the `try` block,
// if `finally` throws then the `finally` error will be thrown.
//
// Yes, we want this. If we set `url` first, then the `url.searchParams`
// would get merged. Instead we set the `searchParams` first, then
// `url.searchParams` is overwritten as expected.
//
/* eslint-disable no-unsafe-finally */
try {
if (is.plainObject(input)) {
try {
this.merge(input);
this.merge(options);
} finally {
this.url = input.url;
}
} else {
try {
this.merge(options);
} finally {
if (options?.url !== undefined) {
if (input === undefined) {
this.url = options.url;
} else {
throw new TypeError('The `url` option is mutually exclusive with the `input` argument');
}
} else if (input !== undefined) {
this.url = input;
}
}
}
} catch (error) {
(error as OptionsError).options = this;
throw error;
}
/* eslint-enable no-unsafe-finally */
}
merge(options?: OptionsInit | Options) {
if (!options) {
return;
}
if (options instanceof Options) {
for (const init of options._init) {
this.merge(init);
}
return;
}
options = cloneRaw(options);
init(this, options, this);
init(options, options, this);
this._merging = true;
// Always merge `isStream` first
if ('isStream' in options) {
this.isStream = options.isStream!;
}
try {
let push = false;
for (const key in options) {
// `got.extend()` options
if (key === 'mutableDefaults' || key === 'handlers') {
continue;
}
// Never merge `url`
if (key === 'url') {
continue;
}
if (!(key in this)) {
throw new Error(`Unexpected option: ${key}`);
}
// @ts-expect-error Type 'unknown' is not assignable to type 'never'.
this[key as keyof Options] = options[key as keyof Options];
push = true;
}
if (push) {
this._init.push(options);
}
} finally {
this._merging = false;
}
}
/**
Custom request function.
The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper).
@default http.request | https.request
*/
get request(): RequestFunction | undefined {
return this._internals.request;
}
set request(value: RequestFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.request = value;
}
/**
An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance.
This is necessary because a request to one protocol might redirect to another.
In such a scenario, Got will switch over to the right protocol agent for you.
If a key is not present, it will default to a global agent.
@example
```
import got from 'got';
import HttpAgent from 'agentkeepalive';
const {HttpsAgent} = HttpAgent;
await got('https://sindresorhus.com', {
agent: {
http: new HttpAgent(),
https: new HttpsAgent()
}
});
```
*/
get agent(): Agents {
return this._internals.agent;
}
set agent(value: Agents) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.agent)) {
throw new TypeError(`Unexpected agent option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.object, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.agent, value);
} else {
this._internals.agent = {...value};
}
}
get h2session(): ClientHttp2Session | undefined {
return this._internals.h2session;
}
set h2session(value: ClientHttp2Session | undefined) {
this._internals.h2session = value;
}
/**
Decompress the response automatically.
This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself.
If this is disabled, a compressed response is returned as a `Buffer`.
This may be useful if you want to handle decompression yourself or stream the raw compressed data.
@default true
*/
get decompress(): boolean {
return this._internals.decompress;
}
set decompress(value: boolean) {
assert.boolean(value);
this._internals.decompress = value;
}
/**
Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property).
By default, there's no timeout.
This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
- `lookup` starts when a socket is assigned and ends when the hostname has been resolved.
Does not apply when using a Unix domain socket.
- `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
- `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
- `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
- `response` starts when the request has been written to the socket and ends when the response headers are received.
- `send` starts when the socket is connected and ends with the request has been written to the socket.
- `request` starts when the request is initiated and ends when the response's end event fires.
*/
get timeout(): Delays {
// We always return `Delays` here.
// It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.timeout;
}
set timeout(value: Delays) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.timeout)) {
throw new Error(`Unexpected timeout option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.number, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.timeout, value);
} else {
this._internals.timeout = {...value};
}
}
/**
When specified, `prefixUrl` will be prepended to `url`.
The prefix can be any valid URL, either relative or absolute.
A trailing slash `/` is optional - one will be added automatically.
__Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance.
__Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion.
For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`.
The latter is used by browsers.
__Tip__: Useful when used with `got.extend()` to create niche-specific Got instances.
__Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`.
If the URL doesn't include it anymore, it will throw.
@example
```
import got from 'got';
await got('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
const instance = got.extend({
prefixUrl: 'https://google.com'
});
await instance('unicorn', {
hooks: {
beforeRequest: [
options => {
options.prefixUrl = 'https://cats.com';
}
]
}
});
//=> 'https://cats.com/unicorn'
```
*/
get prefixUrl(): string | URL {
// We always return `string` here.
// It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.prefixUrl;
}
set prefixUrl(value: string | URL) {
assert.any([is.string, is.urlInstance], value);
if (value === '') {
this._internals.prefixUrl = '';
return;
}
value = value.toString();
if (!value.endsWith('/')) {
value += '/';
}
if (this._internals.prefixUrl && this._internals.url) {
const {href} = this._internals.url as URL;
(this._internals.url as URL).href = value + href.slice((this._internals.prefixUrl as string).length);
}
this._internals.prefixUrl = value;
}
/**
__Note #1__: The `body` option cannot be used with the `json` or `form` option.
__Note #2__: If you provide this option, `got.stream()` will be read-only.
__Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`.
__Note #4__: This option is not enumerable and will not be merged with the instance defaults.
The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`.
*/
get body(): string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined {
return this._internals.body;
}
set body(value: string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined) {
assert.any([is.string, is.buffer, is.nodeStream, is.generator, is.asyncGenerator, isFormData, is.undefined], value);
if (is.nodeStream(value)) {
assert.truthy(value.readable);
}
if (value !== undefined) {
assert.undefined(this._internals.form);
assert.undefined(this._internals.json);
}
this._internals.body = value;
}
/**
The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get form(): Record<string, any> | undefined {
return this._internals.form;
}
set form(value: Record<string, any> | undefined) {
assert.any([is.plainObject, is.undefined], value);
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.json);
}
this._internals.form = value;
}
/**
JSON body. If the `Content-Type` header is not set, it will be set to `application/json`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get json(): unknown {
return this._internals.json;
}
set json(value: unknown) {
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.form);
}
this._internals.json = value;
}
/**
The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
Properties from `options` will override properties in the parsed `url`.
If no protocol is specified, it will throw a `TypeError`.
__Note__: The query string is **not** parsed as search params.
@example
```
await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
// The query string is overridden by `searchParams`
await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
```
*/
get url(): string | URL | undefined {
return this._internals.url;
}
set url(value: string | URL | undefined) {
assert.any([is.string, is.urlInstance, is.undefined], value);
if (value === undefined) {
this._internals.url = undefined;
return;
}
if (is.string(value) && value.startsWith('/')) {
throw new Error('`url` must not start with a slash');
}
const urlString = `${this.prefixUrl as string}${value.toString()}`;
const url = new URL(urlString);
this._internals.url = url;
if (url.protocol === 'unix:') {
url.href = `http://unix${url.pathname}${url.search}`;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
const error: NodeJS.ErrnoException = new Error(`Unsupported protocol: ${url.protocol}`);
error.code = 'ERR_UNSUPPORTED_PROTOCOL';
throw error;
}
if (this._internals.username) {
url.username = this._internals.username;
this._internals.username = '';
}
if (this._internals.password) {
url.password = this._internals.password;
this._internals.password = '';
}
if (this._internals.searchParams) {
url.search = (this._internals.searchParams as URLSearchParams).toString();
this._internals.searchParams = undefined;
}
if (url.hostname === 'unix') {
if (!this._internals.enableUnixSockets) {
throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled');
}
const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);
if (matches?.groups) {
const {socketPath, path} = matches.groups;
this._unixOptions = {
socketPath,
path,
host: '',
};
} else {
this._unixOptions = undefined;
}
return;
}
this._unixOptions = undefined;
}
/**
Cookie support. You don't have to care about parsing or how to store them.
__Note__: If you provide this option, `options.headers.cookie` will be overridden.
*/
get cookieJar(): PromiseCookieJar | ToughCookieJar | undefined {
return this._internals.cookieJar;
}
set cookieJar(value: PromiseCookieJar | ToughCookieJar | undefined) {
assert.any([is.object, is.undefined], value);
if (value === undefined) {
this._internals.cookieJar = undefined;
return;
}
let {setCookie, getCookieString} = value;
assert.function_(setCookie);
assert.function_(getCookieString);
/* istanbul ignore next: Horrible `tough-cookie` v3 check */
if (setCookie.length === 4 && getCookieString.length === 0) {
setCookie = promisify(setCookie.bind(value));
getCookieString = promisify(getCookieString.bind(value));
this._internals.cookieJar = {
setCookie,
getCookieString: getCookieString as PromiseCookieJar['getCookieString'],
};
} else {
this._internals.cookieJar = value;
}
}
/**
You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
*Requires Node.js 16 or later.*
@example
```
import got from 'got';
const abortController = new AbortController();
const request = got('https://httpbin.org/anything', {
signal: abortController.signal
});
setTimeout(() => {
abortController.abort();
}, 100);
```
*/
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
get signal(): any | undefined {
return this._internals.signal;
}
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
set signal(value: any | undefined) {
assert.object(value);
this._internals.signal = value;
}
/**
Ignore invalid cookies instead of throwing an error.
Only useful when the `cookieJar` option has been set. Not recommended.
@default false
*/
get ignoreInvalidCookies(): boolean {
return this._internals.ignoreInvalidCookies;
}
set ignoreInvalidCookies(value: boolean) {
assert.boolean(value);
this._internals.ignoreInvalidCookies = value;
}
/**
Query string that will be added to the request URL.
This will override the query string in `url`.
If you need to pass in an array, you can do it using a `URLSearchParams` instance.
@example
```
import got from 'got';
const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
await got('https://example.com', {searchParams});
console.log(searchParams.toString());
//=> 'key=a&key=b'
```
*/
get searchParams(): string | SearchParameters | URLSearchParams | undefined {
if (this._internals.url) {
return (this._internals.url as URL).searchParams;
}
if (this._internals.searchParams === undefined) {
this._internals.searchParams = new URLSearchParams();
}
return this._internals.searchParams;
}
set searchParams(value: string | SearchParameters | URLSearchParams | undefined) {
assert.any([is.string, is.object, is.undefined], value);
const url = this._internals.url as URL;
if (value === undefined) {
this._internals.searchParams = undefined;
if (url) {
url.search = '';
}
return;
}
const searchParameters = this.searchParams as URLSearchParams;
let updated;
if (is.string(value)) {
updated = new URLSearchParams(value);
} else if (value instanceof URLSearchParams) {
updated = value;
} else {
validateSearchParameters(value);
updated = new URLSearchParams();
// eslint-disable-next-line guard-for-in
for (const key in value) {
const entry = value[key];
if (entry === null) {
updated.append(key, '');
} else if (entry === undefined) {
searchParameters.delete(key);
} else {
updated.append(key, entry as string);
}
}
}
if (this._merging) {
// These keys will be replaced
for (const key of updated.keys()) {
searchParameters.delete(key);
}
for (const [key, value] of updated) {
searchParameters.append(key, value);
}
} else if (url) {
url.search = searchParameters.toString();
} else {
this._internals.searchParams = searchParameters;
}
}
get searchParameters() {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
set searchParameters(_value: unknown) {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
get dnsLookup(): CacheableLookup['lookup'] | undefined {
return this._internals.dnsLookup;
}
set dnsLookup(value: CacheableLookup['lookup'] | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.dnsLookup = value;
}
/**
An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups.
Useful when making lots of requests to different *public* hostnames.
`CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay.
__Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.
@default false
*/
get dnsCache(): CacheableLookup | boolean | undefined {
return this._internals.dnsCache;
}
set dnsCache(value: CacheableLookup | boolean | undefined) {
assert.any([is.object, is.boolean, is.undefined], value);
if (value === true) {
this._internals.dnsCache = getGlobalDnsCache();
} else if (value === false) {
this._internals.dnsCache = undefined;
} else {
this._internals.dnsCache = value;
}
}
/**
User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged.
@example
```
import got from 'got';
const instance = got.extend({
hooks: {
beforeRequest: [
options => {
if (!options.context || !options.context.token) {
throw new Error('Token required');
}
options.headers.token = options.context.token;
}
]
}
});
const context = {
token: 'secret'
};
const response = await instance('https://httpbin.org/headers', {context});
// Let's see the headers
console.log(response.body);
```
*/
get context(): Record<string, unknown> {
return this._internals.context;
}
set context(value: Record<string, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.context, value);
} else {
this._internals.context = {...value};
}
}
/**
Hooks allow modifications during the request lifecycle.
Hook functions may be async and are run serially.
*/
get hooks(): Hooks {
return this._internals.hooks;
}
set hooks(value: Hooks) {
assert.object(value);
// eslint-disable-next-line guard-for-in
for (const knownHookEvent in value) {
if (!(knownHookEvent in this._internals.hooks)) {
throw new Error(`Unexpected hook event: ${knownHookEvent}`);
}
const typedKnownHookEvent = knownHookEvent as keyof Hooks;
const hooks = value[typedKnownHookEvent];
assert.any([is.array, is.undefined], hooks);
if (hooks) {
for (const hook of hooks) {
assert.function_(hook);
}
}
if (this._merging) {
if (hooks) {
// @ts-expect-error FIXME
this._internals.hooks[typedKnownHookEvent].push(...hooks);
}
} else {
if (!hooks) {
throw new Error(`Missing hook event: ${knownHookEvent}`);
}
// @ts-expect-error FIXME
this._internals.hooks[knownHookEvent] = [...hooks];
}
}
}
/**
Defines if redirect responses should be followed automatically.
Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`.
@default true
*/
get followRedirect(): boolean {
return this._internals.followRedirect;
}
set followRedirect(value: boolean) {
assert.boolean(value);
this._internals.followRedirect = value;
}
get followRedirects() {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
set followRedirects(_value: unknown) {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
/**
If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown.
@default 10
*/
get maxRedirects(): number {
return this._internals.maxRedirects;
}
set maxRedirects(value: number) {
assert.number(value);
this._internals.maxRedirects = value;
}
/**
A cache adapter instance for storing cached response data.
@default false
*/
get cache(): string | StorageAdapter | boolean | undefined {
return this._internals.cache;
}
set cache(value: string | StorageAdapter | boolean | undefined) {
assert.any([is.object, is.string, is.boolean, is.undefined], value);
if (value === true) {
this._internals.cache = globalCache;
} else if (value === false) {
this._internals.cache = undefined;
} else {
this._internals.cache = value;
}
}
/**
Determines if a `got.HTTPError` is thrown for unsuccessful responses.
If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing.
This may be useful if you are checking for resource availability and are expecting error responses.
@default true
*/
get throwHttpErrors(): boolean {
return this._internals.throwHttpErrors;
}
set throwHttpErrors(value: boolean) {
assert.boolean(value);
this._internals.throwHttpErrors = value;
}
get username(): string {
const url = this._internals.url as URL;
const value = url ? url.username : this._internals.username;
return decodeURIComponent(value);
}
set username(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.username = fixedValue;
} else {
this._internals.username = fixedValue;
}
}
get password(): string {
const url = this._internals.url as URL;
const value = url ? url.password : this._internals.password;
return decodeURIComponent(value);
}
set password(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.password = fixedValue;
} else {
this._internals.password = fixedValue;
}
}
/**
If set to `true`, Got will additionally accept HTTP2 requests.
It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol.
__Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy.
__Note__: Overriding `options.request` will disable HTTP2 support.
@default false
@example
```
import got from 'got';
const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true});
console.log(headers.via);
//=> '2 nghttpx'
```
*/
get http2(): boolean {
return this._internals.http2;
}
set http2(value: boolean) {
assert.boolean(value);
this._internals.http2 = value;
}
/**
Set this to `true` to allow sending body for the `GET` method.
However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect.
This option is only meant to interact with non-compliant servers when you have no other choice.
__Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__.
@default false
*/
get allowGetBody(): boolean {
return this._internals.allowGetBody;
}
set allowGetBody(value: boolean) {
assert.boolean(value);
this._internals.allowGetBody = value;
}
/**
Request headers.
Existing headers will be overwritten. Headers set to `undefined` will be omitted.
@default {}
*/
get headers(): Headers {
return this._internals.headers;
}
set headers(value: Headers) {
assert.plainObject(value);
if (this._merging) {
Object.assign(this._internals.headers, lowercaseKeys(value));
} else {
this._internals.headers = lowercaseKeys(value);
}
}
/**
Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects.
As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior.
Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers.
__Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7).
@default false
*/
get methodRewriting(): boolean {
return this._internals.methodRewriting;
}
set methodRewriting(value: boolean) {
assert.boolean(value);
this._internals.methodRewriting = value;
}
/**
Indicates which DNS record family to use.
Values:
- `undefined`: IPv4 (if present) or IPv6
- `4`: Only IPv4
- `6`: Only IPv6
@default undefined
*/
get dnsLookupIpVersion(): DnsLookupIpVersion {
return this._internals.dnsLookupIpVersion;
}
set dnsLookupIpVersion(value: DnsLookupIpVersion) {
if (value !== undefined && value !== 4 && value !== 6) {
throw new TypeError(`Invalid DNS lookup IP version: ${value as string}`);
}
this._internals.dnsLookupIpVersion = value;
}
/**
A function used to parse JSON responses.
@example
```
import got from 'got';
import Bourne from '@hapi/bourne';
const parsed = await got('https://example.com', {
parseJson: text => Bourne.parse(text)
}).json();
console.log(parsed);
```
*/
get parseJson(): ParseJsonFunction {
return this._internals.parseJson;
}
set parseJson(value: ParseJsonFunction) {
assert.function_(value);
this._internals.parseJson = value;
}
/**
A function used to stringify the body of JSON requests.
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (key.startsWith('_')) {
return;
}
return value;
}),
json: {
some: 'payload',
_ignoreMe: 1234
}
});
```
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (typeof value === 'number') {
return value.toString();
}
return value;
}),
json: {
some: 'payload',
number: 1
}
});
```
*/
get stringifyJson(): StringifyJsonFunction {
return this._internals.stringifyJson;
}
set stringifyJson(value: StringifyJsonFunction) {
assert.function_(value);
this._internals.stringifyJson = value;
}
/**
An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
By default, it retries *only* on the specified methods, status codes, and on these network errors:
- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
- `ECONNRESET`: Connection was forcibly closed by a peer.
- `EADDRINUSE`: Could not bind to any free port.
- `ECONNREFUSED`: Connection was refused by the server.
- `EPIPE`: The remote side of the stream being written has been closed.
- `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
- `ENETUNREACH`: No internet connection.
- `EAI_AGAIN`: DNS lookup timed out.
__Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
__Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
*/
get retry(): Partial<RetryOptions> {
return this._internals.retry;
}
set retry(value: Partial<RetryOptions>) {
assert.plainObject(value);
assert.any([is.function_, is.undefined], value.calculateDelay);
assert.any([is.number, is.undefined], value.maxRetryAfter);
assert.any([is.number, is.undefined], value.limit);
assert.any([is.array, is.undefined], value.methods);
assert.any([is.array, is.undefined], value.statusCodes);
assert.any([is.array, is.undefined], value.errorCodes);
assert.any([is.number, is.undefined], value.noise);
if (value.noise && Math.abs(value.noise) > 100) {
throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`);
}
for (const key in value) {
if (!(key in this._internals.retry)) {
throw new Error(`Unexpected retry option: ${key}`);
}
}
if (this._merging) {
Object.assign(this._internals.retry, value);
} else {
this._internals.retry = {...value};
}
const {retry} = this._internals;
retry.methods = [...new Set(retry.methods!.map(method => method.toUpperCase() as Method))];
retry.statusCodes = [...new Set(retry.statusCodes)];
retry.errorCodes = [...new Set(retry.errorCodes)];
}
/**
From `http.RequestOptions`.
The IP address used to send the request from.
*/
get localAddress(): string | undefined {
return this._internals.localAddress;
}
set localAddress(value: string | undefined) {
assert.any([is.string, is.undefined], value);
this._internals.localAddress = value;
}
/**
The HTTP method used to make the request.
@default 'GET'
*/
get method(): Method {
return this._internals.method;
}
set method(value: Method) {
assert.string(value);
this._internals.method = value.toUpperCase() as Method;
}
get createConnection(): CreateConnectionFunction | undefined {
return this._internals.createConnection;
}
set createConnection(value: CreateConnectionFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.createConnection = value;
}
/**
From `http-cache-semantics`
@default {}
*/
get cacheOptions(): CacheOptions {
return this._internals.cacheOptions;
}
set cacheOptions(value: CacheOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.shared);
assert.any([is.number, is.undefined], value.cacheHeuristic);
assert.any([is.number, is.undefined], value.immutableMinTimeToLive);
assert.any([is.boolean, is.undefined], value.ignoreCargoCult);
for (const key in value) {
if (!(key in this._internals.cacheOptions)) {
throw new Error(`Cache option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.cacheOptions, value);
} else {
this._internals.cacheOptions = {...value};
}
}
/**
Options for the advanced HTTPS API.
*/
get https(): HttpsOptions {
return this._internals.https;
}
set https(value: HttpsOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.rejectUnauthorized);
assert.any([is.function_, is.undefined], value.checkServerIdentity);
assert.any([is.string, is.object, is.array, is.undefined], value.certificateAuthority);
assert.any([is.string, is.object, is.array, is.undefined], value.key);
assert.any([is.string, is.object, is.array, is.undefined], value.certificate);
assert.any([is.string, is.undefined], value.passphrase);
assert.any([is.string, is.buffer, is.array, is.undefined], value.pfx);
assert.any([is.array, is.undefined], value.alpnProtocols);
assert.any([is.string, is.undefined], value.ciphers);
assert.any([is.string, is.buffer, is.undefined], value.dhparam);
assert.any([is.string, is.undefined], value.signatureAlgorithms);
assert.any([is.string, is.undefined], value.minVersion);
assert.any([is.string, is.undefined], value.maxVersion);
assert.any([is.boolean, is.undefined], value.honorCipherOrder);
assert.any([is.number, is.undefined], value.tlsSessionLifetime);
assert.any([is.string, is.undefined], value.ecdhCurve);
assert.any([is.string, is.buffer, is.array, is.undefined], value.certificateRevocationLists);
for (const key in value) {
if (!(key in this._internals.https)) {
throw new Error(`HTTPS option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.https, value);
} else {
this._internals.https = {...value};
}
}
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead.
Don't set this option to `null`.
__Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`.
@default 'utf-8'
*/
get encoding(): BufferEncoding | undefined {
return this._internals.encoding;
}
set encoding(value: BufferEncoding | undefined) {
if (value === null) {
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
}
assert.any([is.string, is.undefined], value);
this._internals.encoding = value;
}
/**
When set to `true` the promise will return the Response body instead of the Response object.
@default false
*/
get resolveBodyOnly(): boolean {
return this._internals.resolveBodyOnly;
}
set resolveBodyOnly(value: boolean) {
assert.boolean(value);
this._internals.resolveBodyOnly = value;
}
/**
Returns a `Stream` instead of a `Promise`.
This is equivalent to calling `got.stream(url, options?)`.
@default false
*/
get isStream(): boolean {
return this._internals.isStream;
}
set isStream(value: boolean) {
assert.boolean(value);
this._internals.isStream = value;
}
/**
The parsing method.
The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.
It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.
__Note__: When using streams, this option is ignored.
@example
```
const responsePromise = got(url);
const bufferPromise = responsePromise.buffer();
const jsonPromise = responsePromise.json();
const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]);
// `response` is an instance of Got Response
// `buffer` is an instance of Buffer
// `json` is an object
```
@example
```
// This
const body = await got(url).json();
// is semantically the same as this
const body = await got(url, {responseType: 'json', resolveBodyOnly: true});
```
*/
get responseType(): ResponseType {
return this._internals.responseType;
}
set responseType(value: ResponseType) {
if (value === undefined) {
this._internals.responseType = 'text';
return;
}
if (value !== 'text' && value !== 'buffer' && value !== 'json') {
throw new Error(`Invalid \`responseType\` option: ${value as string}`);
}
this._internals.responseType = value;
}
get pagination(): PaginationOptions<unknown, unknown> {
return this._internals.pagination;
}
set pagination(value: PaginationOptions<unknown, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.pagination, value);
} else {
this._internals.pagination = value;
}
}
get auth() {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
set auth(_value: unknown) {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
get setHost() {
return this._internals.setHost;
}
set setHost(value: boolean) {
assert.boolean(value);
this._internals.setHost = value;
}
get maxHeaderSize() {
return this._internals.maxHeaderSize;
}
set maxHeaderSize(value: number | undefined) {
assert.any([is.number, is.undefined], value);
this._internals.maxHeaderSize = value;
}
get enableUnixSockets() {
return this._internals.enableUnixSockets;
}
set enableUnixSockets(value: boolean) {
assert.boolean(value);
this._internals.enableUnixSockets = value;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
toJSON() {
return {...this._internals};
}
[Symbol.for('nodejs.util.inspect.custom')](_depth: number, options: InspectOptions) {
return inspect(this._internals, options);
}
createNativeRequestOptions() {
const internals = this._internals;
const url = internals.url as URL;
let agent;
if (url.protocol === 'https:') {
agent = internals.http2 ? internals.agent : internals.agent.https;
} else {
agent = internals.agent.http;
}
const {https} = internals;
let {pfx} = https;
if (is.array(pfx) && is.plainObject(pfx[0])) {
pfx = (pfx as PfxObject[]).map(object => ({
buf: object.buffer,
passphrase: object.passphrase,
})) as any;
}
return {
...internals.cacheOptions,
...this._unixOptions,
// HTTPS options
// eslint-disable-next-line @typescript-eslint/naming-convention
ALPNProtocols: https.alpnProtocols,
ca: https.certificateAuthority,
cert: https.certificate,
key: https.key,
passphrase: https.passphrase,
pfx: https.pfx,
rejectUnauthorized: https.rejectUnauthorized,
checkServerIdentity: https.checkServerIdentity ?? checkServerIdentity,
ciphers: https.ciphers,
honorCipherOrder: https.honorCipherOrder,
minVersion: https.minVersion,
maxVersion: https.maxVersion,
sigalgs: https.signatureAlgorithms,
sessionTimeout: https.tlsSessionLifetime,
dhparam: https.dhparam,
ecdhCurve: https.ecdhCurve,
crl: https.certificateRevocationLists,
// HTTP options
lookup: internals.dnsLookup ?? (internals.dnsCache as CacheableLookup | undefined)?.lookup,
family: internals.dnsLookupIpVersion,
agent,
setHost: internals.setHost,
method: internals.method,
maxHeaderSize: internals.maxHeaderSize,
localAddress: internals.localAddress,
headers: internals.headers,
createConnection: internals.createConnection,
timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined,
// HTTP/2 options
h2session: internals.h2session,
};
}
getRequestFunction() {
const url = this._internals.url as (URL | undefined);
const {request} = this._internals;
if (!request && url) {
return this.getFallbackRequestFunction();
}
return request;
}
getFallbackRequestFunction() {
const url = this._internals.url as (URL | undefined);
if (!url) {
return;
}
if (url.protocol === 'https:') {
if (this._internals.http2) {
if (major < 15 || (major === 15 && minor < 10)) {
const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above');
(error as NodeJS.ErrnoException).code = 'EUNSUPPORTED';
throw error;
}
return http2wrapper.auto as RequestFunction;
}
return https.request;
}
return http.request;
}
freeze() {
const options = this._internals;
Object.freeze(options);
Object.freeze(options.hooks);
Object.freeze(options.hooks.afterResponse);
Object.freeze(options.hooks.beforeError);
Object.freeze(options.hooks.beforeRedirect);
Object.freeze(options.hooks.beforeRequest);
Object.freeze(options.hooks.beforeRetry);
Object.freeze(options.hooks.init);
Object.freeze(options.https);
Object.freeze(options.cacheOptions);
Object.freeze(options.agent);
Object.freeze(options.headers);
Object.freeze(options.timeout);
Object.freeze(options.retry);
Object.freeze(options.retry.errorCodes);
Object.freeze(options.retry.methods);
Object.freeze(options.retry.statusCodes);
}
} |
360 | (options: Options) => T | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.undefined], input);
assert.any([is.object, is.undefined], options);
assert.any([is.object, is.undefined], defaults);
if (input instanceof Options || options instanceof Options) {
throw new TypeError('The defaults must be passed as the third argument');
}
this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals);
this._init = [...(defaults?._init ?? [])];
this._merging = false;
this._unixOptions = undefined;
// This rule allows `finally` to be considered more important.
// Meaning no matter the error thrown in the `try` block,
// if `finally` throws then the `finally` error will be thrown.
//
// Yes, we want this. If we set `url` first, then the `url.searchParams`
// would get merged. Instead we set the `searchParams` first, then
// `url.searchParams` is overwritten as expected.
//
/* eslint-disable no-unsafe-finally */
try {
if (is.plainObject(input)) {
try {
this.merge(input);
this.merge(options);
} finally {
this.url = input.url;
}
} else {
try {
this.merge(options);
} finally {
if (options?.url !== undefined) {
if (input === undefined) {
this.url = options.url;
} else {
throw new TypeError('The `url` option is mutually exclusive with the `input` argument');
}
} else if (input !== undefined) {
this.url = input;
}
}
}
} catch (error) {
(error as OptionsError).options = this;
throw error;
}
/* eslint-enable no-unsafe-finally */
}
merge(options?: OptionsInit | Options) {
if (!options) {
return;
}
if (options instanceof Options) {
for (const init of options._init) {
this.merge(init);
}
return;
}
options = cloneRaw(options);
init(this, options, this);
init(options, options, this);
this._merging = true;
// Always merge `isStream` first
if ('isStream' in options) {
this.isStream = options.isStream!;
}
try {
let push = false;
for (const key in options) {
// `got.extend()` options
if (key === 'mutableDefaults' || key === 'handlers') {
continue;
}
// Never merge `url`
if (key === 'url') {
continue;
}
if (!(key in this)) {
throw new Error(`Unexpected option: ${key}`);
}
// @ts-expect-error Type 'unknown' is not assignable to type 'never'.
this[key as keyof Options] = options[key as keyof Options];
push = true;
}
if (push) {
this._init.push(options);
}
} finally {
this._merging = false;
}
}
/**
Custom request function.
The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper).
@default http.request | https.request
*/
get request(): RequestFunction | undefined {
return this._internals.request;
}
set request(value: RequestFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.request = value;
}
/**
An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance.
This is necessary because a request to one protocol might redirect to another.
In such a scenario, Got will switch over to the right protocol agent for you.
If a key is not present, it will default to a global agent.
@example
```
import got from 'got';
import HttpAgent from 'agentkeepalive';
const {HttpsAgent} = HttpAgent;
await got('https://sindresorhus.com', {
agent: {
http: new HttpAgent(),
https: new HttpsAgent()
}
});
```
*/
get agent(): Agents {
return this._internals.agent;
}
set agent(value: Agents) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.agent)) {
throw new TypeError(`Unexpected agent option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.object, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.agent, value);
} else {
this._internals.agent = {...value};
}
}
get h2session(): ClientHttp2Session | undefined {
return this._internals.h2session;
}
set h2session(value: ClientHttp2Session | undefined) {
this._internals.h2session = value;
}
/**
Decompress the response automatically.
This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself.
If this is disabled, a compressed response is returned as a `Buffer`.
This may be useful if you want to handle decompression yourself or stream the raw compressed data.
@default true
*/
get decompress(): boolean {
return this._internals.decompress;
}
set decompress(value: boolean) {
assert.boolean(value);
this._internals.decompress = value;
}
/**
Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property).
By default, there's no timeout.
This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
- `lookup` starts when a socket is assigned and ends when the hostname has been resolved.
Does not apply when using a Unix domain socket.
- `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
- `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
- `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
- `response` starts when the request has been written to the socket and ends when the response headers are received.
- `send` starts when the socket is connected and ends with the request has been written to the socket.
- `request` starts when the request is initiated and ends when the response's end event fires.
*/
get timeout(): Delays {
// We always return `Delays` here.
// It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.timeout;
}
set timeout(value: Delays) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.timeout)) {
throw new Error(`Unexpected timeout option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.number, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.timeout, value);
} else {
this._internals.timeout = {...value};
}
}
/**
When specified, `prefixUrl` will be prepended to `url`.
The prefix can be any valid URL, either relative or absolute.
A trailing slash `/` is optional - one will be added automatically.
__Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance.
__Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion.
For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`.
The latter is used by browsers.
__Tip__: Useful when used with `got.extend()` to create niche-specific Got instances.
__Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`.
If the URL doesn't include it anymore, it will throw.
@example
```
import got from 'got';
await got('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
const instance = got.extend({
prefixUrl: 'https://google.com'
});
await instance('unicorn', {
hooks: {
beforeRequest: [
options => {
options.prefixUrl = 'https://cats.com';
}
]
}
});
//=> 'https://cats.com/unicorn'
```
*/
get prefixUrl(): string | URL {
// We always return `string` here.
// It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.prefixUrl;
}
set prefixUrl(value: string | URL) {
assert.any([is.string, is.urlInstance], value);
if (value === '') {
this._internals.prefixUrl = '';
return;
}
value = value.toString();
if (!value.endsWith('/')) {
value += '/';
}
if (this._internals.prefixUrl && this._internals.url) {
const {href} = this._internals.url as URL;
(this._internals.url as URL).href = value + href.slice((this._internals.prefixUrl as string).length);
}
this._internals.prefixUrl = value;
}
/**
__Note #1__: The `body` option cannot be used with the `json` or `form` option.
__Note #2__: If you provide this option, `got.stream()` will be read-only.
__Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`.
__Note #4__: This option is not enumerable and will not be merged with the instance defaults.
The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`.
*/
get body(): string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined {
return this._internals.body;
}
set body(value: string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined) {
assert.any([is.string, is.buffer, is.nodeStream, is.generator, is.asyncGenerator, isFormData, is.undefined], value);
if (is.nodeStream(value)) {
assert.truthy(value.readable);
}
if (value !== undefined) {
assert.undefined(this._internals.form);
assert.undefined(this._internals.json);
}
this._internals.body = value;
}
/**
The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get form(): Record<string, any> | undefined {
return this._internals.form;
}
set form(value: Record<string, any> | undefined) {
assert.any([is.plainObject, is.undefined], value);
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.json);
}
this._internals.form = value;
}
/**
JSON body. If the `Content-Type` header is not set, it will be set to `application/json`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get json(): unknown {
return this._internals.json;
}
set json(value: unknown) {
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.form);
}
this._internals.json = value;
}
/**
The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
Properties from `options` will override properties in the parsed `url`.
If no protocol is specified, it will throw a `TypeError`.
__Note__: The query string is **not** parsed as search params.
@example
```
await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
// The query string is overridden by `searchParams`
await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
```
*/
get url(): string | URL | undefined {
return this._internals.url;
}
set url(value: string | URL | undefined) {
assert.any([is.string, is.urlInstance, is.undefined], value);
if (value === undefined) {
this._internals.url = undefined;
return;
}
if (is.string(value) && value.startsWith('/')) {
throw new Error('`url` must not start with a slash');
}
const urlString = `${this.prefixUrl as string}${value.toString()}`;
const url = new URL(urlString);
this._internals.url = url;
if (url.protocol === 'unix:') {
url.href = `http://unix${url.pathname}${url.search}`;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
const error: NodeJS.ErrnoException = new Error(`Unsupported protocol: ${url.protocol}`);
error.code = 'ERR_UNSUPPORTED_PROTOCOL';
throw error;
}
if (this._internals.username) {
url.username = this._internals.username;
this._internals.username = '';
}
if (this._internals.password) {
url.password = this._internals.password;
this._internals.password = '';
}
if (this._internals.searchParams) {
url.search = (this._internals.searchParams as URLSearchParams).toString();
this._internals.searchParams = undefined;
}
if (url.hostname === 'unix') {
if (!this._internals.enableUnixSockets) {
throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled');
}
const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);
if (matches?.groups) {
const {socketPath, path} = matches.groups;
this._unixOptions = {
socketPath,
path,
host: '',
};
} else {
this._unixOptions = undefined;
}
return;
}
this._unixOptions = undefined;
}
/**
Cookie support. You don't have to care about parsing or how to store them.
__Note__: If you provide this option, `options.headers.cookie` will be overridden.
*/
get cookieJar(): PromiseCookieJar | ToughCookieJar | undefined {
return this._internals.cookieJar;
}
set cookieJar(value: PromiseCookieJar | ToughCookieJar | undefined) {
assert.any([is.object, is.undefined], value);
if (value === undefined) {
this._internals.cookieJar = undefined;
return;
}
let {setCookie, getCookieString} = value;
assert.function_(setCookie);
assert.function_(getCookieString);
/* istanbul ignore next: Horrible `tough-cookie` v3 check */
if (setCookie.length === 4 && getCookieString.length === 0) {
setCookie = promisify(setCookie.bind(value));
getCookieString = promisify(getCookieString.bind(value));
this._internals.cookieJar = {
setCookie,
getCookieString: getCookieString as PromiseCookieJar['getCookieString'],
};
} else {
this._internals.cookieJar = value;
}
}
/**
You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
*Requires Node.js 16 or later.*
@example
```
import got from 'got';
const abortController = new AbortController();
const request = got('https://httpbin.org/anything', {
signal: abortController.signal
});
setTimeout(() => {
abortController.abort();
}, 100);
```
*/
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
get signal(): any | undefined {
return this._internals.signal;
}
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
set signal(value: any | undefined) {
assert.object(value);
this._internals.signal = value;
}
/**
Ignore invalid cookies instead of throwing an error.
Only useful when the `cookieJar` option has been set. Not recommended.
@default false
*/
get ignoreInvalidCookies(): boolean {
return this._internals.ignoreInvalidCookies;
}
set ignoreInvalidCookies(value: boolean) {
assert.boolean(value);
this._internals.ignoreInvalidCookies = value;
}
/**
Query string that will be added to the request URL.
This will override the query string in `url`.
If you need to pass in an array, you can do it using a `URLSearchParams` instance.
@example
```
import got from 'got';
const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
await got('https://example.com', {searchParams});
console.log(searchParams.toString());
//=> 'key=a&key=b'
```
*/
get searchParams(): string | SearchParameters | URLSearchParams | undefined {
if (this._internals.url) {
return (this._internals.url as URL).searchParams;
}
if (this._internals.searchParams === undefined) {
this._internals.searchParams = new URLSearchParams();
}
return this._internals.searchParams;
}
set searchParams(value: string | SearchParameters | URLSearchParams | undefined) {
assert.any([is.string, is.object, is.undefined], value);
const url = this._internals.url as URL;
if (value === undefined) {
this._internals.searchParams = undefined;
if (url) {
url.search = '';
}
return;
}
const searchParameters = this.searchParams as URLSearchParams;
let updated;
if (is.string(value)) {
updated = new URLSearchParams(value);
} else if (value instanceof URLSearchParams) {
updated = value;
} else {
validateSearchParameters(value);
updated = new URLSearchParams();
// eslint-disable-next-line guard-for-in
for (const key in value) {
const entry = value[key];
if (entry === null) {
updated.append(key, '');
} else if (entry === undefined) {
searchParameters.delete(key);
} else {
updated.append(key, entry as string);
}
}
}
if (this._merging) {
// These keys will be replaced
for (const key of updated.keys()) {
searchParameters.delete(key);
}
for (const [key, value] of updated) {
searchParameters.append(key, value);
}
} else if (url) {
url.search = searchParameters.toString();
} else {
this._internals.searchParams = searchParameters;
}
}
get searchParameters() {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
set searchParameters(_value: unknown) {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
get dnsLookup(): CacheableLookup['lookup'] | undefined {
return this._internals.dnsLookup;
}
set dnsLookup(value: CacheableLookup['lookup'] | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.dnsLookup = value;
}
/**
An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups.
Useful when making lots of requests to different *public* hostnames.
`CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay.
__Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.
@default false
*/
get dnsCache(): CacheableLookup | boolean | undefined {
return this._internals.dnsCache;
}
set dnsCache(value: CacheableLookup | boolean | undefined) {
assert.any([is.object, is.boolean, is.undefined], value);
if (value === true) {
this._internals.dnsCache = getGlobalDnsCache();
} else if (value === false) {
this._internals.dnsCache = undefined;
} else {
this._internals.dnsCache = value;
}
}
/**
User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged.
@example
```
import got from 'got';
const instance = got.extend({
hooks: {
beforeRequest: [
options => {
if (!options.context || !options.context.token) {
throw new Error('Token required');
}
options.headers.token = options.context.token;
}
]
}
});
const context = {
token: 'secret'
};
const response = await instance('https://httpbin.org/headers', {context});
// Let's see the headers
console.log(response.body);
```
*/
get context(): Record<string, unknown> {
return this._internals.context;
}
set context(value: Record<string, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.context, value);
} else {
this._internals.context = {...value};
}
}
/**
Hooks allow modifications during the request lifecycle.
Hook functions may be async and are run serially.
*/
get hooks(): Hooks {
return this._internals.hooks;
}
set hooks(value: Hooks) {
assert.object(value);
// eslint-disable-next-line guard-for-in
for (const knownHookEvent in value) {
if (!(knownHookEvent in this._internals.hooks)) {
throw new Error(`Unexpected hook event: ${knownHookEvent}`);
}
const typedKnownHookEvent = knownHookEvent as keyof Hooks;
const hooks = value[typedKnownHookEvent];
assert.any([is.array, is.undefined], hooks);
if (hooks) {
for (const hook of hooks) {
assert.function_(hook);
}
}
if (this._merging) {
if (hooks) {
// @ts-expect-error FIXME
this._internals.hooks[typedKnownHookEvent].push(...hooks);
}
} else {
if (!hooks) {
throw new Error(`Missing hook event: ${knownHookEvent}`);
}
// @ts-expect-error FIXME
this._internals.hooks[knownHookEvent] = [...hooks];
}
}
}
/**
Defines if redirect responses should be followed automatically.
Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`.
@default true
*/
get followRedirect(): boolean {
return this._internals.followRedirect;
}
set followRedirect(value: boolean) {
assert.boolean(value);
this._internals.followRedirect = value;
}
get followRedirects() {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
set followRedirects(_value: unknown) {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
/**
If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown.
@default 10
*/
get maxRedirects(): number {
return this._internals.maxRedirects;
}
set maxRedirects(value: number) {
assert.number(value);
this._internals.maxRedirects = value;
}
/**
A cache adapter instance for storing cached response data.
@default false
*/
get cache(): string | StorageAdapter | boolean | undefined {
return this._internals.cache;
}
set cache(value: string | StorageAdapter | boolean | undefined) {
assert.any([is.object, is.string, is.boolean, is.undefined], value);
if (value === true) {
this._internals.cache = globalCache;
} else if (value === false) {
this._internals.cache = undefined;
} else {
this._internals.cache = value;
}
}
/**
Determines if a `got.HTTPError` is thrown for unsuccessful responses.
If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing.
This may be useful if you are checking for resource availability and are expecting error responses.
@default true
*/
get throwHttpErrors(): boolean {
return this._internals.throwHttpErrors;
}
set throwHttpErrors(value: boolean) {
assert.boolean(value);
this._internals.throwHttpErrors = value;
}
get username(): string {
const url = this._internals.url as URL;
const value = url ? url.username : this._internals.username;
return decodeURIComponent(value);
}
set username(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.username = fixedValue;
} else {
this._internals.username = fixedValue;
}
}
get password(): string {
const url = this._internals.url as URL;
const value = url ? url.password : this._internals.password;
return decodeURIComponent(value);
}
set password(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.password = fixedValue;
} else {
this._internals.password = fixedValue;
}
}
/**
If set to `true`, Got will additionally accept HTTP2 requests.
It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol.
__Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy.
__Note__: Overriding `options.request` will disable HTTP2 support.
@default false
@example
```
import got from 'got';
const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true});
console.log(headers.via);
//=> '2 nghttpx'
```
*/
get http2(): boolean {
return this._internals.http2;
}
set http2(value: boolean) {
assert.boolean(value);
this._internals.http2 = value;
}
/**
Set this to `true` to allow sending body for the `GET` method.
However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect.
This option is only meant to interact with non-compliant servers when you have no other choice.
__Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__.
@default false
*/
get allowGetBody(): boolean {
return this._internals.allowGetBody;
}
set allowGetBody(value: boolean) {
assert.boolean(value);
this._internals.allowGetBody = value;
}
/**
Request headers.
Existing headers will be overwritten. Headers set to `undefined` will be omitted.
@default {}
*/
get headers(): Headers {
return this._internals.headers;
}
set headers(value: Headers) {
assert.plainObject(value);
if (this._merging) {
Object.assign(this._internals.headers, lowercaseKeys(value));
} else {
this._internals.headers = lowercaseKeys(value);
}
}
/**
Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects.
As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior.
Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers.
__Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7).
@default false
*/
get methodRewriting(): boolean {
return this._internals.methodRewriting;
}
set methodRewriting(value: boolean) {
assert.boolean(value);
this._internals.methodRewriting = value;
}
/**
Indicates which DNS record family to use.
Values:
- `undefined`: IPv4 (if present) or IPv6
- `4`: Only IPv4
- `6`: Only IPv6
@default undefined
*/
get dnsLookupIpVersion(): DnsLookupIpVersion {
return this._internals.dnsLookupIpVersion;
}
set dnsLookupIpVersion(value: DnsLookupIpVersion) {
if (value !== undefined && value !== 4 && value !== 6) {
throw new TypeError(`Invalid DNS lookup IP version: ${value as string}`);
}
this._internals.dnsLookupIpVersion = value;
}
/**
A function used to parse JSON responses.
@example
```
import got from 'got';
import Bourne from '@hapi/bourne';
const parsed = await got('https://example.com', {
parseJson: text => Bourne.parse(text)
}).json();
console.log(parsed);
```
*/
get parseJson(): ParseJsonFunction {
return this._internals.parseJson;
}
set parseJson(value: ParseJsonFunction) {
assert.function_(value);
this._internals.parseJson = value;
}
/**
A function used to stringify the body of JSON requests.
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (key.startsWith('_')) {
return;
}
return value;
}),
json: {
some: 'payload',
_ignoreMe: 1234
}
});
```
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (typeof value === 'number') {
return value.toString();
}
return value;
}),
json: {
some: 'payload',
number: 1
}
});
```
*/
get stringifyJson(): StringifyJsonFunction {
return this._internals.stringifyJson;
}
set stringifyJson(value: StringifyJsonFunction) {
assert.function_(value);
this._internals.stringifyJson = value;
}
/**
An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
By default, it retries *only* on the specified methods, status codes, and on these network errors:
- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
- `ECONNRESET`: Connection was forcibly closed by a peer.
- `EADDRINUSE`: Could not bind to any free port.
- `ECONNREFUSED`: Connection was refused by the server.
- `EPIPE`: The remote side of the stream being written has been closed.
- `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
- `ENETUNREACH`: No internet connection.
- `EAI_AGAIN`: DNS lookup timed out.
__Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
__Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
*/
get retry(): Partial<RetryOptions> {
return this._internals.retry;
}
set retry(value: Partial<RetryOptions>) {
assert.plainObject(value);
assert.any([is.function_, is.undefined], value.calculateDelay);
assert.any([is.number, is.undefined], value.maxRetryAfter);
assert.any([is.number, is.undefined], value.limit);
assert.any([is.array, is.undefined], value.methods);
assert.any([is.array, is.undefined], value.statusCodes);
assert.any([is.array, is.undefined], value.errorCodes);
assert.any([is.number, is.undefined], value.noise);
if (value.noise && Math.abs(value.noise) > 100) {
throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`);
}
for (const key in value) {
if (!(key in this._internals.retry)) {
throw new Error(`Unexpected retry option: ${key}`);
}
}
if (this._merging) {
Object.assign(this._internals.retry, value);
} else {
this._internals.retry = {...value};
}
const {retry} = this._internals;
retry.methods = [...new Set(retry.methods!.map(method => method.toUpperCase() as Method))];
retry.statusCodes = [...new Set(retry.statusCodes)];
retry.errorCodes = [...new Set(retry.errorCodes)];
}
/**
From `http.RequestOptions`.
The IP address used to send the request from.
*/
get localAddress(): string | undefined {
return this._internals.localAddress;
}
set localAddress(value: string | undefined) {
assert.any([is.string, is.undefined], value);
this._internals.localAddress = value;
}
/**
The HTTP method used to make the request.
@default 'GET'
*/
get method(): Method {
return this._internals.method;
}
set method(value: Method) {
assert.string(value);
this._internals.method = value.toUpperCase() as Method;
}
get createConnection(): CreateConnectionFunction | undefined {
return this._internals.createConnection;
}
set createConnection(value: CreateConnectionFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.createConnection = value;
}
/**
From `http-cache-semantics`
@default {}
*/
get cacheOptions(): CacheOptions {
return this._internals.cacheOptions;
}
set cacheOptions(value: CacheOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.shared);
assert.any([is.number, is.undefined], value.cacheHeuristic);
assert.any([is.number, is.undefined], value.immutableMinTimeToLive);
assert.any([is.boolean, is.undefined], value.ignoreCargoCult);
for (const key in value) {
if (!(key in this._internals.cacheOptions)) {
throw new Error(`Cache option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.cacheOptions, value);
} else {
this._internals.cacheOptions = {...value};
}
}
/**
Options for the advanced HTTPS API.
*/
get https(): HttpsOptions {
return this._internals.https;
}
set https(value: HttpsOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.rejectUnauthorized);
assert.any([is.function_, is.undefined], value.checkServerIdentity);
assert.any([is.string, is.object, is.array, is.undefined], value.certificateAuthority);
assert.any([is.string, is.object, is.array, is.undefined], value.key);
assert.any([is.string, is.object, is.array, is.undefined], value.certificate);
assert.any([is.string, is.undefined], value.passphrase);
assert.any([is.string, is.buffer, is.array, is.undefined], value.pfx);
assert.any([is.array, is.undefined], value.alpnProtocols);
assert.any([is.string, is.undefined], value.ciphers);
assert.any([is.string, is.buffer, is.undefined], value.dhparam);
assert.any([is.string, is.undefined], value.signatureAlgorithms);
assert.any([is.string, is.undefined], value.minVersion);
assert.any([is.string, is.undefined], value.maxVersion);
assert.any([is.boolean, is.undefined], value.honorCipherOrder);
assert.any([is.number, is.undefined], value.tlsSessionLifetime);
assert.any([is.string, is.undefined], value.ecdhCurve);
assert.any([is.string, is.buffer, is.array, is.undefined], value.certificateRevocationLists);
for (const key in value) {
if (!(key in this._internals.https)) {
throw new Error(`HTTPS option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.https, value);
} else {
this._internals.https = {...value};
}
}
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead.
Don't set this option to `null`.
__Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`.
@default 'utf-8'
*/
get encoding(): BufferEncoding | undefined {
return this._internals.encoding;
}
set encoding(value: BufferEncoding | undefined) {
if (value === null) {
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
}
assert.any([is.string, is.undefined], value);
this._internals.encoding = value;
}
/**
When set to `true` the promise will return the Response body instead of the Response object.
@default false
*/
get resolveBodyOnly(): boolean {
return this._internals.resolveBodyOnly;
}
set resolveBodyOnly(value: boolean) {
assert.boolean(value);
this._internals.resolveBodyOnly = value;
}
/**
Returns a `Stream` instead of a `Promise`.
This is equivalent to calling `got.stream(url, options?)`.
@default false
*/
get isStream(): boolean {
return this._internals.isStream;
}
set isStream(value: boolean) {
assert.boolean(value);
this._internals.isStream = value;
}
/**
The parsing method.
The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.
It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.
__Note__: When using streams, this option is ignored.
@example
```
const responsePromise = got(url);
const bufferPromise = responsePromise.buffer();
const jsonPromise = responsePromise.json();
const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]);
// `response` is an instance of Got Response
// `buffer` is an instance of Buffer
// `json` is an object
```
@example
```
// This
const body = await got(url).json();
// is semantically the same as this
const body = await got(url, {responseType: 'json', resolveBodyOnly: true});
```
*/
get responseType(): ResponseType {
return this._internals.responseType;
}
set responseType(value: ResponseType) {
if (value === undefined) {
this._internals.responseType = 'text';
return;
}
if (value !== 'text' && value !== 'buffer' && value !== 'json') {
throw new Error(`Invalid \`responseType\` option: ${value as string}`);
}
this._internals.responseType = value;
}
get pagination(): PaginationOptions<unknown, unknown> {
return this._internals.pagination;
}
set pagination(value: PaginationOptions<unknown, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.pagination, value);
} else {
this._internals.pagination = value;
}
}
get auth() {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
set auth(_value: unknown) {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
get setHost() {
return this._internals.setHost;
}
set setHost(value: boolean) {
assert.boolean(value);
this._internals.setHost = value;
}
get maxHeaderSize() {
return this._internals.maxHeaderSize;
}
set maxHeaderSize(value: number | undefined) {
assert.any([is.number, is.undefined], value);
this._internals.maxHeaderSize = value;
}
get enableUnixSockets() {
return this._internals.enableUnixSockets;
}
set enableUnixSockets(value: boolean) {
assert.boolean(value);
this._internals.enableUnixSockets = value;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
toJSON() {
return {...this._internals};
}
[Symbol.for('nodejs.util.inspect.custom')](_depth: number, options: InspectOptions) {
return inspect(this._internals, options);
}
createNativeRequestOptions() {
const internals = this._internals;
const url = internals.url as URL;
let agent;
if (url.protocol === 'https:') {
agent = internals.http2 ? internals.agent : internals.agent.https;
} else {
agent = internals.agent.http;
}
const {https} = internals;
let {pfx} = https;
if (is.array(pfx) && is.plainObject(pfx[0])) {
pfx = (pfx as PfxObject[]).map(object => ({
buf: object.buffer,
passphrase: object.passphrase,
})) as any;
}
return {
...internals.cacheOptions,
...this._unixOptions,
// HTTPS options
// eslint-disable-next-line @typescript-eslint/naming-convention
ALPNProtocols: https.alpnProtocols,
ca: https.certificateAuthority,
cert: https.certificate,
key: https.key,
passphrase: https.passphrase,
pfx: https.pfx,
rejectUnauthorized: https.rejectUnauthorized,
checkServerIdentity: https.checkServerIdentity ?? checkServerIdentity,
ciphers: https.ciphers,
honorCipherOrder: https.honorCipherOrder,
minVersion: https.minVersion,
maxVersion: https.maxVersion,
sigalgs: https.signatureAlgorithms,
sessionTimeout: https.tlsSessionLifetime,
dhparam: https.dhparam,
ecdhCurve: https.ecdhCurve,
crl: https.certificateRevocationLists,
// HTTP options
lookup: internals.dnsLookup ?? (internals.dnsCache as CacheableLookup | undefined)?.lookup,
family: internals.dnsLookupIpVersion,
agent,
setHost: internals.setHost,
method: internals.method,
maxHeaderSize: internals.maxHeaderSize,
localAddress: internals.localAddress,
headers: internals.headers,
createConnection: internals.createConnection,
timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined,
// HTTP/2 options
h2session: internals.h2session,
};
}
getRequestFunction() {
const url = this._internals.url as (URL | undefined);
const {request} = this._internals;
if (!request && url) {
return this.getFallbackRequestFunction();
}
return request;
}
getFallbackRequestFunction() {
const url = this._internals.url as (URL | undefined);
if (!url) {
return;
}
if (url.protocol === 'https:') {
if (this._internals.http2) {
if (major < 15 || (major === 15 && minor < 10)) {
const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above');
(error as NodeJS.ErrnoException).code = 'EUNSUPPORTED';
throw error;
}
return http2wrapper.auto as RequestFunction;
}
return https.request;
}
return http.request;
}
freeze() {
const options = this._internals;
Object.freeze(options);
Object.freeze(options.hooks);
Object.freeze(options.hooks.afterResponse);
Object.freeze(options.hooks.beforeError);
Object.freeze(options.hooks.beforeRedirect);
Object.freeze(options.hooks.beforeRequest);
Object.freeze(options.hooks.beforeRetry);
Object.freeze(options.hooks.init);
Object.freeze(options.https);
Object.freeze(options.cacheOptions);
Object.freeze(options.agent);
Object.freeze(options.headers);
Object.freeze(options.timeout);
Object.freeze(options.retry);
Object.freeze(options.retry.errorCodes);
Object.freeze(options.retry.methods);
Object.freeze(options.retry.statusCodes);
}
} |
361 | (options: OptionsOfTextResponseBody): CancelableRequest<Response<string>> | type OptionsOfTextResponseBody = Merge<OptionsInit, {isStream?: false; resolveBodyOnly?: false; responseType?: 'text'}>; |
362 | <T>(options: OptionsOfJSONResponseBody): CancelableRequest<Response<T>> | type OptionsOfJSONResponseBody = Merge<OptionsInit, {isStream?: false; resolveBodyOnly?: false; responseType?: 'json'}>; |
363 | (options: OptionsOfBufferResponseBody): CancelableRequest<Response<Buffer>> | type OptionsOfBufferResponseBody = Merge<OptionsInit, {isStream?: false; resolveBodyOnly?: false; responseType: 'buffer'}>; |
364 | (options: OptionsOfUnknownResponseBody): CancelableRequest<Response> | type OptionsOfUnknownResponseBody = Merge<OptionsInit, {isStream?: false; resolveBodyOnly?: false}>; |
365 | (options: OptionsInit): CancelableRequest | Request | type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
}; |
366 | (defaults: InstanceDefaults): Got => {
defaults = {
options: new Options(undefined, undefined, defaults.options),
handlers: [...defaults.handlers],
mutableDefaults: defaults.mutableDefaults,
};
Object.defineProperty(defaults, 'mutableDefaults', {
enumerable: true,
configurable: false,
writable: false,
});
// Got interface
const got: Got = ((url: string | URL | OptionsInit | undefined, options?: OptionsInit, defaultOptions: Options = defaults.options): GotReturn => {
const request = new Request(url, options, defaultOptions);
let promise: CancelableRequest | undefined;
const lastHandler = (normalized: Options): GotReturn => {
// Note: `options` is `undefined` when `new Options(...)` fails
request.options = normalized;
request._noPipe = !normalized.isStream;
void request.flush();
if (normalized.isStream) {
return request;
}
if (!promise) {
promise = asPromise(request);
}
return promise;
};
let iteration = 0;
const iterateHandlers = (newOptions: Options): GotReturn => {
const handler = defaults.handlers[iteration++] ?? lastHandler;
const result = handler(newOptions, iterateHandlers) as GotReturn;
if (is.promise(result) && !request.options.isStream) {
if (!promise) {
promise = asPromise(request);
}
if (result !== promise) {
const descriptors = Object.getOwnPropertyDescriptors(promise);
for (const key in descriptors) {
if (key in result) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete descriptors[key];
}
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Object.defineProperties(result, descriptors);
result.cancel = promise.cancel;
}
}
return result;
};
return iterateHandlers(request.options);
}) as Got;
got.extend = (...instancesOrOptions) => {
const options = new Options(undefined, undefined, defaults.options);
const handlers = [...defaults.handlers];
let mutableDefaults: boolean | undefined;
for (const value of instancesOrOptions) {
if (isGotInstance(value)) {
options.merge(value.defaults.options);
handlers.push(...value.defaults.handlers);
mutableDefaults = value.defaults.mutableDefaults;
} else {
options.merge(value);
if (value.handlers) {
handlers.push(...value.handlers);
}
mutableDefaults = value.mutableDefaults;
}
}
return create({
options,
handlers,
mutableDefaults: Boolean(mutableDefaults),
});
};
// Pagination
const paginateEach = (async function * <T, R>(url: string | URL, options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T> {
let normalizedOptions = new Options(url, options as OptionsInit, defaults.options);
normalizedOptions.resolveBodyOnly = false;
const {pagination} = normalizedOptions;
assert.function_(pagination.transform);
assert.function_(pagination.shouldContinue);
assert.function_(pagination.filter);
assert.function_(pagination.paginate);
assert.number(pagination.countLimit);
assert.number(pagination.requestLimit);
assert.number(pagination.backoff);
const allItems: T[] = [];
let {countLimit} = pagination;
let numberOfRequests = 0;
while (numberOfRequests < pagination.requestLimit) {
if (numberOfRequests !== 0) {
// eslint-disable-next-line no-await-in-loop
await delay(pagination.backoff);
}
// eslint-disable-next-line no-await-in-loop
const response = (await got(undefined, undefined, normalizedOptions)) as Response;
// eslint-disable-next-line no-await-in-loop
const parsed: unknown[] = await pagination.transform(response);
const currentItems: T[] = [];
assert.array(parsed);
for (const item of parsed) {
if (pagination.filter({item, currentItems, allItems})) {
if (!pagination.shouldContinue({item, currentItems, allItems})) {
return;
}
yield item as T;
if (pagination.stackAllItems) {
allItems.push(item as T);
}
currentItems.push(item as T);
if (--countLimit <= 0) {
return;
}
}
}
const optionsToMerge = pagination.paginate({
response,
currentItems,
allItems,
});
if (optionsToMerge === false) {
return;
}
if (optionsToMerge === response.request.options) {
normalizedOptions = response.request.options;
} else {
normalizedOptions.merge(optionsToMerge);
assert.any([is.urlInstance, is.undefined], optionsToMerge.url);
if (optionsToMerge.url !== undefined) {
normalizedOptions.prefixUrl = '';
normalizedOptions.url = optionsToMerge.url;
}
}
numberOfRequests++;
}
});
got.paginate = paginateEach as GotPaginate;
got.paginate.all = (async <T, R>(url: string | URL, options?: OptionsWithPagination<T, R>) => {
const results: T[] = [];
for await (const item of paginateEach<T, R>(url, options)) {
results.push(item);
}
return results;
}) as GotPaginate['all'];
// For those who like very descriptive names
got.paginate.each = paginateEach as GotPaginate['each'];
// Stream API
got.stream = ((url: string | URL, options?: StreamOptions) => got(url, {...options, isStream: true})) as GotStream;
// Shortcuts
for (const method of aliases) {
got[method] = ((url: string | URL, options?: Options): GotReturn => got(url, {...options, method})) as GotRequestFunction;
got.stream[method] = ((url: string | URL, options?: StreamOptions) => got(url, {...options, method, isStream: true})) as GotStream;
}
if (!defaults.mutableDefaults) {
Object.freeze(defaults.handlers);
defaults.options.freeze();
}
Object.defineProperty(got, 'defaults', {
value: defaults,
writable: false,
configurable: false,
enumerable: true,
});
return got;
} | type InstanceDefaults = {
/**
An object containing the default options of Got.
*/
options: Options;
/**
An array of functions. You execute them directly by calling `got()`.
They are some sort of "global hooks" - these functions are called first.
The last handler (*it's hidden*) is either `asPromise` or `asStream`, depending on the `options.isStream` property.
@default []
*/
handlers: HandlerFunction[];
/**
A read-only boolean describing whether the defaults are mutable or not.
If set to `true`, you can update headers over time, for example, update an access token when it expires.
@default false
*/
mutableDefaults: boolean;
}; |
367 | (normalized: Options): GotReturn => {
// Note: `options` is `undefined` when `new Options(...)` fails
request.options = normalized;
request._noPipe = !normalized.isStream;
void request.flush();
if (normalized.isStream) {
return request;
}
if (!promise) {
promise = asPromise(request);
}
return promise;
} | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.undefined], input);
assert.any([is.object, is.undefined], options);
assert.any([is.object, is.undefined], defaults);
if (input instanceof Options || options instanceof Options) {
throw new TypeError('The defaults must be passed as the third argument');
}
this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals);
this._init = [...(defaults?._init ?? [])];
this._merging = false;
this._unixOptions = undefined;
// This rule allows `finally` to be considered more important.
// Meaning no matter the error thrown in the `try` block,
// if `finally` throws then the `finally` error will be thrown.
//
// Yes, we want this. If we set `url` first, then the `url.searchParams`
// would get merged. Instead we set the `searchParams` first, then
// `url.searchParams` is overwritten as expected.
//
/* eslint-disable no-unsafe-finally */
try {
if (is.plainObject(input)) {
try {
this.merge(input);
this.merge(options);
} finally {
this.url = input.url;
}
} else {
try {
this.merge(options);
} finally {
if (options?.url !== undefined) {
if (input === undefined) {
this.url = options.url;
} else {
throw new TypeError('The `url` option is mutually exclusive with the `input` argument');
}
} else if (input !== undefined) {
this.url = input;
}
}
}
} catch (error) {
(error as OptionsError).options = this;
throw error;
}
/* eslint-enable no-unsafe-finally */
}
merge(options?: OptionsInit | Options) {
if (!options) {
return;
}
if (options instanceof Options) {
for (const init of options._init) {
this.merge(init);
}
return;
}
options = cloneRaw(options);
init(this, options, this);
init(options, options, this);
this._merging = true;
// Always merge `isStream` first
if ('isStream' in options) {
this.isStream = options.isStream!;
}
try {
let push = false;
for (const key in options) {
// `got.extend()` options
if (key === 'mutableDefaults' || key === 'handlers') {
continue;
}
// Never merge `url`
if (key === 'url') {
continue;
}
if (!(key in this)) {
throw new Error(`Unexpected option: ${key}`);
}
// @ts-expect-error Type 'unknown' is not assignable to type 'never'.
this[key as keyof Options] = options[key as keyof Options];
push = true;
}
if (push) {
this._init.push(options);
}
} finally {
this._merging = false;
}
}
/**
Custom request function.
The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper).
@default http.request | https.request
*/
get request(): RequestFunction | undefined {
return this._internals.request;
}
set request(value: RequestFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.request = value;
}
/**
An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance.
This is necessary because a request to one protocol might redirect to another.
In such a scenario, Got will switch over to the right protocol agent for you.
If a key is not present, it will default to a global agent.
@example
```
import got from 'got';
import HttpAgent from 'agentkeepalive';
const {HttpsAgent} = HttpAgent;
await got('https://sindresorhus.com', {
agent: {
http: new HttpAgent(),
https: new HttpsAgent()
}
});
```
*/
get agent(): Agents {
return this._internals.agent;
}
set agent(value: Agents) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.agent)) {
throw new TypeError(`Unexpected agent option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.object, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.agent, value);
} else {
this._internals.agent = {...value};
}
}
get h2session(): ClientHttp2Session | undefined {
return this._internals.h2session;
}
set h2session(value: ClientHttp2Session | undefined) {
this._internals.h2session = value;
}
/**
Decompress the response automatically.
This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself.
If this is disabled, a compressed response is returned as a `Buffer`.
This may be useful if you want to handle decompression yourself or stream the raw compressed data.
@default true
*/
get decompress(): boolean {
return this._internals.decompress;
}
set decompress(value: boolean) {
assert.boolean(value);
this._internals.decompress = value;
}
/**
Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property).
By default, there's no timeout.
This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
- `lookup` starts when a socket is assigned and ends when the hostname has been resolved.
Does not apply when using a Unix domain socket.
- `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
- `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
- `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
- `response` starts when the request has been written to the socket and ends when the response headers are received.
- `send` starts when the socket is connected and ends with the request has been written to the socket.
- `request` starts when the request is initiated and ends when the response's end event fires.
*/
get timeout(): Delays {
// We always return `Delays` here.
// It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.timeout;
}
set timeout(value: Delays) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.timeout)) {
throw new Error(`Unexpected timeout option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.number, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.timeout, value);
} else {
this._internals.timeout = {...value};
}
}
/**
When specified, `prefixUrl` will be prepended to `url`.
The prefix can be any valid URL, either relative or absolute.
A trailing slash `/` is optional - one will be added automatically.
__Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance.
__Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion.
For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`.
The latter is used by browsers.
__Tip__: Useful when used with `got.extend()` to create niche-specific Got instances.
__Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`.
If the URL doesn't include it anymore, it will throw.
@example
```
import got from 'got';
await got('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
const instance = got.extend({
prefixUrl: 'https://google.com'
});
await instance('unicorn', {
hooks: {
beforeRequest: [
options => {
options.prefixUrl = 'https://cats.com';
}
]
}
});
//=> 'https://cats.com/unicorn'
```
*/
get prefixUrl(): string | URL {
// We always return `string` here.
// It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.prefixUrl;
}
set prefixUrl(value: string | URL) {
assert.any([is.string, is.urlInstance], value);
if (value === '') {
this._internals.prefixUrl = '';
return;
}
value = value.toString();
if (!value.endsWith('/')) {
value += '/';
}
if (this._internals.prefixUrl && this._internals.url) {
const {href} = this._internals.url as URL;
(this._internals.url as URL).href = value + href.slice((this._internals.prefixUrl as string).length);
}
this._internals.prefixUrl = value;
}
/**
__Note #1__: The `body` option cannot be used with the `json` or `form` option.
__Note #2__: If you provide this option, `got.stream()` will be read-only.
__Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`.
__Note #4__: This option is not enumerable and will not be merged with the instance defaults.
The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`.
*/
get body(): string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined {
return this._internals.body;
}
set body(value: string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined) {
assert.any([is.string, is.buffer, is.nodeStream, is.generator, is.asyncGenerator, isFormData, is.undefined], value);
if (is.nodeStream(value)) {
assert.truthy(value.readable);
}
if (value !== undefined) {
assert.undefined(this._internals.form);
assert.undefined(this._internals.json);
}
this._internals.body = value;
}
/**
The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get form(): Record<string, any> | undefined {
return this._internals.form;
}
set form(value: Record<string, any> | undefined) {
assert.any([is.plainObject, is.undefined], value);
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.json);
}
this._internals.form = value;
}
/**
JSON body. If the `Content-Type` header is not set, it will be set to `application/json`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get json(): unknown {
return this._internals.json;
}
set json(value: unknown) {
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.form);
}
this._internals.json = value;
}
/**
The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
Properties from `options` will override properties in the parsed `url`.
If no protocol is specified, it will throw a `TypeError`.
__Note__: The query string is **not** parsed as search params.
@example
```
await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
// The query string is overridden by `searchParams`
await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
```
*/
get url(): string | URL | undefined {
return this._internals.url;
}
set url(value: string | URL | undefined) {
assert.any([is.string, is.urlInstance, is.undefined], value);
if (value === undefined) {
this._internals.url = undefined;
return;
}
if (is.string(value) && value.startsWith('/')) {
throw new Error('`url` must not start with a slash');
}
const urlString = `${this.prefixUrl as string}${value.toString()}`;
const url = new URL(urlString);
this._internals.url = url;
if (url.protocol === 'unix:') {
url.href = `http://unix${url.pathname}${url.search}`;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
const error: NodeJS.ErrnoException = new Error(`Unsupported protocol: ${url.protocol}`);
error.code = 'ERR_UNSUPPORTED_PROTOCOL';
throw error;
}
if (this._internals.username) {
url.username = this._internals.username;
this._internals.username = '';
}
if (this._internals.password) {
url.password = this._internals.password;
this._internals.password = '';
}
if (this._internals.searchParams) {
url.search = (this._internals.searchParams as URLSearchParams).toString();
this._internals.searchParams = undefined;
}
if (url.hostname === 'unix') {
if (!this._internals.enableUnixSockets) {
throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled');
}
const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);
if (matches?.groups) {
const {socketPath, path} = matches.groups;
this._unixOptions = {
socketPath,
path,
host: '',
};
} else {
this._unixOptions = undefined;
}
return;
}
this._unixOptions = undefined;
}
/**
Cookie support. You don't have to care about parsing or how to store them.
__Note__: If you provide this option, `options.headers.cookie` will be overridden.
*/
get cookieJar(): PromiseCookieJar | ToughCookieJar | undefined {
return this._internals.cookieJar;
}
set cookieJar(value: PromiseCookieJar | ToughCookieJar | undefined) {
assert.any([is.object, is.undefined], value);
if (value === undefined) {
this._internals.cookieJar = undefined;
return;
}
let {setCookie, getCookieString} = value;
assert.function_(setCookie);
assert.function_(getCookieString);
/* istanbul ignore next: Horrible `tough-cookie` v3 check */
if (setCookie.length === 4 && getCookieString.length === 0) {
setCookie = promisify(setCookie.bind(value));
getCookieString = promisify(getCookieString.bind(value));
this._internals.cookieJar = {
setCookie,
getCookieString: getCookieString as PromiseCookieJar['getCookieString'],
};
} else {
this._internals.cookieJar = value;
}
}
/**
You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
*Requires Node.js 16 or later.*
@example
```
import got from 'got';
const abortController = new AbortController();
const request = got('https://httpbin.org/anything', {
signal: abortController.signal
});
setTimeout(() => {
abortController.abort();
}, 100);
```
*/
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
get signal(): any | undefined {
return this._internals.signal;
}
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
set signal(value: any | undefined) {
assert.object(value);
this._internals.signal = value;
}
/**
Ignore invalid cookies instead of throwing an error.
Only useful when the `cookieJar` option has been set. Not recommended.
@default false
*/
get ignoreInvalidCookies(): boolean {
return this._internals.ignoreInvalidCookies;
}
set ignoreInvalidCookies(value: boolean) {
assert.boolean(value);
this._internals.ignoreInvalidCookies = value;
}
/**
Query string that will be added to the request URL.
This will override the query string in `url`.
If you need to pass in an array, you can do it using a `URLSearchParams` instance.
@example
```
import got from 'got';
const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
await got('https://example.com', {searchParams});
console.log(searchParams.toString());
//=> 'key=a&key=b'
```
*/
get searchParams(): string | SearchParameters | URLSearchParams | undefined {
if (this._internals.url) {
return (this._internals.url as URL).searchParams;
}
if (this._internals.searchParams === undefined) {
this._internals.searchParams = new URLSearchParams();
}
return this._internals.searchParams;
}
set searchParams(value: string | SearchParameters | URLSearchParams | undefined) {
assert.any([is.string, is.object, is.undefined], value);
const url = this._internals.url as URL;
if (value === undefined) {
this._internals.searchParams = undefined;
if (url) {
url.search = '';
}
return;
}
const searchParameters = this.searchParams as URLSearchParams;
let updated;
if (is.string(value)) {
updated = new URLSearchParams(value);
} else if (value instanceof URLSearchParams) {
updated = value;
} else {
validateSearchParameters(value);
updated = new URLSearchParams();
// eslint-disable-next-line guard-for-in
for (const key in value) {
const entry = value[key];
if (entry === null) {
updated.append(key, '');
} else if (entry === undefined) {
searchParameters.delete(key);
} else {
updated.append(key, entry as string);
}
}
}
if (this._merging) {
// These keys will be replaced
for (const key of updated.keys()) {
searchParameters.delete(key);
}
for (const [key, value] of updated) {
searchParameters.append(key, value);
}
} else if (url) {
url.search = searchParameters.toString();
} else {
this._internals.searchParams = searchParameters;
}
}
get searchParameters() {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
set searchParameters(_value: unknown) {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
get dnsLookup(): CacheableLookup['lookup'] | undefined {
return this._internals.dnsLookup;
}
set dnsLookup(value: CacheableLookup['lookup'] | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.dnsLookup = value;
}
/**
An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups.
Useful when making lots of requests to different *public* hostnames.
`CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay.
__Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.
@default false
*/
get dnsCache(): CacheableLookup | boolean | undefined {
return this._internals.dnsCache;
}
set dnsCache(value: CacheableLookup | boolean | undefined) {
assert.any([is.object, is.boolean, is.undefined], value);
if (value === true) {
this._internals.dnsCache = getGlobalDnsCache();
} else if (value === false) {
this._internals.dnsCache = undefined;
} else {
this._internals.dnsCache = value;
}
}
/**
User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged.
@example
```
import got from 'got';
const instance = got.extend({
hooks: {
beforeRequest: [
options => {
if (!options.context || !options.context.token) {
throw new Error('Token required');
}
options.headers.token = options.context.token;
}
]
}
});
const context = {
token: 'secret'
};
const response = await instance('https://httpbin.org/headers', {context});
// Let's see the headers
console.log(response.body);
```
*/
get context(): Record<string, unknown> {
return this._internals.context;
}
set context(value: Record<string, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.context, value);
} else {
this._internals.context = {...value};
}
}
/**
Hooks allow modifications during the request lifecycle.
Hook functions may be async and are run serially.
*/
get hooks(): Hooks {
return this._internals.hooks;
}
set hooks(value: Hooks) {
assert.object(value);
// eslint-disable-next-line guard-for-in
for (const knownHookEvent in value) {
if (!(knownHookEvent in this._internals.hooks)) {
throw new Error(`Unexpected hook event: ${knownHookEvent}`);
}
const typedKnownHookEvent = knownHookEvent as keyof Hooks;
const hooks = value[typedKnownHookEvent];
assert.any([is.array, is.undefined], hooks);
if (hooks) {
for (const hook of hooks) {
assert.function_(hook);
}
}
if (this._merging) {
if (hooks) {
// @ts-expect-error FIXME
this._internals.hooks[typedKnownHookEvent].push(...hooks);
}
} else {
if (!hooks) {
throw new Error(`Missing hook event: ${knownHookEvent}`);
}
// @ts-expect-error FIXME
this._internals.hooks[knownHookEvent] = [...hooks];
}
}
}
/**
Defines if redirect responses should be followed automatically.
Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`.
@default true
*/
get followRedirect(): boolean {
return this._internals.followRedirect;
}
set followRedirect(value: boolean) {
assert.boolean(value);
this._internals.followRedirect = value;
}
get followRedirects() {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
set followRedirects(_value: unknown) {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
/**
If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown.
@default 10
*/
get maxRedirects(): number {
return this._internals.maxRedirects;
}
set maxRedirects(value: number) {
assert.number(value);
this._internals.maxRedirects = value;
}
/**
A cache adapter instance for storing cached response data.
@default false
*/
get cache(): string | StorageAdapter | boolean | undefined {
return this._internals.cache;
}
set cache(value: string | StorageAdapter | boolean | undefined) {
assert.any([is.object, is.string, is.boolean, is.undefined], value);
if (value === true) {
this._internals.cache = globalCache;
} else if (value === false) {
this._internals.cache = undefined;
} else {
this._internals.cache = value;
}
}
/**
Determines if a `got.HTTPError` is thrown for unsuccessful responses.
If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing.
This may be useful if you are checking for resource availability and are expecting error responses.
@default true
*/
get throwHttpErrors(): boolean {
return this._internals.throwHttpErrors;
}
set throwHttpErrors(value: boolean) {
assert.boolean(value);
this._internals.throwHttpErrors = value;
}
get username(): string {
const url = this._internals.url as URL;
const value = url ? url.username : this._internals.username;
return decodeURIComponent(value);
}
set username(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.username = fixedValue;
} else {
this._internals.username = fixedValue;
}
}
get password(): string {
const url = this._internals.url as URL;
const value = url ? url.password : this._internals.password;
return decodeURIComponent(value);
}
set password(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.password = fixedValue;
} else {
this._internals.password = fixedValue;
}
}
/**
If set to `true`, Got will additionally accept HTTP2 requests.
It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol.
__Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy.
__Note__: Overriding `options.request` will disable HTTP2 support.
@default false
@example
```
import got from 'got';
const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true});
console.log(headers.via);
//=> '2 nghttpx'
```
*/
get http2(): boolean {
return this._internals.http2;
}
set http2(value: boolean) {
assert.boolean(value);
this._internals.http2 = value;
}
/**
Set this to `true` to allow sending body for the `GET` method.
However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect.
This option is only meant to interact with non-compliant servers when you have no other choice.
__Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__.
@default false
*/
get allowGetBody(): boolean {
return this._internals.allowGetBody;
}
set allowGetBody(value: boolean) {
assert.boolean(value);
this._internals.allowGetBody = value;
}
/**
Request headers.
Existing headers will be overwritten. Headers set to `undefined` will be omitted.
@default {}
*/
get headers(): Headers {
return this._internals.headers;
}
set headers(value: Headers) {
assert.plainObject(value);
if (this._merging) {
Object.assign(this._internals.headers, lowercaseKeys(value));
} else {
this._internals.headers = lowercaseKeys(value);
}
}
/**
Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects.
As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior.
Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers.
__Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7).
@default false
*/
get methodRewriting(): boolean {
return this._internals.methodRewriting;
}
set methodRewriting(value: boolean) {
assert.boolean(value);
this._internals.methodRewriting = value;
}
/**
Indicates which DNS record family to use.
Values:
- `undefined`: IPv4 (if present) or IPv6
- `4`: Only IPv4
- `6`: Only IPv6
@default undefined
*/
get dnsLookupIpVersion(): DnsLookupIpVersion {
return this._internals.dnsLookupIpVersion;
}
set dnsLookupIpVersion(value: DnsLookupIpVersion) {
if (value !== undefined && value !== 4 && value !== 6) {
throw new TypeError(`Invalid DNS lookup IP version: ${value as string}`);
}
this._internals.dnsLookupIpVersion = value;
}
/**
A function used to parse JSON responses.
@example
```
import got from 'got';
import Bourne from '@hapi/bourne';
const parsed = await got('https://example.com', {
parseJson: text => Bourne.parse(text)
}).json();
console.log(parsed);
```
*/
get parseJson(): ParseJsonFunction {
return this._internals.parseJson;
}
set parseJson(value: ParseJsonFunction) {
assert.function_(value);
this._internals.parseJson = value;
}
/**
A function used to stringify the body of JSON requests.
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (key.startsWith('_')) {
return;
}
return value;
}),
json: {
some: 'payload',
_ignoreMe: 1234
}
});
```
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (typeof value === 'number') {
return value.toString();
}
return value;
}),
json: {
some: 'payload',
number: 1
}
});
```
*/
get stringifyJson(): StringifyJsonFunction {
return this._internals.stringifyJson;
}
set stringifyJson(value: StringifyJsonFunction) {
assert.function_(value);
this._internals.stringifyJson = value;
}
/**
An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
By default, it retries *only* on the specified methods, status codes, and on these network errors:
- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
- `ECONNRESET`: Connection was forcibly closed by a peer.
- `EADDRINUSE`: Could not bind to any free port.
- `ECONNREFUSED`: Connection was refused by the server.
- `EPIPE`: The remote side of the stream being written has been closed.
- `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
- `ENETUNREACH`: No internet connection.
- `EAI_AGAIN`: DNS lookup timed out.
__Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
__Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
*/
get retry(): Partial<RetryOptions> {
return this._internals.retry;
}
set retry(value: Partial<RetryOptions>) {
assert.plainObject(value);
assert.any([is.function_, is.undefined], value.calculateDelay);
assert.any([is.number, is.undefined], value.maxRetryAfter);
assert.any([is.number, is.undefined], value.limit);
assert.any([is.array, is.undefined], value.methods);
assert.any([is.array, is.undefined], value.statusCodes);
assert.any([is.array, is.undefined], value.errorCodes);
assert.any([is.number, is.undefined], value.noise);
if (value.noise && Math.abs(value.noise) > 100) {
throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`);
}
for (const key in value) {
if (!(key in this._internals.retry)) {
throw new Error(`Unexpected retry option: ${key}`);
}
}
if (this._merging) {
Object.assign(this._internals.retry, value);
} else {
this._internals.retry = {...value};
}
const {retry} = this._internals;
retry.methods = [...new Set(retry.methods!.map(method => method.toUpperCase() as Method))];
retry.statusCodes = [...new Set(retry.statusCodes)];
retry.errorCodes = [...new Set(retry.errorCodes)];
}
/**
From `http.RequestOptions`.
The IP address used to send the request from.
*/
get localAddress(): string | undefined {
return this._internals.localAddress;
}
set localAddress(value: string | undefined) {
assert.any([is.string, is.undefined], value);
this._internals.localAddress = value;
}
/**
The HTTP method used to make the request.
@default 'GET'
*/
get method(): Method {
return this._internals.method;
}
set method(value: Method) {
assert.string(value);
this._internals.method = value.toUpperCase() as Method;
}
get createConnection(): CreateConnectionFunction | undefined {
return this._internals.createConnection;
}
set createConnection(value: CreateConnectionFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.createConnection = value;
}
/**
From `http-cache-semantics`
@default {}
*/
get cacheOptions(): CacheOptions {
return this._internals.cacheOptions;
}
set cacheOptions(value: CacheOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.shared);
assert.any([is.number, is.undefined], value.cacheHeuristic);
assert.any([is.number, is.undefined], value.immutableMinTimeToLive);
assert.any([is.boolean, is.undefined], value.ignoreCargoCult);
for (const key in value) {
if (!(key in this._internals.cacheOptions)) {
throw new Error(`Cache option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.cacheOptions, value);
} else {
this._internals.cacheOptions = {...value};
}
}
/**
Options for the advanced HTTPS API.
*/
get https(): HttpsOptions {
return this._internals.https;
}
set https(value: HttpsOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.rejectUnauthorized);
assert.any([is.function_, is.undefined], value.checkServerIdentity);
assert.any([is.string, is.object, is.array, is.undefined], value.certificateAuthority);
assert.any([is.string, is.object, is.array, is.undefined], value.key);
assert.any([is.string, is.object, is.array, is.undefined], value.certificate);
assert.any([is.string, is.undefined], value.passphrase);
assert.any([is.string, is.buffer, is.array, is.undefined], value.pfx);
assert.any([is.array, is.undefined], value.alpnProtocols);
assert.any([is.string, is.undefined], value.ciphers);
assert.any([is.string, is.buffer, is.undefined], value.dhparam);
assert.any([is.string, is.undefined], value.signatureAlgorithms);
assert.any([is.string, is.undefined], value.minVersion);
assert.any([is.string, is.undefined], value.maxVersion);
assert.any([is.boolean, is.undefined], value.honorCipherOrder);
assert.any([is.number, is.undefined], value.tlsSessionLifetime);
assert.any([is.string, is.undefined], value.ecdhCurve);
assert.any([is.string, is.buffer, is.array, is.undefined], value.certificateRevocationLists);
for (const key in value) {
if (!(key in this._internals.https)) {
throw new Error(`HTTPS option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.https, value);
} else {
this._internals.https = {...value};
}
}
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead.
Don't set this option to `null`.
__Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`.
@default 'utf-8'
*/
get encoding(): BufferEncoding | undefined {
return this._internals.encoding;
}
set encoding(value: BufferEncoding | undefined) {
if (value === null) {
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
}
assert.any([is.string, is.undefined], value);
this._internals.encoding = value;
}
/**
When set to `true` the promise will return the Response body instead of the Response object.
@default false
*/
get resolveBodyOnly(): boolean {
return this._internals.resolveBodyOnly;
}
set resolveBodyOnly(value: boolean) {
assert.boolean(value);
this._internals.resolveBodyOnly = value;
}
/**
Returns a `Stream` instead of a `Promise`.
This is equivalent to calling `got.stream(url, options?)`.
@default false
*/
get isStream(): boolean {
return this._internals.isStream;
}
set isStream(value: boolean) {
assert.boolean(value);
this._internals.isStream = value;
}
/**
The parsing method.
The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.
It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.
__Note__: When using streams, this option is ignored.
@example
```
const responsePromise = got(url);
const bufferPromise = responsePromise.buffer();
const jsonPromise = responsePromise.json();
const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]);
// `response` is an instance of Got Response
// `buffer` is an instance of Buffer
// `json` is an object
```
@example
```
// This
const body = await got(url).json();
// is semantically the same as this
const body = await got(url, {responseType: 'json', resolveBodyOnly: true});
```
*/
get responseType(): ResponseType {
return this._internals.responseType;
}
set responseType(value: ResponseType) {
if (value === undefined) {
this._internals.responseType = 'text';
return;
}
if (value !== 'text' && value !== 'buffer' && value !== 'json') {
throw new Error(`Invalid \`responseType\` option: ${value as string}`);
}
this._internals.responseType = value;
}
get pagination(): PaginationOptions<unknown, unknown> {
return this._internals.pagination;
}
set pagination(value: PaginationOptions<unknown, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.pagination, value);
} else {
this._internals.pagination = value;
}
}
get auth() {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
set auth(_value: unknown) {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
get setHost() {
return this._internals.setHost;
}
set setHost(value: boolean) {
assert.boolean(value);
this._internals.setHost = value;
}
get maxHeaderSize() {
return this._internals.maxHeaderSize;
}
set maxHeaderSize(value: number | undefined) {
assert.any([is.number, is.undefined], value);
this._internals.maxHeaderSize = value;
}
get enableUnixSockets() {
return this._internals.enableUnixSockets;
}
set enableUnixSockets(value: boolean) {
assert.boolean(value);
this._internals.enableUnixSockets = value;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
toJSON() {
return {...this._internals};
}
[Symbol.for('nodejs.util.inspect.custom')](_depth: number, options: InspectOptions) {
return inspect(this._internals, options);
}
createNativeRequestOptions() {
const internals = this._internals;
const url = internals.url as URL;
let agent;
if (url.protocol === 'https:') {
agent = internals.http2 ? internals.agent : internals.agent.https;
} else {
agent = internals.agent.http;
}
const {https} = internals;
let {pfx} = https;
if (is.array(pfx) && is.plainObject(pfx[0])) {
pfx = (pfx as PfxObject[]).map(object => ({
buf: object.buffer,
passphrase: object.passphrase,
})) as any;
}
return {
...internals.cacheOptions,
...this._unixOptions,
// HTTPS options
// eslint-disable-next-line @typescript-eslint/naming-convention
ALPNProtocols: https.alpnProtocols,
ca: https.certificateAuthority,
cert: https.certificate,
key: https.key,
passphrase: https.passphrase,
pfx: https.pfx,
rejectUnauthorized: https.rejectUnauthorized,
checkServerIdentity: https.checkServerIdentity ?? checkServerIdentity,
ciphers: https.ciphers,
honorCipherOrder: https.honorCipherOrder,
minVersion: https.minVersion,
maxVersion: https.maxVersion,
sigalgs: https.signatureAlgorithms,
sessionTimeout: https.tlsSessionLifetime,
dhparam: https.dhparam,
ecdhCurve: https.ecdhCurve,
crl: https.certificateRevocationLists,
// HTTP options
lookup: internals.dnsLookup ?? (internals.dnsCache as CacheableLookup | undefined)?.lookup,
family: internals.dnsLookupIpVersion,
agent,
setHost: internals.setHost,
method: internals.method,
maxHeaderSize: internals.maxHeaderSize,
localAddress: internals.localAddress,
headers: internals.headers,
createConnection: internals.createConnection,
timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined,
// HTTP/2 options
h2session: internals.h2session,
};
}
getRequestFunction() {
const url = this._internals.url as (URL | undefined);
const {request} = this._internals;
if (!request && url) {
return this.getFallbackRequestFunction();
}
return request;
}
getFallbackRequestFunction() {
const url = this._internals.url as (URL | undefined);
if (!url) {
return;
}
if (url.protocol === 'https:') {
if (this._internals.http2) {
if (major < 15 || (major === 15 && minor < 10)) {
const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above');
(error as NodeJS.ErrnoException).code = 'EUNSUPPORTED';
throw error;
}
return http2wrapper.auto as RequestFunction;
}
return https.request;
}
return http.request;
}
freeze() {
const options = this._internals;
Object.freeze(options);
Object.freeze(options.hooks);
Object.freeze(options.hooks.afterResponse);
Object.freeze(options.hooks.beforeError);
Object.freeze(options.hooks.beforeRedirect);
Object.freeze(options.hooks.beforeRequest);
Object.freeze(options.hooks.beforeRetry);
Object.freeze(options.hooks.init);
Object.freeze(options.https);
Object.freeze(options.cacheOptions);
Object.freeze(options.agent);
Object.freeze(options.headers);
Object.freeze(options.timeout);
Object.freeze(options.retry);
Object.freeze(options.retry.errorCodes);
Object.freeze(options.retry.methods);
Object.freeze(options.retry.statusCodes);
}
} |
368 | (newOptions: Options): GotReturn => {
const handler = defaults.handlers[iteration++] ?? lastHandler;
const result = handler(newOptions, iterateHandlers) as GotReturn;
if (is.promise(result) && !request.options.isStream) {
if (!promise) {
promise = asPromise(request);
}
if (result !== promise) {
const descriptors = Object.getOwnPropertyDescriptors(promise);
for (const key in descriptors) {
if (key in result) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete descriptors[key];
}
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Object.defineProperties(result, descriptors);
result.cancel = promise.cancel;
}
}
return result;
} | class Options {
private _unixOptions?: NativeRequestOptions;
private _internals: InternalsType;
private _merging: boolean;
private readonly _init: OptionsInit[];
constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options) {
assert.any([is.string, is.urlInstance, is.object, is.undefined], input);
assert.any([is.object, is.undefined], options);
assert.any([is.object, is.undefined], defaults);
if (input instanceof Options || options instanceof Options) {
throw new TypeError('The defaults must be passed as the third argument');
}
this._internals = cloneInternals(defaults?._internals ?? defaults ?? defaultInternals);
this._init = [...(defaults?._init ?? [])];
this._merging = false;
this._unixOptions = undefined;
// This rule allows `finally` to be considered more important.
// Meaning no matter the error thrown in the `try` block,
// if `finally` throws then the `finally` error will be thrown.
//
// Yes, we want this. If we set `url` first, then the `url.searchParams`
// would get merged. Instead we set the `searchParams` first, then
// `url.searchParams` is overwritten as expected.
//
/* eslint-disable no-unsafe-finally */
try {
if (is.plainObject(input)) {
try {
this.merge(input);
this.merge(options);
} finally {
this.url = input.url;
}
} else {
try {
this.merge(options);
} finally {
if (options?.url !== undefined) {
if (input === undefined) {
this.url = options.url;
} else {
throw new TypeError('The `url` option is mutually exclusive with the `input` argument');
}
} else if (input !== undefined) {
this.url = input;
}
}
}
} catch (error) {
(error as OptionsError).options = this;
throw error;
}
/* eslint-enable no-unsafe-finally */
}
merge(options?: OptionsInit | Options) {
if (!options) {
return;
}
if (options instanceof Options) {
for (const init of options._init) {
this.merge(init);
}
return;
}
options = cloneRaw(options);
init(this, options, this);
init(options, options, this);
this._merging = true;
// Always merge `isStream` first
if ('isStream' in options) {
this.isStream = options.isStream!;
}
try {
let push = false;
for (const key in options) {
// `got.extend()` options
if (key === 'mutableDefaults' || key === 'handlers') {
continue;
}
// Never merge `url`
if (key === 'url') {
continue;
}
if (!(key in this)) {
throw new Error(`Unexpected option: ${key}`);
}
// @ts-expect-error Type 'unknown' is not assignable to type 'never'.
this[key as keyof Options] = options[key as keyof Options];
push = true;
}
if (push) {
this._init.push(options);
}
} finally {
this._merging = false;
}
}
/**
Custom request function.
The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper).
@default http.request | https.request
*/
get request(): RequestFunction | undefined {
return this._internals.request;
}
set request(value: RequestFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.request = value;
}
/**
An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance.
This is necessary because a request to one protocol might redirect to another.
In such a scenario, Got will switch over to the right protocol agent for you.
If a key is not present, it will default to a global agent.
@example
```
import got from 'got';
import HttpAgent from 'agentkeepalive';
const {HttpsAgent} = HttpAgent;
await got('https://sindresorhus.com', {
agent: {
http: new HttpAgent(),
https: new HttpsAgent()
}
});
```
*/
get agent(): Agents {
return this._internals.agent;
}
set agent(value: Agents) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.agent)) {
throw new TypeError(`Unexpected agent option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.object, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.agent, value);
} else {
this._internals.agent = {...value};
}
}
get h2session(): ClientHttp2Session | undefined {
return this._internals.h2session;
}
set h2session(value: ClientHttp2Session | undefined) {
this._internals.h2session = value;
}
/**
Decompress the response automatically.
This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself.
If this is disabled, a compressed response is returned as a `Buffer`.
This may be useful if you want to handle decompression yourself or stream the raw compressed data.
@default true
*/
get decompress(): boolean {
return this._internals.decompress;
}
set decompress(value: boolean) {
assert.boolean(value);
this._internals.decompress = value;
}
/**
Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property).
By default, there's no timeout.
This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
- `lookup` starts when a socket is assigned and ends when the hostname has been resolved.
Does not apply when using a Unix domain socket.
- `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
- `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
- `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
- `response` starts when the request has been written to the socket and ends when the response headers are received.
- `send` starts when the socket is connected and ends with the request has been written to the socket.
- `request` starts when the request is initiated and ends when the response's end event fires.
*/
get timeout(): Delays {
// We always return `Delays` here.
// It has to be `Delays | number`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.timeout;
}
set timeout(value: Delays) {
assert.plainObject(value);
// eslint-disable-next-line guard-for-in
for (const key in value) {
if (!(key in this._internals.timeout)) {
throw new Error(`Unexpected timeout option: ${key}`);
}
// @ts-expect-error - No idea why `value[key]` doesn't work here.
assert.any([is.number, is.undefined], value[key]);
}
if (this._merging) {
Object.assign(this._internals.timeout, value);
} else {
this._internals.timeout = {...value};
}
}
/**
When specified, `prefixUrl` will be prepended to `url`.
The prefix can be any valid URL, either relative or absolute.
A trailing slash `/` is optional - one will be added automatically.
__Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance.
__Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion.
For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`.
The latter is used by browsers.
__Tip__: Useful when used with `got.extend()` to create niche-specific Got instances.
__Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`.
If the URL doesn't include it anymore, it will throw.
@example
```
import got from 'got';
await got('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
const instance = got.extend({
prefixUrl: 'https://google.com'
});
await instance('unicorn', {
hooks: {
beforeRequest: [
options => {
options.prefixUrl = 'https://cats.com';
}
]
}
});
//=> 'https://cats.com/unicorn'
```
*/
get prefixUrl(): string | URL {
// We always return `string` here.
// It has to be `string | URL`, otherwise TypeScript will error because the getter and the setter have incompatible types.
return this._internals.prefixUrl;
}
set prefixUrl(value: string | URL) {
assert.any([is.string, is.urlInstance], value);
if (value === '') {
this._internals.prefixUrl = '';
return;
}
value = value.toString();
if (!value.endsWith('/')) {
value += '/';
}
if (this._internals.prefixUrl && this._internals.url) {
const {href} = this._internals.url as URL;
(this._internals.url as URL).href = value + href.slice((this._internals.prefixUrl as string).length);
}
this._internals.prefixUrl = value;
}
/**
__Note #1__: The `body` option cannot be used with the `json` or `form` option.
__Note #2__: If you provide this option, `got.stream()` will be read-only.
__Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`.
__Note #4__: This option is not enumerable and will not be merged with the instance defaults.
The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`.
*/
get body(): string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined {
return this._internals.body;
}
set body(value: string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined) {
assert.any([is.string, is.buffer, is.nodeStream, is.generator, is.asyncGenerator, isFormData, is.undefined], value);
if (is.nodeStream(value)) {
assert.truthy(value.readable);
}
if (value !== undefined) {
assert.undefined(this._internals.form);
assert.undefined(this._internals.json);
}
this._internals.body = value;
}
/**
The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get form(): Record<string, any> | undefined {
return this._internals.form;
}
set form(value: Record<string, any> | undefined) {
assert.any([is.plainObject, is.undefined], value);
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.json);
}
this._internals.form = value;
}
/**
JSON body. If the `Content-Type` header is not set, it will be set to `application/json`.
__Note #1__: If you provide this option, `got.stream()` will be read-only.
__Note #2__: This option is not enumerable and will not be merged with the instance defaults.
*/
get json(): unknown {
return this._internals.json;
}
set json(value: unknown) {
if (value !== undefined) {
assert.undefined(this._internals.body);
assert.undefined(this._internals.form);
}
this._internals.json = value;
}
/**
The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
Properties from `options` will override properties in the parsed `url`.
If no protocol is specified, it will throw a `TypeError`.
__Note__: The query string is **not** parsed as search params.
@example
```
await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
// The query string is overridden by `searchParams`
await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
```
*/
get url(): string | URL | undefined {
return this._internals.url;
}
set url(value: string | URL | undefined) {
assert.any([is.string, is.urlInstance, is.undefined], value);
if (value === undefined) {
this._internals.url = undefined;
return;
}
if (is.string(value) && value.startsWith('/')) {
throw new Error('`url` must not start with a slash');
}
const urlString = `${this.prefixUrl as string}${value.toString()}`;
const url = new URL(urlString);
this._internals.url = url;
if (url.protocol === 'unix:') {
url.href = `http://unix${url.pathname}${url.search}`;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
const error: NodeJS.ErrnoException = new Error(`Unsupported protocol: ${url.protocol}`);
error.code = 'ERR_UNSUPPORTED_PROTOCOL';
throw error;
}
if (this._internals.username) {
url.username = this._internals.username;
this._internals.username = '';
}
if (this._internals.password) {
url.password = this._internals.password;
this._internals.password = '';
}
if (this._internals.searchParams) {
url.search = (this._internals.searchParams as URLSearchParams).toString();
this._internals.searchParams = undefined;
}
if (url.hostname === 'unix') {
if (!this._internals.enableUnixSockets) {
throw new Error('Using UNIX domain sockets but option `enableUnixSockets` is not enabled');
}
const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(`${url.pathname}${url.search}`);
if (matches?.groups) {
const {socketPath, path} = matches.groups;
this._unixOptions = {
socketPath,
path,
host: '',
};
} else {
this._unixOptions = undefined;
}
return;
}
this._unixOptions = undefined;
}
/**
Cookie support. You don't have to care about parsing or how to store them.
__Note__: If you provide this option, `options.headers.cookie` will be overridden.
*/
get cookieJar(): PromiseCookieJar | ToughCookieJar | undefined {
return this._internals.cookieJar;
}
set cookieJar(value: PromiseCookieJar | ToughCookieJar | undefined) {
assert.any([is.object, is.undefined], value);
if (value === undefined) {
this._internals.cookieJar = undefined;
return;
}
let {setCookie, getCookieString} = value;
assert.function_(setCookie);
assert.function_(getCookieString);
/* istanbul ignore next: Horrible `tough-cookie` v3 check */
if (setCookie.length === 4 && getCookieString.length === 0) {
setCookie = promisify(setCookie.bind(value));
getCookieString = promisify(getCookieString.bind(value));
this._internals.cookieJar = {
setCookie,
getCookieString: getCookieString as PromiseCookieJar['getCookieString'],
};
} else {
this._internals.cookieJar = value;
}
}
/**
You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
*Requires Node.js 16 or later.*
@example
```
import got from 'got';
const abortController = new AbortController();
const request = got('https://httpbin.org/anything', {
signal: abortController.signal
});
setTimeout(() => {
abortController.abort();
}, 100);
```
*/
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
get signal(): any | undefined {
return this._internals.signal;
}
// TODO: Replace `any` with `AbortSignal` when targeting Node 16.
set signal(value: any | undefined) {
assert.object(value);
this._internals.signal = value;
}
/**
Ignore invalid cookies instead of throwing an error.
Only useful when the `cookieJar` option has been set. Not recommended.
@default false
*/
get ignoreInvalidCookies(): boolean {
return this._internals.ignoreInvalidCookies;
}
set ignoreInvalidCookies(value: boolean) {
assert.boolean(value);
this._internals.ignoreInvalidCookies = value;
}
/**
Query string that will be added to the request URL.
This will override the query string in `url`.
If you need to pass in an array, you can do it using a `URLSearchParams` instance.
@example
```
import got from 'got';
const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
await got('https://example.com', {searchParams});
console.log(searchParams.toString());
//=> 'key=a&key=b'
```
*/
get searchParams(): string | SearchParameters | URLSearchParams | undefined {
if (this._internals.url) {
return (this._internals.url as URL).searchParams;
}
if (this._internals.searchParams === undefined) {
this._internals.searchParams = new URLSearchParams();
}
return this._internals.searchParams;
}
set searchParams(value: string | SearchParameters | URLSearchParams | undefined) {
assert.any([is.string, is.object, is.undefined], value);
const url = this._internals.url as URL;
if (value === undefined) {
this._internals.searchParams = undefined;
if (url) {
url.search = '';
}
return;
}
const searchParameters = this.searchParams as URLSearchParams;
let updated;
if (is.string(value)) {
updated = new URLSearchParams(value);
} else if (value instanceof URLSearchParams) {
updated = value;
} else {
validateSearchParameters(value);
updated = new URLSearchParams();
// eslint-disable-next-line guard-for-in
for (const key in value) {
const entry = value[key];
if (entry === null) {
updated.append(key, '');
} else if (entry === undefined) {
searchParameters.delete(key);
} else {
updated.append(key, entry as string);
}
}
}
if (this._merging) {
// These keys will be replaced
for (const key of updated.keys()) {
searchParameters.delete(key);
}
for (const [key, value] of updated) {
searchParameters.append(key, value);
}
} else if (url) {
url.search = searchParameters.toString();
} else {
this._internals.searchParams = searchParameters;
}
}
get searchParameters() {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
set searchParameters(_value: unknown) {
throw new Error('The `searchParameters` option does not exist. Use `searchParams` instead.');
}
get dnsLookup(): CacheableLookup['lookup'] | undefined {
return this._internals.dnsLookup;
}
set dnsLookup(value: CacheableLookup['lookup'] | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.dnsLookup = value;
}
/**
An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups.
Useful when making lots of requests to different *public* hostnames.
`CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay.
__Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.
@default false
*/
get dnsCache(): CacheableLookup | boolean | undefined {
return this._internals.dnsCache;
}
set dnsCache(value: CacheableLookup | boolean | undefined) {
assert.any([is.object, is.boolean, is.undefined], value);
if (value === true) {
this._internals.dnsCache = getGlobalDnsCache();
} else if (value === false) {
this._internals.dnsCache = undefined;
} else {
this._internals.dnsCache = value;
}
}
/**
User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged.
@example
```
import got from 'got';
const instance = got.extend({
hooks: {
beforeRequest: [
options => {
if (!options.context || !options.context.token) {
throw new Error('Token required');
}
options.headers.token = options.context.token;
}
]
}
});
const context = {
token: 'secret'
};
const response = await instance('https://httpbin.org/headers', {context});
// Let's see the headers
console.log(response.body);
```
*/
get context(): Record<string, unknown> {
return this._internals.context;
}
set context(value: Record<string, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.context, value);
} else {
this._internals.context = {...value};
}
}
/**
Hooks allow modifications during the request lifecycle.
Hook functions may be async and are run serially.
*/
get hooks(): Hooks {
return this._internals.hooks;
}
set hooks(value: Hooks) {
assert.object(value);
// eslint-disable-next-line guard-for-in
for (const knownHookEvent in value) {
if (!(knownHookEvent in this._internals.hooks)) {
throw new Error(`Unexpected hook event: ${knownHookEvent}`);
}
const typedKnownHookEvent = knownHookEvent as keyof Hooks;
const hooks = value[typedKnownHookEvent];
assert.any([is.array, is.undefined], hooks);
if (hooks) {
for (const hook of hooks) {
assert.function_(hook);
}
}
if (this._merging) {
if (hooks) {
// @ts-expect-error FIXME
this._internals.hooks[typedKnownHookEvent].push(...hooks);
}
} else {
if (!hooks) {
throw new Error(`Missing hook event: ${knownHookEvent}`);
}
// @ts-expect-error FIXME
this._internals.hooks[knownHookEvent] = [...hooks];
}
}
}
/**
Defines if redirect responses should be followed automatically.
Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`.
@default true
*/
get followRedirect(): boolean {
return this._internals.followRedirect;
}
set followRedirect(value: boolean) {
assert.boolean(value);
this._internals.followRedirect = value;
}
get followRedirects() {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
set followRedirects(_value: unknown) {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
/**
If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown.
@default 10
*/
get maxRedirects(): number {
return this._internals.maxRedirects;
}
set maxRedirects(value: number) {
assert.number(value);
this._internals.maxRedirects = value;
}
/**
A cache adapter instance for storing cached response data.
@default false
*/
get cache(): string | StorageAdapter | boolean | undefined {
return this._internals.cache;
}
set cache(value: string | StorageAdapter | boolean | undefined) {
assert.any([is.object, is.string, is.boolean, is.undefined], value);
if (value === true) {
this._internals.cache = globalCache;
} else if (value === false) {
this._internals.cache = undefined;
} else {
this._internals.cache = value;
}
}
/**
Determines if a `got.HTTPError` is thrown for unsuccessful responses.
If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing.
This may be useful if you are checking for resource availability and are expecting error responses.
@default true
*/
get throwHttpErrors(): boolean {
return this._internals.throwHttpErrors;
}
set throwHttpErrors(value: boolean) {
assert.boolean(value);
this._internals.throwHttpErrors = value;
}
get username(): string {
const url = this._internals.url as URL;
const value = url ? url.username : this._internals.username;
return decodeURIComponent(value);
}
set username(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.username = fixedValue;
} else {
this._internals.username = fixedValue;
}
}
get password(): string {
const url = this._internals.url as URL;
const value = url ? url.password : this._internals.password;
return decodeURIComponent(value);
}
set password(value: string) {
assert.string(value);
const url = this._internals.url as URL;
const fixedValue = encodeURIComponent(value);
if (url) {
url.password = fixedValue;
} else {
this._internals.password = fixedValue;
}
}
/**
If set to `true`, Got will additionally accept HTTP2 requests.
It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol.
__Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy.
__Note__: Overriding `options.request` will disable HTTP2 support.
@default false
@example
```
import got from 'got';
const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true});
console.log(headers.via);
//=> '2 nghttpx'
```
*/
get http2(): boolean {
return this._internals.http2;
}
set http2(value: boolean) {
assert.boolean(value);
this._internals.http2 = value;
}
/**
Set this to `true` to allow sending body for the `GET` method.
However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect.
This option is only meant to interact with non-compliant servers when you have no other choice.
__Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__.
@default false
*/
get allowGetBody(): boolean {
return this._internals.allowGetBody;
}
set allowGetBody(value: boolean) {
assert.boolean(value);
this._internals.allowGetBody = value;
}
/**
Request headers.
Existing headers will be overwritten. Headers set to `undefined` will be omitted.
@default {}
*/
get headers(): Headers {
return this._internals.headers;
}
set headers(value: Headers) {
assert.plainObject(value);
if (this._merging) {
Object.assign(this._internals.headers, lowercaseKeys(value));
} else {
this._internals.headers = lowercaseKeys(value);
}
}
/**
Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects.
As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior.
Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers.
__Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7).
@default false
*/
get methodRewriting(): boolean {
return this._internals.methodRewriting;
}
set methodRewriting(value: boolean) {
assert.boolean(value);
this._internals.methodRewriting = value;
}
/**
Indicates which DNS record family to use.
Values:
- `undefined`: IPv4 (if present) or IPv6
- `4`: Only IPv4
- `6`: Only IPv6
@default undefined
*/
get dnsLookupIpVersion(): DnsLookupIpVersion {
return this._internals.dnsLookupIpVersion;
}
set dnsLookupIpVersion(value: DnsLookupIpVersion) {
if (value !== undefined && value !== 4 && value !== 6) {
throw new TypeError(`Invalid DNS lookup IP version: ${value as string}`);
}
this._internals.dnsLookupIpVersion = value;
}
/**
A function used to parse JSON responses.
@example
```
import got from 'got';
import Bourne from '@hapi/bourne';
const parsed = await got('https://example.com', {
parseJson: text => Bourne.parse(text)
}).json();
console.log(parsed);
```
*/
get parseJson(): ParseJsonFunction {
return this._internals.parseJson;
}
set parseJson(value: ParseJsonFunction) {
assert.function_(value);
this._internals.parseJson = value;
}
/**
A function used to stringify the body of JSON requests.
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (key.startsWith('_')) {
return;
}
return value;
}),
json: {
some: 'payload',
_ignoreMe: 1234
}
});
```
@example
```
import got from 'got';
await got.post('https://example.com', {
stringifyJson: object => JSON.stringify(object, (key, value) => {
if (typeof value === 'number') {
return value.toString();
}
return value;
}),
json: {
some: 'payload',
number: 1
}
});
```
*/
get stringifyJson(): StringifyJsonFunction {
return this._internals.stringifyJson;
}
set stringifyJson(value: StringifyJsonFunction) {
assert.function_(value);
this._internals.stringifyJson = value;
}
/**
An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
By default, it retries *only* on the specified methods, status codes, and on these network errors:
- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
- `ECONNRESET`: Connection was forcibly closed by a peer.
- `EADDRINUSE`: Could not bind to any free port.
- `ECONNREFUSED`: Connection was refused by the server.
- `EPIPE`: The remote side of the stream being written has been closed.
- `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
- `ENETUNREACH`: No internet connection.
- `EAI_AGAIN`: DNS lookup timed out.
__Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
__Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
*/
get retry(): Partial<RetryOptions> {
return this._internals.retry;
}
set retry(value: Partial<RetryOptions>) {
assert.plainObject(value);
assert.any([is.function_, is.undefined], value.calculateDelay);
assert.any([is.number, is.undefined], value.maxRetryAfter);
assert.any([is.number, is.undefined], value.limit);
assert.any([is.array, is.undefined], value.methods);
assert.any([is.array, is.undefined], value.statusCodes);
assert.any([is.array, is.undefined], value.errorCodes);
assert.any([is.number, is.undefined], value.noise);
if (value.noise && Math.abs(value.noise) > 100) {
throw new Error(`The maximum acceptable retry noise is +/- 100ms, got ${value.noise}`);
}
for (const key in value) {
if (!(key in this._internals.retry)) {
throw new Error(`Unexpected retry option: ${key}`);
}
}
if (this._merging) {
Object.assign(this._internals.retry, value);
} else {
this._internals.retry = {...value};
}
const {retry} = this._internals;
retry.methods = [...new Set(retry.methods!.map(method => method.toUpperCase() as Method))];
retry.statusCodes = [...new Set(retry.statusCodes)];
retry.errorCodes = [...new Set(retry.errorCodes)];
}
/**
From `http.RequestOptions`.
The IP address used to send the request from.
*/
get localAddress(): string | undefined {
return this._internals.localAddress;
}
set localAddress(value: string | undefined) {
assert.any([is.string, is.undefined], value);
this._internals.localAddress = value;
}
/**
The HTTP method used to make the request.
@default 'GET'
*/
get method(): Method {
return this._internals.method;
}
set method(value: Method) {
assert.string(value);
this._internals.method = value.toUpperCase() as Method;
}
get createConnection(): CreateConnectionFunction | undefined {
return this._internals.createConnection;
}
set createConnection(value: CreateConnectionFunction | undefined) {
assert.any([is.function_, is.undefined], value);
this._internals.createConnection = value;
}
/**
From `http-cache-semantics`
@default {}
*/
get cacheOptions(): CacheOptions {
return this._internals.cacheOptions;
}
set cacheOptions(value: CacheOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.shared);
assert.any([is.number, is.undefined], value.cacheHeuristic);
assert.any([is.number, is.undefined], value.immutableMinTimeToLive);
assert.any([is.boolean, is.undefined], value.ignoreCargoCult);
for (const key in value) {
if (!(key in this._internals.cacheOptions)) {
throw new Error(`Cache option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.cacheOptions, value);
} else {
this._internals.cacheOptions = {...value};
}
}
/**
Options for the advanced HTTPS API.
*/
get https(): HttpsOptions {
return this._internals.https;
}
set https(value: HttpsOptions) {
assert.plainObject(value);
assert.any([is.boolean, is.undefined], value.rejectUnauthorized);
assert.any([is.function_, is.undefined], value.checkServerIdentity);
assert.any([is.string, is.object, is.array, is.undefined], value.certificateAuthority);
assert.any([is.string, is.object, is.array, is.undefined], value.key);
assert.any([is.string, is.object, is.array, is.undefined], value.certificate);
assert.any([is.string, is.undefined], value.passphrase);
assert.any([is.string, is.buffer, is.array, is.undefined], value.pfx);
assert.any([is.array, is.undefined], value.alpnProtocols);
assert.any([is.string, is.undefined], value.ciphers);
assert.any([is.string, is.buffer, is.undefined], value.dhparam);
assert.any([is.string, is.undefined], value.signatureAlgorithms);
assert.any([is.string, is.undefined], value.minVersion);
assert.any([is.string, is.undefined], value.maxVersion);
assert.any([is.boolean, is.undefined], value.honorCipherOrder);
assert.any([is.number, is.undefined], value.tlsSessionLifetime);
assert.any([is.string, is.undefined], value.ecdhCurve);
assert.any([is.string, is.buffer, is.array, is.undefined], value.certificateRevocationLists);
for (const key in value) {
if (!(key in this._internals.https)) {
throw new Error(`HTTPS option \`${key}\` does not exist`);
}
}
if (this._merging) {
Object.assign(this._internals.https, value);
} else {
this._internals.https = {...value};
}
}
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead.
Don't set this option to `null`.
__Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`.
@default 'utf-8'
*/
get encoding(): BufferEncoding | undefined {
return this._internals.encoding;
}
set encoding(value: BufferEncoding | undefined) {
if (value === null) {
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
}
assert.any([is.string, is.undefined], value);
this._internals.encoding = value;
}
/**
When set to `true` the promise will return the Response body instead of the Response object.
@default false
*/
get resolveBodyOnly(): boolean {
return this._internals.resolveBodyOnly;
}
set resolveBodyOnly(value: boolean) {
assert.boolean(value);
this._internals.resolveBodyOnly = value;
}
/**
Returns a `Stream` instead of a `Promise`.
This is equivalent to calling `got.stream(url, options?)`.
@default false
*/
get isStream(): boolean {
return this._internals.isStream;
}
set isStream(value: boolean) {
assert.boolean(value);
this._internals.isStream = value;
}
/**
The parsing method.
The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.
It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.
__Note__: When using streams, this option is ignored.
@example
```
const responsePromise = got(url);
const bufferPromise = responsePromise.buffer();
const jsonPromise = responsePromise.json();
const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]);
// `response` is an instance of Got Response
// `buffer` is an instance of Buffer
// `json` is an object
```
@example
```
// This
const body = await got(url).json();
// is semantically the same as this
const body = await got(url, {responseType: 'json', resolveBodyOnly: true});
```
*/
get responseType(): ResponseType {
return this._internals.responseType;
}
set responseType(value: ResponseType) {
if (value === undefined) {
this._internals.responseType = 'text';
return;
}
if (value !== 'text' && value !== 'buffer' && value !== 'json') {
throw new Error(`Invalid \`responseType\` option: ${value as string}`);
}
this._internals.responseType = value;
}
get pagination(): PaginationOptions<unknown, unknown> {
return this._internals.pagination;
}
set pagination(value: PaginationOptions<unknown, unknown>) {
assert.object(value);
if (this._merging) {
Object.assign(this._internals.pagination, value);
} else {
this._internals.pagination = value;
}
}
get auth() {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
set auth(_value: unknown) {
throw new Error('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
get setHost() {
return this._internals.setHost;
}
set setHost(value: boolean) {
assert.boolean(value);
this._internals.setHost = value;
}
get maxHeaderSize() {
return this._internals.maxHeaderSize;
}
set maxHeaderSize(value: number | undefined) {
assert.any([is.number, is.undefined], value);
this._internals.maxHeaderSize = value;
}
get enableUnixSockets() {
return this._internals.enableUnixSockets;
}
set enableUnixSockets(value: boolean) {
assert.boolean(value);
this._internals.enableUnixSockets = value;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
toJSON() {
return {...this._internals};
}
[Symbol.for('nodejs.util.inspect.custom')](_depth: number, options: InspectOptions) {
return inspect(this._internals, options);
}
createNativeRequestOptions() {
const internals = this._internals;
const url = internals.url as URL;
let agent;
if (url.protocol === 'https:') {
agent = internals.http2 ? internals.agent : internals.agent.https;
} else {
agent = internals.agent.http;
}
const {https} = internals;
let {pfx} = https;
if (is.array(pfx) && is.plainObject(pfx[0])) {
pfx = (pfx as PfxObject[]).map(object => ({
buf: object.buffer,
passphrase: object.passphrase,
})) as any;
}
return {
...internals.cacheOptions,
...this._unixOptions,
// HTTPS options
// eslint-disable-next-line @typescript-eslint/naming-convention
ALPNProtocols: https.alpnProtocols,
ca: https.certificateAuthority,
cert: https.certificate,
key: https.key,
passphrase: https.passphrase,
pfx: https.pfx,
rejectUnauthorized: https.rejectUnauthorized,
checkServerIdentity: https.checkServerIdentity ?? checkServerIdentity,
ciphers: https.ciphers,
honorCipherOrder: https.honorCipherOrder,
minVersion: https.minVersion,
maxVersion: https.maxVersion,
sigalgs: https.signatureAlgorithms,
sessionTimeout: https.tlsSessionLifetime,
dhparam: https.dhparam,
ecdhCurve: https.ecdhCurve,
crl: https.certificateRevocationLists,
// HTTP options
lookup: internals.dnsLookup ?? (internals.dnsCache as CacheableLookup | undefined)?.lookup,
family: internals.dnsLookupIpVersion,
agent,
setHost: internals.setHost,
method: internals.method,
maxHeaderSize: internals.maxHeaderSize,
localAddress: internals.localAddress,
headers: internals.headers,
createConnection: internals.createConnection,
timeout: internals.http2 ? getHttp2TimeoutOption(internals) : undefined,
// HTTP/2 options
h2session: internals.h2session,
};
}
getRequestFunction() {
const url = this._internals.url as (URL | undefined);
const {request} = this._internals;
if (!request && url) {
return this.getFallbackRequestFunction();
}
return request;
}
getFallbackRequestFunction() {
const url = this._internals.url as (URL | undefined);
if (!url) {
return;
}
if (url.protocol === 'https:') {
if (this._internals.http2) {
if (major < 15 || (major === 15 && minor < 10)) {
const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above');
(error as NodeJS.ErrnoException).code = 'EUNSUPPORTED';
throw error;
}
return http2wrapper.auto as RequestFunction;
}
return https.request;
}
return http.request;
}
freeze() {
const options = this._internals;
Object.freeze(options);
Object.freeze(options.hooks);
Object.freeze(options.hooks.afterResponse);
Object.freeze(options.hooks.beforeError);
Object.freeze(options.hooks.beforeRedirect);
Object.freeze(options.hooks.beforeRequest);
Object.freeze(options.hooks.beforeRetry);
Object.freeze(options.hooks.init);
Object.freeze(options.https);
Object.freeze(options.cacheOptions);
Object.freeze(options.agent);
Object.freeze(options.headers);
Object.freeze(options.timeout);
Object.freeze(options.retry);
Object.freeze(options.retry.errorCodes);
Object.freeze(options.retry.methods);
Object.freeze(options.retry.statusCodes);
}
} |
369 | (request: ClientRequest) => void | interface ClientRequest {
[reentry]?: boolean;
} |
370 | (progress: Progress) => void | type Progress = {
percent: number;
transferred: number;
total?: number;
}; |
371 | constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
} | type DefaultsType = ConstructorParameters<typeof Options>[2]; |
372 | constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
} | type UrlType = ConstructorParameters<typeof Options>[0]; |
373 | constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
} | type OptionsType = ConstructorParameters<typeof Options>[1]; |
374 | _beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
} | type Error = NodeJS.ErrnoException; |
375 | _beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
} | type Error = NodeJS.ErrnoException; |
376 | (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
} | type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
}; |
377 | (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
} | type Error = NodeJS.ErrnoException; |
378 | (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
} | type Error = NodeJS.ErrnoException; |
379 | private _onRequest(request: ClientRequest): void {
const {options} = this;
const {timeout, url} = options;
timer(request);
if (this.options.http2) {
// Unset stream timeout, as the `timeout` option was used only for connection timeout.
request.setTimeout(0);
}
this._cancelTimeouts = timedOut(request, timeout, url as URL);
const responseEventName = options.cache ? 'cacheableResponse' : 'response';
request.once(responseEventName, (response: IncomingMessageWithTimings) => {
void this._onResponse(response);
});
request.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
});
this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
this._request = request;
this.emit('uploadProgress', this.uploadProgress);
this._sendBody();
this.emit('request', request);
} | interface ClientRequest {
[reentry]?: boolean;
} |
380 | (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
} | type Error = NodeJS.ErrnoException; |
381 | (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
} | type Error = NodeJS.ErrnoException; |
382 | private async _error(error: RequestError): Promise<void> {
try {
if (error instanceof HTTPError && !this.options.throwHttpErrors) {
// This branch can be reached only when using the Promise API
// Skip calling the hooks on purpose.
// See https://github.com/sindresorhus/got/issues/2103
} else {
for (const hook of this.options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
} catch (error_: any) {
error = new RequestError(error_.message, error_, this);
}
this.destroy(error);
} | class RequestError extends Error {
input?: string;
code: string;
override stack!: string;
declare readonly options: Options;
readonly response?: Response;
readonly request?: Request;
readonly timings?: Timings;
constructor(message: string, error: Partial<Error & {code?: string}>, self: Request | Options) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = 'RequestError';
this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR';
this.input = (error as any).input;
if (isRequest(self)) {
Object.defineProperty(this, 'request', {
enumerable: false,
value: self,
});
Object.defineProperty(this, 'response', {
enumerable: false,
value: self.response,
});
this.options = self.options;
} else {
this.options = self;
}
this.timings = this.request?.timings;
// Recover the original stacktrace
if (is.string(error.stack) && is.string(this.stack)) {
const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;
const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse();
const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message!) + error.message!.length).split('\n').reverse();
// Remove duplicated traces
while (errorStackTrace.length > 0 && errorStackTrace[0] === thisStackTrace[0]) {
thisStackTrace.shift();
}
this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`;
}
}
} |
383 | (response: PlainResponse): boolean => {
const {statusCode} = response;
const limitStatusCode = response.request.options.followRedirect ? 299 : 399;
return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
} | type PlainResponse = {
/**
The original request URL.
*/
requestUrl: URL;
/**
The redirect URLs.
*/
redirectUrls: URL[];
/**
- `options` - The Got options that were set on this request.
__Note__: This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest).
*/
request: Request;
/**
The remote IP address.
This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86).
__Note__: Not available when the response is cached.
*/
ip?: string;
/**
Whether the response was retrieved from the cache.
*/
isFromCache: boolean;
/**
The status code of the response.
*/
statusCode: number;
/**
The request URL or the final URL after redirects.
*/
url: string;
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
timings: Timings;
/**
The number of times the request was retried.
*/
retryCount: number;
// Defined only if request errored
/**
The raw result of the request.
*/
rawBody?: Buffer;
/**
The result of the request.
*/
body?: unknown;
/**
Whether the response was successful.
__Note__: Got throws automatically when `response.ok` is `false` and `throwHttpErrors` is `true`.
*/
ok: boolean;
} & IncomingMessageWithTimings; |
384 | constructor(error: Error, response: Response) {
const {options} = response.request;
super(`${error.message} in "${options.url!.toString()}"`, error, response.request);
this.name = 'ParseError';
this.code = 'ERR_BODY_PARSE_FAILURE';
} | type Response<T = unknown> = {
/**
The result of the request.
*/
body: T;
/**
The raw result of the request.
*/
rawBody: Buffer;
} & PlainResponse; |
385 | constructor(error: Error, response: Response) {
const {options} = response.request;
super(`${error.message} in "${options.url!.toString()}"`, error, response.request);
this.name = 'ParseError';
this.code = 'ERR_BODY_PARSE_FAILURE';
} | type Error = NodeJS.ErrnoException; |
386 | constructor(error: Error, response: Response) {
const {options} = response.request;
super(`${error.message} in "${options.url!.toString()}"`, error, response.request);
this.name = 'ParseError';
this.code = 'ERR_BODY_PARSE_FAILURE';
} | type Error = NodeJS.ErrnoException; |
387 | (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: BufferEncoding): unknown => {
const {rawBody} = response;
try {
if (responseType === 'text') {
return rawBody.toString(encoding);
}
if (responseType === 'json') {
return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding));
}
if (responseType === 'buffer') {
return rawBody;
}
} catch (error) {
throw new ParseError(error as Error, response);
}
throw new ParseError({
message: `Unknown body type '${responseType as string}'`,
name: 'Error',
}, response);
} | type Response<T = unknown> = {
/**
The result of the request.
*/
body: T;
/**
The raw result of the request.
*/
rawBody: Buffer;
} & PlainResponse; |
388 | (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: BufferEncoding): unknown => {
const {rawBody} = response;
try {
if (responseType === 'text') {
return rawBody.toString(encoding);
}
if (responseType === 'json') {
return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding));
}
if (responseType === 'buffer') {
return rawBody;
}
} catch (error) {
throw new ParseError(error as Error, response);
}
throw new ParseError({
message: `Unknown body type '${responseType as string}'`,
name: 'Error',
}, response);
} | type ResponseType = 'json' | 'buffer' | 'text'; |
389 | (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: BufferEncoding): unknown => {
const {rawBody} = response;
try {
if (responseType === 'text') {
return rawBody.toString(encoding);
}
if (responseType === 'json') {
return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding));
}
if (responseType === 'buffer') {
return rawBody;
}
} catch (error) {
throw new ParseError(error as Error, response);
}
throw new ParseError({
message: `Unknown body type '${responseType as string}'`,
name: 'Error',
}, response);
} | type ParseJsonFunction = (text: string) => unknown; |
390 | constructor(request: Request) {
super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);
this.name = 'MaxRedirectsError';
this.code = 'ERR_TOO_MANY_REDIRECTS';
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUrls: URL[];
retryCount: number;
declare private _requestOptions: NativeRequestOptions;
private _stopRetry: () => void;
private _downloadedSize: number;
private _uploadedSize: number;
private _stopReading: boolean;
private readonly _pipedServerResponses: Set<ServerResponse>;
private _request?: ClientRequest;
private _responseSize?: number;
private _bodySize?: number;
private _unproxyEvents: () => void;
private _isFromCache?: boolean;
private _cannotHaveBody: boolean;
private _triggerRead: boolean;
declare private _jobs: Array<() => void>;
private _cancelTimeouts: () => void;
private readonly _removeListeners: () => void;
private _nativeResponse?: IncomingMessageWithTimings;
private _flushed: boolean;
private _aborted: boolean;
// We need this because `this._request` if `undefined` when using cache
private _requestInitialized: boolean;
constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
}
async flush() {
if (this._flushed) {
return;
}
this._flushed = true;
try {
await this._finalizeBody();
if (this.destroyed) {
return;
}
await this._makeRequest();
if (this.destroyed) {
this._request?.destroy();
return;
}
// Queued writes etc.
for (const job of this._jobs) {
job();
}
// Prevent memory leak
this._jobs.length = 0;
this._requestInitialized = true;
} catch (error: any) {
this._beforeError(error);
}
}
_beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
}
override _read(): void {
this._triggerRead = true;
const {response} = this;
if (response && !this._stopReading) {
// We cannot put this in the `if` above
// because `.read()` also triggers the `end` event
if (response.readableLength) {
this._triggerRead = false;
}
let data;
while ((data = response.read()) !== null) {
this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands
const progress = this.downloadProgress;
if (progress.percent < 1) {
this.emit('downloadProgress', progress);
}
this.push(data);
}
}
}
override _write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const write = (): void => {
this._writeRequest(chunk, encoding, callback);
};
if (this._requestInitialized) {
write();
} else {
this._jobs.push(write);
}
}
override _final(callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const endRequest = (): void => {
// We need to check if `this._request` is present,
// because it isn't when we use cache.
if (!this._request || this._request.destroyed) {
callback();
return;
}
this._request.end((error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The request has been destroyed before `_final` finished.
// See https://github.com/nodejs/node/issues/39356
if ((this._request as any)._writableState?.errored) {
return;
}
if (!error) {
this._bodySize = this._uploadedSize;
this.emit('uploadProgress', this.uploadProgress);
this._request!.emit('upload-complete');
}
callback(error);
});
};
if (this._requestInitialized) {
endRequest();
} else {
this._jobs.push(endRequest);
}
}
override _destroy(error: Error | null, callback: (error: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
this._stopReading = true;
this.flush = async () => {};
// Prevent further retries
this._stopRetry();
this._cancelTimeouts();
this._removeListeners();
if (this.options) {
const {body} = this.options;
if (is.nodeStream(body)) {
body.destroy();
}
}
if (this._request) {
this._request.destroy();
}
if (error !== null && !is.undefined(error) && !(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
callback(error);
}
override pipe<T extends NodeJS.WritableStream>(destination: T, options?: {end?: boolean}): T {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.add(destination);
}
return super.pipe(destination, options);
}
override unpipe<T extends NodeJS.WritableStream>(destination: T): this {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.delete(destination);
}
super.unpipe(destination);
return this;
}
private async _finalizeBody(): Promise<void> {
const {options} = this;
const {headers} = options;
const isForm = !is.undefined(options.form);
// eslint-disable-next-line @typescript-eslint/naming-convention
const isJSON = !is.undefined(options.json);
const isBody = !is.undefined(options.body);
const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);
this._cannotHaveBody = cannotHaveBody;
if (isForm || isJSON || isBody) {
if (cannotHaveBody) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
// Serialize body
const noContentType = !is.string(headers['content-type']);
if (isBody) {
// Body is spec-compliant FormData
if (isFormDataLike(options.body)) {
const encoder = new FormDataEncoder(options.body);
if (noContentType) {
headers['content-type'] = encoder.headers['Content-Type'];
}
if ('Content-Length' in encoder.headers) {
headers['content-length'] = encoder.headers['Content-Length'];
}
options.body = encoder.encode();
}
// Special case for https://github.com/form-data/form-data
if (isFormData(options.body) && noContentType) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
} else if (isForm) {
if (noContentType) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
const {form} = options;
options.form = undefined;
options.body = (new URLSearchParams(form as Record<string, string>)).toString();
} else {
if (noContentType) {
headers['content-type'] = 'application/json';
}
const {json} = options;
options.json = undefined;
options.body = options.stringifyJson(json);
}
const uploadBodySize = await getBodySize(options.body, options.headers);
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body. For example, a Content-Length header
// field is normally sent in a POST request even when the value is 0
// (indicating an empty payload body). A user agent SHOULD NOT send a
// Content-Length header field when the request message does not contain
// a payload body and the method semantics do not anticipate such a
// body.
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is.undefined(uploadBodySize)) {
headers['content-length'] = String(uploadBodySize);
}
}
if (options.responseType === 'json' && !('accept' in options.headers)) {
options.headers.accept = 'application/json';
}
this._bodySize = Number(headers['content-length']) || undefined;
}
private async _onResponseBase(response: IncomingMessageWithTimings): Promise<void> {
// This will be called e.g. when using cache so we need to check if this request has been aborted.
if (this.isAborted) {
return;
}
const {options} = this;
const {url} = options;
this._nativeResponse = response;
if (options.decompress) {
response = decompressResponse(response);
}
const statusCode = response.statusCode!;
const typedResponse = response as PlainResponse;
typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];
typedResponse.url = options.url!.toString();
typedResponse.requestUrl = this.requestUrl!;
typedResponse.redirectUrls = this.redirectUrls;
typedResponse.request = this;
typedResponse.isFromCache = (this._nativeResponse as any).fromCache ?? false;
typedResponse.ip = this.ip;
typedResponse.retryCount = this.retryCount;
typedResponse.ok = isResponseOk(typedResponse);
this._isFromCache = typedResponse.isFromCache;
this._responseSize = Number(response.headers['content-length']) || undefined;
this.response = typedResponse;
response.once('end', () => {
this._responseSize = this._downloadedSize;
this.emit('downloadProgress', this.downloadProgress);
});
response.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
});
response.once('aborted', () => {
this._aborted = true;
this._beforeError(new ReadError({
name: 'Error',
message: 'The server aborted pending request',
code: 'ECONNRESET',
}, this));
});
this.emit('downloadProgress', this.downloadProgress);
const rawCookies = response.headers['set-cookie'];
if (is.object(options.cookieJar) && rawCookies) {
let promises: Array<Promise<unknown>> = rawCookies.map(async (rawCookie: string) => (options.cookieJar as PromiseCookieJar).setCookie(rawCookie, url!.toString()));
if (options.ignoreInvalidCookies) {
promises = promises.map(async promise => {
try {
await promise;
} catch {}
});
}
try {
await Promise.all(promises);
} catch (error: any) {
this._beforeError(error);
return;
}
}
// The above is running a promise, therefore we need to check if this request has been aborted yet again.
if (this.isAborted) {
return;
}
if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
// We're being redirected, we don't care about the response.
// It'd be best to abort the request, but we can't because
// we would have to sacrifice the TCP connection. We don't want that.
response.resume();
this._cancelTimeouts();
this._unproxyEvents();
if (this.redirectUrls.length >= options.maxRedirects) {
this._beforeError(new MaxRedirectsError(this));
return;
}
this._request = undefined;
const updatedOptions = new Options(undefined, undefined, this.options);
const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
const canRewrite = statusCode !== 307 && statusCode !== 308;
const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
if (serverRequestedGet || userRequestedGet) {
updatedOptions.method = 'GET';
updatedOptions.body = undefined;
updatedOptions.json = undefined;
updatedOptions.form = undefined;
delete updatedOptions.headers['content-length'];
}
try {
// We need this in order to support UTF-8
const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
const redirectUrl = new URL(redirectBuffer, url);
if (!isUnixSocketURL(url as URL) && isUnixSocketURL(redirectUrl)) {
this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
return;
}
// Redirecting to a different site, clear sensitive data.
if (redirectUrl.hostname !== (url as URL).hostname || redirectUrl.port !== (url as URL).port) {
if ('host' in updatedOptions.headers) {
delete updatedOptions.headers.host;
}
if ('cookie' in updatedOptions.headers) {
delete updatedOptions.headers.cookie;
}
if ('authorization' in updatedOptions.headers) {
delete updatedOptions.headers.authorization;
}
if (updatedOptions.username || updatedOptions.password) {
updatedOptions.username = '';
updatedOptions.password = '';
}
} else {
redirectUrl.username = updatedOptions.username;
redirectUrl.password = updatedOptions.password;
}
this.redirectUrls.push(redirectUrl);
updatedOptions.prefixUrl = '';
updatedOptions.url = redirectUrl;
for (const hook of updatedOptions.hooks.beforeRedirect) {
// eslint-disable-next-line no-await-in-loop
await hook(updatedOptions, typedResponse);
}
this.emit('redirect', updatedOptions, typedResponse);
this.options = updatedOptions;
await this._makeRequest();
} catch (error: any) {
this._beforeError(error);
return;
}
return;
}
// `HTTPError`s always have `error.response.body` defined.
// Therefore we cannot retry if `options.throwHttpErrors` is false.
// On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
// but that wouldn't be possible since the body would be already read in `error.response.body`.
if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
this._beforeError(new HTTPError(typedResponse));
return;
}
response.on('readable', () => {
if (this._triggerRead) {
this._read();
}
});
this.on('resume', () => {
response.resume();
});
this.on('pause', () => {
response.pause();
});
response.once('end', () => {
this.push(null);
});
if (this._noPipe) {
const success = await this._setRawBody();
if (success) {
this.emit('response', response);
}
return;
}
this.emit('response', response);
for (const destination of this._pipedServerResponses) {
if (destination.headersSent) {
continue;
}
// eslint-disable-next-line guard-for-in
for (const key in response.headers) {
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
const value = response.headers[key];
if (isAllowed) {
destination.setHeader(key, value!);
}
}
destination.statusCode = statusCode;
}
}
private async _setRawBody(from: Readable = this): Promise<boolean> {
if (from.readableEnded) {
return false;
}
try {
// Errors are emitted via the `error` event
const rawBody = await getBuffer(from);
// On retry Request is destroyed with no error, therefore the above will successfully resolve.
// So in order to check if this was really successfull, we need to check if it has been properly ended.
if (!this.isAborted) {
this.response!.rawBody = rawBody;
return true;
}
} catch {}
return false;
}
private async _onResponse(response: IncomingMessageWithTimings): Promise<void> {
try {
await this._onResponseBase(response);
} catch (error: any) {
/* istanbul ignore next: better safe than sorry */
this._beforeError(error);
}
}
private _onRequest(request: ClientRequest): void {
const {options} = this;
const {timeout, url} = options;
timer(request);
if (this.options.http2) {
// Unset stream timeout, as the `timeout` option was used only for connection timeout.
request.setTimeout(0);
}
this._cancelTimeouts = timedOut(request, timeout, url as URL);
const responseEventName = options.cache ? 'cacheableResponse' : 'response';
request.once(responseEventName, (response: IncomingMessageWithTimings) => {
void this._onResponse(response);
});
request.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
});
this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
this._request = request;
this.emit('uploadProgress', this.uploadProgress);
this._sendBody();
this.emit('request', request);
}
private async _asyncWrite(chunk: any): Promise<void> {
return new Promise((resolve, reject) => {
super.write(chunk, error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
private _sendBody() {
// Send body
const {body} = this.options;
const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this;
if (is.nodeStream(body)) {
body.pipe(currentRequest);
} else if (is.generator(body) || is.asyncGenerator(body)) {
(async () => {
try {
for await (const chunk of body) {
await this._asyncWrite(chunk);
}
super.end();
} catch (error: any) {
this._beforeError(error);
}
})();
} else if (!is.undefined(body)) {
this._writeRequest(body, undefined, () => {});
currentRequest.end();
} else if (this._cannotHaveBody || this._noPipe) {
currentRequest.end();
}
}
private _prepareCache(cache: string | StorageAdapter) {
if (!cacheableStore.has(cache)) {
const cacheableRequest = new CacheableRequest(
((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
const result = (requestOptions as any)._request(requestOptions, handler);
// TODO: remove this when `cacheable-request` supports async request functions.
if (is.promise(result)) {
// We only need to implement the error handler in order to support HTTP2 caching.
// The result will be a promise anyway.
// @ts-expect-error ignore
// eslint-disable-next-line @typescript-eslint/promise-function-async
result.once = (event: string, handler: (reason: unknown) => void) => {
if (event === 'error') {
(async () => {
try {
await result;
} catch (error) {
handler(error);
}
})();
} else if (event === 'abort') {
// The empty catch is needed here in case when
// it rejects before it's `await`ed in `_makeRequest`.
(async () => {
try {
const request = (await result) as ClientRequest;
request.once('abort', handler);
} catch {}
})();
} else {
/* istanbul ignore next: safety check */
throw new Error(`Unknown HTTP2 promise event: ${event}`);
}
return result;
};
}
return result;
}) as typeof http.request,
cache as StorageAdapter,
);
cacheableStore.set(cache, cacheableRequest.request());
}
}
private async _createCacheableRequest(url: URL, options: RequestOptions): Promise<ClientRequest | ResponseLike> {
return new Promise<ClientRequest | ResponseLike>((resolve, reject) => {
// TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed
Object.assign(options, urlToOptions(url));
let request: ClientRequest | Promise<ClientRequest>;
// TODO: Fix `cacheable-response`. This is ugly.
const cacheRequest = cacheableStore.get((options as any).cache)!(options as CacheableOptions, async (response: any) => {
response._readableState.autoDestroy = false;
if (request) {
const fix = () => {
if (response.req) {
response.complete = response.req.res.complete;
}
};
response.prependOnceListener('end', fix);
fix();
(await request).emit('cacheableResponse', response);
}
resolve(response);
});
cacheRequest.once('error', reject);
cacheRequest.once('request', async (requestOrPromise: ClientRequest | Promise<ClientRequest>) => {
request = requestOrPromise;
resolve(request);
});
});
}
private async _makeRequest(): Promise<void> {
const {options} = this;
const {headers, username, password} = options;
const cookieJar = options.cookieJar as PromiseCookieJar | undefined;
for (const key in headers) {
if (is.undefined(headers[key])) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete headers[key];
} else if (is.null_(headers[key])) {
throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
}
}
if (options.decompress && is.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';
}
if (username || password) {
const credentials = Buffer.from(`${username}:${password}`).toString('base64');
headers.authorization = `Basic ${credentials}`;
}
// Set cookies
if (cookieJar) {
const cookieString: string = await cookieJar.getCookieString(options.url!.toString());
if (is.nonEmptyString(cookieString)) {
headers.cookie = cookieString;
}
}
// Reset `prefixUrl`
options.prefixUrl = '';
let request: ReturnType<Options['getRequestFunction']> | undefined;
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
const result = await hook(options);
if (!is.undefined(result)) {
// @ts-expect-error Skip the type mismatch to support abstract responses
request = () => result;
break;
}
}
if (!request) {
request = options.getRequestFunction();
}
const url = options.url as URL;
this._requestOptions = options.createNativeRequestOptions() as NativeRequestOptions;
if (options.cache) {
(this._requestOptions as any)._request = request;
(this._requestOptions as any).cache = options.cache;
(this._requestOptions as any).body = options.body;
this._prepareCache(options.cache as StorageAdapter);
}
// Cache support
const fn = options.cache ? this._createCacheableRequest : request;
try {
// We can't do `await fn(...)`,
// because stream `error` event can be emitted before `Promise.resolve()`.
let requestOrResponse = fn!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
// Fallback
if (is.undefined(requestOrResponse)) {
requestOrResponse = options.getFallbackRequestFunction()!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
}
if (isClientRequest(requestOrResponse!)) {
this._onRequest(requestOrResponse);
} else if (this.writable) {
this.once('finish', () => {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
});
this._sendBody();
} else {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
}
} catch (error) {
if (error instanceof CacheableCacheError) {
throw new CacheError(error, this);
}
throw error;
}
}
private async _error(error: RequestError): Promise<void> {
try {
if (error instanceof HTTPError && !this.options.throwHttpErrors) {
// This branch can be reached only when using the Promise API
// Skip calling the hooks on purpose.
// See https://github.com/sindresorhus/got/issues/2103
} else {
for (const hook of this.options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
} catch (error_: any) {
error = new RequestError(error_.message, error_, this);
}
this.destroy(error);
}
private _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
if (!this._request || this._request.destroyed) {
// Probably the `ClientRequest` instance will throw
return;
}
this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && !this._request!.destroyed) {
this._uploadedSize += Buffer.byteLength(chunk, encoding);
const progress = this.uploadProgress;
if (progress.percent < 1) {
this.emit('uploadProgress', progress);
}
}
callback(error);
});
}
/**
The remote IP address.
*/
get ip(): string | undefined {
return this.socket?.remoteAddress;
}
/**
Indicates whether the request has been aborted or not.
*/
get isAborted(): boolean {
return this._aborted;
}
get socket(): Socket | undefined {
return this._request?.socket ?? undefined;
}
/**
Progress event for downloading (receiving a response).
*/
get downloadProgress(): Progress {
let percent;
if (this._responseSize) {
percent = this._downloadedSize / this._responseSize;
} else if (this._responseSize === this._downloadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._downloadedSize,
total: this._responseSize,
};
}
/**
Progress event for uploading (sending a request).
*/
get uploadProgress(): Progress {
let percent;
if (this._bodySize) {
percent = this._uploadedSize / this._bodySize;
} else if (this._bodySize === this._uploadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._uploadedSize,
total: this._bodySize,
};
}
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
get timings(): Timings | undefined {
return (this._request as ClientRequestWithTimings)?.timings;
}
/**
Whether the response was retrieved from the cache.
*/
get isFromCache(): boolean | undefined {
return this._isFromCache;
}
get reusedSocket(): boolean | undefined {
return this._request?.reusedSocket;
}
} |
391 | constructor(response: PlainResponse) {
super(`Response code ${response.statusCode} (${response.statusMessage!})`, {}, response.request);
this.name = 'HTTPError';
this.code = 'ERR_NON_2XX_3XX_RESPONSE';
} | type PlainResponse = {
/**
The original request URL.
*/
requestUrl: URL;
/**
The redirect URLs.
*/
redirectUrls: URL[];
/**
- `options` - The Got options that were set on this request.
__Note__: This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest).
*/
request: Request;
/**
The remote IP address.
This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86).
__Note__: Not available when the response is cached.
*/
ip?: string;
/**
Whether the response was retrieved from the cache.
*/
isFromCache: boolean;
/**
The status code of the response.
*/
statusCode: number;
/**
The request URL or the final URL after redirects.
*/
url: string;
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
timings: Timings;
/**
The number of times the request was retried.
*/
retryCount: number;
// Defined only if request errored
/**
The raw result of the request.
*/
rawBody?: Buffer;
/**
The result of the request.
*/
body?: unknown;
/**
Whether the response was successful.
__Note__: Got throws automatically when `response.ok` is `false` and `throwHttpErrors` is `true`.
*/
ok: boolean;
} & IncomingMessageWithTimings; |
392 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'CacheError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code;
} | type Error = NodeJS.ErrnoException; |
393 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'CacheError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code;
} | type Error = NodeJS.ErrnoException; |
394 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'CacheError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_CACHE_ACCESS' : this.code;
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUrls: URL[];
retryCount: number;
declare private _requestOptions: NativeRequestOptions;
private _stopRetry: () => void;
private _downloadedSize: number;
private _uploadedSize: number;
private _stopReading: boolean;
private readonly _pipedServerResponses: Set<ServerResponse>;
private _request?: ClientRequest;
private _responseSize?: number;
private _bodySize?: number;
private _unproxyEvents: () => void;
private _isFromCache?: boolean;
private _cannotHaveBody: boolean;
private _triggerRead: boolean;
declare private _jobs: Array<() => void>;
private _cancelTimeouts: () => void;
private readonly _removeListeners: () => void;
private _nativeResponse?: IncomingMessageWithTimings;
private _flushed: boolean;
private _aborted: boolean;
// We need this because `this._request` if `undefined` when using cache
private _requestInitialized: boolean;
constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
}
async flush() {
if (this._flushed) {
return;
}
this._flushed = true;
try {
await this._finalizeBody();
if (this.destroyed) {
return;
}
await this._makeRequest();
if (this.destroyed) {
this._request?.destroy();
return;
}
// Queued writes etc.
for (const job of this._jobs) {
job();
}
// Prevent memory leak
this._jobs.length = 0;
this._requestInitialized = true;
} catch (error: any) {
this._beforeError(error);
}
}
_beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
}
override _read(): void {
this._triggerRead = true;
const {response} = this;
if (response && !this._stopReading) {
// We cannot put this in the `if` above
// because `.read()` also triggers the `end` event
if (response.readableLength) {
this._triggerRead = false;
}
let data;
while ((data = response.read()) !== null) {
this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands
const progress = this.downloadProgress;
if (progress.percent < 1) {
this.emit('downloadProgress', progress);
}
this.push(data);
}
}
}
override _write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const write = (): void => {
this._writeRequest(chunk, encoding, callback);
};
if (this._requestInitialized) {
write();
} else {
this._jobs.push(write);
}
}
override _final(callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const endRequest = (): void => {
// We need to check if `this._request` is present,
// because it isn't when we use cache.
if (!this._request || this._request.destroyed) {
callback();
return;
}
this._request.end((error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The request has been destroyed before `_final` finished.
// See https://github.com/nodejs/node/issues/39356
if ((this._request as any)._writableState?.errored) {
return;
}
if (!error) {
this._bodySize = this._uploadedSize;
this.emit('uploadProgress', this.uploadProgress);
this._request!.emit('upload-complete');
}
callback(error);
});
};
if (this._requestInitialized) {
endRequest();
} else {
this._jobs.push(endRequest);
}
}
override _destroy(error: Error | null, callback: (error: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
this._stopReading = true;
this.flush = async () => {};
// Prevent further retries
this._stopRetry();
this._cancelTimeouts();
this._removeListeners();
if (this.options) {
const {body} = this.options;
if (is.nodeStream(body)) {
body.destroy();
}
}
if (this._request) {
this._request.destroy();
}
if (error !== null && !is.undefined(error) && !(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
callback(error);
}
override pipe<T extends NodeJS.WritableStream>(destination: T, options?: {end?: boolean}): T {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.add(destination);
}
return super.pipe(destination, options);
}
override unpipe<T extends NodeJS.WritableStream>(destination: T): this {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.delete(destination);
}
super.unpipe(destination);
return this;
}
private async _finalizeBody(): Promise<void> {
const {options} = this;
const {headers} = options;
const isForm = !is.undefined(options.form);
// eslint-disable-next-line @typescript-eslint/naming-convention
const isJSON = !is.undefined(options.json);
const isBody = !is.undefined(options.body);
const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);
this._cannotHaveBody = cannotHaveBody;
if (isForm || isJSON || isBody) {
if (cannotHaveBody) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
// Serialize body
const noContentType = !is.string(headers['content-type']);
if (isBody) {
// Body is spec-compliant FormData
if (isFormDataLike(options.body)) {
const encoder = new FormDataEncoder(options.body);
if (noContentType) {
headers['content-type'] = encoder.headers['Content-Type'];
}
if ('Content-Length' in encoder.headers) {
headers['content-length'] = encoder.headers['Content-Length'];
}
options.body = encoder.encode();
}
// Special case for https://github.com/form-data/form-data
if (isFormData(options.body) && noContentType) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
} else if (isForm) {
if (noContentType) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
const {form} = options;
options.form = undefined;
options.body = (new URLSearchParams(form as Record<string, string>)).toString();
} else {
if (noContentType) {
headers['content-type'] = 'application/json';
}
const {json} = options;
options.json = undefined;
options.body = options.stringifyJson(json);
}
const uploadBodySize = await getBodySize(options.body, options.headers);
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body. For example, a Content-Length header
// field is normally sent in a POST request even when the value is 0
// (indicating an empty payload body). A user agent SHOULD NOT send a
// Content-Length header field when the request message does not contain
// a payload body and the method semantics do not anticipate such a
// body.
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is.undefined(uploadBodySize)) {
headers['content-length'] = String(uploadBodySize);
}
}
if (options.responseType === 'json' && !('accept' in options.headers)) {
options.headers.accept = 'application/json';
}
this._bodySize = Number(headers['content-length']) || undefined;
}
private async _onResponseBase(response: IncomingMessageWithTimings): Promise<void> {
// This will be called e.g. when using cache so we need to check if this request has been aborted.
if (this.isAborted) {
return;
}
const {options} = this;
const {url} = options;
this._nativeResponse = response;
if (options.decompress) {
response = decompressResponse(response);
}
const statusCode = response.statusCode!;
const typedResponse = response as PlainResponse;
typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];
typedResponse.url = options.url!.toString();
typedResponse.requestUrl = this.requestUrl!;
typedResponse.redirectUrls = this.redirectUrls;
typedResponse.request = this;
typedResponse.isFromCache = (this._nativeResponse as any).fromCache ?? false;
typedResponse.ip = this.ip;
typedResponse.retryCount = this.retryCount;
typedResponse.ok = isResponseOk(typedResponse);
this._isFromCache = typedResponse.isFromCache;
this._responseSize = Number(response.headers['content-length']) || undefined;
this.response = typedResponse;
response.once('end', () => {
this._responseSize = this._downloadedSize;
this.emit('downloadProgress', this.downloadProgress);
});
response.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
});
response.once('aborted', () => {
this._aborted = true;
this._beforeError(new ReadError({
name: 'Error',
message: 'The server aborted pending request',
code: 'ECONNRESET',
}, this));
});
this.emit('downloadProgress', this.downloadProgress);
const rawCookies = response.headers['set-cookie'];
if (is.object(options.cookieJar) && rawCookies) {
let promises: Array<Promise<unknown>> = rawCookies.map(async (rawCookie: string) => (options.cookieJar as PromiseCookieJar).setCookie(rawCookie, url!.toString()));
if (options.ignoreInvalidCookies) {
promises = promises.map(async promise => {
try {
await promise;
} catch {}
});
}
try {
await Promise.all(promises);
} catch (error: any) {
this._beforeError(error);
return;
}
}
// The above is running a promise, therefore we need to check if this request has been aborted yet again.
if (this.isAborted) {
return;
}
if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
// We're being redirected, we don't care about the response.
// It'd be best to abort the request, but we can't because
// we would have to sacrifice the TCP connection. We don't want that.
response.resume();
this._cancelTimeouts();
this._unproxyEvents();
if (this.redirectUrls.length >= options.maxRedirects) {
this._beforeError(new MaxRedirectsError(this));
return;
}
this._request = undefined;
const updatedOptions = new Options(undefined, undefined, this.options);
const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
const canRewrite = statusCode !== 307 && statusCode !== 308;
const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
if (serverRequestedGet || userRequestedGet) {
updatedOptions.method = 'GET';
updatedOptions.body = undefined;
updatedOptions.json = undefined;
updatedOptions.form = undefined;
delete updatedOptions.headers['content-length'];
}
try {
// We need this in order to support UTF-8
const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
const redirectUrl = new URL(redirectBuffer, url);
if (!isUnixSocketURL(url as URL) && isUnixSocketURL(redirectUrl)) {
this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
return;
}
// Redirecting to a different site, clear sensitive data.
if (redirectUrl.hostname !== (url as URL).hostname || redirectUrl.port !== (url as URL).port) {
if ('host' in updatedOptions.headers) {
delete updatedOptions.headers.host;
}
if ('cookie' in updatedOptions.headers) {
delete updatedOptions.headers.cookie;
}
if ('authorization' in updatedOptions.headers) {
delete updatedOptions.headers.authorization;
}
if (updatedOptions.username || updatedOptions.password) {
updatedOptions.username = '';
updatedOptions.password = '';
}
} else {
redirectUrl.username = updatedOptions.username;
redirectUrl.password = updatedOptions.password;
}
this.redirectUrls.push(redirectUrl);
updatedOptions.prefixUrl = '';
updatedOptions.url = redirectUrl;
for (const hook of updatedOptions.hooks.beforeRedirect) {
// eslint-disable-next-line no-await-in-loop
await hook(updatedOptions, typedResponse);
}
this.emit('redirect', updatedOptions, typedResponse);
this.options = updatedOptions;
await this._makeRequest();
} catch (error: any) {
this._beforeError(error);
return;
}
return;
}
// `HTTPError`s always have `error.response.body` defined.
// Therefore we cannot retry if `options.throwHttpErrors` is false.
// On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
// but that wouldn't be possible since the body would be already read in `error.response.body`.
if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
this._beforeError(new HTTPError(typedResponse));
return;
}
response.on('readable', () => {
if (this._triggerRead) {
this._read();
}
});
this.on('resume', () => {
response.resume();
});
this.on('pause', () => {
response.pause();
});
response.once('end', () => {
this.push(null);
});
if (this._noPipe) {
const success = await this._setRawBody();
if (success) {
this.emit('response', response);
}
return;
}
this.emit('response', response);
for (const destination of this._pipedServerResponses) {
if (destination.headersSent) {
continue;
}
// eslint-disable-next-line guard-for-in
for (const key in response.headers) {
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
const value = response.headers[key];
if (isAllowed) {
destination.setHeader(key, value!);
}
}
destination.statusCode = statusCode;
}
}
private async _setRawBody(from: Readable = this): Promise<boolean> {
if (from.readableEnded) {
return false;
}
try {
// Errors are emitted via the `error` event
const rawBody = await getBuffer(from);
// On retry Request is destroyed with no error, therefore the above will successfully resolve.
// So in order to check if this was really successfull, we need to check if it has been properly ended.
if (!this.isAborted) {
this.response!.rawBody = rawBody;
return true;
}
} catch {}
return false;
}
private async _onResponse(response: IncomingMessageWithTimings): Promise<void> {
try {
await this._onResponseBase(response);
} catch (error: any) {
/* istanbul ignore next: better safe than sorry */
this._beforeError(error);
}
}
private _onRequest(request: ClientRequest): void {
const {options} = this;
const {timeout, url} = options;
timer(request);
if (this.options.http2) {
// Unset stream timeout, as the `timeout` option was used only for connection timeout.
request.setTimeout(0);
}
this._cancelTimeouts = timedOut(request, timeout, url as URL);
const responseEventName = options.cache ? 'cacheableResponse' : 'response';
request.once(responseEventName, (response: IncomingMessageWithTimings) => {
void this._onResponse(response);
});
request.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
});
this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
this._request = request;
this.emit('uploadProgress', this.uploadProgress);
this._sendBody();
this.emit('request', request);
}
private async _asyncWrite(chunk: any): Promise<void> {
return new Promise((resolve, reject) => {
super.write(chunk, error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
private _sendBody() {
// Send body
const {body} = this.options;
const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this;
if (is.nodeStream(body)) {
body.pipe(currentRequest);
} else if (is.generator(body) || is.asyncGenerator(body)) {
(async () => {
try {
for await (const chunk of body) {
await this._asyncWrite(chunk);
}
super.end();
} catch (error: any) {
this._beforeError(error);
}
})();
} else if (!is.undefined(body)) {
this._writeRequest(body, undefined, () => {});
currentRequest.end();
} else if (this._cannotHaveBody || this._noPipe) {
currentRequest.end();
}
}
private _prepareCache(cache: string | StorageAdapter) {
if (!cacheableStore.has(cache)) {
const cacheableRequest = new CacheableRequest(
((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
const result = (requestOptions as any)._request(requestOptions, handler);
// TODO: remove this when `cacheable-request` supports async request functions.
if (is.promise(result)) {
// We only need to implement the error handler in order to support HTTP2 caching.
// The result will be a promise anyway.
// @ts-expect-error ignore
// eslint-disable-next-line @typescript-eslint/promise-function-async
result.once = (event: string, handler: (reason: unknown) => void) => {
if (event === 'error') {
(async () => {
try {
await result;
} catch (error) {
handler(error);
}
})();
} else if (event === 'abort') {
// The empty catch is needed here in case when
// it rejects before it's `await`ed in `_makeRequest`.
(async () => {
try {
const request = (await result) as ClientRequest;
request.once('abort', handler);
} catch {}
})();
} else {
/* istanbul ignore next: safety check */
throw new Error(`Unknown HTTP2 promise event: ${event}`);
}
return result;
};
}
return result;
}) as typeof http.request,
cache as StorageAdapter,
);
cacheableStore.set(cache, cacheableRequest.request());
}
}
private async _createCacheableRequest(url: URL, options: RequestOptions): Promise<ClientRequest | ResponseLike> {
return new Promise<ClientRequest | ResponseLike>((resolve, reject) => {
// TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed
Object.assign(options, urlToOptions(url));
let request: ClientRequest | Promise<ClientRequest>;
// TODO: Fix `cacheable-response`. This is ugly.
const cacheRequest = cacheableStore.get((options as any).cache)!(options as CacheableOptions, async (response: any) => {
response._readableState.autoDestroy = false;
if (request) {
const fix = () => {
if (response.req) {
response.complete = response.req.res.complete;
}
};
response.prependOnceListener('end', fix);
fix();
(await request).emit('cacheableResponse', response);
}
resolve(response);
});
cacheRequest.once('error', reject);
cacheRequest.once('request', async (requestOrPromise: ClientRequest | Promise<ClientRequest>) => {
request = requestOrPromise;
resolve(request);
});
});
}
private async _makeRequest(): Promise<void> {
const {options} = this;
const {headers, username, password} = options;
const cookieJar = options.cookieJar as PromiseCookieJar | undefined;
for (const key in headers) {
if (is.undefined(headers[key])) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete headers[key];
} else if (is.null_(headers[key])) {
throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
}
}
if (options.decompress && is.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';
}
if (username || password) {
const credentials = Buffer.from(`${username}:${password}`).toString('base64');
headers.authorization = `Basic ${credentials}`;
}
// Set cookies
if (cookieJar) {
const cookieString: string = await cookieJar.getCookieString(options.url!.toString());
if (is.nonEmptyString(cookieString)) {
headers.cookie = cookieString;
}
}
// Reset `prefixUrl`
options.prefixUrl = '';
let request: ReturnType<Options['getRequestFunction']> | undefined;
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
const result = await hook(options);
if (!is.undefined(result)) {
// @ts-expect-error Skip the type mismatch to support abstract responses
request = () => result;
break;
}
}
if (!request) {
request = options.getRequestFunction();
}
const url = options.url as URL;
this._requestOptions = options.createNativeRequestOptions() as NativeRequestOptions;
if (options.cache) {
(this._requestOptions as any)._request = request;
(this._requestOptions as any).cache = options.cache;
(this._requestOptions as any).body = options.body;
this._prepareCache(options.cache as StorageAdapter);
}
// Cache support
const fn = options.cache ? this._createCacheableRequest : request;
try {
// We can't do `await fn(...)`,
// because stream `error` event can be emitted before `Promise.resolve()`.
let requestOrResponse = fn!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
// Fallback
if (is.undefined(requestOrResponse)) {
requestOrResponse = options.getFallbackRequestFunction()!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
}
if (isClientRequest(requestOrResponse!)) {
this._onRequest(requestOrResponse);
} else if (this.writable) {
this.once('finish', () => {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
});
this._sendBody();
} else {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
}
} catch (error) {
if (error instanceof CacheableCacheError) {
throw new CacheError(error, this);
}
throw error;
}
}
private async _error(error: RequestError): Promise<void> {
try {
if (error instanceof HTTPError && !this.options.throwHttpErrors) {
// This branch can be reached only when using the Promise API
// Skip calling the hooks on purpose.
// See https://github.com/sindresorhus/got/issues/2103
} else {
for (const hook of this.options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
} catch (error_: any) {
error = new RequestError(error_.message, error_, this);
}
this.destroy(error);
}
private _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
if (!this._request || this._request.destroyed) {
// Probably the `ClientRequest` instance will throw
return;
}
this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && !this._request!.destroyed) {
this._uploadedSize += Buffer.byteLength(chunk, encoding);
const progress = this.uploadProgress;
if (progress.percent < 1) {
this.emit('uploadProgress', progress);
}
}
callback(error);
});
}
/**
The remote IP address.
*/
get ip(): string | undefined {
return this.socket?.remoteAddress;
}
/**
Indicates whether the request has been aborted or not.
*/
get isAborted(): boolean {
return this._aborted;
}
get socket(): Socket | undefined {
return this._request?.socket ?? undefined;
}
/**
Progress event for downloading (receiving a response).
*/
get downloadProgress(): Progress {
let percent;
if (this._responseSize) {
percent = this._downloadedSize / this._responseSize;
} else if (this._responseSize === this._downloadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._downloadedSize,
total: this._responseSize,
};
}
/**
Progress event for uploading (sending a request).
*/
get uploadProgress(): Progress {
let percent;
if (this._bodySize) {
percent = this._uploadedSize / this._bodySize;
} else if (this._bodySize === this._uploadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._uploadedSize,
total: this._bodySize,
};
}
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
get timings(): Timings | undefined {
return (this._request as ClientRequestWithTimings)?.timings;
}
/**
Whether the response was retrieved from the cache.
*/
get isFromCache(): boolean | undefined {
return this._isFromCache;
}
get reusedSocket(): boolean | undefined {
return this._request?.reusedSocket;
}
} |
395 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'UploadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code;
} | type Error = NodeJS.ErrnoException; |
396 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'UploadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code;
} | type Error = NodeJS.ErrnoException; |
397 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'UploadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_UPLOAD' : this.code;
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUrls: URL[];
retryCount: number;
declare private _requestOptions: NativeRequestOptions;
private _stopRetry: () => void;
private _downloadedSize: number;
private _uploadedSize: number;
private _stopReading: boolean;
private readonly _pipedServerResponses: Set<ServerResponse>;
private _request?: ClientRequest;
private _responseSize?: number;
private _bodySize?: number;
private _unproxyEvents: () => void;
private _isFromCache?: boolean;
private _cannotHaveBody: boolean;
private _triggerRead: boolean;
declare private _jobs: Array<() => void>;
private _cancelTimeouts: () => void;
private readonly _removeListeners: () => void;
private _nativeResponse?: IncomingMessageWithTimings;
private _flushed: boolean;
private _aborted: boolean;
// We need this because `this._request` if `undefined` when using cache
private _requestInitialized: boolean;
constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
}
async flush() {
if (this._flushed) {
return;
}
this._flushed = true;
try {
await this._finalizeBody();
if (this.destroyed) {
return;
}
await this._makeRequest();
if (this.destroyed) {
this._request?.destroy();
return;
}
// Queued writes etc.
for (const job of this._jobs) {
job();
}
// Prevent memory leak
this._jobs.length = 0;
this._requestInitialized = true;
} catch (error: any) {
this._beforeError(error);
}
}
_beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
}
override _read(): void {
this._triggerRead = true;
const {response} = this;
if (response && !this._stopReading) {
// We cannot put this in the `if` above
// because `.read()` also triggers the `end` event
if (response.readableLength) {
this._triggerRead = false;
}
let data;
while ((data = response.read()) !== null) {
this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands
const progress = this.downloadProgress;
if (progress.percent < 1) {
this.emit('downloadProgress', progress);
}
this.push(data);
}
}
}
override _write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const write = (): void => {
this._writeRequest(chunk, encoding, callback);
};
if (this._requestInitialized) {
write();
} else {
this._jobs.push(write);
}
}
override _final(callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const endRequest = (): void => {
// We need to check if `this._request` is present,
// because it isn't when we use cache.
if (!this._request || this._request.destroyed) {
callback();
return;
}
this._request.end((error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The request has been destroyed before `_final` finished.
// See https://github.com/nodejs/node/issues/39356
if ((this._request as any)._writableState?.errored) {
return;
}
if (!error) {
this._bodySize = this._uploadedSize;
this.emit('uploadProgress', this.uploadProgress);
this._request!.emit('upload-complete');
}
callback(error);
});
};
if (this._requestInitialized) {
endRequest();
} else {
this._jobs.push(endRequest);
}
}
override _destroy(error: Error | null, callback: (error: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
this._stopReading = true;
this.flush = async () => {};
// Prevent further retries
this._stopRetry();
this._cancelTimeouts();
this._removeListeners();
if (this.options) {
const {body} = this.options;
if (is.nodeStream(body)) {
body.destroy();
}
}
if (this._request) {
this._request.destroy();
}
if (error !== null && !is.undefined(error) && !(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
callback(error);
}
override pipe<T extends NodeJS.WritableStream>(destination: T, options?: {end?: boolean}): T {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.add(destination);
}
return super.pipe(destination, options);
}
override unpipe<T extends NodeJS.WritableStream>(destination: T): this {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.delete(destination);
}
super.unpipe(destination);
return this;
}
private async _finalizeBody(): Promise<void> {
const {options} = this;
const {headers} = options;
const isForm = !is.undefined(options.form);
// eslint-disable-next-line @typescript-eslint/naming-convention
const isJSON = !is.undefined(options.json);
const isBody = !is.undefined(options.body);
const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);
this._cannotHaveBody = cannotHaveBody;
if (isForm || isJSON || isBody) {
if (cannotHaveBody) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
// Serialize body
const noContentType = !is.string(headers['content-type']);
if (isBody) {
// Body is spec-compliant FormData
if (isFormDataLike(options.body)) {
const encoder = new FormDataEncoder(options.body);
if (noContentType) {
headers['content-type'] = encoder.headers['Content-Type'];
}
if ('Content-Length' in encoder.headers) {
headers['content-length'] = encoder.headers['Content-Length'];
}
options.body = encoder.encode();
}
// Special case for https://github.com/form-data/form-data
if (isFormData(options.body) && noContentType) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
} else if (isForm) {
if (noContentType) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
const {form} = options;
options.form = undefined;
options.body = (new URLSearchParams(form as Record<string, string>)).toString();
} else {
if (noContentType) {
headers['content-type'] = 'application/json';
}
const {json} = options;
options.json = undefined;
options.body = options.stringifyJson(json);
}
const uploadBodySize = await getBodySize(options.body, options.headers);
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body. For example, a Content-Length header
// field is normally sent in a POST request even when the value is 0
// (indicating an empty payload body). A user agent SHOULD NOT send a
// Content-Length header field when the request message does not contain
// a payload body and the method semantics do not anticipate such a
// body.
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is.undefined(uploadBodySize)) {
headers['content-length'] = String(uploadBodySize);
}
}
if (options.responseType === 'json' && !('accept' in options.headers)) {
options.headers.accept = 'application/json';
}
this._bodySize = Number(headers['content-length']) || undefined;
}
private async _onResponseBase(response: IncomingMessageWithTimings): Promise<void> {
// This will be called e.g. when using cache so we need to check if this request has been aborted.
if (this.isAborted) {
return;
}
const {options} = this;
const {url} = options;
this._nativeResponse = response;
if (options.decompress) {
response = decompressResponse(response);
}
const statusCode = response.statusCode!;
const typedResponse = response as PlainResponse;
typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];
typedResponse.url = options.url!.toString();
typedResponse.requestUrl = this.requestUrl!;
typedResponse.redirectUrls = this.redirectUrls;
typedResponse.request = this;
typedResponse.isFromCache = (this._nativeResponse as any).fromCache ?? false;
typedResponse.ip = this.ip;
typedResponse.retryCount = this.retryCount;
typedResponse.ok = isResponseOk(typedResponse);
this._isFromCache = typedResponse.isFromCache;
this._responseSize = Number(response.headers['content-length']) || undefined;
this.response = typedResponse;
response.once('end', () => {
this._responseSize = this._downloadedSize;
this.emit('downloadProgress', this.downloadProgress);
});
response.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
});
response.once('aborted', () => {
this._aborted = true;
this._beforeError(new ReadError({
name: 'Error',
message: 'The server aborted pending request',
code: 'ECONNRESET',
}, this));
});
this.emit('downloadProgress', this.downloadProgress);
const rawCookies = response.headers['set-cookie'];
if (is.object(options.cookieJar) && rawCookies) {
let promises: Array<Promise<unknown>> = rawCookies.map(async (rawCookie: string) => (options.cookieJar as PromiseCookieJar).setCookie(rawCookie, url!.toString()));
if (options.ignoreInvalidCookies) {
promises = promises.map(async promise => {
try {
await promise;
} catch {}
});
}
try {
await Promise.all(promises);
} catch (error: any) {
this._beforeError(error);
return;
}
}
// The above is running a promise, therefore we need to check if this request has been aborted yet again.
if (this.isAborted) {
return;
}
if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
// We're being redirected, we don't care about the response.
// It'd be best to abort the request, but we can't because
// we would have to sacrifice the TCP connection. We don't want that.
response.resume();
this._cancelTimeouts();
this._unproxyEvents();
if (this.redirectUrls.length >= options.maxRedirects) {
this._beforeError(new MaxRedirectsError(this));
return;
}
this._request = undefined;
const updatedOptions = new Options(undefined, undefined, this.options);
const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
const canRewrite = statusCode !== 307 && statusCode !== 308;
const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
if (serverRequestedGet || userRequestedGet) {
updatedOptions.method = 'GET';
updatedOptions.body = undefined;
updatedOptions.json = undefined;
updatedOptions.form = undefined;
delete updatedOptions.headers['content-length'];
}
try {
// We need this in order to support UTF-8
const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
const redirectUrl = new URL(redirectBuffer, url);
if (!isUnixSocketURL(url as URL) && isUnixSocketURL(redirectUrl)) {
this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
return;
}
// Redirecting to a different site, clear sensitive data.
if (redirectUrl.hostname !== (url as URL).hostname || redirectUrl.port !== (url as URL).port) {
if ('host' in updatedOptions.headers) {
delete updatedOptions.headers.host;
}
if ('cookie' in updatedOptions.headers) {
delete updatedOptions.headers.cookie;
}
if ('authorization' in updatedOptions.headers) {
delete updatedOptions.headers.authorization;
}
if (updatedOptions.username || updatedOptions.password) {
updatedOptions.username = '';
updatedOptions.password = '';
}
} else {
redirectUrl.username = updatedOptions.username;
redirectUrl.password = updatedOptions.password;
}
this.redirectUrls.push(redirectUrl);
updatedOptions.prefixUrl = '';
updatedOptions.url = redirectUrl;
for (const hook of updatedOptions.hooks.beforeRedirect) {
// eslint-disable-next-line no-await-in-loop
await hook(updatedOptions, typedResponse);
}
this.emit('redirect', updatedOptions, typedResponse);
this.options = updatedOptions;
await this._makeRequest();
} catch (error: any) {
this._beforeError(error);
return;
}
return;
}
// `HTTPError`s always have `error.response.body` defined.
// Therefore we cannot retry if `options.throwHttpErrors` is false.
// On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
// but that wouldn't be possible since the body would be already read in `error.response.body`.
if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
this._beforeError(new HTTPError(typedResponse));
return;
}
response.on('readable', () => {
if (this._triggerRead) {
this._read();
}
});
this.on('resume', () => {
response.resume();
});
this.on('pause', () => {
response.pause();
});
response.once('end', () => {
this.push(null);
});
if (this._noPipe) {
const success = await this._setRawBody();
if (success) {
this.emit('response', response);
}
return;
}
this.emit('response', response);
for (const destination of this._pipedServerResponses) {
if (destination.headersSent) {
continue;
}
// eslint-disable-next-line guard-for-in
for (const key in response.headers) {
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
const value = response.headers[key];
if (isAllowed) {
destination.setHeader(key, value!);
}
}
destination.statusCode = statusCode;
}
}
private async _setRawBody(from: Readable = this): Promise<boolean> {
if (from.readableEnded) {
return false;
}
try {
// Errors are emitted via the `error` event
const rawBody = await getBuffer(from);
// On retry Request is destroyed with no error, therefore the above will successfully resolve.
// So in order to check if this was really successfull, we need to check if it has been properly ended.
if (!this.isAborted) {
this.response!.rawBody = rawBody;
return true;
}
} catch {}
return false;
}
private async _onResponse(response: IncomingMessageWithTimings): Promise<void> {
try {
await this._onResponseBase(response);
} catch (error: any) {
/* istanbul ignore next: better safe than sorry */
this._beforeError(error);
}
}
private _onRequest(request: ClientRequest): void {
const {options} = this;
const {timeout, url} = options;
timer(request);
if (this.options.http2) {
// Unset stream timeout, as the `timeout` option was used only for connection timeout.
request.setTimeout(0);
}
this._cancelTimeouts = timedOut(request, timeout, url as URL);
const responseEventName = options.cache ? 'cacheableResponse' : 'response';
request.once(responseEventName, (response: IncomingMessageWithTimings) => {
void this._onResponse(response);
});
request.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
});
this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
this._request = request;
this.emit('uploadProgress', this.uploadProgress);
this._sendBody();
this.emit('request', request);
}
private async _asyncWrite(chunk: any): Promise<void> {
return new Promise((resolve, reject) => {
super.write(chunk, error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
private _sendBody() {
// Send body
const {body} = this.options;
const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this;
if (is.nodeStream(body)) {
body.pipe(currentRequest);
} else if (is.generator(body) || is.asyncGenerator(body)) {
(async () => {
try {
for await (const chunk of body) {
await this._asyncWrite(chunk);
}
super.end();
} catch (error: any) {
this._beforeError(error);
}
})();
} else if (!is.undefined(body)) {
this._writeRequest(body, undefined, () => {});
currentRequest.end();
} else if (this._cannotHaveBody || this._noPipe) {
currentRequest.end();
}
}
private _prepareCache(cache: string | StorageAdapter) {
if (!cacheableStore.has(cache)) {
const cacheableRequest = new CacheableRequest(
((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
const result = (requestOptions as any)._request(requestOptions, handler);
// TODO: remove this when `cacheable-request` supports async request functions.
if (is.promise(result)) {
// We only need to implement the error handler in order to support HTTP2 caching.
// The result will be a promise anyway.
// @ts-expect-error ignore
// eslint-disable-next-line @typescript-eslint/promise-function-async
result.once = (event: string, handler: (reason: unknown) => void) => {
if (event === 'error') {
(async () => {
try {
await result;
} catch (error) {
handler(error);
}
})();
} else if (event === 'abort') {
// The empty catch is needed here in case when
// it rejects before it's `await`ed in `_makeRequest`.
(async () => {
try {
const request = (await result) as ClientRequest;
request.once('abort', handler);
} catch {}
})();
} else {
/* istanbul ignore next: safety check */
throw new Error(`Unknown HTTP2 promise event: ${event}`);
}
return result;
};
}
return result;
}) as typeof http.request,
cache as StorageAdapter,
);
cacheableStore.set(cache, cacheableRequest.request());
}
}
private async _createCacheableRequest(url: URL, options: RequestOptions): Promise<ClientRequest | ResponseLike> {
return new Promise<ClientRequest | ResponseLike>((resolve, reject) => {
// TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed
Object.assign(options, urlToOptions(url));
let request: ClientRequest | Promise<ClientRequest>;
// TODO: Fix `cacheable-response`. This is ugly.
const cacheRequest = cacheableStore.get((options as any).cache)!(options as CacheableOptions, async (response: any) => {
response._readableState.autoDestroy = false;
if (request) {
const fix = () => {
if (response.req) {
response.complete = response.req.res.complete;
}
};
response.prependOnceListener('end', fix);
fix();
(await request).emit('cacheableResponse', response);
}
resolve(response);
});
cacheRequest.once('error', reject);
cacheRequest.once('request', async (requestOrPromise: ClientRequest | Promise<ClientRequest>) => {
request = requestOrPromise;
resolve(request);
});
});
}
private async _makeRequest(): Promise<void> {
const {options} = this;
const {headers, username, password} = options;
const cookieJar = options.cookieJar as PromiseCookieJar | undefined;
for (const key in headers) {
if (is.undefined(headers[key])) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete headers[key];
} else if (is.null_(headers[key])) {
throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
}
}
if (options.decompress && is.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';
}
if (username || password) {
const credentials = Buffer.from(`${username}:${password}`).toString('base64');
headers.authorization = `Basic ${credentials}`;
}
// Set cookies
if (cookieJar) {
const cookieString: string = await cookieJar.getCookieString(options.url!.toString());
if (is.nonEmptyString(cookieString)) {
headers.cookie = cookieString;
}
}
// Reset `prefixUrl`
options.prefixUrl = '';
let request: ReturnType<Options['getRequestFunction']> | undefined;
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
const result = await hook(options);
if (!is.undefined(result)) {
// @ts-expect-error Skip the type mismatch to support abstract responses
request = () => result;
break;
}
}
if (!request) {
request = options.getRequestFunction();
}
const url = options.url as URL;
this._requestOptions = options.createNativeRequestOptions() as NativeRequestOptions;
if (options.cache) {
(this._requestOptions as any)._request = request;
(this._requestOptions as any).cache = options.cache;
(this._requestOptions as any).body = options.body;
this._prepareCache(options.cache as StorageAdapter);
}
// Cache support
const fn = options.cache ? this._createCacheableRequest : request;
try {
// We can't do `await fn(...)`,
// because stream `error` event can be emitted before `Promise.resolve()`.
let requestOrResponse = fn!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
// Fallback
if (is.undefined(requestOrResponse)) {
requestOrResponse = options.getFallbackRequestFunction()!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
}
if (isClientRequest(requestOrResponse!)) {
this._onRequest(requestOrResponse);
} else if (this.writable) {
this.once('finish', () => {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
});
this._sendBody();
} else {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
}
} catch (error) {
if (error instanceof CacheableCacheError) {
throw new CacheError(error, this);
}
throw error;
}
}
private async _error(error: RequestError): Promise<void> {
try {
if (error instanceof HTTPError && !this.options.throwHttpErrors) {
// This branch can be reached only when using the Promise API
// Skip calling the hooks on purpose.
// See https://github.com/sindresorhus/got/issues/2103
} else {
for (const hook of this.options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
} catch (error_: any) {
error = new RequestError(error_.message, error_, this);
}
this.destroy(error);
}
private _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
if (!this._request || this._request.destroyed) {
// Probably the `ClientRequest` instance will throw
return;
}
this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && !this._request!.destroyed) {
this._uploadedSize += Buffer.byteLength(chunk, encoding);
const progress = this.uploadProgress;
if (progress.percent < 1) {
this.emit('uploadProgress', progress);
}
}
callback(error);
});
}
/**
The remote IP address.
*/
get ip(): string | undefined {
return this.socket?.remoteAddress;
}
/**
Indicates whether the request has been aborted or not.
*/
get isAborted(): boolean {
return this._aborted;
}
get socket(): Socket | undefined {
return this._request?.socket ?? undefined;
}
/**
Progress event for downloading (receiving a response).
*/
get downloadProgress(): Progress {
let percent;
if (this._responseSize) {
percent = this._downloadedSize / this._responseSize;
} else if (this._responseSize === this._downloadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._downloadedSize,
total: this._responseSize,
};
}
/**
Progress event for uploading (sending a request).
*/
get uploadProgress(): Progress {
let percent;
if (this._bodySize) {
percent = this._uploadedSize / this._bodySize;
} else if (this._bodySize === this._uploadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._uploadedSize,
total: this._bodySize,
};
}
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
get timings(): Timings | undefined {
return (this._request as ClientRequestWithTimings)?.timings;
}
/**
Whether the response was retrieved from the cache.
*/
get isFromCache(): boolean | undefined {
return this._isFromCache;
}
get reusedSocket(): boolean | undefined {
return this._request?.reusedSocket;
}
} |
398 | constructor(error: TimedOutTimeoutError, timings: Timings, request: Request) {
super(error.message, error, request);
this.name = 'TimeoutError';
this.event = error.event;
this.timings = timings;
} | class Request extends Duplex implements RequestEvents<Request> {
// @ts-expect-error - Ignoring for now.
override ['constructor']: typeof Request;
_noPipe?: boolean;
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
options: Options;
response?: PlainResponse;
requestUrl?: URL;
redirectUrls: URL[];
retryCount: number;
declare private _requestOptions: NativeRequestOptions;
private _stopRetry: () => void;
private _downloadedSize: number;
private _uploadedSize: number;
private _stopReading: boolean;
private readonly _pipedServerResponses: Set<ServerResponse>;
private _request?: ClientRequest;
private _responseSize?: number;
private _bodySize?: number;
private _unproxyEvents: () => void;
private _isFromCache?: boolean;
private _cannotHaveBody: boolean;
private _triggerRead: boolean;
declare private _jobs: Array<() => void>;
private _cancelTimeouts: () => void;
private readonly _removeListeners: () => void;
private _nativeResponse?: IncomingMessageWithTimings;
private _flushed: boolean;
private _aborted: boolean;
// We need this because `this._request` if `undefined` when using cache
private _requestInitialized: boolean;
constructor(url: UrlType, options?: OptionsType, defaults?: DefaultsType) {
super({
// Don't destroy immediately, as the error may be emitted on unsuccessful retry
autoDestroy: false,
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0,
});
this._downloadedSize = 0;
this._uploadedSize = 0;
this._stopReading = false;
this._pipedServerResponses = new Set<ServerResponse>();
this._cannotHaveBody = false;
this._unproxyEvents = noop;
this._triggerRead = false;
this._cancelTimeouts = noop;
this._removeListeners = noop;
this._jobs = [];
this._flushed = false;
this._requestInitialized = false;
this._aborted = false;
this.redirectUrls = [];
this.retryCount = 0;
this._stopRetry = noop;
this.on('pipe', source => {
if (source.headers) {
Object.assign(this.options.headers, source.headers);
}
});
this.on('newListener', event => {
if (event === 'retry' && this.listenerCount('retry') > 0) {
throw new Error('A retry listener has been attached already.');
}
});
try {
this.options = new Options(url, options, defaults);
if (!this.options.url) {
if (this.options.prefixUrl === '') {
throw new TypeError('Missing `url` property');
}
this.options.url = '';
}
this.requestUrl = this.options.url as URL;
} catch (error: any) {
const {options} = error as OptionsError;
if (options) {
this.options = options;
}
this.flush = async () => {
this.flush = async () => {};
this.destroy(error);
};
return;
}
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
// The below is run only once.
const {body} = this.options;
if (is.nodeStream(body)) {
body.once('error', error => {
if (this._flushed) {
this._beforeError(new UploadError(error, this));
} else {
this.flush = async () => {
this.flush = async () => {};
this._beforeError(new UploadError(error, this));
};
}
});
}
if (this.options.signal) {
const abort = () => {
this.destroy(new AbortError(this));
};
if (this.options.signal.aborted) {
abort();
} else {
this.options.signal.addEventListener('abort', abort);
this._removeListeners = () => {
this.options.signal.removeEventListener('abort', abort);
};
}
}
}
async flush() {
if (this._flushed) {
return;
}
this._flushed = true;
try {
await this._finalizeBody();
if (this.destroyed) {
return;
}
await this._makeRequest();
if (this.destroyed) {
this._request?.destroy();
return;
}
// Queued writes etc.
for (const job of this._jobs) {
job();
}
// Prevent memory leak
this._jobs.length = 0;
this._requestInitialized = true;
} catch (error: any) {
this._beforeError(error);
}
}
_beforeError(error: Error): void {
if (this._stopReading) {
return;
}
const {response, options} = this;
const attemptCount = this.retryCount + (error.name === 'RetryError' ? 0 : 1);
this._stopReading = true;
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
const typedError = error as RequestError;
void (async () => {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
//
// Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
// but makes the response unreadable. So we additionally need to check `response.readable`.
if (response?.readable && !response.rawBody && !this._request?.socket?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);
const success = await this._setRawBody(response);
if (success) {
response.body = response.rawBody!.toString();
}
}
if (this.listenerCount('retry') !== 0) {
let backoff: number;
try {
let retryAfter;
if (response && 'retry-after' in response.headers) {
retryAfter = Number(response.headers['retry-after']);
if (Number.isNaN(retryAfter)) {
retryAfter = Date.parse(response.headers['retry-after']!) - Date.now();
if (retryAfter <= 0) {
retryAfter = 1;
}
} else {
retryAfter *= 1000;
}
}
const retryOptions = options.retry as RetryOptions;
backoff = await retryOptions.calculateDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: calculateRetryDelay({
attemptCount,
retryOptions,
error: typedError,
retryAfter,
computedValue: retryOptions.maxRetryAfter ?? options.timeout.request ?? Number.POSITIVE_INFINITY,
}),
});
} catch (error_: any) {
void this._error(new RequestError(error_.message, error_, this));
return;
}
if (backoff) {
await new Promise<void>(resolve => {
const timeout = setTimeout(resolve, backoff);
this._stopRetry = () => {
clearTimeout(timeout);
resolve();
};
});
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
try {
for (const hook of this.options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedError, this.retryCount + 1);
}
} catch (error_: any) {
void this._error(new RequestError(error_.message, error, this));
return;
}
// Something forced us to abort the retry
if (this.destroyed) {
return;
}
this.destroy();
this.emit('retry', this.retryCount + 1, error, (updatedOptions?: OptionsInit) => {
const request = new Request(options.url, updatedOptions, options);
request.retryCount = this.retryCount + 1;
process.nextTick(() => {
void request.flush();
});
return request;
});
return;
}
}
void this._error(typedError);
})();
}
override _read(): void {
this._triggerRead = true;
const {response} = this;
if (response && !this._stopReading) {
// We cannot put this in the `if` above
// because `.read()` also triggers the `end` event
if (response.readableLength) {
this._triggerRead = false;
}
let data;
while ((data = response.read()) !== null) {
this._downloadedSize += data.length; // eslint-disable-line @typescript-eslint/restrict-plus-operands
const progress = this.downloadProgress;
if (progress.percent < 1) {
this.emit('downloadProgress', progress);
}
this.push(data);
}
}
}
override _write(chunk: unknown, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const write = (): void => {
this._writeRequest(chunk, encoding, callback);
};
if (this._requestInitialized) {
write();
} else {
this._jobs.push(write);
}
}
override _final(callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
const endRequest = (): void => {
// We need to check if `this._request` is present,
// because it isn't when we use cache.
if (!this._request || this._request.destroyed) {
callback();
return;
}
this._request.end((error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The request has been destroyed before `_final` finished.
// See https://github.com/nodejs/node/issues/39356
if ((this._request as any)._writableState?.errored) {
return;
}
if (!error) {
this._bodySize = this._uploadedSize;
this.emit('uploadProgress', this.uploadProgress);
this._request!.emit('upload-complete');
}
callback(error);
});
};
if (this._requestInitialized) {
endRequest();
} else {
this._jobs.push(endRequest);
}
}
override _destroy(error: Error | null, callback: (error: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
this._stopReading = true;
this.flush = async () => {};
// Prevent further retries
this._stopRetry();
this._cancelTimeouts();
this._removeListeners();
if (this.options) {
const {body} = this.options;
if (is.nodeStream(body)) {
body.destroy();
}
}
if (this._request) {
this._request.destroy();
}
if (error !== null && !is.undefined(error) && !(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
callback(error);
}
override pipe<T extends NodeJS.WritableStream>(destination: T, options?: {end?: boolean}): T {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.add(destination);
}
return super.pipe(destination, options);
}
override unpipe<T extends NodeJS.WritableStream>(destination: T): this {
if (destination instanceof ServerResponse) {
this._pipedServerResponses.delete(destination);
}
super.unpipe(destination);
return this;
}
private async _finalizeBody(): Promise<void> {
const {options} = this;
const {headers} = options;
const isForm = !is.undefined(options.form);
// eslint-disable-next-line @typescript-eslint/naming-convention
const isJSON = !is.undefined(options.json);
const isBody = !is.undefined(options.body);
const cannotHaveBody = methodsWithoutBody.has(options.method) && !(options.method === 'GET' && options.allowGetBody);
this._cannotHaveBody = cannotHaveBody;
if (isForm || isJSON || isBody) {
if (cannotHaveBody) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
// Serialize body
const noContentType = !is.string(headers['content-type']);
if (isBody) {
// Body is spec-compliant FormData
if (isFormDataLike(options.body)) {
const encoder = new FormDataEncoder(options.body);
if (noContentType) {
headers['content-type'] = encoder.headers['Content-Type'];
}
if ('Content-Length' in encoder.headers) {
headers['content-length'] = encoder.headers['Content-Length'];
}
options.body = encoder.encode();
}
// Special case for https://github.com/form-data/form-data
if (isFormData(options.body) && noContentType) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
} else if (isForm) {
if (noContentType) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
const {form} = options;
options.form = undefined;
options.body = (new URLSearchParams(form as Record<string, string>)).toString();
} else {
if (noContentType) {
headers['content-type'] = 'application/json';
}
const {json} = options;
options.json = undefined;
options.body = options.stringifyJson(json);
}
const uploadBodySize = await getBodySize(options.body, options.headers);
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body. For example, a Content-Length header
// field is normally sent in a POST request even when the value is 0
// (indicating an empty payload body). A user agent SHOULD NOT send a
// Content-Length header field when the request message does not contain
// a payload body and the method semantics do not anticipate such a
// body.
if (is.undefined(headers['content-length']) && is.undefined(headers['transfer-encoding']) && !cannotHaveBody && !is.undefined(uploadBodySize)) {
headers['content-length'] = String(uploadBodySize);
}
}
if (options.responseType === 'json' && !('accept' in options.headers)) {
options.headers.accept = 'application/json';
}
this._bodySize = Number(headers['content-length']) || undefined;
}
private async _onResponseBase(response: IncomingMessageWithTimings): Promise<void> {
// This will be called e.g. when using cache so we need to check if this request has been aborted.
if (this.isAborted) {
return;
}
const {options} = this;
const {url} = options;
this._nativeResponse = response;
if (options.decompress) {
response = decompressResponse(response);
}
const statusCode = response.statusCode!;
const typedResponse = response as PlainResponse;
typedResponse.statusMessage = typedResponse.statusMessage ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];
typedResponse.url = options.url!.toString();
typedResponse.requestUrl = this.requestUrl!;
typedResponse.redirectUrls = this.redirectUrls;
typedResponse.request = this;
typedResponse.isFromCache = (this._nativeResponse as any).fromCache ?? false;
typedResponse.ip = this.ip;
typedResponse.retryCount = this.retryCount;
typedResponse.ok = isResponseOk(typedResponse);
this._isFromCache = typedResponse.isFromCache;
this._responseSize = Number(response.headers['content-length']) || undefined;
this.response = typedResponse;
response.once('end', () => {
this._responseSize = this._downloadedSize;
this.emit('downloadProgress', this.downloadProgress);
});
response.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages don't do this.
// TODO: Fix decompress-response
response.destroy();
this._beforeError(new ReadError(error, this));
});
response.once('aborted', () => {
this._aborted = true;
this._beforeError(new ReadError({
name: 'Error',
message: 'The server aborted pending request',
code: 'ECONNRESET',
}, this));
});
this.emit('downloadProgress', this.downloadProgress);
const rawCookies = response.headers['set-cookie'];
if (is.object(options.cookieJar) && rawCookies) {
let promises: Array<Promise<unknown>> = rawCookies.map(async (rawCookie: string) => (options.cookieJar as PromiseCookieJar).setCookie(rawCookie, url!.toString()));
if (options.ignoreInvalidCookies) {
promises = promises.map(async promise => {
try {
await promise;
} catch {}
});
}
try {
await Promise.all(promises);
} catch (error: any) {
this._beforeError(error);
return;
}
}
// The above is running a promise, therefore we need to check if this request has been aborted yet again.
if (this.isAborted) {
return;
}
if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
// We're being redirected, we don't care about the response.
// It'd be best to abort the request, but we can't because
// we would have to sacrifice the TCP connection. We don't want that.
response.resume();
this._cancelTimeouts();
this._unproxyEvents();
if (this.redirectUrls.length >= options.maxRedirects) {
this._beforeError(new MaxRedirectsError(this));
return;
}
this._request = undefined;
const updatedOptions = new Options(undefined, undefined, this.options);
const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
const canRewrite = statusCode !== 307 && statusCode !== 308;
const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
if (serverRequestedGet || userRequestedGet) {
updatedOptions.method = 'GET';
updatedOptions.body = undefined;
updatedOptions.json = undefined;
updatedOptions.form = undefined;
delete updatedOptions.headers['content-length'];
}
try {
// We need this in order to support UTF-8
const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
const redirectUrl = new URL(redirectBuffer, url);
if (!isUnixSocketURL(url as URL) && isUnixSocketURL(redirectUrl)) {
this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
return;
}
// Redirecting to a different site, clear sensitive data.
if (redirectUrl.hostname !== (url as URL).hostname || redirectUrl.port !== (url as URL).port) {
if ('host' in updatedOptions.headers) {
delete updatedOptions.headers.host;
}
if ('cookie' in updatedOptions.headers) {
delete updatedOptions.headers.cookie;
}
if ('authorization' in updatedOptions.headers) {
delete updatedOptions.headers.authorization;
}
if (updatedOptions.username || updatedOptions.password) {
updatedOptions.username = '';
updatedOptions.password = '';
}
} else {
redirectUrl.username = updatedOptions.username;
redirectUrl.password = updatedOptions.password;
}
this.redirectUrls.push(redirectUrl);
updatedOptions.prefixUrl = '';
updatedOptions.url = redirectUrl;
for (const hook of updatedOptions.hooks.beforeRedirect) {
// eslint-disable-next-line no-await-in-loop
await hook(updatedOptions, typedResponse);
}
this.emit('redirect', updatedOptions, typedResponse);
this.options = updatedOptions;
await this._makeRequest();
} catch (error: any) {
this._beforeError(error);
return;
}
return;
}
// `HTTPError`s always have `error.response.body` defined.
// Therefore we cannot retry if `options.throwHttpErrors` is false.
// On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
// but that wouldn't be possible since the body would be already read in `error.response.body`.
if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
this._beforeError(new HTTPError(typedResponse));
return;
}
response.on('readable', () => {
if (this._triggerRead) {
this._read();
}
});
this.on('resume', () => {
response.resume();
});
this.on('pause', () => {
response.pause();
});
response.once('end', () => {
this.push(null);
});
if (this._noPipe) {
const success = await this._setRawBody();
if (success) {
this.emit('response', response);
}
return;
}
this.emit('response', response);
for (const destination of this._pipedServerResponses) {
if (destination.headersSent) {
continue;
}
// eslint-disable-next-line guard-for-in
for (const key in response.headers) {
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
const value = response.headers[key];
if (isAllowed) {
destination.setHeader(key, value!);
}
}
destination.statusCode = statusCode;
}
}
private async _setRawBody(from: Readable = this): Promise<boolean> {
if (from.readableEnded) {
return false;
}
try {
// Errors are emitted via the `error` event
const rawBody = await getBuffer(from);
// On retry Request is destroyed with no error, therefore the above will successfully resolve.
// So in order to check if this was really successfull, we need to check if it has been properly ended.
if (!this.isAborted) {
this.response!.rawBody = rawBody;
return true;
}
} catch {}
return false;
}
private async _onResponse(response: IncomingMessageWithTimings): Promise<void> {
try {
await this._onResponseBase(response);
} catch (error: any) {
/* istanbul ignore next: better safe than sorry */
this._beforeError(error);
}
}
private _onRequest(request: ClientRequest): void {
const {options} = this;
const {timeout, url} = options;
timer(request);
if (this.options.http2) {
// Unset stream timeout, as the `timeout` option was used only for connection timeout.
request.setTimeout(0);
}
this._cancelTimeouts = timedOut(request, timeout, url as URL);
const responseEventName = options.cache ? 'cacheableResponse' : 'response';
request.once(responseEventName, (response: IncomingMessageWithTimings) => {
void this._onResponse(response);
});
request.once('error', (error: Error) => {
this._aborted = true;
// Force clean-up, because some packages (e.g. nock) don't do this.
request.destroy();
error = error instanceof TimedOutTimeoutError ? new TimeoutError(error, this.timings!, this) : new RequestError(error.message, error, this);
this._beforeError(error);
});
this._unproxyEvents = proxyEvents(request, this, proxiedRequestEvents);
this._request = request;
this.emit('uploadProgress', this.uploadProgress);
this._sendBody();
this.emit('request', request);
}
private async _asyncWrite(chunk: any): Promise<void> {
return new Promise((resolve, reject) => {
super.write(chunk, error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
private _sendBody() {
// Send body
const {body} = this.options;
const currentRequest = this.redirectUrls.length === 0 ? this : this._request ?? this;
if (is.nodeStream(body)) {
body.pipe(currentRequest);
} else if (is.generator(body) || is.asyncGenerator(body)) {
(async () => {
try {
for await (const chunk of body) {
await this._asyncWrite(chunk);
}
super.end();
} catch (error: any) {
this._beforeError(error);
}
})();
} else if (!is.undefined(body)) {
this._writeRequest(body, undefined, () => {});
currentRequest.end();
} else if (this._cannotHaveBody || this._noPipe) {
currentRequest.end();
}
}
private _prepareCache(cache: string | StorageAdapter) {
if (!cacheableStore.has(cache)) {
const cacheableRequest = new CacheableRequest(
((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
const result = (requestOptions as any)._request(requestOptions, handler);
// TODO: remove this when `cacheable-request` supports async request functions.
if (is.promise(result)) {
// We only need to implement the error handler in order to support HTTP2 caching.
// The result will be a promise anyway.
// @ts-expect-error ignore
// eslint-disable-next-line @typescript-eslint/promise-function-async
result.once = (event: string, handler: (reason: unknown) => void) => {
if (event === 'error') {
(async () => {
try {
await result;
} catch (error) {
handler(error);
}
})();
} else if (event === 'abort') {
// The empty catch is needed here in case when
// it rejects before it's `await`ed in `_makeRequest`.
(async () => {
try {
const request = (await result) as ClientRequest;
request.once('abort', handler);
} catch {}
})();
} else {
/* istanbul ignore next: safety check */
throw new Error(`Unknown HTTP2 promise event: ${event}`);
}
return result;
};
}
return result;
}) as typeof http.request,
cache as StorageAdapter,
);
cacheableStore.set(cache, cacheableRequest.request());
}
}
private async _createCacheableRequest(url: URL, options: RequestOptions): Promise<ClientRequest | ResponseLike> {
return new Promise<ClientRequest | ResponseLike>((resolve, reject) => {
// TODO: Remove `utils/url-to-options.ts` when `cacheable-request` is fixed
Object.assign(options, urlToOptions(url));
let request: ClientRequest | Promise<ClientRequest>;
// TODO: Fix `cacheable-response`. This is ugly.
const cacheRequest = cacheableStore.get((options as any).cache)!(options as CacheableOptions, async (response: any) => {
response._readableState.autoDestroy = false;
if (request) {
const fix = () => {
if (response.req) {
response.complete = response.req.res.complete;
}
};
response.prependOnceListener('end', fix);
fix();
(await request).emit('cacheableResponse', response);
}
resolve(response);
});
cacheRequest.once('error', reject);
cacheRequest.once('request', async (requestOrPromise: ClientRequest | Promise<ClientRequest>) => {
request = requestOrPromise;
resolve(request);
});
});
}
private async _makeRequest(): Promise<void> {
const {options} = this;
const {headers, username, password} = options;
const cookieJar = options.cookieJar as PromiseCookieJar | undefined;
for (const key in headers) {
if (is.undefined(headers[key])) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete headers[key];
} else if (is.null_(headers[key])) {
throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
}
}
if (options.decompress && is.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';
}
if (username || password) {
const credentials = Buffer.from(`${username}:${password}`).toString('base64');
headers.authorization = `Basic ${credentials}`;
}
// Set cookies
if (cookieJar) {
const cookieString: string = await cookieJar.getCookieString(options.url!.toString());
if (is.nonEmptyString(cookieString)) {
headers.cookie = cookieString;
}
}
// Reset `prefixUrl`
options.prefixUrl = '';
let request: ReturnType<Options['getRequestFunction']> | undefined;
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
const result = await hook(options);
if (!is.undefined(result)) {
// @ts-expect-error Skip the type mismatch to support abstract responses
request = () => result;
break;
}
}
if (!request) {
request = options.getRequestFunction();
}
const url = options.url as URL;
this._requestOptions = options.createNativeRequestOptions() as NativeRequestOptions;
if (options.cache) {
(this._requestOptions as any)._request = request;
(this._requestOptions as any).cache = options.cache;
(this._requestOptions as any).body = options.body;
this._prepareCache(options.cache as StorageAdapter);
}
// Cache support
const fn = options.cache ? this._createCacheableRequest : request;
try {
// We can't do `await fn(...)`,
// because stream `error` event can be emitted before `Promise.resolve()`.
let requestOrResponse = fn!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
// Fallback
if (is.undefined(requestOrResponse)) {
requestOrResponse = options.getFallbackRequestFunction()!(url, this._requestOptions);
if (is.promise(requestOrResponse)) {
requestOrResponse = await requestOrResponse;
}
}
if (isClientRequest(requestOrResponse!)) {
this._onRequest(requestOrResponse);
} else if (this.writable) {
this.once('finish', () => {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
});
this._sendBody();
} else {
void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
}
} catch (error) {
if (error instanceof CacheableCacheError) {
throw new CacheError(error, this);
}
throw error;
}
}
private async _error(error: RequestError): Promise<void> {
try {
if (error instanceof HTTPError && !this.options.throwHttpErrors) {
// This branch can be reached only when using the Promise API
// Skip calling the hooks on purpose.
// See https://github.com/sindresorhus/got/issues/2103
} else {
for (const hook of this.options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
}
} catch (error_: any) {
error = new RequestError(error_.message, error_, this);
}
this.destroy(error);
}
private _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void { // eslint-disable-line @typescript-eslint/ban-types
if (!this._request || this._request.destroyed) {
// Probably the `ClientRequest` instance will throw
return;
}
this._request.write(chunk, encoding!, (error?: Error | null) => { // eslint-disable-line @typescript-eslint/ban-types
// The `!destroyed` check is required to prevent `uploadProgress` being emitted after the stream was destroyed
if (!error && !this._request!.destroyed) {
this._uploadedSize += Buffer.byteLength(chunk, encoding);
const progress = this.uploadProgress;
if (progress.percent < 1) {
this.emit('uploadProgress', progress);
}
}
callback(error);
});
}
/**
The remote IP address.
*/
get ip(): string | undefined {
return this.socket?.remoteAddress;
}
/**
Indicates whether the request has been aborted or not.
*/
get isAborted(): boolean {
return this._aborted;
}
get socket(): Socket | undefined {
return this._request?.socket ?? undefined;
}
/**
Progress event for downloading (receiving a response).
*/
get downloadProgress(): Progress {
let percent;
if (this._responseSize) {
percent = this._downloadedSize / this._responseSize;
} else if (this._responseSize === this._downloadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._downloadedSize,
total: this._responseSize,
};
}
/**
Progress event for uploading (sending a request).
*/
get uploadProgress(): Progress {
let percent;
if (this._bodySize) {
percent = this._uploadedSize / this._bodySize;
} else if (this._bodySize === this._uploadedSize) {
percent = 1;
} else {
percent = 0;
}
return {
percent,
transferred: this._uploadedSize,
total: this._bodySize,
};
}
/**
The object contains the following properties:
- `start` - Time when the request started.
- `socket` - Time when a socket was assigned to the request.
- `lookup` - Time when the DNS lookup finished.
- `connect` - Time when the socket successfully connected.
- `secureConnect` - Time when the socket securely connected.
- `upload` - Time when the request finished uploading.
- `response` - Time when the request fired `response` event.
- `end` - Time when the response fired `end` event.
- `error` - Time when the request fired `error` event.
- `abort` - Time when the request fired `abort` event.
- `phases`
- `wait` - `timings.socket - timings.start`
- `dns` - `timings.lookup - timings.socket`
- `tcp` - `timings.connect - timings.lookup`
- `tls` - `timings.secureConnect - timings.connect`
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
- `firstByte` - `timings.response - timings.upload`
- `download` - `timings.end - timings.response`
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
If something has not been measured yet, it will be `undefined`.
__Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
*/
get timings(): Timings | undefined {
return (this._request as ClientRequestWithTimings)?.timings;
}
/**
Whether the response was retrieved from the cache.
*/
get isFromCache(): boolean | undefined {
return this._isFromCache;
}
get reusedSocket(): boolean | undefined {
return this._request?.reusedSocket;
}
} |
399 | constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'ReadError';
this.code = this.code === 'ERR_GOT_REQUEST_ERROR' ? 'ERR_READING_RESPONSE_STREAM' : this.code;
} | type Error = NodeJS.ErrnoException; |