Initial commit

This commit is contained in:
jiapengyu
2026-07-27 13:37:48 +08:00
commit ecba71e2a5
39123 changed files with 5989154 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
import { CancelableRequest, NormalizedOptions } from './types';
export declare function createRejection(error: Error): CancelableRequest<never>;
export default function asPromise<T>(options: NormalizedOptions): CancelableRequest<T>;
+152
View File
@@ -0,0 +1,152 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const EventEmitter = require("events");
const getStream = require("get-stream");
const PCancelable = require("p-cancelable");
const is_1 = require("@sindresorhus/is");
const errors_1 = require("./errors");
const normalize_arguments_1 = require("./normalize-arguments");
const request_as_event_emitter_1 = require("./request-as-event-emitter");
const parseBody = (body, responseType, encoding) => {
if (responseType === 'json') {
return body.length === 0 ? '' : JSON.parse(body.toString());
}
if (responseType === 'buffer') {
return Buffer.from(body);
}
if (responseType === 'text') {
return body.toString(encoding);
}
throw new TypeError(`Unknown body type '${responseType}'`);
};
function createRejection(error) {
const promise = Promise.reject(error);
const returnPromise = () => promise;
promise.json = returnPromise;
promise.text = returnPromise;
promise.buffer = returnPromise;
promise.on = returnPromise;
return promise;
}
exports.createRejection = createRejection;
function asPromise(options) {
const proxy = new EventEmitter();
let body;
const promise = new PCancelable((resolve, reject, onCancel) => {
const emitter = request_as_event_emitter_1.default(options);
onCancel(emitter.abort);
const emitError = async (error) => {
try {
for (const hook of options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
reject(error);
}
catch (error_) {
reject(error_);
}
};
emitter.on('response', async (response) => {
var _a;
proxy.emit('response', response);
// Download body
try {
body = await getStream.buffer(response, { encoding: 'binary' });
}
catch (error) {
emitError(new errors_1.ReadError(error, options));
return;
}
if ((_a = response.req) === null || _a === void 0 ? void 0 : _a.aborted) {
// Canceled while downloading - will throw a `CancelError` or `TimeoutError` error
return;
}
const isOk = () => {
const { statusCode } = response;
const limitStatusCode = options.followRedirect ? 299 : 399;
return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
};
// Parse body
try {
response.body = parseBody(body, options.responseType, options.encoding);
}
catch (error) {
// Fall back to `utf8`
response.body = body.toString();
if (isOk()) {
const parseError = new errors_1.ParseError(error, response, options);
emitError(parseError);
return;
}
}
try {
for (const [index, hook] of options.hooks.afterResponse.entries()) {
// @ts-ignore TS doesn't notice that CancelableRequest is a Promise
// eslint-disable-next-line no-await-in-loop
response = await hook(response, async (updatedOptions) => {
const typedOptions = normalize_arguments_1.normalizeArguments(normalize_arguments_1.mergeOptions(options, {
...updatedOptions,
retry: {
calculateDelay: () => 0
},
throwHttpErrors: false,
resolveBodyOnly: false
}));
// Remove any further hooks for that request, because we'll call them anyway.
// The loop continues. We don't want duplicates (asPromise recursion).
typedOptions.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
for (const hook of options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedOptions);
}
const promise = asPromise(typedOptions);
onCancel(() => {
promise.catch(() => { });
promise.cancel();
});
return promise;
});
}
}
catch (error) {
emitError(error);
return;
}
// Check for HTTP error codes
if (!isOk()) {
const error = new errors_1.HTTPError(response, options);
if (emitter.retry(error)) {
return;
}
if (options.throwHttpErrors) {
emitError(error);
return;
}
}
resolve(options.resolveBodyOnly ? response.body : response);
});
emitter.once('error', reject);
request_as_event_emitter_1.proxyEvents(proxy, emitter);
});
promise.on = (name, fn) => {
proxy.on(name, fn);
return promise;
};
const shortcut = (responseType) => {
// eslint-disable-next-line promise/prefer-await-to-then
const newPromise = promise.then(() => parseBody(body, responseType, options.encoding));
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
return newPromise;
};
promise.json = () => {
if (is_1.default.undefined(body) && is_1.default.undefined(options.headers.accept)) {
options.headers.accept = 'application/json';
}
return shortcut('json');
};
promise.buffer = () => shortcut('buffer');
promise.text = () => shortcut('text');
return promise;
}
exports.default = asPromise;
+7
View File
@@ -0,0 +1,7 @@
/// <reference types="node" />
import { Duplex as DuplexStream } from 'stream';
import { GotEvents, NormalizedOptions } from './types';
export declare class ProxyStream<T = unknown> extends DuplexStream implements GotEvents<ProxyStream<T>> {
isFromCache?: boolean;
}
export default function asStream<T>(options: NormalizedOptions): ProxyStream<T>;
+121
View File
@@ -0,0 +1,121 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const duplexer3 = require("duplexer3");
const http_1 = require("http");
const stream_1 = require("stream");
const errors_1 = require("./errors");
const request_as_event_emitter_1 = require("./request-as-event-emitter");
class ProxyStream extends stream_1.Duplex {
}
exports.ProxyStream = ProxyStream;
function asStream(options) {
const input = new stream_1.PassThrough();
const output = new stream_1.PassThrough();
const proxy = duplexer3(input, output);
const piped = new Set();
let isFinished = false;
options.retry.calculateDelay = () => 0;
if (options.body || options.json || options.form) {
proxy.write = () => {
proxy.destroy();
throw new Error('Got\'s stream is not writable when the `body`, `json` or `form` option is used');
};
}
else if (options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH' || (options.allowGetBody && options.method === 'GET')) {
options.body = input;
}
else {
proxy.write = () => {
proxy.destroy();
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
};
}
const emitter = request_as_event_emitter_1.default(options);
const emitError = async (error) => {
try {
for (const hook of options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
proxy.emit('error', error);
}
catch (error_) {
proxy.emit('error', error_);
}
};
// Cancels the request
proxy._destroy = (error, callback) => {
callback(error);
emitter.abort();
};
emitter.on('response', (response) => {
const { statusCode, isFromCache } = response;
proxy.isFromCache = isFromCache;
if (options.throwHttpErrors && statusCode !== 304 && (statusCode < 200 || statusCode > 299)) {
emitError(new errors_1.HTTPError(response, options));
return;
}
{
const read = proxy._read;
proxy._read = (...args) => {
isFinished = true;
proxy._read = read;
return read.apply(proxy, args);
};
}
if (options.encoding) {
proxy.setEncoding(options.encoding);
}
// We cannot use `stream.pipeline(...)` here,
// because if we did then `output` would throw
// the original error before throwing `ReadError`.
response.pipe(output);
response.once('error', error => {
emitError(new errors_1.ReadError(error, options));
});
for (const destination of piped) {
if (destination.headersSent) {
continue;
}
for (const [key, value] of Object.entries(response.headers)) {
// Got gives *decompressed* data. Overriding `content-encoding` header would result in an error.
// It's not possible to decompress already decompressed data, is it?
const isAllowed = options.decompress ? key !== 'content-encoding' : true;
if (isAllowed) {
destination.setHeader(key, value);
}
}
destination.statusCode = response.statusCode;
}
proxy.emit('response', response);
});
request_as_event_emitter_1.proxyEvents(proxy, emitter);
emitter.on('error', (error) => proxy.emit('error', error));
const pipe = proxy.pipe.bind(proxy);
const unpipe = proxy.unpipe.bind(proxy);
proxy.pipe = (destination, options) => {
if (isFinished) {
throw new Error('Failed to pipe. The response has been emitted already.');
}
pipe(destination, options);
if (destination instanceof http_1.ServerResponse) {
piped.add(destination);
}
return destination;
};
proxy.unpipe = stream => {
piped.delete(stream);
return unpipe(stream);
};
proxy.on('pipe', source => {
if (source instanceof http_1.IncomingMessage) {
options.headers = {
...source.headers,
...options.headers
};
}
});
proxy.isFromCache = undefined;
return proxy;
}
exports.default = asStream;
+3
View File
@@ -0,0 +1,3 @@
import { RetryFunction } from './types';
declare const calculateRetryDelay: RetryFunction;
export default calculateRetryDelay;
+39
View File
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
const errors_1 = require("./errors");
const retryAfterStatusCodes = new Set([413, 429, 503]);
const isErrorWithResponse = (error) => (error instanceof errors_1.HTTPError || error instanceof errors_1.ParseError || error instanceof errors_1.MaxRedirectsError);
const calculateRetryDelay = ({ attemptCount, retryOptions, error }) => {
if (attemptCount > retryOptions.limit) {
return 0;
}
const hasMethod = retryOptions.methods.includes(error.options.method);
const hasErrorCode = Reflect.has(error, 'code') && retryOptions.errorCodes.includes(error.code);
const hasStatusCode = isErrorWithResponse(error) && retryOptions.statusCodes.includes(error.response.statusCode);
if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {
return 0;
}
if (isErrorWithResponse(error)) {
const { response } = error;
if (response && Reflect.has(response.headers, 'retry-after') && retryAfterStatusCodes.has(response.statusCode)) {
let after = Number(response.headers['retry-after']);
if (is_1.default.nan(after)) {
after = Date.parse(response.headers['retry-after']) - Date.now();
}
else {
after *= 1000;
}
if (after > retryOptions.maxRetryAfter) {
return 0;
}
return after;
}
if (response.statusCode === 413) {
return 0;
}
}
const noise = Math.random() * 100;
return ((2 ** (attemptCount - 1)) * 1000) + noise;
};
exports.default = calculateRetryDelay;
+83
View File
@@ -0,0 +1,83 @@
/// <reference types="node" />
import { Merge, Except } from 'type-fest';
import { ProxyStream } from './as-stream';
import * as errors from './errors';
import { CancelableRequest, Defaults, ExtendOptions, HandlerFunction, NormalizedOptions, Options, Response, URLOrOptions, PaginationOptions } from './types';
export declare type HTTPAlias = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';
export declare type ReturnStream = <T>(url: string | Merge<Options, {
isStream?: true;
}>, options?: Merge<Options, {
isStream?: true;
}>) => ProxyStream<T>;
export declare type GotReturn<T = unknown> = CancelableRequest<T> | ProxyStream<T>;
export declare type OptionsOfDefaultResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
responseType?: 'default';
}>;
declare type OptionsOfTextResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
responseType: 'text';
}>;
declare type OptionsOfJSONResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
responseType: 'json';
}>;
declare type OptionsOfBufferResponseBody = Merge<Options, {
isStream?: false;
resolveBodyOnly?: false;
responseType: 'buffer';
}>;
declare type ResponseBodyOnly = {
resolveBodyOnly: true;
};
/**
Can be used to match methods explicitly or parameters extraction: `Parameters<GotRequestMethod>`.
*/
export interface GotRequestMethod {
<T = string>(url: string | OptionsOfDefaultResponseBody, options?: OptionsOfDefaultResponseBody): CancelableRequest<Response<T>>;
(url: string | OptionsOfTextResponseBody, options?: OptionsOfTextResponseBody): CancelableRequest<Response<string>>;
<T>(url: string | OptionsOfJSONResponseBody, options?: OptionsOfJSONResponseBody): CancelableRequest<Response<T>>;
(url: string | OptionsOfBufferResponseBody, options?: OptionsOfBufferResponseBody): CancelableRequest<Response<Buffer>>;
<T = string>(url: string | Merge<OptionsOfDefaultResponseBody, ResponseBodyOnly>, options?: Merge<OptionsOfDefaultResponseBody, ResponseBodyOnly>): CancelableRequest<T>;
(url: string | Merge<OptionsOfTextResponseBody, ResponseBodyOnly>, options?: Merge<OptionsOfTextResponseBody, ResponseBodyOnly>): CancelableRequest<string>;
<T>(url: string | Merge<OptionsOfJSONResponseBody, ResponseBodyOnly>, options?: Merge<OptionsOfJSONResponseBody, ResponseBodyOnly>): CancelableRequest<T>;
(url: string | Merge<OptionsOfBufferResponseBody, ResponseBodyOnly>, options?: Merge<OptionsOfBufferResponseBody, ResponseBodyOnly>): CancelableRequest<Buffer>;
<T>(url: string | Merge<Options, {
isStream: true;
}>, options?: Merge<Options, {
isStream: true;
}>): ProxyStream<T>;
}
export declare type GotPaginateOptions<T> = Except<Options, keyof PaginationOptions<unknown>> & PaginationOptions<T>;
export declare type URLOrGotPaginateOptions<T> = string | GotPaginateOptions<T>;
export interface GotPaginate {
<T>(url: URLOrGotPaginateOptions<T>, options?: GotPaginateOptions<T>): AsyncIterableIterator<T>;
all<T>(url: URLOrGotPaginateOptions<T>, options?: GotPaginateOptions<T>): Promise<T[]>;
}
export interface Got extends Record<HTTPAlias, GotRequestMethod>, GotRequestMethod {
stream: GotStream;
paginate: GotPaginate;
defaults: Defaults;
GotError: typeof errors.GotError;
CacheError: typeof errors.CacheError;
RequestError: typeof errors.RequestError;
ReadError: typeof errors.ReadError;
ParseError: typeof errors.ParseError;
HTTPError: typeof errors.HTTPError;
MaxRedirectsError: typeof errors.MaxRedirectsError;
UnsupportedProtocolError: typeof errors.UnsupportedProtocolError;
TimeoutError: typeof errors.TimeoutError;
CancelError: typeof errors.CancelError;
extend(...instancesOrOptions: Array<Got | ExtendOptions>): Got;
mergeInstances(parent: Got, ...instances: Got[]): Got;
mergeOptions(...sources: Options[]): NormalizedOptions;
}
export interface GotStream extends Record<HTTPAlias, ReturnStream> {
(url: URLOrOptions, options?: Options): ProxyStream;
}
export declare const defaultHandler: HandlerFunction;
declare const create: (defaults: Defaults) => Got;
export default create;
+153
View File
@@ -0,0 +1,153 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
const as_promise_1 = require("./as-promise");
const as_stream_1 = require("./as-stream");
const errors = require("./errors");
const normalize_arguments_1 = require("./normalize-arguments");
const deep_freeze_1 = require("./utils/deep-freeze");
const getPromiseOrStream = (options) => options.isStream ? as_stream_1.default(options) : as_promise_1.default(options);
const isGotInstance = (value) => (Reflect.has(value, 'defaults') && Reflect.has(value.defaults, 'options'));
const aliases = [
'get',
'post',
'put',
'patch',
'head',
'delete'
];
exports.defaultHandler = (options, next) => next(options);
const create = (defaults) => {
// Proxy properties from next handlers
defaults._rawHandlers = defaults.handlers;
defaults.handlers = defaults.handlers.map(fn => ((options, next) => {
// This will be assigned by assigning result
let root;
const result = fn(options, newOptions => {
root = next(newOptions);
return root;
});
if (result !== root && !options.isStream && root) {
const typedResult = result;
const { then: promiseThen, catch: promiseCatch, finally: promiseFianlly } = typedResult;
Object.setPrototypeOf(typedResult, Object.getPrototypeOf(root));
Object.defineProperties(typedResult, Object.getOwnPropertyDescriptors(root));
// These should point to the new promise
// eslint-disable-next-line promise/prefer-await-to-then
typedResult.then = promiseThen;
typedResult.catch = promiseCatch;
typedResult.finally = promiseFianlly;
}
return result;
}));
// @ts-ignore Because the for loop handles it for us, as well as the other Object.defines
const got = (url, options) => {
var _a;
let iteration = 0;
const iterateHandlers = (newOptions) => {
return defaults.handlers[iteration++](newOptions, iteration === defaults.handlers.length ? getPromiseOrStream : iterateHandlers);
};
/* eslint-disable @typescript-eslint/return-await */
try {
return iterateHandlers(normalize_arguments_1.normalizeArguments(url, options, defaults));
}
catch (error) {
if ((_a = options) === null || _a === void 0 ? void 0 : _a.isStream) {
throw error;
}
else {
// @ts-ignore It's an Error not a response, but TS thinks it's calling .resolve
return as_promise_1.createRejection(error);
}
}
/* eslint-enable @typescript-eslint/return-await */
};
got.extend = (...instancesOrOptions) => {
const optionsArray = [defaults.options];
let handlers = [...defaults._rawHandlers];
let isMutableDefaults;
for (const value of instancesOrOptions) {
if (isGotInstance(value)) {
optionsArray.push(value.defaults.options);
handlers.push(...value.defaults._rawHandlers);
isMutableDefaults = value.defaults.mutableDefaults;
}
else {
optionsArray.push(value);
if (Reflect.has(value, 'handlers')) {
handlers.push(...value.handlers);
}
isMutableDefaults = value.mutableDefaults;
}
}
handlers = handlers.filter(handler => handler !== exports.defaultHandler);
if (handlers.length === 0) {
handlers.push(exports.defaultHandler);
}
return create({
options: normalize_arguments_1.mergeOptions(...optionsArray),
handlers,
mutableDefaults: Boolean(isMutableDefaults)
});
};
// @ts-ignore The missing methods because the for-loop handles it for us
got.stream = (url, options) => got(url, { ...options, isStream: true });
for (const method of aliases) {
// @ts-ignore Cannot properly type a function with multiple definitions yet
got[method] = (url, options) => got(url, { ...options, method });
got.stream[method] = (url, options) => got.stream(url, { ...options, method });
}
// @ts-ignore The missing property is added below
got.paginate = async function* (url, options) {
let normalizedOptions = normalize_arguments_1.normalizeArguments(url, options, defaults);
const pagination = normalizedOptions._pagination;
if (!is_1.default.object(pagination)) {
throw new Error('`options._pagination` must be implemented');
}
const all = [];
while (true) {
// @ts-ignore See https://github.com/sindresorhus/got/issues/954
// eslint-disable-next-line no-await-in-loop
const result = await got(normalizedOptions);
// eslint-disable-next-line no-await-in-loop
const parsed = await pagination.transform(result);
const current = [];
for (const item of parsed) {
if (pagination.filter(item, all, current)) {
if (!pagination.shouldContinue(item, all, current)) {
return;
}
yield item;
all.push(item);
current.push(item);
if (all.length === pagination.countLimit) {
return;
}
}
}
const optionsToMerge = pagination.paginate(result, all, current);
if (optionsToMerge === false) {
return;
}
if (optionsToMerge !== undefined) {
normalizedOptions = normalize_arguments_1.normalizeArguments(normalizedOptions, optionsToMerge);
}
}
};
got.paginate.all = async (url, options) => {
const results = [];
for await (const item of got.paginate(url, options)) {
results.push(item);
}
return results;
};
Object.assign(got, { ...errors, mergeOptions: normalize_arguments_1.mergeOptions });
Object.defineProperty(got, 'defaults', {
value: defaults.mutableDefaults ? defaults : deep_freeze_1.default(defaults),
writable: defaults.mutableDefaults,
configurable: defaults.mutableDefaults,
enumerable: true
});
return got;
};
exports.default = create;
+41
View File
@@ -0,0 +1,41 @@
import { Timings } from '@szmarczak/http-timer';
import { TimeoutError as TimedOutError } from './utils/timed-out';
import { Response, NormalizedOptions } from './types';
export declare class GotError extends Error {
code?: string;
stack: string;
readonly options: NormalizedOptions;
constructor(message: string, error: Partial<Error & {
code?: string;
}>, options: NormalizedOptions);
}
export declare class CacheError extends GotError {
constructor(error: Error, options: NormalizedOptions);
}
export declare class RequestError extends GotError {
constructor(error: Error, options: NormalizedOptions);
}
export declare class ReadError extends GotError {
constructor(error: Error, options: NormalizedOptions);
}
export declare class ParseError extends GotError {
readonly response: Response;
constructor(error: Error, response: Response, options: NormalizedOptions);
}
export declare class HTTPError extends GotError {
readonly response: Response;
constructor(response: Response, options: NormalizedOptions);
}
export declare class MaxRedirectsError extends GotError {
readonly response: Response;
constructor(response: Response, maxRedirects: number, options: NormalizedOptions);
}
export declare class UnsupportedProtocolError extends GotError {
constructor(options: NormalizedOptions);
}
export declare class TimeoutError extends GotError {
timings: Timings;
event: string;
constructor(error: TimedOutError, timings: Timings, options: NormalizedOptions);
}
export { CancelError } from 'p-cancelable';
+103
View File
@@ -0,0 +1,103 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
class GotError extends Error {
constructor(message, error, options) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = 'GotError';
if (!is_1.default.undefined(error.code)) {
this.code = error.code;
}
Object.defineProperty(this, 'options', {
// This fails because of TS 3.7.2 useDefineForClassFields
// Ref: https://github.com/microsoft/TypeScript/issues/34972
enumerable: false,
value: options
});
// Recover the original stacktrace
if (!is_1.default.undefined(error.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')}`;
}
}
}
exports.GotError = GotError;
class CacheError extends GotError {
constructor(error, options) {
super(error.message, error, options);
this.name = 'CacheError';
}
}
exports.CacheError = CacheError;
class RequestError extends GotError {
constructor(error, options) {
super(error.message, error, options);
this.name = 'RequestError';
}
}
exports.RequestError = RequestError;
class ReadError extends GotError {
constructor(error, options) {
super(error.message, error, options);
this.name = 'ReadError';
}
}
exports.ReadError = ReadError;
class ParseError extends GotError {
constructor(error, response, options) {
super(`${error.message} in "${options.url.toString()}"`, error, options);
this.name = 'ParseError';
Object.defineProperty(this, 'response', {
enumerable: false,
value: response
});
}
}
exports.ParseError = ParseError;
class HTTPError extends GotError {
constructor(response, options) {
super(`Response code ${response.statusCode} (${response.statusMessage})`, {}, options);
this.name = 'HTTPError';
Object.defineProperty(this, 'response', {
enumerable: false,
value: response
});
}
}
exports.HTTPError = HTTPError;
class MaxRedirectsError extends GotError {
constructor(response, maxRedirects, options) {
super(`Redirected ${maxRedirects} times. Aborting.`, {}, options);
this.name = 'MaxRedirectsError';
Object.defineProperty(this, 'response', {
enumerable: false,
value: response
});
}
}
exports.MaxRedirectsError = MaxRedirectsError;
class UnsupportedProtocolError extends GotError {
constructor(options) {
super(`Unsupported protocol "${options.url.protocol}"`, {}, options);
this.name = 'UnsupportedProtocolError';
}
}
exports.UnsupportedProtocolError = UnsupportedProtocolError;
class TimeoutError extends GotError {
constructor(error, timings, options) {
super(error.message, error, options);
this.name = 'TimeoutError';
this.event = error.event;
this.timings = timings;
}
}
exports.TimeoutError = TimeoutError;
var p_cancelable_1 = require("p-cancelable");
exports.CancelError = p_cancelable_1.CancelError;
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="node" />
import EventEmitter = require('events');
import { IncomingMessage } from 'http';
import { NormalizedOptions } from './types';
declare const _default: (response: IncomingMessage, options: NormalizedOptions, emitter: EventEmitter) => Promise<void>;
export default _default;
+25
View File
@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const decompressResponse = require("decompress-response");
const mimicResponse = require("mimic-response");
const stream = require("stream");
const util_1 = require("util");
const progress_1 = require("./progress");
const pipeline = util_1.promisify(stream.pipeline);
exports.default = async (response, options, emitter) => {
var _a;
const downloadBodySize = Number(response.headers['content-length']) || undefined;
const progressStream = progress_1.createProgressStream('downloadProgress', emitter, downloadBodySize);
mimicResponse(response, progressStream);
const newResponse = (options.decompress &&
options.method !== 'HEAD' ? decompressResponse(progressStream) : progressStream);
if (!options.decompress && ['gzip', 'deflate', 'br'].includes((_a = newResponse.headers['content-encoding'], (_a !== null && _a !== void 0 ? _a : '')))) {
options.responseType = 'buffer';
}
emitter.emit('response', newResponse);
return pipeline(response, progressStream).catch(error => {
if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
throw error;
}
});
};
+7
View File
@@ -0,0 +1,7 @@
declare const got: import("./create").Got;
export default got;
export * from './types';
export { Got, GotStream, ReturnStream, GotRequestMethod, GotReturn } from './create';
export { ProxyStream as ResponseStream } from './as-stream';
export { GotError, CacheError, RequestError, ReadError, ParseError, HTTPError, MaxRedirectsError, UnsupportedProtocolError, TimeoutError, CancelError } from './errors';
export { InitHook, BeforeRequestHook, BeforeRedirectHook, BeforeRetryHook, BeforeErrorHook, AfterResponseHook, HookType, Hooks, HookEvent } from './known-hook-events';
+129
View File
@@ -0,0 +1,129 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const create_1 = require("./create");
const defaults = {
options: {
method: 'GET',
retry: {
limit: 2,
methods: [
'GET',
'PUT',
'HEAD',
'DELETE',
'OPTIONS',
'TRACE'
],
statusCodes: [
408,
413,
429,
500,
502,
503,
504,
521,
522,
524
],
errorCodes: [
'ETIMEDOUT',
'ECONNRESET',
'EADDRINUSE',
'ECONNREFUSED',
'EPIPE',
'ENOTFOUND',
'ENETUNREACH',
'EAI_AGAIN'
],
maxRetryAfter: undefined,
calculateDelay: ({ computedValue }) => computedValue
},
timeout: {},
headers: {
'user-agent': 'got (https://github.com/sindresorhus/got)'
},
hooks: {
init: [],
beforeRequest: [],
beforeRedirect: [],
beforeRetry: [],
beforeError: [],
afterResponse: []
},
decompress: true,
throwHttpErrors: true,
followRedirect: true,
isStream: false,
cache: false,
dnsCache: false,
useElectronNet: false,
responseType: 'text',
resolveBodyOnly: false,
maxRedirects: 10,
prefixUrl: '',
methodRewriting: true,
allowGetBody: false,
ignoreInvalidCookies: false,
context: {},
_pagination: {
transform: (response) => {
if (response.request.options.responseType === 'json') {
return response.body;
}
return JSON.parse(response.body);
},
paginate: response => {
if (!Reflect.has(response.headers, 'link')) {
return false;
}
const items = response.headers.link.split(',');
let next;
for (const item of items) {
const parsed = item.split(';');
if (parsed[1].includes('next')) {
next = parsed[0].trimStart().trim();
next = next.slice(1, -1);
break;
}
}
if (next) {
const options = {
url: new url_1.URL(next)
};
return options;
}
return false;
},
filter: () => true,
shouldContinue: () => true,
countLimit: Infinity
}
},
handlers: [create_1.defaultHandler],
mutableDefaults: false
};
const got = create_1.default(defaults);
exports.default = got;
// For CommonJS default export support
module.exports = got;
module.exports.default = got;
// Export types
__export(require("./types"));
var as_stream_1 = require("./as-stream");
exports.ResponseStream = as_stream_1.ProxyStream;
var errors_1 = require("./errors");
exports.GotError = errors_1.GotError;
exports.CacheError = errors_1.CacheError;
exports.RequestError = errors_1.RequestError;
exports.ReadError = errors_1.ReadError;
exports.ParseError = errors_1.ParseError;
exports.HTTPError = errors_1.HTTPError;
exports.MaxRedirectsError = errors_1.MaxRedirectsError;
exports.UnsupportedProtocolError = errors_1.UnsupportedProtocolError;
exports.TimeoutError = errors_1.TimeoutError;
exports.CancelError = errors_1.CancelError;
+88
View File
@@ -0,0 +1,88 @@
import { CancelableRequest, GeneralError, NormalizedOptions, Options, Response } from './types';
/**
Called with plain request options, right before their normalization. This is especially useful in conjunction with `got.extend()` when the input needs custom handling.
**Note:** This hook must be synchronous.
@see [Request migration guide](https://github.com/sindresorhus/got/blob/master/migration-guides.md#breaking-changes) for an example.
*/
export declare type InitHook = (options: Options) => void;
/**
Called with normalized [request options](https://github.com/sindresorhus/got#options). Got will make no further changes to the request before it is sent (except the body serialization). This is especially useful in conjunction with [`got.extend()`](https://github.com/sindresorhus/got#instances) when you want to create an API client that, for example, uses HMAC-signing.
@see [AWS section](https://github.com/sindresorhus/got#aws) for an example.
*/
export declare type BeforeRequestHook = (options: NormalizedOptions) => void | Promise<void>;
/**
Called with normalized [request options](https://github.com/sindresorhus/got#options). Got will make no further changes to the request. This is especially useful when you want to avoid dead sites.
*/
export declare type BeforeRedirectHook = (options: NormalizedOptions, response: Response) => void | Promise<void>;
/**
Called with normalized [request options](https://github.com/sindresorhus/got#options), the error and the retry count. Got will make no further changes to the request. This is especially useful when some extra work is required before the next try.
*/
export declare type BeforeRetryHook = (options: NormalizedOptions, error?: GeneralError, retryCount?: number) => void | Promise<void>;
/**
Called with an `Error` instance. The error is passed to the hook right before it's thrown. This is especially useful when you want to have more detailed errors.
**Note:** Errors thrown while normalizing input options are thrown directly and not part of this hook.
*/
export declare type BeforeErrorHook = <ErrorLike extends GeneralError>(error: ErrorLike) => GeneralError | Promise<GeneralError>;
/**
Called with [response object](https://github.com/sindresorhus/got#response) and a retry function.
Each function should return the response. This is especially useful when you want to refresh an access token.
*/
export declare type AfterResponseHook = (response: Response, retryWithMergedOptions: (options: Options) => CancelableRequest<Response>) => Response | CancelableRequest<Response> | Promise<Response | CancelableRequest<Response>>;
export declare type HookType = BeforeErrorHook | InitHook | BeforeRequestHook | BeforeRedirectHook | BeforeRetryHook | AfterResponseHook;
/**
Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
*/
export interface Hooks {
/**
Called with plain request options, right before their normalization. This is especially useful in conjunction with `got.extend()` when the input needs custom handling.
**Note:** This hook must be synchronous.
@see [Request migration guide](https://github.com/sindresorhus/got/blob/master/migration-guides.md#breaking-changes) for an example.
@default []
*/
init?: InitHook[];
/**
Called with normalized [request options](https://github.com/sindresorhus/got#options). Got will make no further changes to the request before it is sent (except the body serialization). This is especially useful in conjunction with [`got.extend()`](https://github.com/sindresorhus/got#instances) when you want to create an API client that, for example, uses HMAC-signing.
@see [AWS section](https://github.com/sindresorhus/got#aws) for an example.
@default []
*/
beforeRequest?: BeforeRequestHook[];
/**
Called with normalized [request options](https://github.com/sindresorhus/got#options). Got will make no further changes to the request. This is especially useful when you want to avoid dead sites.
@default []
*/
beforeRedirect?: BeforeRedirectHook[];
/**
Called with normalized [request options](https://github.com/sindresorhus/got#options), the error and the retry count. Got will make no further changes to the request. This is especially useful when some extra work is required before the next try.
@default []
*/
beforeRetry?: BeforeRetryHook[];
/**
Called with an `Error` instance. The error is passed to the hook right before it's thrown. This is especially useful when you want to have more detailed errors.
**Note:** Errors thrown while normalizing input options are thrown directly and not part of this hook.
@default []
*/
beforeError?: BeforeErrorHook[];
/**
Called with [response object](https://github.com/sindresorhus/got#response) and a retry function.
Each function should return the response. This is especially useful when you want to refresh an access token.
@default []
*/
afterResponse?: AfterResponseHook[];
}
export declare type HookEvent = keyof Hooks;
declare const knownHookEvents: readonly HookEvent[];
export default knownHookEvents;
+11
View File
@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const knownHookEvents = [
'beforeError',
'init',
'beforeRequest',
'beforeRedirect',
'beforeRetry',
'afterResponse'
];
exports.default = knownHookEvents;
+19
View File
@@ -0,0 +1,19 @@
/// <reference types="node" />
import http = require('http');
import https = require('https');
import stream = require('stream');
import { Merge } from 'type-fest';
import { Defaults, NormalizedOptions, RequestFunction, URLOrOptions, requestSymbol } from './types';
export declare const preNormalizeArguments: (options: Merge<https.RequestOptions, Merge<import("./types").GotOptions, import("./utils/options-to-url").URLOptions>>, defaults?: NormalizedOptions | undefined) => NormalizedOptions;
export declare const mergeOptions: (...sources: Merge<https.RequestOptions, Merge<import("./types").GotOptions, import("./utils/options-to-url").URLOptions>>[]) => NormalizedOptions;
export declare const normalizeArguments: (url: URLOrOptions, options?: Merge<https.RequestOptions, Merge<import("./types").GotOptions, import("./utils/options-to-url").URLOptions>> | undefined, defaults?: Defaults | undefined) => NormalizedOptions;
export declare type NormalizedRequestArguments = Merge<https.RequestOptions, {
body?: stream.Readable;
[requestSymbol]: RequestFunction;
url: Pick<NormalizedOptions, 'url'>;
}>;
export declare const normalizeRequestArguments: (options: NormalizedOptions) => Promise<Merge<https.RequestOptions, {
body?: stream.Readable | undefined;
url: Pick<NormalizedOptions, "url">;
[requestSymbol]: typeof http.request;
}>>;
+441
View File
@@ -0,0 +1,441 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const util_1 = require("util");
const CacheableRequest = require("cacheable-request");
const http = require("http");
const https = require("https");
const lowercaseKeys = require("lowercase-keys");
const toReadableStream = require("to-readable-stream");
const is_1 = require("@sindresorhus/is");
const cacheable_lookup_1 = require("cacheable-lookup");
const errors_1 = require("./errors");
const known_hook_events_1 = require("./known-hook-events");
const dynamic_require_1 = require("./utils/dynamic-require");
const get_body_size_1 = require("./utils/get-body-size");
const is_form_data_1 = require("./utils/is-form-data");
const merge_1 = require("./utils/merge");
const options_to_url_1 = require("./utils/options-to-url");
const supports_brotli_1 = require("./utils/supports-brotli");
const types_1 = require("./types");
const nonEnumerableProperties = [
'context',
'body',
'json',
'form'
];
const isAgentByProtocol = (agent) => is_1.default.object(agent);
// TODO: `preNormalizeArguments` should merge `options` & `defaults`
exports.preNormalizeArguments = (options, defaults) => {
var _a, _b, _c, _d, _e, _f;
// `options.headers`
if (is_1.default.undefined(options.headers)) {
options.headers = {};
}
else {
options.headers = lowercaseKeys(options.headers);
}
for (const [key, value] of Object.entries(options.headers)) {
if (is_1.default.null_(value)) {
throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
}
}
// `options.prefixUrl`
if (is_1.default.urlInstance(options.prefixUrl) || is_1.default.string(options.prefixUrl)) {
options.prefixUrl = options.prefixUrl.toString();
if (options.prefixUrl.length !== 0 && !options.prefixUrl.endsWith('/')) {
options.prefixUrl += '/';
}
}
else {
options.prefixUrl = defaults ? defaults.prefixUrl : '';
}
// `options.hooks`
if (is_1.default.undefined(options.hooks)) {
options.hooks = {};
}
if (is_1.default.object(options.hooks)) {
for (const event of known_hook_events_1.default) {
if (Reflect.has(options.hooks, event)) {
if (!is_1.default.array(options.hooks[event])) {
throw new TypeError(`Parameter \`${event}\` must be an Array, not ${is_1.default(options.hooks[event])}`);
}
}
else {
options.hooks[event] = [];
}
}
}
else {
throw new TypeError(`Parameter \`hooks\` must be an Object, not ${is_1.default(options.hooks)}`);
}
if (defaults) {
for (const event of known_hook_events_1.default) {
if (!(Reflect.has(options.hooks, event) && is_1.default.undefined(options.hooks[event]))) {
// @ts-ignore Union type array is not assignable to union array type
options.hooks[event] = [
...defaults.hooks[event],
...options.hooks[event]
];
}
}
}
// `options.timeout`
if (is_1.default.number(options.timeout)) {
options.timeout = { request: options.timeout };
}
else if (!is_1.default.object(options.timeout)) {
options.timeout = {};
}
// `options.retry`
const { retry } = options;
if (defaults) {
options.retry = { ...defaults.retry };
}
else {
options.retry = {
calculateDelay: retryObject => retryObject.computedValue,
limit: 0,
methods: [],
statusCodes: [],
errorCodes: [],
maxRetryAfter: undefined
};
}
if (is_1.default.object(retry)) {
options.retry = {
...options.retry,
...retry
};
}
else if (is_1.default.number(retry)) {
options.retry.limit = retry;
}
if (options.retry.maxRetryAfter === undefined) {
options.retry.maxRetryAfter = Math.min(...[options.timeout.request, options.timeout.connect].filter((n) => !is_1.default.nullOrUndefined(n)));
}
options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))];
options.retry.statusCodes = [...new Set(options.retry.statusCodes)];
options.retry.errorCodes = [...new Set(options.retry.errorCodes)];
// `options.dnsCache`
if (options.dnsCache && !(options.dnsCache instanceof cacheable_lookup_1.default)) {
options.dnsCache = new cacheable_lookup_1.default({ cacheAdapter: options.dnsCache });
}
// `options.method`
if (is_1.default.string(options.method)) {
options.method = options.method.toUpperCase();
}
else {
options.method = (_b = (_a = defaults) === null || _a === void 0 ? void 0 : _a.method, (_b !== null && _b !== void 0 ? _b : 'GET'));
}
// Better memory management, so we don't have to generate a new object every time
if (options.cache) {
options.cacheableRequest = new CacheableRequest(
// @ts-ignore Cannot properly type a function with multiple definitions yet
(requestOptions, handler) => requestOptions[types_1.requestSymbol](requestOptions, handler), options.cache);
}
// `options.cookieJar`
if (is_1.default.object(options.cookieJar)) {
let { setCookie, getCookieString } = options.cookieJar;
// Horrible `tough-cookie` check
if (setCookie.length === 4 && getCookieString.length === 0) {
if (!Reflect.has(setCookie, util_1.promisify.custom)) {
// @ts-ignore TS is dumb - it says `setCookie` is `never`.
setCookie = util_1.promisify(setCookie.bind(options.cookieJar));
getCookieString = util_1.promisify(getCookieString.bind(options.cookieJar));
}
}
else if (setCookie.length !== 2) {
throw new TypeError('`options.cookieJar.setCookie` needs to be an async function with 2 arguments');
}
else if (getCookieString.length !== 1) {
throw new TypeError('`options.cookieJar.getCookieString` needs to be an async function with 1 argument');
}
options.cookieJar = { setCookie, getCookieString };
}
// `options.encoding`
if (is_1.default.null_(options.encoding)) {
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
}
// `options.maxRedirects`
if (!Reflect.has(options, 'maxRedirects') && !(defaults && Reflect.has(defaults, 'maxRedirects'))) {
options.maxRedirects = 0;
}
// Merge defaults
if (defaults) {
options = merge_1.default({}, defaults, options);
}
// `options._pagination`
if (is_1.default.object(options._pagination)) {
const { _pagination: pagination } = options;
if (!is_1.default.function_(pagination.transform)) {
throw new TypeError('`options._pagination.transform` must be implemented');
}
if (!is_1.default.function_(pagination.shouldContinue)) {
throw new TypeError('`options._pagination.shouldContinue` must be implemented');
}
if (!is_1.default.function_(pagination.filter)) {
throw new TypeError('`options._pagination.filter` must be implemented');
}
if (!is_1.default.function_(pagination.paginate)) {
throw new TypeError('`options._pagination.paginate` must be implemented');
}
}
// Other values
options.decompress = Boolean(options.decompress);
options.isStream = Boolean(options.isStream);
options.throwHttpErrors = Boolean(options.throwHttpErrors);
options.ignoreInvalidCookies = Boolean(options.ignoreInvalidCookies);
options.cache = (_c = options.cache, (_c !== null && _c !== void 0 ? _c : false));
options.responseType = (_d = options.responseType, (_d !== null && _d !== void 0 ? _d : 'text'));
options.resolveBodyOnly = Boolean(options.resolveBodyOnly);
options.followRedirect = Boolean(options.followRedirect);
options.dnsCache = (_e = options.dnsCache, (_e !== null && _e !== void 0 ? _e : false));
options.useElectronNet = Boolean(options.useElectronNet);
options.methodRewriting = Boolean(options.methodRewriting);
options.allowGetBody = Boolean(options.allowGetBody);
options.context = (_f = options.context, (_f !== null && _f !== void 0 ? _f : {}));
return options;
};
exports.mergeOptions = (...sources) => {
let mergedOptions = exports.preNormalizeArguments({});
// Non enumerable properties shall not be merged
const properties = {};
for (const source of sources) {
mergedOptions = exports.preNormalizeArguments(merge_1.default({}, source), mergedOptions);
for (const name of nonEnumerableProperties) {
if (!Reflect.has(source, name)) {
continue;
}
properties[name] = {
writable: true,
configurable: true,
enumerable: false,
value: source[name]
};
}
}
Object.defineProperties(mergedOptions, properties);
return mergedOptions;
};
exports.normalizeArguments = (url, options, defaults) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
// Merge options
if (typeof url === 'undefined') {
throw new TypeError('Missing `url` argument');
}
const runInitHooks = (hooks, options) => {
if (hooks && options) {
for (const hook of hooks) {
const result = hook(options);
if (is_1.default.promise(result)) {
throw new TypeError('The `init` hook must be a synchronous function');
}
}
}
};
const hasUrl = is_1.default.urlInstance(url) || is_1.default.string(url);
if (hasUrl) {
if (options) {
if (Reflect.has(options, 'url')) {
throw new TypeError('The `url` option cannot be used if the input is a valid URL.');
}
}
else {
options = {};
}
// @ts-ignore URL is not URL
options.url = url;
runInitHooks((_a = defaults) === null || _a === void 0 ? void 0 : _a.options.hooks.init, options);
runInitHooks((_b = options.hooks) === null || _b === void 0 ? void 0 : _b.init, options);
}
else if (Reflect.has(url, 'resolve')) {
throw new Error('The legacy `url.Url` is deprecated. Use `URL` instead.');
}
else {
runInitHooks((_c = defaults) === null || _c === void 0 ? void 0 : _c.options.hooks.init, url);
runInitHooks((_d = url.hooks) === null || _d === void 0 ? void 0 : _d.init, url);
if (options) {
runInitHooks((_e = defaults) === null || _e === void 0 ? void 0 : _e.options.hooks.init, options);
runInitHooks((_f = options.hooks) === null || _f === void 0 ? void 0 : _f.init, options);
}
}
if (hasUrl) {
options = exports.mergeOptions((_h = (_g = defaults) === null || _g === void 0 ? void 0 : _g.options, (_h !== null && _h !== void 0 ? _h : {})), (options !== null && options !== void 0 ? options : {}));
}
else {
options = exports.mergeOptions((_k = (_j = defaults) === null || _j === void 0 ? void 0 : _j.options, (_k !== null && _k !== void 0 ? _k : {})), url, (options !== null && options !== void 0 ? options : {}));
}
// Normalize URL
// TODO: drop `optionsToUrl` in Got 12
if (is_1.default.string(options.url)) {
options.url = options.prefixUrl + options.url;
options.url = options.url.replace(/^unix:/, 'http://$&');
if (options.searchParams || options.search) {
options.url = options.url.split('?')[0];
}
// @ts-ignore URL is not URL
options.url = options_to_url_1.default({
origin: options.url,
...options
});
}
else if (!is_1.default.urlInstance(options.url)) {
// @ts-ignore URL is not URL
options.url = options_to_url_1.default({ origin: options.prefixUrl, ...options });
}
const normalizedOptions = options;
// Make it possible to change `options.prefixUrl`
let prefixUrl = options.prefixUrl;
Object.defineProperty(normalizedOptions, 'prefixUrl', {
set: (value) => {
if (!normalizedOptions.url.href.startsWith(value)) {
throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${normalizedOptions.url.href}`);
}
normalizedOptions.url = new url_1.URL(value + normalizedOptions.url.href.slice(prefixUrl.length));
prefixUrl = value;
},
get: () => prefixUrl
});
// Make it possible to remove default headers
for (const [key, value] of Object.entries(normalizedOptions.headers)) {
if (is_1.default.undefined(value)) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete normalizedOptions.headers[key];
}
}
return normalizedOptions;
};
const withoutBody = new Set(['HEAD']);
const withoutBodyUnlessSpecified = 'GET';
exports.normalizeRequestArguments = async (options) => {
var _a, _b, _c;
options = exports.mergeOptions(options);
// Serialize body
const { headers } = options;
const hasNoContentType = is_1.default.undefined(headers['content-type']);
{
// TODO: these checks should be moved to `preNormalizeArguments`
const isForm = !is_1.default.undefined(options.form);
const isJson = !is_1.default.undefined(options.json);
const isBody = !is_1.default.undefined(options.body);
if ((isBody || isForm || isJson) && withoutBody.has(options.method)) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
if (!options.allowGetBody && (isBody || isForm || isJson) && withoutBodyUnlessSpecified === options.method) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
if ([isBody, isForm, isJson].filter(isTrue => isTrue).length > 1) {
throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');
}
if (isBody &&
!is_1.default.nodeStream(options.body) &&
!is_1.default.string(options.body) &&
!is_1.default.buffer(options.body) &&
!(is_1.default.object(options.body) && is_form_data_1.default(options.body))) {
throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');
}
if (isForm && !is_1.default.object(options.form)) {
throw new TypeError('The `form` option must be an Object');
}
}
if (options.body) {
// Special case for https://github.com/form-data/form-data
if (is_1.default.object(options.body) && is_form_data_1.default(options.body) && hasNoContentType) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
}
else if (options.form) {
if (hasNoContentType) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
options.body = (new url_1.URLSearchParams(options.form)).toString();
}
else if (options.json) {
if (hasNoContentType) {
headers['content-type'] = 'application/json';
}
options.body = JSON.stringify(options.json);
}
const uploadBodySize = await get_body_size_1.default(options);
if (!is_1.default.nodeStream(options.body)) {
options.body = toReadableStream(options.body);
}
// 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_1.default.undefined(headers['content-length']) && is_1.default.undefined(headers['transfer-encoding'])) {
if ((options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH' || options.method === 'DELETE' || (options.allowGetBody && options.method === 'GET')) &&
!is_1.default.undefined(uploadBodySize)) {
// @ts-ignore We assign if it is undefined, so this IS correct
headers['content-length'] = String(uploadBodySize);
}
}
if (!options.isStream && options.responseType === 'json' && is_1.default.undefined(headers.accept)) {
headers.accept = 'application/json';
}
if (options.decompress && is_1.default.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supports_brotli_1.default ? 'gzip, deflate, br' : 'gzip, deflate';
}
// Validate URL
if (options.url.protocol !== 'http:' && options.url.protocol !== 'https:') {
throw new errors_1.UnsupportedProtocolError(options);
}
decodeURI(options.url.toString());
// Normalize request function
if (is_1.default.function_(options.request)) {
options[types_1.requestSymbol] = options.request;
delete options.request;
}
else {
options[types_1.requestSymbol] = options.url.protocol === 'https:' ? https.request : http.request;
}
// UNIX sockets
if (options.url.hostname === 'unix') {
const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(options.url.pathname);
if ((_a = matches) === null || _a === void 0 ? void 0 : _a.groups) {
const { socketPath, path } = matches.groups;
options = {
...options,
socketPath,
path,
host: ''
};
}
}
if (isAgentByProtocol(options.agent)) {
options.agent = (_b = options.agent[options.url.protocol.slice(0, -1)], (_b !== null && _b !== void 0 ? _b : options.agent));
}
if (options.dnsCache) {
options.lookup = options.dnsCache.lookup;
}
/* istanbul ignore next: electron.net is broken */
// No point in typing process.versions correctly, as
// `process.version.electron` is used only once, right here.
if (options.useElectronNet && process.versions.electron) {
const electron = dynamic_require_1.default(module, 'electron'); // Trick webpack
options.request = util_1.deprecate((_c = electron.net.request, (_c !== null && _c !== void 0 ? _c : electron.remote.net.request)), 'Electron support has been deprecated and will be removed in Got 11.\n' +
'See https://github.com/sindresorhus/got/issues/899 for further information.', 'GOT_ELECTRON');
}
// Got's `timeout` is an object, http's `timeout` is a number, so they're not compatible.
delete options.timeout;
// Set cookies
if (options.cookieJar) {
const cookieString = await options.cookieJar.getCookieString(options.url.toString());
if (is_1.default.nonEmptyString(cookieString)) {
options.headers.cookie = cookieString;
}
else {
delete options.headers.cookie;
}
}
// `http-cache-semantics` checks this
delete options.url;
return options;
};
+4
View File
@@ -0,0 +1,4 @@
/// <reference types="node" />
import EventEmitter = require('events');
import { Transform as TransformStream } from 'stream';
export declare function createProgressStream(name: 'downloadProgress' | 'uploadProgress', emitter: EventEmitter, totalBytes?: number | string): TransformStream;
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const stream_1 = require("stream");
const is_1 = require("@sindresorhus/is");
function createProgressStream(name, emitter, totalBytes) {
let transformedBytes = 0;
if (is_1.default.string(totalBytes)) {
totalBytes = Number(totalBytes);
}
const progressStream = new stream_1.Transform({
transform(chunk, _encoding, callback) {
transformedBytes += chunk.length;
const percent = totalBytes ? transformedBytes / totalBytes : 0;
// Let `flush()` be responsible for emitting the last event
if (percent < 1) {
emitter.emit(name, {
percent,
transferred: transformedBytes,
total: totalBytes
});
}
callback(undefined, chunk);
},
flush(callback) {
emitter.emit(name, {
percent: 1,
transferred: transformedBytes,
total: totalBytes
});
callback();
}
});
emitter.emit(name, {
percent: 0,
transferred: 0,
total: totalBytes
});
return progressStream;
}
exports.createProgressStream = createProgressStream;
+12
View File
@@ -0,0 +1,12 @@
/// <reference types="node" />
import EventEmitter = require('events');
import { ProxyStream } from './as-stream';
import { RequestError, TimeoutError } from './errors';
import { NormalizedOptions } from './types';
export interface RequestAsEventEmitter extends EventEmitter {
retry: (error: TimeoutError | RequestError) => boolean;
abort: () => void;
}
declare const _default: (options: NormalizedOptions) => RequestAsEventEmitter;
export default _default;
export declare const proxyEvents: (proxy: EventEmitter | ProxyStream<unknown>, emitter: RequestAsEventEmitter) => void;
+284
View File
@@ -0,0 +1,284 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const CacheableRequest = require("cacheable-request");
const EventEmitter = require("events");
const http = require("http");
const stream = require("stream");
const url_1 = require("url");
const util_1 = require("util");
const is_1 = require("@sindresorhus/is");
const http_timer_1 = require("@szmarczak/http-timer");
const calculate_retry_delay_1 = require("./calculate-retry-delay");
const errors_1 = require("./errors");
const get_response_1 = require("./get-response");
const normalize_arguments_1 = require("./normalize-arguments");
const progress_1 = require("./progress");
const timed_out_1 = require("./utils/timed-out");
const types_1 = require("./types");
const url_to_options_1 = require("./utils/url-to-options");
const pEvent = require("p-event");
const setImmediateAsync = async () => new Promise(resolve => setImmediate(resolve));
const pipeline = util_1.promisify(stream.pipeline);
const redirectCodes = new Set([300, 301, 302, 303, 304, 307, 308]);
exports.default = (options) => {
const emitter = new EventEmitter();
const requestUrl = options.url.toString();
const redirects = [];
let retryCount = 0;
let currentRequest;
// `request.aborted` is a boolean since v11.0.0: https://github.com/nodejs/node/commit/4b00c4fafaa2ae8c41c1f78823c0feb810ae4723#diff-e3bc37430eb078ccbafe3aa3b570c91a
const isAborted = () => typeof currentRequest.aborted === 'number' || currentRequest.aborted;
const emitError = async (error) => {
try {
for (const hook of options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
emitter.emit('error', error);
}
catch (error_) {
emitter.emit('error', error_);
}
};
const get = async () => {
let httpOptions = await normalize_arguments_1.normalizeRequestArguments(options);
const handleResponse = async (response) => {
var _a;
try {
/* istanbul ignore next: fixes https://github.com/electron/electron/blob/cbb460d47628a7a146adf4419ed48550a98b2923/lib/browser/api/net.js#L59-L65 */
if (options.useElectronNet) {
response = new Proxy(response, {
get: (target, name) => {
if (name === 'trailers' || name === 'rawTrailers') {
return [];
}
const value = target[name];
return is_1.default.function_(value) ? value.bind(target) : value;
}
});
}
const typedResponse = response;
const { statusCode } = typedResponse;
typedResponse.statusMessage = is_1.default.nonEmptyString(typedResponse.statusMessage) ? typedResponse.statusMessage : http.STATUS_CODES[statusCode];
typedResponse.url = options.url.toString();
typedResponse.requestUrl = requestUrl;
typedResponse.retryCount = retryCount;
typedResponse.redirectUrls = redirects;
typedResponse.request = { options };
typedResponse.isFromCache = (_a = typedResponse.fromCache, (_a !== null && _a !== void 0 ? _a : false));
delete typedResponse.fromCache;
if (!typedResponse.isFromCache) {
typedResponse.ip = response.socket.remoteAddress;
}
const rawCookies = typedResponse.headers['set-cookie'];
if (Reflect.has(options, 'cookieJar') && rawCookies) {
let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, typedResponse.url));
if (options.ignoreInvalidCookies) {
promises = promises.map(async (p) => p.catch(() => { }));
}
await Promise.all(promises);
}
if (options.followRedirect && Reflect.has(typedResponse.headers, 'location') && redirectCodes.has(statusCode)) {
typedResponse.resume(); // We're being redirected, we don't care about the response.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-boolean-literal-compare
if (statusCode === 303 || options.methodRewriting === false) {
if (options.method !== 'GET' && options.method !== 'HEAD') {
// Server responded with "see other", indicating that the resource exists at another location,
// and the client should request it from that location via GET or HEAD.
options.method = 'GET';
}
if (Reflect.has(options, 'body')) {
delete options.body;
}
if (Reflect.has(options, 'json')) {
delete options.json;
}
if (Reflect.has(options, 'form')) {
delete options.form;
}
}
if (redirects.length >= options.maxRedirects) {
throw new errors_1.MaxRedirectsError(typedResponse, options.maxRedirects, options);
}
// Handles invalid URLs. See https://github.com/sindresorhus/got/issues/604
const redirectBuffer = Buffer.from(typedResponse.headers.location, 'binary').toString();
const redirectUrl = new url_1.URL(redirectBuffer, options.url);
// Redirecting to a different site, clear cookies.
if (redirectUrl.hostname !== options.url.hostname && Reflect.has(options.headers, 'cookie')) {
delete options.headers.cookie;
}
redirects.push(redirectUrl.toString());
options.url = redirectUrl;
for (const hook of options.hooks.beforeRedirect) {
// eslint-disable-next-line no-await-in-loop
await hook(options, typedResponse);
}
emitter.emit('redirect', response, options);
await get();
return;
}
await get_response_1.default(typedResponse, options, emitter);
}
catch (error) {
emitError(error);
}
};
const handleRequest = async (request) => {
let isPiped = false;
let isFinished = false;
// `request.finished` doesn't indicate whether this has been emitted or not
request.once('finish', () => {
isFinished = true;
});
currentRequest = request;
const onError = (error) => {
if (error instanceof timed_out_1.TimeoutError) {
error = new errors_1.TimeoutError(error, request.timings, options);
}
else {
error = new errors_1.RequestError(error, options);
}
if (!emitter.retry(error)) {
emitError(error);
}
};
request.on('error', error => {
if (isPiped) {
// Check if it's caught by `stream.pipeline(...)`
if (!isFinished) {
return;
}
// We need to let `TimedOutTimeoutError` through, because `stream.pipeline(…)` aborts the request automatically.
if (isAborted() && !(error instanceof timed_out_1.TimeoutError)) {
return;
}
}
onError(error);
});
try {
http_timer_1.default(request);
timed_out_1.default(request, options.timeout, options.url);
emitter.emit('request', request);
const uploadStream = progress_1.createProgressStream('uploadProgress', emitter, httpOptions.headers['content-length']);
isPiped = true;
await pipeline(httpOptions.body, uploadStream, request);
request.emit('upload-complete');
}
catch (error) {
if (isAborted() && error.message === 'Premature close') {
// The request was aborted on purpose
return;
}
onError(error);
}
};
if (options.cache) {
// `cacheable-request` doesn't support Node 10 API, fallback.
httpOptions = {
...httpOptions,
...url_to_options_1.default(options.url)
};
// @ts-ignore `cacheable-request` has got invalid types
const cacheRequest = options.cacheableRequest(httpOptions, handleResponse);
cacheRequest.once('error', (error) => {
if (error instanceof CacheableRequest.RequestError) {
emitError(new errors_1.RequestError(error, options));
}
else {
emitError(new errors_1.CacheError(error, options));
}
});
cacheRequest.once('request', handleRequest);
}
else {
// Catches errors thrown by calling `requestFn(…)`
try {
handleRequest(httpOptions[types_1.requestSymbol](options.url, httpOptions, handleResponse));
}
catch (error) {
emitError(new errors_1.RequestError(error, options));
}
}
};
emitter.retry = error => {
let backoff;
retryCount++;
try {
backoff = options.retry.calculateDelay({
attemptCount: retryCount,
retryOptions: options.retry,
error,
computedValue: calculate_retry_delay_1.default({
attemptCount: retryCount,
retryOptions: options.retry,
error,
computedValue: 0
})
});
}
catch (error_) {
emitError(error_);
return false;
}
if (backoff) {
const retry = async (options) => {
try {
for (const hook of options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(options, error, retryCount);
}
await get();
}
catch (error_) {
emitError(error_);
}
};
setTimeout(retry, backoff, { ...options, forceRefresh: true });
return true;
}
return false;
};
emitter.abort = () => {
emitter.prependListener('request', (request) => {
request.abort();
});
if (currentRequest) {
currentRequest.abort();
}
};
(async () => {
try {
if (options.body instanceof fs_1.ReadStream) {
await pEvent(options.body, 'open');
}
// Promises are executed immediately.
// If there were no `setImmediate` here,
// `promise.json()` would have no effect
// as the request would be sent already.
await setImmediateAsync();
for (const hook of options.hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
await hook(options);
}
await get();
}
catch (error) {
emitError(error);
}
})();
return emitter;
};
exports.proxyEvents = (proxy, emitter) => {
const events = [
'request',
'redirect',
'uploadProgress',
'downloadProgress'
];
for (const event of events) {
emitter.on(event, (...args) => {
proxy.emit(event, ...args);
});
}
};
+210
View File
@@ -0,0 +1,210 @@
/// <reference types="node" />
import http = require('http');
import https = require('https');
import Keyv = require('keyv');
import CacheableRequest = require('cacheable-request');
import PCancelable = require('p-cancelable');
import ResponseLike = require('responselike');
import { URL } from 'url';
import { Readable as ReadableStream } from 'stream';
import { Timings, IncomingMessageWithTimings } from '@szmarczak/http-timer';
import CacheableLookup from 'cacheable-lookup';
import { Except, Merge } from 'type-fest';
import { GotReturn } from './create';
import { GotError, HTTPError, MaxRedirectsError, ParseError, TimeoutError, RequestError } from './errors';
import { Hooks } from './known-hook-events';
import { URLOptions } from './utils/options-to-url';
export declare type GeneralError = Error | GotError | HTTPError | MaxRedirectsError | ParseError;
export declare type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE' | 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace';
export declare type ResponseType = 'json' | 'buffer' | 'text';
export interface Response<BodyType = unknown> extends IncomingMessageWithTimings {
body: BodyType;
statusCode: number;
/**
The remote IP address.
Note: Not available when the response is cached. This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86).
*/
ip: string;
fromCache?: boolean;
isFromCache?: boolean;
req?: http.ClientRequest;
requestUrl: string;
retryCount: number;
timings: Timings;
redirectUrls: string[];
request: {
options: NormalizedOptions;
};
url: string;
}
export interface ResponseObject extends Partial<ResponseLike> {
socket: {
remoteAddress: string;
};
}
export interface RetryObject {
attemptCount: number;
retryOptions: Required<RetryOptions>;
error: TimeoutError | RequestError;
computedValue: number;
}
export declare type RetryFunction = (retryObject: RetryObject) => number;
export declare type HandlerFunction = <T extends GotReturn>(options: NormalizedOptions, next: (options: NormalizedOptions) => T) => T | Promise<T>;
export interface DefaultRetryOptions {
limit: number;
methods: Method[];
statusCodes: number[];
errorCodes: string[];
calculateDelay: RetryFunction;
maxRetryAfter?: number;
}
export interface RetryOptions extends Partial<DefaultRetryOptions> {
retries?: number;
}
export declare type RequestFunction = typeof http.request;
export interface AgentByProtocol {
http?: http.Agent;
https?: https.Agent;
}
export interface Delays {
lookup?: number;
connect?: number;
secureConnect?: number;
socket?: number;
response?: number;
send?: number;
request?: number;
}
export declare type Headers = Record<string, string | string[] | undefined>;
interface ToughCookieJar {
getCookieString(currentUrl: string, options: {
[key: string]: unknown;
}, cb: (err: Error | null, cookies: string) => void): void;
getCookieString(url: string, callback: (error: Error | null, cookieHeader: string) => void): void;
setCookie(cookieOrString: unknown, currentUrl: string, options: {
[key: string]: unknown;
}, cb: (err: Error | null, cookie: unknown) => void): void;
setCookie(rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void): void;
}
interface PromiseCookieJar {
getCookieString(url: string): Promise<string>;
setCookie(rawCookie: string, url: string): Promise<unknown>;
}
export declare const requestSymbol: unique symbol;
export declare type DefaultOptions = Merge<Required<Except<GotOptions, 'hooks' | 'retry' | 'timeout' | 'context' | '_pagination' | 'agent' | 'body' | 'cookieJar' | 'encoding' | 'form' | 'json' | 'lookup' | 'request' | 'url' | typeof requestSymbol>>, {
hooks: Required<Hooks>;
retry: DefaultRetryOptions;
timeout: Delays;
context: {
[key: string]: any;
};
_pagination?: PaginationOptions<unknown>['_pagination'];
}>;
export interface PaginationOptions<T> {
_pagination?: {
transform?: (response: Response) => Promise<T[]> | T[];
filter?: (item: T, allItems: T[], currentItems: T[]) => boolean;
paginate?: (response: Response, allItems: T[], currentItems: T[]) => Options | false;
shouldContinue?: (item: T, allItems: T[], currentItems: T[]) => boolean;
countLimit?: number;
};
}
export interface GotOptions extends PaginationOptions<unknown> {
[requestSymbol]?: RequestFunction;
url?: URL | string;
body?: string | Buffer | ReadableStream;
hooks?: Hooks;
decompress?: boolean;
isStream?: boolean;
encoding?: BufferEncoding;
method?: Method;
retry?: RetryOptions | number;
throwHttpErrors?: boolean;
cookieJar?: ToughCookieJar | PromiseCookieJar;
ignoreInvalidCookies?: boolean;
request?: RequestFunction;
agent?: http.Agent | https.Agent | boolean | AgentByProtocol;
cache?: string | CacheableRequest.StorageAdapter | false;
headers?: Headers;
responseType?: ResponseType;
resolveBodyOnly?: boolean;
followRedirect?: boolean;
prefixUrl?: URL | string;
timeout?: number | Delays;
dnsCache?: CacheableLookup | Map<string, string> | Keyv | false;
useElectronNet?: boolean;
form?: {
[key: string]: any;
};
json?: {
[key: string]: any;
};
context?: {
[key: string]: any;
};
maxRedirects?: number;
lookup?: CacheableLookup['lookup'];
allowGetBody?: boolean;
methodRewriting?: boolean;
}
export declare type Options = Merge<https.RequestOptions, Merge<GotOptions, URLOptions>>;
export interface NormalizedOptions extends Options {
headers: Headers;
hooks: Required<Hooks>;
timeout: Delays;
dnsCache: CacheableLookup | false;
lookup?: CacheableLookup['lookup'];
retry: Required<RetryOptions>;
prefixUrl: string;
method: Method;
url: URL;
cacheableRequest?: (options: string | URL | http.RequestOptions, callback?: (response: http.ServerResponse | ResponseLike) => void) => CacheableRequest.Emitter;
cookieJar?: PromiseCookieJar;
maxRedirects: number;
pagination?: Required<PaginationOptions<unknown>['_pagination']>;
[requestSymbol]: RequestFunction;
decompress: boolean;
isStream: boolean;
throwHttpErrors: boolean;
ignoreInvalidCookies: boolean;
cache: CacheableRequest.StorageAdapter | false;
responseType: ResponseType;
resolveBodyOnly: boolean;
followRedirect: boolean;
useElectronNet: boolean;
methodRewriting: boolean;
allowGetBody: boolean;
context: {
[key: string]: any;
};
path?: string;
}
export interface ExtendOptions extends Options {
handlers?: HandlerFunction[];
mutableDefaults?: boolean;
}
export interface Defaults {
options: DefaultOptions;
handlers: HandlerFunction[];
mutableDefaults: boolean;
_rawHandlers?: HandlerFunction[];
}
export declare type URLOrOptions = Options | string;
export interface Progress {
percent: number;
transferred: number;
total?: number;
}
export interface GotEvents<T> {
on(name: 'request', listener: (request: http.ClientRequest) => void): T;
on(name: 'response', listener: (response: Response) => void): T;
on(name: 'redirect', listener: (response: Response, nextOptions: NormalizedOptions) => void): T;
on(name: 'uploadProgress' | 'downloadProgress', listener: (progress: Progress) => void): T;
}
export interface CancelableRequest<T extends Response | Response['body']> extends PCancelable<T>, GotEvents<CancelableRequest<T>> {
json<ReturnType>(): CancelableRequest<ReturnType>;
buffer(): CancelableRequest<Buffer>;
text(): CancelableRequest<string>;
}
export {};
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestSymbol = Symbol('request');
+1
View File
@@ -0,0 +1 @@
export default function deepFreeze<T extends object>(object: T): Readonly<T>;
+12
View File
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
function deepFreeze(object) {
for (const value of Object.values(object)) {
if (is_1.default.plainObject(value) || is_1.default.array(value)) {
deepFreeze(value);
}
}
return Object.freeze(object);
}
exports.default = deepFreeze;
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="node" />
declare const _default: (moduleObject: NodeModule, moduleId: string) => unknown;
export default _default;
+4
View File
@@ -0,0 +1,4 @@
"use strict";
/* istanbul ignore file: used for webpack */
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (moduleObject, moduleId) => moduleObject.require(moduleId);
+8
View File
@@ -0,0 +1,8 @@
/// <reference types="node" />
import { ClientRequestArgs } from 'http';
interface Options {
body?: unknown;
headers: ClientRequestArgs['headers'];
}
declare const _default: (options: Options) => Promise<number | undefined>;
export default _default;
+30
View File
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const util_1 = require("util");
const is_1 = require("@sindresorhus/is");
const is_form_data_1 = require("./is-form-data");
const statAsync = util_1.promisify(fs_1.stat);
exports.default = async (options) => {
const { body, headers } = options;
if (headers && 'content-length' in headers) {
return Number(headers['content-length']);
}
if (!body) {
return 0;
}
if (is_1.default.string(body)) {
return Buffer.byteLength(body);
}
if (is_1.default.buffer(body)) {
return body.length;
}
if (is_form_data_1.default(body)) {
return util_1.promisify(body.getLength.bind(body))();
}
if (body instanceof fs_1.ReadStream) {
const { size } = await statAsync(body.path);
return size;
}
return undefined;
};
+3
View File
@@ -0,0 +1,3 @@
import FormData = require('form-data');
declare const _default: (body: unknown) => body is FormData;
export default _default;
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
exports.default = (body) => is_1.default.nodeStream(body) && is_1.default.function_(body.getBoundary);
+6
View File
@@ -0,0 +1,6 @@
import { Merge } from 'type-fest';
export default function merge<Target extends {
[key: string]: any;
}, Source extends {
[key: string]: any;
}>(target: Target, ...sources: Source[]): Merge<Source, Target>;
+35
View File
@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const is_1 = require("@sindresorhus/is");
function merge(target, ...sources) {
for (const source of sources) {
for (const [key, sourceValue] of Object.entries(source)) {
const targetValue = target[key];
if (is_1.default.urlInstance(targetValue) && is_1.default.string(sourceValue)) {
// @ts-ignore TS doesn't recognise Target accepts string keys
target[key] = new url_1.URL(sourceValue, targetValue);
}
else if (is_1.default.plainObject(sourceValue)) {
if (is_1.default.plainObject(targetValue)) {
// @ts-ignore TS doesn't recognise Target accepts string keys
target[key] = merge({}, targetValue, sourceValue);
}
else {
// @ts-ignore TS doesn't recognise Target accepts string keys
target[key] = merge({}, sourceValue);
}
}
else if (is_1.default.array(sourceValue)) {
// @ts-ignore TS doesn't recognise Target accepts string keys
target[key] = sourceValue.slice();
}
else {
// @ts-ignore TS doesn't recognise Target accepts string keys
target[key] = sourceValue;
}
}
}
return target;
}
exports.default = merge;
+19
View File
@@ -0,0 +1,19 @@
/// <reference types="node" />
import { URL, URLSearchParams } from 'url';
export interface URLOptions {
href?: string;
origin?: string;
protocol?: string;
username?: string;
password?: string;
host?: string;
hostname?: string;
port?: string | number;
pathname?: string;
search?: string;
searchParams?: Record<string, string | number | boolean | null> | URLSearchParams | string;
hash?: string;
path?: string;
}
declare const _default: (options: URLOptions) => URL;
export default _default;
+82
View File
@@ -0,0 +1,82 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
function validateSearchParams(searchParams) {
for (const value of Object.values(searchParams)) {
if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' && value !== null) {
throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`);
}
}
}
const keys = [
'protocol',
'username',
'password',
'host',
'hostname',
'port',
'pathname',
'search',
'hash'
];
exports.default = (options) => {
var _a, _b;
let origin;
if (options.path) {
if (options.pathname) {
throw new TypeError('Parameters `path` and `pathname` are mutually exclusive.');
}
if (options.search) {
throw new TypeError('Parameters `path` and `search` are mutually exclusive.');
}
if (options.searchParams) {
throw new TypeError('Parameters `path` and `searchParams` are mutually exclusive.');
}
}
if (Reflect.has(options, 'auth')) {
throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
if (options.search && options.searchParams) {
throw new TypeError('Parameters `search` and `searchParams` are mutually exclusive.');
}
if (options.href) {
return new url_1.URL(options.href);
}
if (options.origin) {
origin = options.origin;
}
else {
if (!options.protocol) {
throw new TypeError('No URL protocol specified');
}
origin = `${options.protocol}//${_b = (_a = options.hostname, (_a !== null && _a !== void 0 ? _a : options.host)), (_b !== null && _b !== void 0 ? _b : '')}`;
}
const url = new url_1.URL(origin);
if (options.path) {
const searchIndex = options.path.indexOf('?');
if (searchIndex === -1) {
options.pathname = options.path;
}
else {
options.pathname = options.path.slice(0, searchIndex);
options.search = options.path.slice(searchIndex + 1);
}
}
if (Reflect.has(options, 'path')) {
delete options.path;
}
for (const key of keys) {
if (Reflect.has(options, key)) {
url[key] = options[key].toString();
}
}
if (options.searchParams) {
if (typeof options.searchParams !== 'string' && !(options.searchParams instanceof url_1.URLSearchParams)) {
validateSearchParams(options.searchParams);
}
(new url_1.URLSearchParams(options.searchParams)).forEach((value, key) => {
url.searchParams.append(key, value);
});
}
return url;
};
+2
View File
@@ -0,0 +1,2 @@
declare const _default: boolean;
export default _default;
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const zlib = require("zlib");
exports.default = typeof zlib.createBrotliDecompress === 'function';
+29
View File
@@ -0,0 +1,29 @@
import { ClientRequest } from 'http';
declare const reentry: unique symbol;
interface TimedOutOptions {
host?: string;
hostname?: string;
protocol?: string;
}
export interface Delays {
lookup?: number;
connect?: number;
secureConnect?: number;
socket?: number;
response?: number;
send?: number;
request?: number;
}
export declare type ErrorCode = 'ETIMEDOUT' | 'ECONNRESET' | 'EADDRINUSE' | 'ECONNREFUSED' | 'EPIPE' | 'ENOTFOUND' | 'ENETUNREACH' | 'EAI_AGAIN';
export declare class TimeoutError extends Error {
event: string;
code: ErrorCode;
constructor(threshold: number, event: string);
}
declare const _default: (request: ClientRequest, delays: Delays, options: TimedOutOptions) => () => void;
export default _default;
declare module 'http' {
interface ClientRequest {
[reentry]: boolean;
}
}
+125
View File
@@ -0,0 +1,125 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const net = require("net");
const unhandle_1 = require("./unhandle");
const reentry = Symbol('reentry');
const noop = () => { };
class TimeoutError extends Error {
constructor(threshold, event) {
super(`Timeout awaiting '${event}' for ${threshold}ms`);
this.event = event;
this.name = 'TimeoutError';
this.code = 'ETIMEDOUT';
}
}
exports.TimeoutError = TimeoutError;
exports.default = (request, delays, options) => {
if (Reflect.has(request, reentry)) {
return noop;
}
request[reentry] = true;
const cancelers = [];
const { once, unhandleAll } = unhandle_1.default();
const addTimeout = (delay, callback, event) => {
var _a, _b;
const timeout = setTimeout(callback, delay, delay, event);
(_b = (_a = timeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
const cancel = () => {
clearTimeout(timeout);
};
cancelers.push(cancel);
return cancel;
};
const { host, hostname } = options;
const timeoutHandler = (delay, event) => {
if (request.socket) {
// @ts-ignore We do not want the `socket hang up` error
request.socket._hadError = true;
}
request.abort();
request.emit('error', new TimeoutError(delay, event));
};
const cancelTimeouts = () => {
for (const cancel of cancelers) {
cancel();
}
unhandleAll();
};
request.once('error', error => {
cancelTimeouts();
// Save original behavior
if (request.listenerCount('error') === 0) {
throw error;
}
});
request.once('abort', cancelTimeouts);
once(request, 'response', (response) => {
once(response, 'end', cancelTimeouts);
});
if (typeof delays.request !== 'undefined') {
addTimeout(delays.request, timeoutHandler, 'request');
}
if (typeof delays.socket !== 'undefined') {
const socketTimeoutHandler = () => {
timeoutHandler(delays.socket, 'socket');
};
request.setTimeout(delays.socket, socketTimeoutHandler);
// `request.setTimeout(0)` causes a memory leak.
// We can just remove the listener and forget about the timer - it's unreffed.
// See https://github.com/sindresorhus/got/issues/690
cancelers.push(() => {
request.removeListener('timeout', socketTimeoutHandler);
});
}
once(request, 'socket', (socket) => {
var _a;
// @ts-ignore Node typings doesn't have this property
const { socketPath } = request;
/* istanbul ignore next: hard to test */
if (socket.connecting) {
const hasPath = Boolean((socketPath !== null && socketPath !== void 0 ? socketPath : net.isIP((_a = (hostname !== null && hostname !== void 0 ? hostname : host), (_a !== null && _a !== void 0 ? _a : ''))) !== 0));
if (typeof delays.lookup !== 'undefined' && !hasPath && typeof socket.address().address === 'undefined') {
const cancelTimeout = addTimeout(delays.lookup, timeoutHandler, 'lookup');
once(socket, 'lookup', cancelTimeout);
}
if (typeof delays.connect !== 'undefined') {
const timeConnect = () => addTimeout(delays.connect, timeoutHandler, 'connect');
if (hasPath) {
once(socket, 'connect', timeConnect());
}
else {
once(socket, 'lookup', (error) => {
if (error === null) {
once(socket, 'connect', timeConnect());
}
});
}
}
if (typeof delays.secureConnect !== 'undefined' && options.protocol === 'https:') {
once(socket, 'connect', () => {
const cancelTimeout = addTimeout(delays.secureConnect, timeoutHandler, 'secureConnect');
once(socket, 'secureConnect', cancelTimeout);
});
}
}
if (typeof delays.send !== 'undefined') {
const timeRequest = () => addTimeout(delays.send, timeoutHandler, 'send');
/* istanbul ignore next: hard to test */
if (socket.connecting) {
once(socket, 'connect', () => {
once(request, 'upload-complete', timeRequest());
});
}
else {
once(request, 'upload-complete', timeRequest());
}
}
});
if (typeof delays.response !== 'undefined') {
once(request, 'upload-complete', () => {
const cancelTimeout = addTimeout(delays.response, timeoutHandler, 'response');
once(request, 'response', cancelTimeout);
});
}
return cancelTimeouts;
};
+11
View File
@@ -0,0 +1,11 @@
/// <reference types="node" />
import EventEmitter = require('events');
declare type Origin = EventEmitter;
declare type Event = string | symbol;
declare type Fn = (...args: any[]) => void;
interface Unhandler {
once: (origin: Origin, event: Event, fn: Fn) => void;
unhandleAll: () => void;
}
declare const _default: () => Unhandler;
export default _default;
+22
View File
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// When attaching listeners, it's very easy to forget about them.
// Especially if you do error handling and set timeouts.
// So instead of checking if it's proper to throw an error on every timeout ever,
// use this simple tool which will remove all listeners you have attached.
exports.default = () => {
const handlers = [];
return {
once(origin, event, fn) {
origin.once(event, fn);
handlers.push({ origin, event, fn });
},
unhandleAll() {
for (const handler of handlers) {
const { origin, event, fn } = handler;
origin.removeListener(event, fn);
}
handlers.length = 0;
}
};
};
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="node" />
import { URL, UrlWithStringQuery } from 'url';
export interface LegacyUrlOptions {
protocol: string;
hostname: string;
host: string;
hash: string | null;
search: string | null;
pathname: string;
href: string;
path: string;
port?: number;
auth?: string;
}
declare const _default: (url: URL | UrlWithStringQuery) => LegacyUrlOptions;
export default _default;
+24
View File
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = require("@sindresorhus/is");
exports.default = (url) => {
// Cast to URL
url = url;
const options = {
protocol: url.protocol,
hostname: is_1.default.string(url.hostname) && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname,
host: url.host,
hash: url.hash,
search: url.search,
pathname: url.pathname,
href: url.href,
path: `${url.pathname || ''}${url.search || ''}`
};
if (is_1.default.string(url.port) && url.port.length !== 0) {
options.port = Number(url.port);
}
if (url.username || url.password) {
options.auth = `${url.username || ''}:${url.password || ''}`;
}
return options;
};
Generated Vendored
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+52
View File
@@ -0,0 +1,52 @@
'use strict';
const {PassThrough: PassThroughStream} = require('stream');
module.exports = options => {
options = {...options};
const {array} = options;
let {encoding} = options;
const isBuffer = encoding === 'buffer';
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || 'utf8';
}
if (isBuffer) {
encoding = null;
}
const stream = new PassThroughStream({objectMode});
if (encoding) {
stream.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream.on('data', chunk => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
};
stream.getBufferedLength = () => length;
return stream;
};
+108
View File
@@ -0,0 +1,108 @@
/// <reference types="node"/>
import {Stream} from 'stream';
declare class MaxBufferErrorClass extends Error {
readonly name: 'MaxBufferError';
constructor();
}
declare namespace getStream {
interface Options {
/**
Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `MaxBufferError` error.
@default Infinity
*/
readonly maxBuffer?: number;
}
interface OptionsWithEncoding<EncodingType = BufferEncoding> extends Options {
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream.
@default 'utf8'
*/
readonly encoding?: EncodingType;
}
type MaxBufferError = MaxBufferErrorClass;
}
declare const getStream: {
/**
Get the `stream` as a string.
@returns A promise that resolves when the end event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode.
@example
```
import * as fs from 'fs';
import getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
// ,,))))))));,
// __)))))))))))))),
// \|/ -\(((((''''((((((((.
// -*-==//////(('' . `)))))),
// /|\ ))| o ;-. '((((( ,(,
// ( `| / ) ;))))' ,_))^;(~
// | | | ,))((((_ _____------~~~-. %,;(;(>';'~
// o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
// ; ''''```` `: `:::|\,__,%% );`'; ~
// | _ ) / `:|`----' `-'
// ______/\/~ | / /
// /~;;.____/;;' / ___--,-( `;;;/
// / // _;______;'------~~~~~ /;;/\ /
// // | | / ; \;;,\
// (<_ | ; /',/-----' _>
// \_| ||_ //~;~~~~~~~~~
// `\_| (,~~
// \~\
// ~~
})();
```
*/
(stream: Stream, options?: getStream.OptionsWithEncoding): Promise<string>;
/**
Get the `stream` as a buffer.
It honors the `maxBuffer` option as above, but it refers to byte length rather than string length.
*/
buffer(
stream: Stream,
options?: getStream.OptionsWithEncoding
): Promise<Buffer>;
/**
Get the `stream` as an array of values.
It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen:
- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes).
- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array.
- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array.
*/
array<StreamObjectModeType>(
stream: Stream,
options?: getStream.Options
): Promise<StreamObjectModeType[]>;
array(
stream: Stream,
options: getStream.OptionsWithEncoding<'buffer'>
): Promise<Buffer[]>;
array(
stream: Stream,
options: getStream.OptionsWithEncoding<BufferEncoding>
): Promise<string[]>;
MaxBufferError: typeof MaxBufferErrorClass;
// TODO: Remove this for the next major release
default: typeof getStream;
};
export = getStream;
+60
View File
@@ -0,0 +1,60 @@
'use strict';
const {constants: BufferConstants} = require('buffer');
const pump = require('pump');
const bufferStream = require('./buffer-stream');
class MaxBufferError extends Error {
constructor() {
super('maxBuffer exceeded');
this.name = 'MaxBufferError';
}
}
async function getStream(inputStream, options) {
if (!inputStream) {
return Promise.reject(new Error('Expected a stream'));
}
options = {
maxBuffer: Infinity,
...options
};
const {maxBuffer} = options;
let stream;
await new Promise((resolve, reject) => {
const rejectPromise = error => {
// Don't retrieve an oversized buffer.
if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
error.bufferedData = stream.getBufferedValue();
}
reject(error);
};
stream = pump(inputStream, bufferStream(options), error => {
if (error) {
rejectPromise(error);
return;
}
resolve();
});
stream.on('data', () => {
if (stream.getBufferedLength() > maxBuffer) {
rejectPromise(new MaxBufferError());
}
});
});
return stream.getBufferedValue();
}
module.exports = getStream;
// TODO: Remove this for the next major release
module.exports.default = getStream;
module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});
module.exports.array = (stream, options) => getStream(stream, {...options, array: true});
module.exports.MaxBufferError = MaxBufferError;
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+50
View File
@@ -0,0 +1,50 @@
{
"name": "get-stream",
"version": "5.2.0",
"description": "Get a stream as a string, buffer, or array",
"license": "MIT",
"repository": "sindresorhus/get-stream",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts",
"buffer-stream.js"
],
"keywords": [
"get",
"stream",
"promise",
"concat",
"string",
"text",
"buffer",
"read",
"data",
"consume",
"readable",
"readablestream",
"array",
"object"
],
"dependencies": {
"pump": "^3.0.0"
},
"devDependencies": {
"@types/node": "^12.0.7",
"ava": "^2.0.0",
"into-stream": "^5.0.0",
"tsd": "^0.7.2",
"xo": "^0.24.0"
}
}
+124
View File
@@ -0,0 +1,124 @@
# get-stream [![Build Status](https://travis-ci.com/sindresorhus/get-stream.svg?branch=master)](https://travis-ci.com/github/sindresorhus/get-stream)
> Get a stream as a string, buffer, or array
## Install
```
$ npm install get-stream
```
## Usage
```js
const fs = require('fs');
const getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
/*
,,))))))));,
__)))))))))))))),
\|/ -\(((((''''((((((((.
-*-==//////(('' . `)))))),
/|\ ))| o ;-. '((((( ,(,
( `| / ) ;))))' ,_))^;(~
| | | ,))((((_ _____------~~~-. %,;(;(>';'~
o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
; ''''```` `: `:::|\,__,%% );`'; ~
| _ ) / `:|`----' `-'
______/\/~ | / /
/~;;.____/;;' / ___--,-( `;;;/
/ // _;______;'------~~~~~ /;;/\ /
// | | / ; \;;,\
(<_ | ; /',/-----' _>
\_| ||_ //~;~~~~~~~~~
`\_| (,~~
\~\
~~
*/
})();
```
## API
The methods returns a promise that resolves when the `end` event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode.
### getStream(stream, options?)
Get the `stream` as a string.
#### options
Type: `object`
##### encoding
Type: `string`\
Default: `'utf8'`
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream.
##### maxBuffer
Type: `number`\
Default: `Infinity`
Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `getStream.MaxBufferError` error.
### getStream.buffer(stream, options?)
Get the `stream` as a buffer.
It honors the `maxBuffer` option as above, but it refers to byte length rather than string length.
### getStream.array(stream, options?)
Get the `stream` as an array of values.
It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen:
- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes).
- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array.
- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array.
## Errors
If the input stream emits an `error` event, the promise will be rejected with the error. The buffered data will be attached to the `bufferedData` property of the error.
```js
(async () => {
try {
await getStream(streamThatErrorsAtTheEnd('unicorn'));
} catch (error) {
console.log(error.bufferedData);
//=> 'unicorn'
}
})()
```
## FAQ
### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)?
This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, buffer, or array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package.
## Related
- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-get-stream?utm_source=npm-get-stream&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
+2
View File
@@ -0,0 +1,2 @@
github: mafintosh
tidelift: "npm/pump"
+5
View File
@@ -0,0 +1,5 @@
language: node_js
node_js:
- "0.10"
script: "npm test"
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Mathias Buus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+74
View File
@@ -0,0 +1,74 @@
# pump
pump is a small node module that pipes streams together and destroys all of them if one of them closes.
```
npm install pump
```
[![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump)
## What problem does it solve?
When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error.
You are also not able to provide a callback to tell when then pipe has finished.
pump does these two things for you
## Usage
Simply pass the streams you want to pipe together to pump and add an optional callback
``` js
var pump = require('pump')
var fs = require('fs')
var source = fs.createReadStream('/dev/random')
var dest = fs.createWriteStream('/dev/null')
pump(source, dest, function(err) {
console.log('pipe finished', err)
})
setTimeout(function() {
dest.destroy() // when dest is closed pump will destroy source
}, 1000)
```
You can use pump to pipe more than two streams together as well
``` js
var transform = someTransformStream()
pump(source, transform, anotherTransform, dest, function(err) {
console.log('pipe finished', err)
})
```
If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed.
Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do:
```
return pump(s1, s2) // returns s2
```
Note that `pump` attaches error handlers to the streams to do internal error handling, so if `s2` emits an
error in the above scenario, it will not trigger a `proccess.on('uncaughtException')` if you do not listen for it.
If you want to return a stream that combines *both* s1 and s2 to a single stream use
[pumpify](https://github.com/mafintosh/pumpify) instead.
## License
MIT
## Related
`pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one.
## For enterprise
Available as part of the Tidelift Subscription.
The maintainers of pump and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-pump?utm_source=npm-pump&utm_medium=referral&utm_campaign=enterprise)
+5
View File
@@ -0,0 +1,5 @@
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
+1
View File
@@ -0,0 +1 @@
module.exports = null
+86
View File
@@ -0,0 +1,86 @@
var once = require('once')
var eos = require('end-of-stream')
var fs
try {
fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes
} catch (e) {}
var noop = function () {}
var ancient = typeof process === 'undefined' ? false : /^v?\.0/.test(process.version)
var isFn = function (fn) {
return typeof fn === 'function'
}
var isFS = function (stream) {
if (!ancient) return false // newer node version do not need to care about fs is a special way
if (!fs) return false // browser
return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close)
}
var isRequest = function (stream) {
return stream.setHeader && isFn(stream.abort)
}
var destroyer = function (stream, reading, writing, callback) {
callback = once(callback)
var closed = false
stream.on('close', function () {
closed = true
})
eos(stream, {readable: reading, writable: writing}, function (err) {
if (err) return callback(err)
closed = true
callback()
})
var destroyed = false
return function (err) {
if (closed) return
if (destroyed) return
destroyed = true
if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
if (isFn(stream.destroy)) return stream.destroy()
callback(err || new Error('stream was destroyed'))
}
}
var call = function (fn) {
fn()
}
var pipe = function (from, to) {
return from.pipe(to)
}
var pump = function () {
var streams = Array.prototype.slice.call(arguments)
var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop
if (Array.isArray(streams[0])) streams = streams[0]
if (streams.length < 2) throw new Error('pump requires two streams per minimum')
var error
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1
var writing = i > 0
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err
if (err) destroys.forEach(call)
if (reading) return
destroys.forEach(call)
callback(error)
})
})
return streams.reduce(pipe)
}
module.exports = pump
+30
View File
@@ -0,0 +1,30 @@
{
"name": "pump",
"version": "3.0.4",
"repository": "git://github.com/mafintosh/pump.git",
"license": "MIT",
"description": "pipe streams together and close all of them if one of them closes",
"browser": {
"fs": false
},
"imports": {
"fs": {
"bare": "./empty.js",
"default": "fs"
}
},
"keywords": [
"streams",
"pipe",
"destroy",
"callback"
],
"author": "Mathias Buus Madsen <mathiasbuus@gmail.com>",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
},
"scripts": {
"test": "node test-browser.js && node test-node.js"
}
}
+66
View File
@@ -0,0 +1,66 @@
var stream = require('stream')
var pump = require('./index')
var rs = new stream.Readable()
var ws = new stream.Writable()
rs._read = function (size) {
this.push(Buffer(size).fill('abc'))
}
ws._write = function (chunk, encoding, cb) {
setTimeout(function () {
cb()
}, 100)
}
var toHex = function () {
var reverse = new (require('stream').Transform)()
reverse._transform = function (chunk, enc, callback) {
reverse.push(chunk.toString('hex'))
callback()
}
return reverse
}
var wsClosed = false
var rsClosed = false
var callbackCalled = false
var check = function () {
if (wsClosed && rsClosed && callbackCalled) {
console.log('test-browser.js passes')
clearTimeout(timeout)
}
}
ws.on('finish', function () {
wsClosed = true
check()
})
rs.on('end', function () {
rsClosed = true
check()
})
var res = pump(rs, toHex(), toHex(), toHex(), ws, function () {
callbackCalled = true
check()
})
if (res !== ws) {
throw new Error('should return last stream')
}
setTimeout(function () {
rs.push(null)
rs.emit('close')
}, 1000)
var timeout = setTimeout(function () {
check()
throw new Error('timeout')
}, 5000)
+53
View File
@@ -0,0 +1,53 @@
var pump = require('./index')
var rs = require('fs').createReadStream('/dev/random')
var ws = require('fs').createWriteStream('/dev/null')
var toHex = function () {
var reverse = new (require('stream').Transform)()
reverse._transform = function (chunk, enc, callback) {
reverse.push(chunk.toString('hex'))
callback()
}
return reverse
}
var wsClosed = false
var rsClosed = false
var callbackCalled = false
var check = function () {
if (wsClosed && rsClosed && callbackCalled) {
console.log('test-node.js passes')
clearTimeout(timeout)
}
}
ws.on('close', function () {
wsClosed = true
check()
})
rs.on('close', function () {
rsClosed = true
check()
})
var res = pump(rs, toHex(), toHex(), toHex(), ws, function () {
callbackCalled = true
check()
})
if (res !== ws) {
throw new Error('should return last stream')
}
setTimeout(function () {
rs.destroy()
}, 1000)
var timeout = setTimeout(function () {
throw new Error('timeout')
}, 5000)
+21
View File
@@ -0,0 +1,21 @@
// Basic
export * from './source/basic';
// Utilities
export {Except} from './source/except';
export {Mutable} from './source/mutable';
export {Merge} from './source/merge';
export {MergeExclusive} from './source/merge-exclusive';
export {RequireAtLeastOne} from './source/require-at-least-one';
export {RequireExactlyOne} from './source/require-exactly-one';
export {PartialDeep} from './source/partial-deep';
export {ReadonlyDeep} from './source/readonly-deep';
export {LiteralUnion} from './source/literal-union';
export {Promisable} from './source/promisable';
export {Opaque} from './source/opaque';
export {SetOptional} from './source/set-optional';
export {SetRequired} from './source/set-required';
// Miscellaneous
export {PackageJson} from './source/package-json';
export {TsConfigJson} from './source/tsconfig-json';
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+53
View File
@@ -0,0 +1,53 @@
{
"name": "type-fest",
"version": "0.10.0",
"description": "A collection of essential TypeScript types",
"license": "(MIT OR CC0-1.0)",
"repository": "sindresorhus/type-fest",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && tsd"
},
"files": [
"index.d.ts",
"source"
],
"keywords": [
"typescript",
"ts",
"types",
"utility",
"util",
"utilities",
"omit",
"merge",
"json"
],
"devDependencies": {
"@sindresorhus/tsconfig": "^0.7.0",
"@typescript-eslint/eslint-plugin": "2.17.0",
"@typescript-eslint/parser": "2.17.0",
"eslint-config-xo-typescript": "^0.24.1",
"tsd": "^0.7.3",
"typescript": "3.7.5",
"xo": "^0.25.3"
},
"xo": {
"extends": "xo-typescript",
"extensions": [
"ts"
],
"rules": {
"import/no-unresolved": "off",
"@typescript-eslint/indent": "off"
}
}
}
+632
View File
@@ -0,0 +1,632 @@
<div align="center">
<br>
<br>
<img src="media/logo.svg" alt="type-fest" height="300">
<br>
<br>
<b>A collection of essential TypeScript types</b>
<br>
<hr>
</div>
<br>
<br>
[![Build Status](https://travis-ci.com/sindresorhus/type-fest.svg?branch=master)](https://travis-ci.com/sindresorhus/type-fest)
[![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
<!-- Commented out until they actually show anything
[![npm dependents](https://badgen.net/npm/dependents/type-fest)](https://www.npmjs.com/package/type-fest?activeTab=dependents) [![npm downloads](https://badgen.net/npm/dt/type-fest)](https://www.npmjs.com/package/type-fest)
-->
Many of the types here should have been built-in. You can help by suggesting some of them to the [TypeScript project](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md).
Either add this package as a dependency or copy-paste the needed types. No credit required. 👌
PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first.
## Install
```
$ npm install type-fest
```
*Requires TypeScript >=3.2*
## Usage
```ts
import {Except} from 'type-fest';
type Foo = {
unicorn: string;
rainbow: boolean;
};
type FooWithoutRainbow = Except<Foo, 'rainbow'>;
//=> {unicorn: string}
```
## API
Click the type names for complete docs.
### Basic
- [`Primitive`](source/basic.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
- [`Class`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
- [`TypedArray`](source/basic.d.ts) - Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
- [`JsonObject`](source/basic.d.ts) - Matches a JSON object.
- [`JsonArray`](source/basic.d.ts) - Matches a JSON array.
- [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value.
- [`ObservableLike`](source/basic.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
### Utilities
- [`Except`](source/except.d.ts) - Create a type from an object type without certain keys. This is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type).
- [`Mutable`](source/mutable.d.ts) - Convert an object with `readonly` keys into a mutable object. The inverse of `Readonly<T>`.
- [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type.
- [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys.
- [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys.
- [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more.
- [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) if you only need one level deep.
- [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) if you only need one level deep.
- [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729).
- [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`.
- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
### Miscellaneous
- [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file).
- [`TsConfigJson`](source/tsconfig-json.d.ts) - Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 3.7).
## Declined types
*If we decline a type addition, we will make sure to document the better solution here.*
- [`Diff` and `Spread`](https://github.com/sindresorhus/type-fest/pull/7) - The PR author didn't provide any real-world use-cases and the PR went stale. If you think this type is useful, provide some real-world use-cases and we might reconsider.
- [`Dictionary`](https://github.com/sindresorhus/type-fest/issues/33) - You only save a few characters (`Dictionary<number>` vs `Record<string, number>`) from [`Record`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434), which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have `Map` in JavaScript now.
## Tips
### Built-in types
There are many advanced types most users don't know about.
- [`Partial<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) - Make all properties in `T` optional.
<details>
<summary>
Example
</summary>
[Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA)
```ts
interface NodeConfig {
appName: string;
port: number;
}
class NodeAppBuilder {
private configuration: NodeConfig = {
appName: 'NodeApp',
port: 3000
};
private updateConfig<Key extends keyof NodeConfig>(key: Key, value: NodeConfig[Key]) {
this.configuration[key] = value;
}
config(config: Partial<NodeConfig>) {
type NodeConfigKey = keyof NodeConfig;
for (const key of Object.keys(config) as NodeConfigKey[]) {
const updateValue = config[key];
if (updateValue === undefined) {
continue;
}
this.updateConfig(key, updateValue);
}
return this;
}
}
// `Partial<NodeConfig>`` allows us to provide only a part of the
// NodeConfig interface.
new NodeAppBuilder().config({appName: 'ToDoApp'});
```
</details>
- [`Required<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1408-L1413) - Make all properties in `T` required.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA)
```ts
interface ContactForm {
email?: string;
message?: string;
}
function submitContactForm(formData: Required<ContactForm>) {
// Send the form data to the server.
}
submitContactForm({
email: 'ex@mple.com',
message: 'Hi! Could you tell me more about…',
});
// TypeScript error: missing property 'message'
submitContactForm({
email: 'ex@mple.com',
});
```
</details>
- [`Readonly<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) - Make all properties in `T` readonly.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA)
```ts
enum LogLevel {
Off,
Debug,
Error,
Fatal
};
interface LoggerConfig {
name: string;
level: LogLevel;
}
class Logger {
config: Readonly<LoggerConfig>;
constructor({name, level}: LoggerConfig) {
this.config = {name, level};
Object.freeze(this.config);
}
}
const config: LoggerConfig = {
name: 'MyApp',
level: LogLevel.Debug
};
const logger = new Logger(config);
// TypeScript Error: cannot assign to read-only property.
logger.config.level = LogLevel.Error;
// We are able to edit config variable as we please.
config.level = LogLevel.Error;
```
</details>
- [`Pick<T, K>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1422-L1427) - From `T`, pick a set of properties whose keys are in the union `K`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA)
```ts
interface Article {
title: string;
thumbnail: string;
content: string;
}
// Creates new type out of the `Article` interface composed
// from the Articles' two properties: `title` and `thumbnail`.
// `ArticlePreview = {title: string; thumbnail: string}`
type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>;
// Render a list of articles using only title and description.
function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement {
const articles = document.createElement('div');
for (const preview of previews) {
// Append preview to the articles.
}
return articles;
}
const articles = renderArticlePreviews([
{
title: 'TypeScript tutorial!',
thumbnail: '/assets/ts.jpg'
}
]);
```
</details>
- [`Record<K, T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434) - Construct a type with a set of properties `K` of type `T`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA)
```ts
// Positions of employees in our company.
type MemberPosition = 'intern' | 'developer' | 'tech-lead';
// Interface describing properties of a single employee.
interface Employee {
firstName: string;
lastName: string;
yearsOfExperience: number;
}
// Create an object that has all possible `MemberPosition` values set as keys.
// Those keys will store a collection of Employees of the same position.
const team: Record<MemberPosition, Employee[]> = {
intern: [],
developer: [],
'tech-lead': [],
};
// Our team has decided to help John with his dream of becoming Software Developer.
team.intern.push({
firstName: 'John',
lastName: 'Doe',
yearsOfExperience: 0
});
// `Record` forces you to initialize all of the property keys.
// TypeScript Error: "tech-lead" property is missing
const teamEmpty: Record<MemberPosition, null> = {
intern: null,
developer: null,
};
```
</details>
- [`Exclude<T, U>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1436-L1439) - Exclude from `T` those types that are assignable to `U`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA)
```ts
interface ServerConfig {
port: null | string | number;
}
type RequestHandler = (request: Request, response: Response) => void;
// Exclude `null` type from `null | string | number`.
// In case the port is equal to `null`, we will use default value.
function getPortValue(port: Exclude<ServerConfig['port'], null>): number {
if (typeof port === 'string') {
return parseInt(port, 10);
}
return port;
}
function startServer(handler: RequestHandler, config: ServerConfig): void {
const server = require('http').createServer(handler);
const port = config.port === null ? 3000 : getPortValue(config.port);
server.listen(port);
}
```
</details>
- [`Extract<T, U>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1441-L1444) - Extract from `T` those types that are assignable to `U`.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA)
```ts
declare function uniqueId(): number;
const ID = Symbol('ID');
interface Person {
[ID]: number;
name: string;
age: number;
}
// Allows changing the person data as long as the property key is of string type.
function changePersonData<
Obj extends Person,
Key extends Extract<keyof Person, string>,
Value extends Obj[Key]
> (obj: Obj, key: Key, value: Value): void {
obj[key] = value;
}
// Tiny Andrew was born.
const andrew = {
[ID]: uniqueId(),
name: 'Andrew',
age: 0,
};
// Cool, we're fine with that.
changePersonData(andrew, 'name', 'Pony');
// Goverment didn't like the fact that you wanted to change your identity.
changePersonData(andrew, ID, uniqueId());
```
</details>
- [`NonNullable<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1446-L1449) - Exclude `null` and `undefined` from `T`.
<details>
<summary>
Example
</summary>
Works with <code>strictNullChecks</code> set to <code>true</code>. (Read more <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html">here</a>)
[Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA)
```ts
type PortNumber = string | number | null;
/** Part of a class definition that is used to build a server */
class ServerBuilder {
portNumber!: NonNullable<PortNumber>;
port(this: ServerBuilder, port: PortNumber): ServerBuilder {
if (port == null) {
this.portNumber = 8000;
} else {
this.portNumber = port;
}
return this;
}
}
const serverBuilder = new ServerBuilder();
serverBuilder
.port('8000') // portNumber = '8000'
.port(null) // portNumber = 8000
.port(3000); // portNumber = 3000
// TypeScript error
serverBuilder.portNumber = null;
```
</details>
- [`Parameters<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1451-L1454) - Obtain the parameters of a function type in a tuple.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA)
```ts
function shuffle(input: any[]): void {
// Mutate array randomly changing its' elements indexes.
}
function callNTimes<Fn extends (...args: any[]) => any> (func: Fn, callCount: number) {
// Type that represents the type of the received function parameters.
type FunctionParameters = Parameters<Fn>;
return function (...args: FunctionParameters) {
for (let i = 0; i < callCount; i++) {
func(...args);
}
}
}
const shuffleTwice = callNTimes(shuffle, 2);
```
</details>
- [`ConstructorParameters<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1456-L1459) - Obtain the parameters of a constructor function type in a tuple.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA)
```ts
class ArticleModel {
title: string;
content?: string;
constructor(title: string) {
this.title = title;
}
}
class InstanceCache<T extends (new (...args: any[]) => any)> {
private ClassConstructor: T;
private cache: Map<string, InstanceType<T>> = new Map();
constructor (ctr: T) {
this.ClassConstructor = ctr;
}
getInstance (...args: ConstructorParameters<T>): InstanceType<T> {
const hash = this.calculateArgumentsHash(...args);
const existingInstance = this.cache.get(hash);
if (existingInstance !== undefined) {
return existingInstance;
}
return new this.ClassConstructor(...args);
}
private calculateArgumentsHash(...args: any[]): string {
// Calculate hash.
return 'hash';
}
}
const articleCache = new InstanceCache(ArticleModel);
const amazonArticle = articleCache.getInstance('Amazon forests burining!');
```
</details>
- [`ReturnType<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1461-L1464) Obtain the return type of a function type.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
```ts
/** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */
function mapIter<
Elem,
Func extends (elem: Elem) => any,
Ret extends ReturnType<Func>
>(iter: Iterable<Elem>, callback: Func): Ret[] {
const mapped: Ret[] = [];
for (const elem of iter) {
mapped.push(callback(elem));
}
return mapped;
}
const setObject: Set<string> = new Set();
const mapObject: Map<number, string> = new Map();
mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[]
mapIter(mapObject, ([key, value]: [number, string]) => {
return key % 2 === 0 ? value : 'Odd';
}); // string[]
```
</details>
- [`InstanceType<T>`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1466-L1469) Obtain the instance type of a constructor function type.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)
```ts
class IdleService {
doNothing (): void {}
}
class News {
title: string;
content: string;
constructor(title: string, content: string) {
this.title = title;
this.content = content;
}
}
const instanceCounter: Map<Function, number> = new Map();
interface Constructor {
new(...args: any[]): any;
}
// Keep track how many instances of `Constr` constructor have been created.
function getInstance<
Constr extends Constructor,
Args extends ConstructorParameters<Constr>
>(constructor: Constr, ...args: Args): InstanceType<Constr> {
let count = instanceCounter.get(constructor) || 0;
const instance = new constructor(...args);
instanceCounter.set(constructor, count + 1);
console.log(`Created ${count + 1} instances of ${Constr.name} class`);
return instance;
}
const idleService = getInstance(IdleService);
// Will log: `Created 1 instances of IdleService class`
const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...');
// Will log: `Created 1 instances of News class`
```
</details>
- [`Omit<T, K>`](https://github.com/microsoft/TypeScript/blob/71af02f7459dc812e85ac31365bfe23daf14b4e4/src/lib/es5.d.ts#L1446) Constructs a type by picking all properties from T and then removing K.
<details>
<summary>
Example
</summary>
[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA)
```ts
interface Animal {
imageUrl: string;
species: string;
images: string[];
paragraphs: string[];
}
// Creates new type with all properties of the `Animal` interface
// except 'images' and 'paragraphs' properties. We can use this
// type to render small hover tooltip for a wiki entry list.
type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>;
function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement {
const container = document.createElement('div');
// Internal implementation.
return container;
}
```
</details>
You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#predefined-conditional-types).
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Jarek Radosz](https://github.com/CvX)
- [Dimitri Benin](https://github.com/BendingBender)
## License
(MIT OR CC0-1.0)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-type-fest?utm_source=npm-type-fest&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
+67
View File
@@ -0,0 +1,67 @@
/// <reference lib="esnext"/>
// TODO: This can just be `export type Primitive = not object` when the `not` keyword is out.
/**
Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
*/
export type Primitive =
| null
| undefined
| string
| number
| boolean
| symbol
| bigint;
// TODO: Remove the `= unknown` sometime in the future when most users are on TS 3.5 as it's now the default
/**
Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
*/
export type Class<T = unknown, Arguments extends any[] = any[]> = new(...arguments_: Arguments) => T;
/**
Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
*/
export type TypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| BigInt64Array
| BigUint64Array;
/**
Matches a JSON object.
This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`.
*/
export type JsonObject = {[key: string]: JsonValue};
/**
Matches a JSON array.
*/
export interface JsonArray extends Array<JsonValue> {}
/**
Matches any valid JSON value.
*/
export type JsonValue = string | number | boolean | null | JsonObject | JsonArray;
declare global {
interface SymbolConstructor {
readonly observable: symbol;
}
}
/**
Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
*/
export interface ObservableLike {
subscribe(observer: (value: unknown) => void): void;
[Symbol.observable](): ObservableLike;
}
+22
View File
@@ -0,0 +1,22 @@
/**
Create a type from an object type without certain keys.
This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/30825) if you want to have the stricter version as a built-in in TypeScript.
@example
```
import {Except} from 'type-fest';
type Foo = {
a: number;
b: string;
c: boolean;
};
type FooWithoutA = Except<Foo, 'a' | 'c'>;
//=> {b: string};
```
*/
export type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
+33
View File
@@ -0,0 +1,33 @@
import {Primitive} from './basic';
/**
Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union.
Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals.
This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore.
@example
```
import {LiteralUnion} from 'type-fest';
// Before
type Pet = 'dog' | 'cat' | string;
const pet: Pet = '';
// Start typing in your TypeScript-enabled IDE.
// You **will not** get auto-completion for `dog` and `cat` literals.
// After
type Pet2 = LiteralUnion<'dog' | 'cat', string>;
const pet: Pet2 = '';
// You **will** get auto-completion for `dog` and `cat` literals.
```
*/
export type LiteralUnion<
LiteralType extends BaseType,
BaseType extends Primitive
> = LiteralType | (BaseType & {_?: never});
+39
View File
@@ -0,0 +1,39 @@
// Helper type. Not useful on its own.
type Without<FirstType, SecondType> = {[KeyType in Exclude<keyof FirstType, keyof SecondType>]?: never};
/**
Create a type that has mutually exclusive keys.
This type was inspired by [this comment](https://github.com/Microsoft/TypeScript/issues/14094#issuecomment-373782604).
This type works with a helper type, called `Without`. `Without<FirstType, SecondType>` produces a type that has only keys from `FirstType` which are not present on `SecondType` and sets the value type for these keys to `never`. This helper type is then used in `MergeExclusive` to remove keys from either `FirstType` or `SecondType`.
@example
```
import {MergeExclusive} from 'type-fest';
interface ExclusiveVariation1 {
exclusive1: boolean;
}
interface ExclusiveVariation2 {
exclusive2: string;
}
type ExclusiveOptions = MergeExclusive<ExclusiveVariation1, ExclusiveVariation2>;
let exclusiveOptions: ExclusiveOptions;
exclusiveOptions = {exclusive1: true};
//=> Works
exclusiveOptions = {exclusive2: 'hi'};
//=> Works
exclusiveOptions = {exclusive1: true, exclusive2: 'hi'};
//=> Error
```
*/
export type MergeExclusive<FirstType, SecondType> =
(FirstType | SecondType) extends object ?
(Without<FirstType, SecondType> & SecondType) | (Without<SecondType, FirstType> & FirstType) :
FirstType | SecondType;
+22
View File
@@ -0,0 +1,22 @@
import {Except} from './except';
/**
Merge two types into a new type. Keys of the second type overrides keys of the first type.
@example
```
import {Merge} from 'type-fest';
type Foo = {
a: number;
b: string;
};
type Bar = {
b: number;
};
const ab: Merge<Foo, Bar> = {a: 1, b: 2};
```
*/
export type Merge<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
+22
View File
@@ -0,0 +1,22 @@
/**
Convert an object with `readonly` keys into a mutable object. Inverse of `Readonly<T>`.
This can be used to [store and mutate options within a class](https://github.com/sindresorhus/pageres/blob/4a5d05fca19a5fbd2f53842cbf3eb7b1b63bddd2/source/index.ts#L72), [edit `readonly` objects within tests](https://stackoverflow.com/questions/50703834), and [construct a `readonly` object within a function](https://github.com/Microsoft/TypeScript/issues/24509).
@example
```
import {Mutable} from 'type-fest';
type Foo = {
readonly a: number;
readonly b: string;
};
const mutableFoo: Mutable<Foo> = {a: 1, b: '2'};
mutableFoo.a = 3;
```
*/
export type Mutable<ObjectType> = {
// For each `Key` in the keys of `ObjectType`, make a mapped type by removing the `readonly` modifier from the key.
-readonly [KeyType in keyof ObjectType]: ObjectType[KeyType];
};
+65
View File
@@ -0,0 +1,65 @@
/**
Create an opaque type, which hides its internal details from the public, and can only be created by being used explicitly.
The generic type parameter can be anything. It doesn't have to be an object.
[Read more about opaque types.](https://codemix.com/opaque-types-in-javascript/)
There have been several discussions about adding this feature to TypeScript via the `opaque type` operator, similar to how Flow does it. Unfortunately, nothing has (yet) moved forward:
- [Microsoft/TypeScript#15408](https://github.com/Microsoft/TypeScript/issues/15408)
- [Microsoft/TypeScript#15807](https://github.com/Microsoft/TypeScript/issues/15807)
@example
```
import {Opaque} from 'type-fest';
type AccountNumber = Opaque<number, 'AccountNumber'>;
type AccountBalance = Opaque<number, 'AccountBalance'>;
// The Token parameter allows the compiler to differentiate between types, whereas "unknown" will not. For example, consider the following structures:
type ThingOne = Opaque<string>;
type ThingTwo = Opaque<string>;
// To the compiler, these types are allowed to be cast to each other as they have the same underlying type. They are both `string & { __opaque__: unknown }`.
// To avoid this behaviour, you would instead pass the "Token" parameter, like so.
type NewThingOne = Opaque<string, 'ThingOne'>;
type NewThingTwo = Opaque<string, 'ThingTwo'>;
// Now they're completely separate types, so the following will fail to compile.
function createNewThingOne (): NewThingOne {
// As you can see, casting from a string is still allowed. However, you may not cast NewThingOne to NewThingTwo, and vice versa.
return 'new thing one' as NewThingOne;
}
// This will fail to compile, as they are fundamentally different types.
const thingTwo = createNewThingOne() as NewThingTwo;
// Here's another example of opaque typing.
function createAccountNumber(): AccountNumber {
return 2 as AccountNumber;
}
function getMoneyForAccount(accountNumber: AccountNumber): AccountBalance {
return 4 as AccountBalance;
}
// This will compile successfully.
getMoneyForAccount(createAccountNumber());
// But this won't, because it has to be explicitly passed as an `AccountNumber` type.
getMoneyForAccount(2);
// You can use opaque values like they aren't opaque too.
const accountNumber = createAccountNumber();
// This will not compile successfully.
const newAccountNumber = accountNumber + 2;
// As a side note, you can (and should) use recursive types for your opaque types to make them stronger and hopefully easier to type.
type Person = {
id: Opaque<number, Person>;
name: string;
};
```
*/
export type Opaque<Type, Token = unknown> = Type & {readonly __opaque__: Token};
+548
View File
@@ -0,0 +1,548 @@
import {LiteralUnion} from '..';
declare namespace PackageJson {
/**
A person who has been involved in creating or maintaining the package.
*/
export type Person =
| string
| {
name: string;
url?: string;
email?: string;
};
export type BugsLocation =
| string
| {
/**
The URL to the package's issue tracker.
*/
url?: string;
/**
The email address to which issues should be reported.
*/
email?: string;
};
export interface DirectoryLocations {
[directoryType: string]: unknown;
/**
Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder.
*/
bin?: string;
/**
Location for Markdown files.
*/
doc?: string;
/**
Location for example scripts.
*/
example?: string;
/**
Location for the bulk of the library.
*/
lib?: string;
/**
Location for man pages. Sugar to generate a `man` array by walking the folder.
*/
man?: string;
/**
Location for test files.
*/
test?: string;
}
export type Scripts = {
/**
Run **before** the package is published (Also run on local `npm install` without any arguments).
*/
prepublish?: string;
/**
Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`.
*/
prepare?: string;
/**
Run **before** the package is prepared and packed, **only** on `npm publish`.
*/
prepublishOnly?: string;
/**
Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies).
*/
prepack?: string;
/**
Run **after** the tarball has been generated and moved to its final destination.
*/
postpack?: string;
/**
Run **after** the package is published.
*/
publish?: string;
/**
Run **after** the package is published.
*/
postpublish?: string;
/**
Run **before** the package is installed.
*/
preinstall?: string;
/**
Run **after** the package is installed.
*/
install?: string;
/**
Run **after** the package is installed and after `install`.
*/
postinstall?: string;
/**
Run **before** the package is uninstalled and before `uninstall`.
*/
preuninstall?: string;
/**
Run **before** the package is uninstalled.
*/
uninstall?: string;
/**
Run **after** the package is uninstalled.
*/
postuninstall?: string;
/**
Run **before** bump the package version and before `version`.
*/
preversion?: string;
/**
Run **before** bump the package version.
*/
version?: string;
/**
Run **after** bump the package version.
*/
postversion?: string;
/**
Run with the `npm test` command, before `test`.
*/
pretest?: string;
/**
Run with the `npm test` command.
*/
test?: string;
/**
Run with the `npm test` command, after `test`.
*/
posttest?: string;
/**
Run with the `npm stop` command, before `stop`.
*/
prestop?: string;
/**
Run with the `npm stop` command.
*/
stop?: string;
/**
Run with the `npm stop` command, after `stop`.
*/
poststop?: string;
/**
Run with the `npm start` command, before `start`.
*/
prestart?: string;
/**
Run with the `npm start` command.
*/
start?: string;
/**
Run with the `npm start` command, after `start`.
*/
poststart?: string;
/**
Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
*/
prerestart?: string;
/**
Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
*/
restart?: string;
/**
Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided.
*/
postrestart?: string;
} & {
[scriptName: string]: string;
};
/**
Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL.
*/
export interface Dependency {
[packageName: string]: string;
}
export interface NonStandardEntryPoints {
/**
An ECMAScript module ID that is the primary entry point to the program.
*/
module?: string;
/**
A module ID with untranspiled code that is the primary entry point to the program.
*/
esnext?:
| string
| {
[moduleName: string]: string | undefined;
main?: string;
browser?: string;
};
/**
A hint to JavaScript bundlers or component tools when packaging modules for client side use.
*/
browser?:
| string
| {
[moduleName: string]: string | false;
};
/**
Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused.
[Read more.](https://webpack.js.org/guides/tree-shaking/)
*/
sideEffects?: boolean | string[];
}
export interface TypeScriptConfiguration {
/**
Location of the bundled TypeScript declaration file.
*/
types?: string;
/**
Location of the bundled TypeScript declaration file. Alias of `types`.
*/
typings?: string;
}
export interface YarnConfiguration {
/**
If your package only allows one version of a given dependency, and youd like to enforce the same behavior as `yarn install --flat` on the command line, set this to `true`.
Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an application), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line.
*/
flat?: boolean;
/**
Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file.
*/
resolutions?: Dependency;
}
export interface JSPMConfiguration {
/**
JSPM configuration.
*/
jspm?: PackageJson;
}
}
/**
Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn.
*/
export type PackageJson = {
/**
The name of the package.
*/
name?: string;
/**
Package version, parseable by [`node-semver`](https://github.com/npm/node-semver).
*/
version?: string;
/**
Package description, listed in `npm search`.
*/
description?: string;
/**
Keywords associated with package, listed in `npm search`.
*/
keywords?: string[];
/**
The URL to the package's homepage.
*/
homepage?: LiteralUnion<'.', string>;
/**
The URL to the package's issue tracker and/or the email address to which issues should be reported.
*/
bugs?: PackageJson.BugsLocation;
/**
The license for the package.
*/
license?: string;
/**
The licenses for the package.
*/
licenses?: Array<{
type?: string;
url?: string;
}>;
author?: PackageJson.Person;
/**
A list of people who contributed to the package.
*/
contributors?: PackageJson.Person[];
/**
A list of people who maintain the package.
*/
maintainers?: PackageJson.Person[];
/**
The files included in the package.
*/
files?: string[];
/**
The module ID that is the primary entry point to the program.
*/
main?: string;
/**
The executable files that should be installed into the `PATH`.
*/
bin?:
| string
| {
[binary: string]: string;
};
/**
Filenames to put in place for the `man` program to find.
*/
man?: string | string[];
/**
Indicates the structure of the package.
*/
directories?: PackageJson.DirectoryLocations;
/**
Location for the code repository.
*/
repository?:
| string
| {
type: string;
url: string;
/**
Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo).
[Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md)
*/
directory?: string;
};
/**
Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point.
*/
scripts?: PackageJson.Scripts;
/**
Is used to set configuration parameters used in package scripts that persist across upgrades.
*/
config?: {
[configKey: string]: unknown;
};
/**
The dependencies of the package.
*/
dependencies?: PackageJson.Dependency;
/**
Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling.
*/
devDependencies?: PackageJson.Dependency;
/**
Dependencies that are skipped if they fail to install.
*/
optionalDependencies?: PackageJson.Dependency;
/**
Dependencies that will usually be required by the package user directly or via another dependency.
*/
peerDependencies?: PackageJson.Dependency;
/**
Indicate peer dependencies that are optional.
*/
peerDependenciesMeta?: {
[packageName: string]: {
optional: true;
};
};
/**
Package names that are bundled when the package is published.
*/
bundledDependencies?: string[];
/**
Alias of `bundledDependencies`.
*/
bundleDependencies?: string[];
/**
Engines that this package runs on.
*/
engines?: {
[EngineName in 'npm' | 'node' | string]: string;
};
/**
@deprecated
*/
engineStrict?: boolean;
/**
Operating systems the module runs on.
*/
os?: Array<LiteralUnion<
| 'aix'
| 'darwin'
| 'freebsd'
| 'linux'
| 'openbsd'
| 'sunos'
| 'win32'
| '!aix'
| '!darwin'
| '!freebsd'
| '!linux'
| '!openbsd'
| '!sunos'
| '!win32',
string
>>;
/**
CPU architectures the module runs on.
*/
cpu?: Array<LiteralUnion<
| 'arm'
| 'arm64'
| 'ia32'
| 'mips'
| 'mipsel'
| 'ppc'
| 'ppc64'
| 's390'
| 's390x'
| 'x32'
| 'x64'
| '!arm'
| '!arm64'
| '!ia32'
| '!mips'
| '!mipsel'
| '!ppc'
| '!ppc64'
| '!s390'
| '!s390x'
| '!x32'
| '!x64',
string
>>;
/**
If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally.
@deprecated
*/
preferGlobal?: boolean;
/**
If set to `true`, then npm will refuse to publish it.
*/
private?: boolean;
/**
A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default.
*/
publishConfig?: {
[config: string]: unknown;
};
/**
Describes and notifies consumers of a package's monetary support information.
[Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md)
*/
funding?: string | {
/**
The type of funding.
*/
type?: LiteralUnion<
| 'github'
| 'opencollective'
| 'patreon'
| 'individual'
| 'foundation'
| 'corporation',
string
>;
/**
The URL to the funding page.
*/
url: string;
};
} &
PackageJson.NonStandardEntryPoints &
PackageJson.TypeScriptConfiguration &
PackageJson.YarnConfiguration &
PackageJson.JSPMConfiguration & {
[key: string]: unknown;
};
+72
View File
@@ -0,0 +1,72 @@
import {Primitive} from './basic';
/**
Create a type from another type with all keys and nested keys set to optional.
Use-cases:
- Merging a default settings/config object with another object, the second object would be a deep partial of the default object.
- Mocking and testing complex entities, where populating an entire object with its keys would be redundant in terms of the mock or test.
@example
```
import {PartialDeep} from 'type-fest';
const settings: Settings = {
textEditor: {
fontSize: 14;
fontColor: '#000000';
fontWeight: 400;
}
autocomplete: false;
autosave: true;
};
const applySavedSettings = (savedSettings: PartialDeep<Settings>) => {
return {...settings, ...savedSettings};
}
settings = applySavedSettings({textEditor: {fontWeight: 500}});
```
*/
export type PartialDeep<T> = T extends Primitive
? Partial<T>
: T extends Map<infer KeyType, infer ValueType>
? PartialMapDeep<KeyType, ValueType>
: T extends Set<infer ItemType>
? PartialSetDeep<ItemType>
: T extends ReadonlyMap<infer KeyType, infer ValueType>
? PartialReadonlyMapDeep<KeyType, ValueType>
: T extends ReadonlySet<infer ItemType>
? PartialReadonlySetDeep<ItemType>
: T extends ((...arguments: any[]) => unknown)
? T | undefined
: T extends object
? PartialObjectDeep<T>
: unknown;
/**
Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`.
*/
interface PartialMapDeep<KeyType, ValueType> extends Map<PartialDeep<KeyType>, PartialDeep<ValueType>> {}
/**
Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`.
*/
interface PartialSetDeep<T> extends Set<PartialDeep<T>> {}
/**
Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`.
*/
interface PartialReadonlyMapDeep<KeyType, ValueType> extends ReadonlyMap<PartialDeep<KeyType>, PartialDeep<ValueType>> {}
/**
Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`.
*/
interface PartialReadonlySetDeep<T> extends ReadonlySet<PartialDeep<T>> {}
/**
Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`.
*/
type PartialObjectDeep<ObjectType extends object> = {
[KeyType in keyof ObjectType]?: PartialDeep<ObjectType[KeyType]>
};
+23
View File
@@ -0,0 +1,23 @@
/**
Create a type that represents either the value or the value wrapped in `PromiseLike`.
Use-cases:
- A function accepts a callback that may either return a value synchronously or may return a promised value.
- This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks.
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript.
@example
```
import {Promisable} from 'type-fest';
async function logger(getLogEntry: () => Promisable<string>): Promise<void> {
const entry = await getLogEntry();
console.log(entry);
}
logger(() => 'foo');
logger(() => Promise.resolve('bar'));
```
*/
export type Promisable<T> = T | PromiseLike<T>;
+59
View File
@@ -0,0 +1,59 @@
import {Primitive} from './basic';
/**
Convert `object`s, `Map`s, `Set`s, and `Array`s and all of their keys/elements into immutable structures recursively.
This is useful when a deeply nested structure needs to be exposed as completely immutable, for example, an imported JSON module or when receiving an API response that is passed around.
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/13923) if you want to have this type as a built-in in TypeScript.
@example
```
// data.json
{
"foo": ["bar"]
}
// main.ts
import {ReadonlyDeep} from 'type-fest';
import dataJson = require('./data.json');
const data: ReadonlyDeep<typeof dataJson> = dataJson;
export default data;
// test.ts
import data from './main';
data.foo.push('bar');
//=> error TS2339: Property 'push' does not exist on type 'readonly string[]'
```
*/
export type ReadonlyDeep<T> = T extends Primitive | ((...arguments: any[]) => unknown)
? T
: T extends ReadonlyMap<infer KeyType, infer ValueType>
? ReadonlyMapDeep<KeyType, ValueType>
: T extends ReadonlySet<infer ItemType>
? ReadonlySetDeep<ItemType>
: T extends object
? ReadonlyObjectDeep<T>
: unknown;
/**
Same as `ReadonlyDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `ReadonlyDeep`.
*/
interface ReadonlyMapDeep<KeyType, ValueType>
extends ReadonlyMap<ReadonlyDeep<KeyType>, ReadonlyDeep<ValueType>> {}
/**
Same as `ReadonlyDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `ReadonlyDeep`.
*/
interface ReadonlySetDeep<ItemType>
extends ReadonlySet<ReadonlyDeep<ItemType>> {}
/**
Same as `ReadonlyDeep`, but accepts only `object`s as inputs. Internal helper for `ReadonlyDeep`.
*/
type ReadonlyObjectDeep<ObjectType extends object> = {
readonly [KeyType in keyof ObjectType]: ReadonlyDeep<ObjectType[KeyType]>
};
@@ -0,0 +1,32 @@
import {Except} from './except';
/**
Create a type that requires at least one of the given keys. The remaining keys are kept as is.
@example
```
import {RequireAtLeastOne} from 'type-fest';
type Responder = {
text?: () => string;
json?: () => string;
secure?: boolean;
};
const responder: RequireAtLeastOne<Responder, 'text' | 'json'> = {
json: () => '{"message": "ok"}',
secure: true
};
```
*/
export type RequireAtLeastOne<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> =
{
// For each Key in KeysType make a mapped type
[Key in KeysType]: (
// …by picking that Key's type and making it required
Required<Pick<ObjectType, Key>>
)
}[KeysType]
// …then, make intersection types by adding the remaining keys to each mapped type.
& Except<ObjectType, KeysType>;
@@ -0,0 +1,36 @@
// TODO: Remove this when we target TypeScript >=3.5.
// eslint-disable-next-line @typescript-eslint/generic-type-naming
type _Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
/**
Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is.
Use-cases:
- Creating interfaces for components that only need one of the keys to display properly.
- Declaring generic keys in a single place for a single use-case that gets narrowed down via `RequireExactlyOne`.
The caveat with `RequireExactlyOne` is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore `RequireExactlyOne` can't do anything to prevent extra keys it doesn't know about.
@example
```
import {RequireExactlyOne} from 'type-fest';
type Responder = {
text: () => string;
json: () => string;
secure: boolean;
};
const responder: RequireExactlyOne<Responder, 'text' | 'json'> = {
// Adding a `text` key here would cause a compile error.
json: () => '{"message": "ok"}',
secure: true
};
```
*/
export type RequireExactlyOne<ObjectType, KeysType extends keyof ObjectType = keyof ObjectType> =
{[Key in KeysType]: (
Required<Pick<ObjectType, Key>> &
Partial<Record<Exclude<KeysType, Key>, never>>
)}[KeysType] & _Omit<ObjectType, KeysType>;
+32
View File
@@ -0,0 +1,32 @@
/**
Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type.
Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional.
@example
```
import {SetOptional} from 'type-fest';
type Foo = {
a: number;
b?: string;
c: boolean;
}
type SomeOptional = SetOptional<Foo, 'b' | 'c'>;
// type SomeOptional = {
// a: number;
// b?: string; // Was already optional and still is.
// c?: boolean; // Is now optional.
// }
```
*/
export type SetOptional<BaseType, Keys extends keyof BaseType = keyof BaseType> =
// Pick just the keys that are not optional from the base type.
Pick<BaseType, Exclude<keyof BaseType, Keys>> &
// Pick the keys that should be optional from the base type and make them optional.
Partial<Pick<BaseType, Keys>> extends
// If `InferredType` extends the previous, then for each key, use the inferred type key.
infer InferredType
? {[KeyType in keyof InferredType]: InferredType[KeyType]}
: never;
+32
View File
@@ -0,0 +1,32 @@
/**
Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type.
Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required.
@example
```
import {SetRequired} from 'type-fest';
type Foo = {
a?: number;
b: string;
c?: boolean;
}
type SomeRequired = SetRequired<Foo, 'b' | 'c'>;
// type SomeRequired = {
// a?: number;
// b: string; // Was already required and still is.
// c: boolean; // Is now required.
// }
```
*/
export type SetRequired<BaseType, Keys extends keyof BaseType = keyof BaseType> =
// Pick just the keys that are not required from the base type.
Pick<BaseType, Exclude<keyof BaseType, Keys>> &
// Pick the keys that should be required from the base type and make them required.
Required<Pick<BaseType, Keys>> extends
// If `InferredType` extends the previous, then for each key, use the inferred type key.
infer InferredType
? {[KeyType in keyof InferredType]: InferredType[KeyType]}
: never;
+872
View File
@@ -0,0 +1,872 @@
declare namespace TsConfigJson {
namespace CompilerOptions {
export type JSX =
| 'preserve'
| 'react'
| 'react-native';
export type Module =
| 'CommonJS'
| 'AMD'
| 'System'
| 'UMD'
| 'ES6'
| 'ES2015'
| 'ESNext'
| 'None'
// Lowercase alternatives
| 'commonjs'
| 'amd'
| 'system'
| 'umd'
| 'es6'
| 'es2015'
| 'esnext'
| 'none';
export type NewLine =
| 'CRLF'
| 'LF'
// Lowercase alternatives
| 'crlf'
| 'lf';
export type Target =
| 'ES3'
| 'ES5'
| 'ES6'
| 'ES2015'
| 'ES2016'
| 'ES2017'
| 'ES2018'
| 'ES2019'
| 'ES2020'
| 'ESNext'
// Lowercase alternatives
| 'es3'
| 'es5'
| 'es6'
| 'es2015'
| 'es2016'
| 'es2017'
| 'es2018'
| 'es2019'
| 'es2020'
| 'esnext';
export type Lib =
| 'ES5'
| 'ES6'
| 'ES7'
| 'ES2015'
| 'ES2015.Collection'
| 'ES2015.Core'
| 'ES2015.Generator'
| 'ES2015.Iterable'
| 'ES2015.Promise'
| 'ES2015.Proxy'
| 'ES2015.Reflect'
| 'ES2015.Symbol.WellKnown'
| 'ES2015.Symbol'
| 'ES2016'
| 'ES2016.Array.Include'
| 'ES2017'
| 'ES2017.Intl'
| 'ES2017.Object'
| 'ES2017.SharedMemory'
| 'ES2017.String'
| 'ES2017.TypedArrays'
| 'ES2018'
| 'ES2018.AsyncIterable'
| 'ES2018.Intl'
| 'ES2018.Promise'
| 'ES2018.Regexp'
| 'ES2019'
| 'ES2019.Array'
| 'ES2019.Object'
| 'ES2019.String'
| 'ES2019.Symbol'
| 'ES2020'
| 'ES2020.String'
| 'ES2020.Symbol.WellKnown'
| 'ESNext'
| 'ESNext.Array'
| 'ESNext.AsyncIterable'
| 'ESNext.BigInt'
| 'ESNext.Intl'
| 'ESNext.Symbol'
| 'DOM'
| 'DOM.Iterable'
| 'ScriptHost'
| 'WebWorker'
| 'WebWorker.ImportScripts'
// Lowercase alternatives
| 'es5'
| 'es6'
| 'es7'
| 'es2015'
| 'es2015.collection'
| 'es2015.core'
| 'es2015.generator'
| 'es2015.iterable'
| 'es2015.promise'
| 'es2015.proxy'
| 'es2015.reflect'
| 'es2015.symbol.wellknown'
| 'es2015.symbol'
| 'es2016'
| 'es2016.array.include'
| 'es2017'
| 'es2017.intl'
| 'es2017.object'
| 'es2017.sharedmemory'
| 'es2017.string'
| 'es2017.typedarrays'
| 'es2018'
| 'es2018.asynciterable'
| 'es2018.intl'
| 'es2018.promise'
| 'es2018.regexp'
| 'es2019'
| 'es2019.array'
| 'es2019.object'
| 'es2019.string'
| 'es2019.symbol'
| 'es2020'
| 'es2020.string'
| 'es2020.symbol.wellknown'
| 'esnext'
| 'esnext.array'
| 'esnext.asynciterable'
| 'esnext.bigint'
| 'esnext.intl'
| 'esnext.symbol'
| 'dom'
| 'dom.iterable'
| 'scripthost'
| 'webworker'
| 'webworker.importscripts';
export interface Plugin {
[key: string]: unknown;
/**
Plugin name.
*/
name?: string;
}
}
export interface CompilerOptions {
/**
The character set of the input files.
@default 'utf8'
*/
charset?: string;
/**
Enables building for project references.
@default true
*/
composite?: boolean;
/**
Generates corresponding d.ts files.
@default false
*/
declaration?: boolean;
/**
Specify output directory for generated declaration files.
Requires TypeScript version 2.0 or later.
*/
declarationDir?: string;
/**
Show diagnostic information.
@default false
*/
diagnostics?: boolean;
/**
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.
@default false
*/
emitBOM?: boolean;
/**
Only emit `.d.ts` declaration files.
@default false
*/
emitDeclarationOnly?: boolean;
/**
Enable incremental compilation.
@default `composite`
*/
incremental?: boolean;
/**
Specify file to store incremental compilation information.
@default '.tsbuildinfo'
*/
tsBuildInfoFile?: string;
/**
Emit a single file with source maps instead of having a separate file.
@default false
*/
inlineSourceMap?: boolean;
/**
Emit the source alongside the sourcemaps within a single file.
Requires `--inlineSourceMap` to be set.
@default false
*/
inlineSources?: boolean;
/**
Specify JSX code generation: `'preserve'`, `'react'`, or `'react-native'`.
@default 'preserve'
*/
jsx?: CompilerOptions.JSX;
/**
Specifies the object invoked for `createElement` and `__spread` when targeting `'react'` JSX emit.
@default 'React'
*/
reactNamespace?: string;
/**
Print names of files part of the compilation.
@default false
*/
listFiles?: boolean;
/**
Specifies the location where debugger should locate map files instead of generated locations.
*/
mapRoot?: string;
/**
Specify module code generation: 'None', 'CommonJS', 'AMD', 'System', 'UMD', 'ES6', 'ES2015' or 'ESNext'. Only 'AMD' and 'System' can be used in conjunction with `--outFile`. 'ES6' and 'ES2015' values may be used when targeting 'ES5' or lower.
@default ['ES3', 'ES5'].includes(target) ? 'CommonJS' : 'ES6'
*/
module?: CompilerOptions.Module;
/**
Specifies the end of line sequence to be used when emitting files: 'crlf' (Windows) or 'lf' (Unix).
Default: Platform specific
*/
newLine?: CompilerOptions.NewLine;
/**
Do not emit output.
@default false
*/
noEmit?: boolean;
/**
Do not generate custom helper functions like `__extends` in compiled output.
@default false
*/
noEmitHelpers?: boolean;
/**
Do not emit outputs if any type checking errors were reported.
@default false
*/
noEmitOnError?: boolean;
/**
Warn on expressions and declarations with an implied 'any' type.
@default false
*/
noImplicitAny?: boolean;
/**
Raise error on 'this' expressions with an implied any type.
@default false
*/
noImplicitThis?: boolean;
/**
Report errors on unused locals.
Requires TypeScript version 2.0 or later.
@default false
*/
noUnusedLocals?: boolean;
/**
Report errors on unused parameters.
Requires TypeScript version 2.0 or later.
@default false
*/
noUnusedParameters?: boolean;
/**
Do not include the default library file (lib.d.ts).
@default false
*/
noLib?: boolean;
/**
Do not add triple-slash references or module import targets to the list of compiled files.
@default false
*/
noResolve?: boolean;
/**
Disable strict checking of generic signatures in function types.
@default false
*/
noStrictGenericChecks?: boolean;
/**
@deprecated use `skipLibCheck` instead.
*/
skipDefaultLibCheck?: boolean;
/**
Skip type checking of declaration files.
Requires TypeScript version 2.0 or later.
@default false
*/
skipLibCheck?: boolean;
/**
Concatenate and emit output to single file.
*/
outFile?: string;
/**
Redirect output structure to the directory.
*/
outDir?: string;
/**
Do not erase const enum declarations in generated code.
@default false
*/
preserveConstEnums?: boolean;
/**
Do not resolve symlinks to their real path; treat a symlinked file like a real one.
@default false
*/
preserveSymlinks?: boolean;
/**
Keep outdated console output in watch mode instead of clearing the screen.
@default false
*/
preserveWatchOutput?: boolean;
/**
Stylize errors and messages using color and context (experimental).
@default true // Unless piping to another program or redirecting output to a file.
*/
pretty?: boolean;
/**
Do not emit comments to output.
@default false
*/
removeComments?: boolean;
/**
Specifies the root directory of input files.
Use to control the output directory structure with `--outDir`.
*/
rootDir?: string;
/**
Unconditionally emit imports for unresolved files.
@default false
*/
isolatedModules?: boolean;
/**
Generates corresponding '.map' file.
@default false
*/
sourceMap?: boolean;
/**
Specifies the location where debugger should locate TypeScript files instead of source locations.
*/
sourceRoot?: string;
/**
Suppress excess property checks for object literals.
@default false
*/
suppressExcessPropertyErrors?: boolean;
/**
Suppress noImplicitAny errors for indexing objects lacking index signatures.
@default false
*/
suppressImplicitAnyIndexErrors?: boolean;
/**
Do not emit declarations for code that has an `@internal` annotation.
*/
stripInternal?: boolean;
/**
Specify ECMAScript target version.
@default 'es3'
*/
target?: CompilerOptions.Target;
/**
Watch input files.
@default false
*/
watch?: boolean;
/**
Enables experimental support for ES7 decorators.
@default false
*/
experimentalDecorators?: boolean;
/**
Emit design-type metadata for decorated declarations in source.
@default false
*/
emitDecoratorMetadata?: boolean;
/**
Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6).
@default ['AMD', 'System', 'ES6'].includes(module) ? 'classic' : 'node'
*/
moduleResolution?: 'classic' | 'node';
/**
Do not report errors on unused labels.
@default false
*/
allowUnusedLabels?: boolean;
/**
Report error when not all code paths in function return a value.
@default false
*/
noImplicitReturns?: boolean;
/**
Report errors for fallthrough cases in switch statement.
@default false
*/
noFallthroughCasesInSwitch?: boolean;
/**
Do not report errors on unreachable code.
@default false
*/
allowUnreachableCode?: boolean;
/**
Disallow inconsistently-cased references to the same file.
@default false
*/
forceConsistentCasingInFileNames?: boolean;
/**
Base directory to resolve non-relative module names.
*/
baseUrl?: string;
/**
Specify path mapping to be computed relative to baseUrl option.
*/
paths?: {
[key: string]: string[];
};
/**
List of TypeScript language server plugins to load.
Requires TypeScript version 2.3 or later.
*/
plugins?: CompilerOptions.Plugin[];
/**
Specify list of root directories to be used when resolving modules.
*/
rootDirs?: string[];
/**
Specify list of directories for type definition files to be included.
Requires TypeScript version 2.0 or later.
*/
typeRoots?: string[];
/**
Type declaration files to be included in compilation.
Requires TypeScript version 2.0 or later.
*/
types?: string[];
/**
Enable tracing of the name resolution process.
@default false
*/
traceResolution?: boolean;
/**
Allow javascript files to be compiled.
@default false
*/
allowJs?: boolean;
/**
Do not truncate error messages.
@default false
*/
noErrorTruncation?: boolean;
/**
Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
@default module === 'system' || esModuleInterop
*/
allowSyntheticDefaultImports?: boolean;
/**
Do not emit `'use strict'` directives in module output.
@default false
*/
noImplicitUseStrict?: boolean;
/**
Enable to list all emitted files.
Requires TypeScript version 2.0 or later.
@default false
*/
listEmittedFiles?: boolean;
/**
Disable size limit for JavaScript project.
Requires TypeScript version 2.0 or later.
@default false
*/
disableSizeLimit?: boolean;
/**
List of library files to be included in the compilation.
Requires TypeScript version 2.0 or later.
*/
lib?: CompilerOptions.Lib[];
/**
Enable strict null checks.
Requires TypeScript version 2.0 or later.
@default false
*/
strictNullChecks?: boolean;
/**
The maximum dependency depth to search under `node_modules` and load JavaScript files. Only applicable with `--allowJs`.
@default 0
*/
maxNodeModuleJsDepth?: number;
/**
Import emit helpers (e.g. `__extends`, `__rest`, etc..) from tslib.
Requires TypeScript version 2.1 or later.
@default false
*/
importHelpers?: boolean;
/**
Specify the JSX factory function to use when targeting React JSX emit, e.g. `React.createElement` or `h`.
Requires TypeScript version 2.1 or later.
@default 'React.createElement'
*/
jsxFactory?: string;
/**
Parse in strict mode and emit `'use strict'` for each source file.
Requires TypeScript version 2.1 or later.
@default false
*/
alwaysStrict?: boolean;
/**
Enable all strict type checking options.
Requires TypeScript version 2.3 or later.
@default false
*/
strict?: boolean;
/**
Enable stricter checking of of the `bind`, `call`, and `apply` methods on functions.
@default false
*/
strictBindCallApply?: boolean;
/**
Provide full support for iterables in `for-of`, spread, and destructuring when targeting `ES5` or `ES3`.
Requires TypeScript version 2.3 or later.
@default false
*/
downlevelIteration?: boolean;
/**
Report errors in `.js` files.
Requires TypeScript version 2.3 or later.
@default false
*/
checkJs?: boolean;
/**
Disable bivariant parameter checking for function types.
Requires TypeScript version 2.6 or later.
@default false
*/
strictFunctionTypes?: boolean;
/**
Ensure non-undefined class properties are initialized in the constructor.
Requires TypeScript version 2.7 or later.
@default false
*/
strictPropertyInitialization?: boolean;
/**
Emit `__importStar` and `__importDefault` helpers for runtime Babel ecosystem compatibility and enable `--allowSyntheticDefaultImports` for typesystem compatibility.
Requires TypeScript version 2.7 or later.
@default false
*/
esModuleInterop?: boolean;
/**
Allow accessing UMD globals from modules.
@default false
*/
allowUmdGlobalAccess?: boolean;
/**
Resolve `keyof` to string valued property names only (no numbers or symbols).
Requires TypeScript version 2.9 or later.
@default false
*/
keyofStringsOnly?: boolean;
/**
Emit ECMAScript standard class fields.
Requires TypeScript version 3.7 or later.
@default false
*/
useDefineForClassFields?: boolean;
/**
Generates a sourcemap for each corresponding `.d.ts` file.
Requires TypeScript version 2.9 or later.
@default false
*/
declarationMap?: boolean;
/**
Include modules imported with `.json` extension.
Requires TypeScript version 2.9 or later.
@default false
*/
resolveJsonModule?: boolean;
}
/**
Auto type (.d.ts) acquisition options for this project.
Requires TypeScript version 2.1 or later.
*/
export interface TypeAcquisition {
/**
Enable auto type acquisition.
*/
enable?: boolean;
/**
Specifies a list of type declarations to be included in auto type acquisition. For example, `['jquery', 'lodash']`.
*/
include?: string[];
/**
Specifies a list of type declarations to be excluded from auto type acquisition. For example, `['jquery', 'lodash']`.
*/
exclude?: string[];
}
export interface References {
/**
A normalized path on disk.
*/
path: string;
/**
The path as the user originally wrote it.
*/
originalPath?: string;
/**
True if the output of this reference should be prepended to the output of this project.
Only valid for `--outFile` compilations.
*/
prepend?: boolean;
/**
True if it is intended that this reference form a circularity.
*/
circular?: boolean;
}
}
export interface TsConfigJson {
/**
Instructs the TypeScript compiler how to compile `.ts` files.
*/
compilerOptions?: TsConfigJson.CompilerOptions;
/**
Auto type (.d.ts) acquisition options for this project.
Requires TypeScript version 2.1 or later.
*/
typeAcquisition?: TsConfigJson.TypeAcquisition;
/**
Enable Compile-on-Save for this project.
*/
compileOnSave?: boolean;
/**
Path to base configuration file to inherit from.
Requires TypeScript version 2.1 or later.
*/
extends?: string;
/**
If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. When a `files` property is specified, only those files and those specified by `include` are included.
*/
files?: string[];
/**
Specifies a list of files to be excluded from compilation. The `exclude` property only affects the files included via the `include` property and not the `files` property.
Glob patterns require TypeScript version 2.0 or later.
*/
exclude?: string[];
/**
Specifies a list of glob patterns that match files to be included in compilation.
If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`.
Requires TypeScript version 2.0 or later.
*/
include?: string[];
/**
Referenced projects.
Requires TypeScript version 3.0 or later.
*/
references?: TsConfigJson.References[];
}
+132
View File
@@ -0,0 +1,132 @@
{
"name": "got",
"version": "10.7.0",
"description": "Human-friendly and powerful HTTP request library for Node.js",
"license": "MIT",
"repository": "sindresorhus/got",
"funding": "https://github.com/sindresorhus/got?sponsor=1",
"main": "dist/source",
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && tsc --noEmit && nyc ava",
"release": "np",
"build": "del-cli dist && tsc",
"prepare": "npm run build"
},
"files": [
"dist/source"
],
"keywords": [
"http",
"https",
"http2",
"get",
"got",
"url",
"uri",
"request",
"simple",
"curl",
"wget",
"fetch",
"net",
"network",
"electron",
"brotli",
"requests",
"human-friendly",
"axios",
"superagent"
],
"dependencies": {
"@sindresorhus/is": "^2.0.0",
"@szmarczak/http-timer": "^4.0.0",
"@types/cacheable-request": "^6.0.1",
"cacheable-lookup": "^2.0.0",
"cacheable-request": "^7.0.1",
"decompress-response": "^5.0.0",
"duplexer3": "^0.1.4",
"get-stream": "^5.0.0",
"lowercase-keys": "^2.0.0",
"mimic-response": "^2.1.0",
"p-cancelable": "^2.0.0",
"p-event": "^4.0.0",
"responselike": "^2.0.0",
"to-readable-stream": "^2.0.0",
"type-fest": "^0.10.0"
},
"devDependencies": {
"@ava/typescript": "^1.1.1",
"@sindresorhus/tsconfig": "^0.7.0",
"@types/duplexer3": "^0.1.0",
"@types/express": "^4.17.2",
"@types/lolex": "^5.1.0",
"@types/node": "13.1.2",
"@types/proxyquire": "^1.3.28",
"@types/sinon": "^7.0.13",
"@types/tough-cookie": "^2.3.5",
"@typescript-eslint/eslint-plugin": "^2.19.2",
"@typescript-eslint/parser": "^2.19.2",
"ava": "^3.3.0",
"coveralls": "^3.0.4",
"create-test-server": "^3.0.1",
"del-cli": "^3.0.0",
"delay": "^4.3.0",
"eslint-config-xo-typescript": "^0.26.0",
"express": "^4.17.1",
"form-data": "^3.0.0",
"get-port": "^5.0.0",
"keyv": "^4.0.0",
"lolex": "^6.0.0",
"nock": "^12.0.0",
"np": "^6.0.0",
"nyc": "^15.0.0",
"proxyquire": "^2.0.1",
"sinon": "^8.1.1",
"slow-stream": "0.0.4",
"tempy": "^0.4.0",
"tough-cookie": "^3.0.0",
"typescript": "3.7.5",
"xo": "^0.26.0"
},
"types": "dist/source",
"sideEffects": false,
"browser": {
"electron": false
},
"ava": {
"files": [
"test/*"
],
"timeout": "1m",
"typescript": {
"rewritePaths": {
"test/": "dist/test/"
}
}
},
"nyc": {
"extension": [
".ts"
],
"exclude": [
"**/test/**"
]
},
"xo": {
"extends": "xo-typescript",
"extensions": [
"ts"
],
"ignores": [
"documentation/examples/*"
],
"rules": {
"@typescript-eslint/no-empty-function": "off",
"node/prefer-global/url": "off",
"node/prefer-global/url-search-params": "off"
}
}
}
Generated Vendored
+1803
View File
File diff suppressed because it is too large Load Diff