Commit f0131599 authored by Spark's avatar Spark
Browse files

typescript client

parent ec4d4f56
MIT License
Copyright (c) Microsoft Corporation.
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
# Installation
> `npm install --save @types/jest`
# Summary
This package contains type definitions for Jest (https://jestjs.io/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest.
### Additional Details
* Last updated: Mon, 26 Apr 2021 11:01:22 GMT
* Dependencies: [@types/jest-diff](https://npmjs.com/package/@types/jest-diff), [@types/pretty-format](https://npmjs.com/package/@types/pretty-format)
* Global values: `afterAll`, `afterEach`, `beforeAll`, `beforeEach`, `describe`, `expect`, `fail`, `fdescribe`, `fit`, `it`, `jasmine`, `jest`, `pending`, `spyOn`, `test`, `xdescribe`, `xit`, `xtest`
# Credits
These definitions were written by [Asana (https://asana.com)
// Ivo Stratev](https://github.com/NoHomey), [jwbay](https://github.com/jwbay), [Alexey Svetliakov](https://github.com/asvetliakov), [Alex Jover Morales](https://github.com/alexjoverm), [Allan Lukwago](https://github.com/epicallan), [Ika](https://github.com/ikatyang), [Waseem Dahman](https://github.com/wsmd), [Jamie Mason](https://github.com/JamieMason), [Douglas Duteil](https://github.com/douglasduteil), [Ahn](https://github.com/ahnpnl), [Josh Goldberg](https://github.com/joshuakgoldberg), [Jeff Lau](https://github.com/UselessPickles), [Andrew Makarov](https://github.com/r3nya), [Martin Hochel](https://github.com/hotell), [Sebastian Sebald](https://github.com/sebald), [Andy](https://github.com/andys8), [Antoine Brault](https://github.com/antoinebrault), [Gregor Stamać](https://github.com/gstamac), [ExE Boss](https://github.com/ExE-Boss), [Alex Bolenok](https://github.com/quassnoi), [Mario Beltrán Alarcón](https://github.com/Belco90), [Tony Hallett](https://github.com/tonyhallett), [Jason Yu](https://github.com/ycmjason), [Devansh Jethmalani](https://github.com/devanshj), [Pawel Fajfer](https://github.com/pawfa), [Regev Brody](https://github.com/regevbr), and [Alexandre Germain](https://github.com/gerkindev).
// Type definitions for Jest 26.0
// Project: https://jestjs.io/
// Definitions by: Asana (https://asana.com)
// Ivo Stratev <https://github.com/NoHomey>
// jwbay <https://github.com/jwbay>
// Alexey Svetliakov <https://github.com/asvetliakov>
// Alex Jover Morales <https://github.com/alexjoverm>
// Allan Lukwago <https://github.com/epicallan>
// Ika <https://github.com/ikatyang>
// Waseem Dahman <https://github.com/wsmd>
// Jamie Mason <https://github.com/JamieMason>
// Douglas Duteil <https://github.com/douglasduteil>
// Ahn <https://github.com/ahnpnl>
// Josh Goldberg <https://github.com/joshuakgoldberg>
// Jeff Lau <https://github.com/UselessPickles>
// Andrew Makarov <https://github.com/r3nya>
// Martin Hochel <https://github.com/hotell>
// Sebastian Sebald <https://github.com/sebald>
// Andy <https://github.com/andys8>
// Antoine Brault <https://github.com/antoinebrault>
// Gregor Stamać <https://github.com/gstamac>
// ExE Boss <https://github.com/ExE-Boss>
// Alex Bolenok <https://github.com/quassnoi>
// Mario Beltrán Alarcón <https://github.com/Belco90>
// Tony Hallett <https://github.com/tonyhallett>
// Jason Yu <https://github.com/ycmjason>
// Devansh Jethmalani <https://github.com/devanshj>
// Pawel Fajfer <https://github.com/pawfa>
// Regev Brody <https://github.com/regevbr>
// Alexandre Germain <https://github.com/gerkindev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Minimum TypeScript Version: 3.8
declare var beforeAll: jest.Lifecycle;
declare var beforeEach: jest.Lifecycle;
declare var afterAll: jest.Lifecycle;
declare var afterEach: jest.Lifecycle;
declare var describe: jest.Describe;
declare var fdescribe: jest.Describe;
declare var xdescribe: jest.Describe;
declare var it: jest.It;
declare var fit: jest.It;
declare var xit: jest.It;
declare var test: jest.It;
declare var xtest: jest.It;
declare const expect: jest.Expect;
type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
1: [T[0]],
2: [T[0], T[1]],
3: [T[0], T[1], T[2]],
4: [T[0], T[1], T[2], T[3]],
5: [T[0], T[1], T[2], T[3], T[4]],
6: [T[0], T[1], T[2], T[3], T[4], T[5]],
7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]],
8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]],
9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]],
10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]],
'fallback': Array<(T extends ReadonlyArray<infer U>? U: any)>
}[
T extends Readonly<[any]> ? 1
: T extends Readonly<[any, any]> ? 2
: T extends Readonly<[any, any, any]> ? 3
: T extends Readonly<[any, any, any, any]> ? 4
: T extends Readonly<[any, any, any, any, any]> ? 5
: T extends Readonly<[any, any, any, any, any, any]> ? 6
: T extends Readonly<[any, any, any, any, any, any, any]> ? 7
: T extends Readonly<[any, any, any, any, any, any, any, any]> ? 8
: T extends Readonly<[any, any, any, any, any, any, any, any, any]> ? 9
: T extends Readonly<[any, any, any, any, any, any, any, any, any, any]> ? 10
: 'fallback'
];
declare namespace jest {
/**
* Provides a way to add Jasmine-compatible matchers into your Jest context.
*/
function addMatchers(matchers: jasmine.CustomMatcherFactories): typeof jest;
/**
* Disables automatic mocking in the module loader.
*/
function autoMockOff(): typeof jest;
/**
* Enables automatic mocking in the module loader.
*/
function autoMockOn(): typeof jest;
/**
* Clears the mock.calls and mock.instances properties of all mocks.
* Equivalent to calling .mockClear() on every mocked function.
*/
function clearAllMocks(): typeof jest;
/**
* Use the automatic mocking system to generate a mocked version of the given module.
*/
// tslint:disable-next-line: no-unnecessary-generics
function createMockFromModule<T>(moduleName: string): T;
/**
* Resets the state of all mocks.
* Equivalent to calling .mockReset() on every mocked function.
*/
function resetAllMocks(): typeof jest;
/**
* available since Jest 21.1.0
* Restores all mocks back to their original value.
* Equivalent to calling .mockRestore on every mocked function.
* Beware that jest.restoreAllMocks() only works when mock was created with
* jest.spyOn; other mocks will require you to manually restore them.
*/
function restoreAllMocks(): typeof jest;
/**
* Removes any pending timers from the timer system. If any timers have
* been scheduled, they will be cleared and will never have the opportunity
* to execute in the future.
*/
function clearAllTimers(): typeof jest;
/**
* Returns the number of fake timers still left to run.
*/
function getTimerCount(): number;
/**
* Set the current system time used by fake timers. Simulates a user
* changing the system clock while your program is running. It affects the
* current time but it does not in itself cause e.g. timers to fire; they
* will fire exactly as they would have done without the call to
* jest.setSystemTime().
*
* > Note: This function is only available when using modern fake timers
* > implementation
*/
function setSystemTime(now?: number | Date): void;
/**
* When mocking time, Date.now() will also be mocked. If you for some
* reason need access to the real current time, you can invoke this
* function.
*
* > Note: This function is only available when using modern fake timers
* > implementation
*/
function getRealSystemTime(): number;
/**
* Indicates that the module system should never return a mocked version
* of the specified module, including all of the specificied module's dependencies.
*/
function deepUnmock(moduleName: string): typeof jest;
/**
* Disables automatic mocking in the module loader.
*/
function disableAutomock(): typeof jest;
/**
* Mocks a module with an auto-mocked version when it is being required.
*/
function doMock(moduleName: string, factory?: () => unknown, options?: MockOptions): typeof jest;
/**
* Indicates that the module system should never return a mocked version
* of the specified module from require() (e.g. that it should always return the real module).
*/
function dontMock(moduleName: string): typeof jest;
/**
* Enables automatic mocking in the module loader.
*/
function enableAutomock(): typeof jest;
/**
* Creates a mock function. Optionally takes a mock implementation.
*/
function fn(): Mock;
/**
* Creates a mock function. Optionally takes a mock implementation.
*/
function fn<T, Y extends any[]>(implementation?: (...args: Y) => T): Mock<T, Y>;
/**
* (renamed to `createMockFromModule` in Jest 26.0.0+)
* Use the automatic mocking system to generate a mocked version of the given module.
*/
// tslint:disable-next-line: no-unnecessary-generics
function genMockFromModule<T>(moduleName: string): T;
/**
* Returns whether the given function is a mock function.
*/
function isMockFunction(fn: any): fn is Mock;
/**
* Mocks a module with an auto-mocked version when it is being required.
*/
function mock(moduleName: string, factory?: () => unknown, options?: MockOptions): typeof jest;
/**
* Returns the actual module instead of a mock, bypassing all checks on
* whether the module should receive a mock implementation or not.
*/
// tslint:disable-next-line: no-unnecessary-generics
function requireActual<TModule extends {} = any>(moduleName: string): TModule;
/**
* Returns a mock module instead of the actual module, bypassing all checks
* on whether the module should be required normally or not.
*/
// tslint:disable-next-line: no-unnecessary-generics
function requireMock<TModule extends {} = any>(moduleName: string): TModule;
/**
* Resets the module registry - the cache of all required modules. This is
* useful to isolate modules where local state might conflict between tests.
*/
function resetModuleRegistry(): typeof jest;
/**
* Resets the module registry - the cache of all required modules. This is
* useful to isolate modules where local state might conflict between tests.
*/
function resetModules(): typeof jest;
/**
* Creates a sandbox registry for the modules that are loaded inside the callback function..
* This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests.
*/
function isolateModules(fn: () => void): typeof jest;
/**
* Runs failed tests n-times until they pass or until the max number of retries is exhausted.
* This only works with jest-circus!
*/
function retryTimes(numRetries: number): typeof jest;
/**
* Exhausts tasks queued by setImmediate().
*/
function runAllImmediates(): typeof jest;
/**
* Exhausts the micro-task queue (usually interfaced in node via process.nextTick).
*/
function runAllTicks(): typeof jest;
/**
* Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()).
*/
function runAllTimers(): typeof jest;
/**
* Executes only the macro-tasks that are currently pending (i.e., only the
* tasks that have been queued by setTimeout() or setInterval() up to this point).
* If any of the currently pending macro-tasks schedule new macro-tasks,
* those new tasks will not be executed by this call.
*/
function runOnlyPendingTimers(): typeof jest;
/**
* (renamed to `advanceTimersByTime` in Jest 21.3.0+) Executes only the macro
* task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()).
*/
function runTimersToTime(msToRun: number): typeof jest;
/**
* Advances all timers by msToRun milliseconds. All pending "macro-tasks" that have been
* queued via setTimeout() or setInterval(), and would be executed within this timeframe
* will be executed.
*/
function advanceTimersByTime(msToRun: number): typeof jest;
/**
* Advances all timers by the needed milliseconds so that only the next
* timeouts/intervals will run. Optionally, you can provide steps, so it
* will run steps amount of next timeouts/intervals.
*/
function advanceTimersToNextTimer(step?: number): void;
/**
* Explicitly supplies the mock object that the module system should return
* for the specified module.
*/
// tslint:disable-next-line: no-unnecessary-generics
function setMock<T>(moduleName: string, moduleExports: T): typeof jest;
/**
* Set the default timeout interval for tests and before/after hooks in milliseconds.
* Note: The default timeout interval is 5 seconds if this method is not called.
*/
function setTimeout(timeout: number): typeof jest;
/**
* Creates a mock function similar to jest.fn but also tracks calls to `object[methodName]`
*
* Note: By default, jest.spyOn also calls the spied method. This is different behavior from most
* other test libraries.
*
* @example
*
* const video = require('./video');
*
* test('plays video', () => {
* const spy = jest.spyOn(video, 'play');
* const isPlaying = video.play();
*
* expect(spy).toHaveBeenCalled();
* expect(isPlaying).toBe(true);
*
* spy.mockReset();
* spy.mockRestore();
* });
*/
function spyOn<T extends {}, M extends NonFunctionPropertyNames<Required<T>>>(
object: T,
method: M,
accessType: 'get'
): SpyInstance<Required<T>[M], []>;
function spyOn<T extends {}, M extends NonFunctionPropertyNames<Required<T>>>(
object: T,
method: M,
accessType: 'set'
): SpyInstance<void, [Required<T>[M]]>;
function spyOn<T extends {}, M extends FunctionPropertyNames<Required<T>>>(
object: T,
method: M
): Required<T>[M] extends (...args: any[]) => any
? SpyInstance<ReturnType<Required<T>[M]>, ArgsType<Required<T>[M]>>
: never;
function spyOn<T extends {}, M extends ConstructorPropertyNames<Required<T>>>(
object: T,
method: M
): Required<T>[M] extends new (...args: any[]) => any
? SpyInstance<InstanceType<Required<T>[M]>, ConstructorArgsType<Required<T>[M]>>
: never;
/**
* Indicates that the module system should never return a mocked version of
* the specified module from require() (e.g. that it should always return the real module).
*/
function unmock(moduleName: string): typeof jest;
/**
* Instructs Jest to use fake versions of the standard timer functions.
*/
function useFakeTimers(implementation?: 'modern' | 'legacy'): typeof jest;
/**
* Instructs Jest to use the real versions of the standard timer functions.
*/
function useRealTimers(): typeof jest;
interface MockOptions {
virtual?: boolean;
}
type EmptyFunction = () => void;
type ArgsType<T> = T extends (...args: infer A) => any ? A : never;
type ConstructorArgsType<T> = T extends new (...args: infer A) => any ? A : never;
type RejectedValue<T> = T extends PromiseLike<any> ? any : never;
type ResolvedValue<T> = T extends PromiseLike<infer U> ? U | T : never;
// see https://github.com/Microsoft/TypeScript/issues/25215
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? never : K }[keyof T] &
string;
type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never }[keyof T] &
string;
type ConstructorPropertyNames<T> = { [K in keyof T]: T[K] extends new (...args: any[]) => any ? K : never }[keyof T] &
string;
interface DoneCallback {
(...args: any[]): any;
fail(error?: string | { message: string }): any;
}
type ProvidesCallback = (cb: DoneCallback) => any;
type Lifecycle = (fn: ProvidesCallback, timeout?: number) => any;
interface FunctionLike {
readonly name: string;
}
interface Each {
// Exclusively arrays.
<T extends any[] | [any]>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T) => any, timeout?: number) => void;
<T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): (name: string, fn: (...args: ExtractEachCallbackArgs<T>) => any, timeout?: number) => void;
// Not arrays.
<T>(cases: ReadonlyArray<T>): (name: string, fn: (...args: T[]) => any, timeout?: number) => void;
(cases: ReadonlyArray<ReadonlyArray<any>>): (
name: string,
fn: (...args: any[]) => any,
timeout?: number
) => void;
(strings: TemplateStringsArray, ...placeholders: any[]): (
name: string,
fn: (arg: any) => any,
timeout?: number
) => void;
}
/**
* Creates a test closure
*/
interface It {
/**
* Creates a test closure.
*
* @param name The name of your test
* @param fn The function for your test
* @param timeout The timeout for an async function test
*/
(name: string, fn?: ProvidesCallback, timeout?: number): void;
/**
* Only runs this test in the current file.
*/
only: It;
/**
* Skips running this test in the current file.
*/
skip: It;
/**
* Sketch out which tests to write in the future.
*/
todo: It;
/**
* Experimental and should be avoided.
*/
concurrent: It;
/**
* Use if you keep duplicating the same test with different data. `.each` allows you to write the
* test once and pass data in.
*
* `.each` is available with two APIs:
*
* #### 1 `test.each(table)(name, fn)`
*
* - `table`: Array of Arrays with the arguments that are passed into the test fn for each row.
* - `name`: String the title of the test block.
* - `fn`: Function the test to be ran, this is the function that will receive the parameters in each row as function arguments.
*
*
* #### 2 `test.each table(name, fn)`
*
* - `table`: Tagged Template Literal
* - `name`: String the title of the test, use `$variable` to inject test data into the test title from the tagged template expressions.
* - `fn`: Function the test to be ran, this is the function that will receive the test data object..
*
* @example
*
* // API 1
* test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])(
* '.add(%i, %i)',
* (a, b, expected) => {
* expect(a + b).toBe(expected);
* },
* );
*
* // API 2
* test.each`
* a | b | expected
* ${1} | ${1} | ${2}
* ${1} | ${2} | ${3}
* ${2} | ${1} | ${3}
* `('returns $expected when $a is added $b', ({a, b, expected}) => {
* expect(a + b).toBe(expected);
* });
*
*/
each: Each;
}
interface Describe {
// tslint:disable-next-line ban-types
(name: number | string | Function | FunctionLike, fn: EmptyFunction): void;
/** Only runs the tests inside this `describe` for the current file */
only: Describe;
/** Skips running the tests inside this `describe` for the current file */
skip: Describe;
each: Each;
}
type PrintLabel = (string: string) => string;
type MatcherHintColor = (arg: string) => string;
interface MatcherHintOptions {
comment?: string;
expectedColor?: MatcherHintColor;
isDirectExpectCall?: boolean;
isNot?: boolean;
promise?: string;
receivedColor?: MatcherHintColor;
secondArgument?: string;
secondArgumentColor?: MatcherHintColor;
}
interface ChalkFunction {
(text: TemplateStringsArray, ...placeholders: any[]): string;
(...text: any[]): string;
}
interface ChalkColorSupport {
level: 0 | 1 | 2 | 3;
hasBasic: boolean;
has256: boolean;
has16m: boolean;
}
type MatcherColorFn = ChalkFunction & { supportsColor: ChalkColorSupport };
type EqualityTester = (a: any, b: any) => boolean | undefined;
interface MatcherUtils {
readonly isNot: boolean;
readonly dontThrow: () => void;
readonly promise: string;
readonly assertionCalls: number;
readonly expectedAssertionsNumber: number | null;
readonly isExpectingAssertions: boolean;
readonly suppressedErrors: any[];
readonly expand: boolean;
readonly testPath: string;
readonly currentTestName: string;
utils: {
readonly EXPECTED_COLOR: MatcherColorFn;
readonly RECEIVED_COLOR: MatcherColorFn;
readonly INVERTED_COLOR: MatcherColorFn;
readonly BOLD_WEIGHT: MatcherColorFn;
readonly DIM_COLOR: MatcherColorFn;
readonly SUGGEST_TO_CONTAIN_EQUAL: string;
diff(a: any, b: any, options?: import("jest-diff").DiffOptions): string | null;
ensureActualIsNumber(actual: any, matcherName: string, options?: MatcherHintOptions): void;
ensureExpectedIsNumber(actual: any, matcherName: string, options?: MatcherHintOptions): void;
ensureNoExpected(actual: any, matcherName: string, options?: MatcherHintOptions): void;
ensureNumbers(actual: any, expected: any, matcherName: string, options?: MatcherHintOptions): void;
ensureExpectedIsNonNegativeInteger(expected: any, matcherName: string, options?: MatcherHintOptions): void;
matcherHint(
matcherName: string,
received?: string,
expected?: string,
options?: MatcherHintOptions
): string;
matcherErrorMessage(
hint: string,
generic: string,
specific: string
): string;
pluralize(word: string, count: number): string;
printReceived(object: any): string;
printExpected(value: any): string;
printWithType(name: string, value: any, print: (value: any) => string): string;
stringify(object: {}, maxDepth?: number): string;
highlightTrailingWhitespace(text: string): string;
printDiffOrStringify(expected: any, received: any, expectedLabel: string, receivedLabel: string, expand: boolean): string;
getLabelPrinter(...strings: string[]): PrintLabel;
iterableEquality: EqualityTester;
subsetEquality: EqualityTester;
};
/**
* This is a deep-equality function that will return true if two objects have the same values (recursively).
*/
equals(a: any, b: any, customTesters?: EqualityTester[], strictCheck?: boolean): boolean;
[other: string]: any;
}
interface ExpectExtendMap {
[key: string]: CustomMatcher;
}
type MatcherContext = MatcherUtils & Readonly<MatcherState>;
type CustomMatcher = (
this: MatcherContext,
received: any,
...actual: any[]
) => CustomMatcherResult | Promise<CustomMatcherResult>;
interface CustomMatcherResult {
pass: boolean;
message: () => string;
}
type SnapshotSerializerPlugin = import('pretty-format').Plugin;
interface InverseAsymmetricMatchers {
/**
* `expect.not.arrayContaining(array)` matches a received array which
* does not contain all of the elements in the expected array. That is,
* the expected array is not a subset of the received array. It is the
* inverse of `expect.arrayContaining`.
*
* Optionally, you can provide a type for the elements via a generic.
*/
// tslint:disable-next-line: no-unnecessary-generics
arrayContaining<E = any>(arr: E[]): any;
/**
* `expect.not.objectContaining(object)` matches any received object
* that does not recursively match the expected properties. That is, the
* expected object is not a subset of the received object. Therefore,
* it matches a received object which contains properties that are not
* in the expected object. It is the inverse of `expect.objectContaining`.
*
* Optionally, you can provide a type for the object via a generic.
* This ensures that the object contains the desired structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
objectContaining<E = {}>(obj: E): any;
/**
* `expect.not.stringMatching(string | regexp)` matches the received
* string that does not match the expected regexp. It is the inverse of
* `expect.stringMatching`.
*/
stringMatching(str: string | RegExp): any;
/**
* `expect.not.stringContaining(string)` matches the received string
* that does not contain the exact expected string. It is the inverse of
* `expect.stringContaining`.
*/
stringContaining(str: string): any;
}
interface MatcherState {
assertionCalls: number;
currentTestName: string;
expand: boolean;
expectedAssertionsNumber: number;
isExpectingAssertions?: boolean;
suppressedErrors: Error[];
testPath: string;
}
/**
* The `expect` function is used every time you want to test a value.
* You will rarely call `expect` by itself.
*/
interface Expect {
/**
* The `expect` function is used every time you want to test a value.
* You will rarely call `expect` by itself.
*
* @param actual The value to apply matchers against.
*/
<T = any>(actual: T): JestMatchers<T>;
/**
* Matches anything but null or undefined. You can use it inside `toEqual` or `toBeCalledWith` instead
* of a literal value. For example, if you want to check that a mock function is called with a
* non-null argument:
*
* @example
*
* test('map calls its argument with a non-null argument', () => {
* const mock = jest.fn();
* [1].map(x => mock(x));
* expect(mock).toBeCalledWith(expect.anything());
* });
*
*/
anything(): any;
/**
* Matches anything that was created with the given constructor.
* You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
*
* @example
*
* function randocall(fn) {
* return fn(Math.floor(Math.random() * 6 + 1));
* }
*
* test('randocall calls its callback with a number', () => {
* const mock = jest.fn();
* randocall(mock);
* expect(mock).toBeCalledWith(expect.any(Number));
* });
*/
any(classType: any): any;
/**
* Matches any array made up entirely of elements in the provided array.
* You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
*
* Optionally, you can provide a type for the elements via a generic.
*/
// tslint:disable-next-line: no-unnecessary-generics
arrayContaining<E = any>(arr: E[]): any;
/**
* Verifies that a certain number of assertions are called during a test.
* This is often useful when testing asynchronous code, in order to
* make sure that assertions in a callback actually got called.
*/
assertions(num: number): void;
/**
* Verifies that at least one assertion is called during a test.
* This is often useful when testing asynchronous code, in order to
* make sure that assertions in a callback actually got called.
*/
hasAssertions(): void;
/**
* You can use `expect.extend` to add your own matchers to Jest.
*/
extend(obj: ExpectExtendMap): void;
/**
* Adds a module to format application-specific data structures for serialization.
*/
addSnapshotSerializer(serializer: SnapshotSerializerPlugin): void;
/**
* Matches any object that recursively matches the provided keys.
* This is often handy in conjunction with other asymmetric matchers.
*
* Optionally, you can provide a type for the object via a generic.
* This ensures that the object contains the desired structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
objectContaining<E = {}>(obj: E): any;
/**
* Matches any string that contains the exact provided string
*/
stringMatching(str: string | RegExp): any;
/**
* Matches any received string that contains the exact expected string
*/
stringContaining(str: string): any;
not: InverseAsymmetricMatchers;
setState(state: object): void;
getState(): MatcherState & Record<string, any>;
}
type JestMatchers<T> = JestMatchersShape<Matchers<void, T>, Matchers<Promise<void>, T>>;
type JestMatchersShape<TNonPromise extends {} = {}, TPromise extends {} = {}> = {
/**
* Use resolves to unwrap the value of a fulfilled promise so any other
* matcher can be chained. If the promise is rejected the assertion fails.
*/
resolves: AndNot<TPromise>,
/**
* Unwraps the reason of a rejected promise so any other matcher can be chained.
* If the promise is fulfilled the assertion fails.
*/
rejects: AndNot<TPromise>
} & AndNot<TNonPromise>;
type AndNot<T> = T & {
not: T
};
// should be R extends void|Promise<void> but getting dtslint error
interface Matchers<R, T = {}> {
/**
* Ensures the last call to a mock function was provided specific args.
*
* Optionally, you can provide a type for the expected arguments via a generic.
* Note that the type must be either an array or a tuple.
*/
// tslint:disable-next-line: no-unnecessary-generics
lastCalledWith<E extends any[]>(...args: E): R;
/**
* Ensure that the last call to a mock function has returned a specified value.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
lastReturnedWith<E = any>(value: E): R;
/**
* Ensure that a mock function is called with specific arguments on an Nth call.
*
* Optionally, you can provide a type for the expected arguments via a generic.
* Note that the type must be either an array or a tuple.
*/
// tslint:disable-next-line: no-unnecessary-generics
nthCalledWith<E extends any[]>(nthCall: number, ...params: E): R;
/**
* Ensure that the nth call to a mock function has returned a specified value.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
nthReturnedWith<E = any>(n: number, value: E): R;
/**
* Checks that a value is what you expect. It uses `Object.is` to check strict equality.
* Don't use `toBe` with floating-point numbers.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toBe<E = any>(expected: E): R;
/**
* Ensures that a mock function is called.
*/
toBeCalled(): R;
/**
* Ensures that a mock function is called an exact number of times.
*/
toBeCalledTimes(expected: number): R;
/**
* Ensure that a mock function is called with specific arguments.
*
* Optionally, you can provide a type for the expected arguments via a generic.
* Note that the type must be either an array or a tuple.
*/
// tslint:disable-next-line: no-unnecessary-generics
toBeCalledWith<E extends any[]>(...args: E): R;
/**
* Using exact equality with floating point numbers is a bad idea.
* Rounding means that intuitive things fail.
* The default for numDigits is 2.
*/
toBeCloseTo(expected: number, numDigits?: number): R;
/**
* Ensure that a variable is not undefined.
*/
toBeDefined(): R;
/**
* When you don't care what a value is, you just want to
* ensure a value is false in a boolean context.
*/
toBeFalsy(): R;
/**
* For comparing floating point or big integer numbers.
*/
toBeGreaterThan(expected: number | bigint): R;
/**
* For comparing floating point or big integer numbers.
*/
toBeGreaterThanOrEqual(expected: number | bigint): R;
/**
* Ensure that an object is an instance of a class.
* This matcher uses `instanceof` underneath.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toBeInstanceOf<E = any>(expected: E): R;
/**
* For comparing floating point or big integer numbers.
*/
toBeLessThan(expected: number | bigint): R;
/**
* For comparing floating point or big integer numbers.
*/
toBeLessThanOrEqual(expected: number | bigint): R;
/**
* This is the same as `.toBe(null)` but the error messages are a bit nicer.
* So use `.toBeNull()` when you want to check that something is null.
*/
toBeNull(): R;
/**
* Use when you don't care what a value is, you just want to ensure a value
* is true in a boolean context. In JavaScript, there are six falsy values:
* `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy.
*/
toBeTruthy(): R;
/**
* Used to check that a variable is undefined.
*/
toBeUndefined(): R;
/**
* Used to check that a variable is NaN.
*/
toBeNaN(): R;
/**
* Used when you want to check that an item is in a list.
* For testing the items in the list, this uses `===`, a strict equality check.
* It can also check whether a string is a substring of another string.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toContain<E = any>(expected: E): R;
/**
* Used when you want to check that an item is in a list.
* For testing the items in the list, this matcher recursively checks the
* equality of all fields, rather than checking for object identity.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toContainEqual<E = any>(expected: E): R;
/**
* Used when you want to check that two objects have the same value.
* This matcher recursively checks the equality of all fields, rather than checking for object identity.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toEqual<E = any>(expected: E): R;
/**
* Ensures that a mock function is called.
*/
toHaveBeenCalled(): R;
/**
* Ensures that a mock function is called an exact number of times.
*/
toHaveBeenCalledTimes(expected: number): R;
/**
* Ensure that a mock function is called with specific arguments.
*
* Optionally, you can provide a type for the expected arguments via a generic.
* Note that the type must be either an array or a tuple.
*/
// tslint:disable-next-line: no-unnecessary-generics
toHaveBeenCalledWith<E extends any[]>(...params: E): R;
/**
* Ensure that a mock function is called with specific arguments on an Nth call.
*
* Optionally, you can provide a type for the expected arguments via a generic.
* Note that the type must be either an array or a tuple.
*/
// tslint:disable-next-line: no-unnecessary-generics
toHaveBeenNthCalledWith<E extends any[]>(nthCall: number, ...params: E): R;
/**
* If you have a mock function, you can use `.toHaveBeenLastCalledWith`
* to test what arguments it was last called with.
*
* Optionally, you can provide a type for the expected arguments via a generic.
* Note that the type must be either an array or a tuple.
*/
// tslint:disable-next-line: no-unnecessary-generics
toHaveBeenLastCalledWith<E extends any[]>(...params: E): R;
/**
* Use to test the specific value that a mock function last returned.
* If the last call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toHaveLastReturnedWith<E = any>(expected: E): R;
/**
* Used to check that an object has a `.length` property
* and it is set to a certain numeric value.
*/
toHaveLength(expected: number): R;
/**
* Use to test the specific value that a mock function returned for the nth call.
* If the nth call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toHaveNthReturnedWith<E = any>(nthCall: number, expected: E): R;
/**
* Use to check if property at provided reference keyPath exists for an object.
* For checking deeply nested properties in an object you may use dot notation or an array containing
* the keyPath for deep references.
*
* Optionally, you can provide a value to check if it's equal to the value present at keyPath
* on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks
* the equality of all fields.
*
* @example
*
* expect(houseForSale).toHaveProperty('kitchen.area', 20);
*/
// tslint:disable-next-line: no-unnecessary-generics
toHaveProperty<E = any>(propertyPath: string | any[], value?: E): R;
/**
* Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
*/
toHaveReturned(): R;
/**
* Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
* Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
*/
toHaveReturnedTimes(expected: number): R;
/**
* Use to ensure that a mock function returned a specific value.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toHaveReturnedWith<E = any>(expected: E): R;
/**
* Check that a string matches a regular expression.
*/
toMatch(expected: string | RegExp): R;
/**
* Used to check that a JavaScript object matches a subset of the properties of an object
*
* Optionally, you can provide an object to use as Generic type for the expected value.
* This ensures that the matching object matches the structure of the provided object-like type.
*
* @example
*
* type House = {
* bath: boolean;
* bedrooms: number;
* kitchen: {
* amenities: string[];
* area: number;
* wallColor: string;
* }
* };
*
* expect(desiredHouse).toMatchObject<House>({...standardHouse, kitchen: {area: 20}}) // wherein standardHouse is some base object of type House
*/
// tslint:disable-next-line: no-unnecessary-generics
toMatchObject<E extends {} | any[]>(expected: E): R;
/**
* This ensures that a value matches the most recent snapshot with property matchers.
* Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
*/
// tslint:disable-next-line: no-unnecessary-generics
toMatchSnapshot<U extends { [P in keyof T]: any }>(propertyMatchers: Partial<U>, snapshotName?: string): R;
/**
* This ensures that a value matches the most recent snapshot.
* Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
*/
toMatchSnapshot(snapshotName?: string): R;
/**
* This ensures that a value matches the most recent snapshot with property matchers.
* Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
* Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
*/
// tslint:disable-next-line: no-unnecessary-generics
toMatchInlineSnapshot<U extends { [P in keyof T]: any }>(propertyMatchers: Partial<U>, snapshot?: string): R;
/**
* This ensures that a value matches the most recent snapshot with property matchers.
* Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
* Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
*/
toMatchInlineSnapshot(snapshot?: string): R;
/**
* Ensure that a mock function has returned (as opposed to thrown) at least once.
*/
toReturn(): R;
/**
* Ensure that a mock function has returned (as opposed to thrown) a specified number of times.
*/
toReturnTimes(count: number): R;
/**
* Ensure that a mock function has returned a specified value at least once.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toReturnWith<E = any>(value: E): R;
/**
* Use to test that objects have the same types as well as structure.
*
* Optionally, you can provide a type for the expected value via a generic.
* This is particularly useful for ensuring expected objects have the right structure.
*/
// tslint:disable-next-line: no-unnecessary-generics
toStrictEqual<E = any>(expected: E): R;
/**
* Used to test that a function throws when it is called.
*/
toThrow(error?: string | Constructable | RegExp | Error): R;
/**
* If you want to test that a specific error is thrown inside a function.
*/
toThrowError(error?: string | Constructable | RegExp | Error): R;
/**
* Used to test that a function throws a error matching the most recent snapshot when it is called.
*/
toThrowErrorMatchingSnapshot(snapshotName?: string): R;
/**
* Used to test that a function throws a error matching the most recent snapshot when it is called.
* Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
*/
toThrowErrorMatchingInlineSnapshot(snapshot?: string): R;
}
type RemoveFirstFromTuple<T extends any[]> =
T['length'] extends 0 ? [] :
(((...b: T) => void) extends (a: any, ...b: infer I) => void ? I : []);
interface AsymmetricMatcher {
asymmetricMatch(other: unknown): boolean;
}
type NonAsyncMatchers<TMatchers extends ExpectExtendMap> = {
[K in keyof TMatchers]: ReturnType<TMatchers[K]> extends Promise<CustomMatcherResult>? never: K
}[keyof TMatchers];
type CustomAsyncMatchers<TMatchers extends ExpectExtendMap> = {[K in NonAsyncMatchers<TMatchers>]: CustomAsymmetricMatcher<TMatchers[K]>};
type CustomAsymmetricMatcher<TMatcher extends (...args: any[]) => any> = (...args: RemoveFirstFromTuple<Parameters<TMatcher>>) => AsymmetricMatcher;
// should be TMatcherReturn extends void|Promise<void> but getting dtslint error
type CustomJestMatcher<TMatcher extends (...args: any[]) => any, TMatcherReturn> = (...args: RemoveFirstFromTuple<Parameters<TMatcher>>) => TMatcherReturn;
type ExpectProperties= {
[K in keyof Expect]: Expect[K]
};
// should be TMatcherReturn extends void|Promise<void> but getting dtslint error
// Use the `void` type for return types only. Otherwise, use `undefined`. See: https://github.com/Microsoft/dtslint/blob/master/docs/void-return.md
// have added issue https://github.com/microsoft/dtslint/issues/256 - Cannot have type union containing void ( to be used as return type only
type ExtendedMatchers<TMatchers extends ExpectExtendMap, TMatcherReturn, TActual> = Matchers<TMatcherReturn, TActual> & {[K in keyof TMatchers]: CustomJestMatcher<TMatchers[K], TMatcherReturn>};
type JestExtendedMatchers<TMatchers extends ExpectExtendMap, TActual> = JestMatchersShape<ExtendedMatchers<TMatchers, void, TActual>, ExtendedMatchers<TMatchers, Promise<void>, TActual>>;
// when have called expect.extend
type ExtendedExpectFunction<TMatchers extends ExpectExtendMap> = <TActual>(actual: TActual) => JestExtendedMatchers<TMatchers, TActual>;
type ExtendedExpect<TMatchers extends ExpectExtendMap>=
ExpectProperties &
AndNot<CustomAsyncMatchers<TMatchers>> &
ExtendedExpectFunction<TMatchers>;
type NonPromiseMatchers<T extends JestMatchersShape<any>> = Omit<T, 'resolves' | 'rejects' | 'not'>;
type PromiseMatchers<T extends JestMatchersShape> = Omit<T['resolves'], 'not'>;
interface Constructable {
new (...args: any[]): any;
}
interface Mock<T = any, Y extends any[] = any> extends Function, MockInstance<T, Y> {
new (...args: Y): T;
(...args: Y): T;
}
interface SpyInstance<T = any, Y extends any[] = any> extends MockInstance<T, Y> {}
/**
* Represents a function that has been spied on.
*/
type SpiedFunction<T extends (...args: any[]) => any> = SpyInstance<ReturnType<T>, ArgsType<T>>;
/**
* Wrap a function with mock definitions
*
* @example
*
* import { myFunction } from "./library";
* jest.mock("./library");
*
* const mockMyFunction = myFunction as jest.MockedFunction<typeof myFunction>;
* expect(mockMyFunction.mock.calls[0][0]).toBe(42);
*/
type MockedFunction<T extends (...args: any[]) => any> = MockInstance<ReturnType<T>, ArgsType<T>> & T;
/**
* Wrap a class with mock definitions
*
* @example
*
* import { MyClass } from "./library";
* jest.mock("./library");
*
* const mockedMyClass = MyClass as jest.MockedClass<typeof MyClass>;
*
* expect(mockedMyClass.mock.calls[0][0]).toBe(42); // Constructor calls
* expect(mockedMyClass.prototype.myMethod.mock.calls[0][0]).toBe(42); // Method calls
*/
type MockedClass<T extends Constructable> = MockInstance<
InstanceType<T>,
T extends new (...args: infer P) => any ? P : never
> & {
prototype: T extends { prototype: any } ? Mocked<T['prototype']> : never;
} & T;
/**
* Wrap an object or a module with mock definitions
*
* @example
*
* jest.mock("../api");
* import * as api from "../api";
*
* const mockApi = api as jest.Mocked<typeof api>;
* api.MyApi.prototype.myApiMethod.mockImplementation(() => "test");
*/
type Mocked<T> = {
[P in keyof T]: T[P] extends (...args: any[]) => any
? MockInstance<ReturnType<T[P]>, ArgsType<T[P]>>
: T[P] extends Constructable
? MockedClass<T[P]>
: T[P]
} &
T;
interface MockInstance<T, Y extends any[]> {
/** Returns the mock name string set by calling `mockFn.mockName(value)`. */
getMockName(): string;
/** Provides access to the mock's metadata */
mock: MockContext<T, Y>;
/**
* Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays.
*
* Often this is useful when you want to clean up a mock's usage data between two assertions.
*
* Beware that `mockClear` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`.
* You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you
* don't access stale data.
*/
mockClear(): this;
/**
* Resets all information stored in the mock, including any initial implementation and mock name given.
*
* This is useful when you want to completely restore a mock back to its initial state.
*
* Beware that `mockReset` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`.
* You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you
* don't access stale data.
*/
mockReset(): this;
/**
* Does everything that `mockFn.mockReset()` does, and also restores the original (non-mocked) implementation.
*
* This is useful when you want to mock functions in certain test cases and restore the original implementation in others.
*
* Beware that `mockFn.mockRestore` only works when mock was created with `jest.spyOn`. Thus you have to take care of restoration
* yourself when manually assigning `jest.fn()`.
*
* The [`restoreMocks`](https://jestjs.io/docs/en/configuration.html#restoremocks-boolean) configuration option is available
* to restore mocks automatically between tests.
*/
mockRestore(): void;
/**
* Returns the function that was set as the implementation of the mock (using mockImplementation).
*/
getMockImplementation(): ((...args: Y) => T) | undefined;
/**
* Accepts a function that should be used as the implementation of the mock. The mock itself will still record
* all calls that go into and instances that come from itself – the only difference is that the implementation
* will also be executed when the mock is called.
*
* Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`.
*/
mockImplementation(fn?: (...args: Y) => T): this;
/**
* Accepts a function that will be used as an implementation of the mock for one call to the mocked function.
* Can be chained so that multiple function calls produce different results.
*
* @example
*
* const myMockFn = jest
* .fn()
* .mockImplementationOnce(cb => cb(null, true))
* .mockImplementationOnce(cb => cb(null, false));
*
* myMockFn((err, val) => console.log(val)); // true
*
* myMockFn((err, val) => console.log(val)); // false
*/
mockImplementationOnce(fn: (...args: Y) => T): this;
/** Sets the name of the mock`. */
mockName(name: string): this;
/**
* Just a simple sugar function for:
*
* @example
*
* jest.fn(function() {
* return this;
* });
*/
mockReturnThis(): this;
/**
* Accepts a value that will be returned whenever the mock function is called.
*
* @example
*
* const mock = jest.fn();
* mock.mockReturnValue(42);
* mock(); // 42
* mock.mockReturnValue(43);
* mock(); // 43
*/
mockReturnValue(value: T): this;
/**
* Accepts a value that will be returned for one call to the mock function. Can be chained so that
* successive calls to the mock function return different values. When there are no more
* `mockReturnValueOnce` values to use, calls will return a value specified by `mockReturnValue`.
*
* @example
*
* const myMockFn = jest.fn()
* .mockReturnValue('default')
* .mockReturnValueOnce('first call')
* .mockReturnValueOnce('second call');
*
* // 'first call', 'second call', 'default', 'default'
* console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
*
*/
mockReturnValueOnce(value: T): this;
/**
* Simple sugar function for: `jest.fn().mockImplementation(() => Promise.resolve(value));`
*/
mockResolvedValue(value: ResolvedValue<T>): this;
/**
* Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.resolve(value));`
*
* @example
*
* test('async test', async () => {
* const asyncMock = jest
* .fn()
* .mockResolvedValue('default')
* .mockResolvedValueOnce('first call')
* .mockResolvedValueOnce('second call');
*
* await asyncMock(); // first call
* await asyncMock(); // second call
* await asyncMock(); // default
* await asyncMock(); // default
* });
*
*/
mockResolvedValueOnce(value: ResolvedValue<T>): this;
/**
* Simple sugar function for: `jest.fn().mockImplementation(() => Promise.reject(value));`
*
* @example
*
* test('async test', async () => {
* const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
*
* await asyncMock(); // throws "Async error"
* });
*/
mockRejectedValue(value: RejectedValue<T>): this;
/**
* Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.reject(value));`
*
* @example
*
* test('async test', async () => {
* const asyncMock = jest
* .fn()
* .mockResolvedValueOnce('first call')
* .mockRejectedValueOnce(new Error('Async error'));
*
* await asyncMock(); // first call
* await asyncMock(); // throws "Async error"
* });
*
*/
mockRejectedValueOnce(value: RejectedValue<T>): this;
}
/**
* Represents the result of a single call to a mock function with a return value.
*/
interface MockResultReturn<T> {
type: 'return';
value: T;
}
/**
* Represents the result of a single incomplete call to a mock function.
*/
interface MockResultIncomplete {
type: 'incomplete';
value: undefined;
}
/**
* Represents the result of a single call to a mock function with a thrown error.
*/
interface MockResultThrow {
type: 'throw';
value: any;
}
type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
interface MockContext<T, Y extends any[]> {
calls: Y[];
instances: T[];
invocationCallOrder: number[];
/**
* List of results of calls to the mock function.
*/
results: Array<MockResult<T>>;
}
}
// Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected.
// Relevant parts of Jasmine's API are below so they can be changed and removed over time.
// This file can't reference jasmine.d.ts since the globals aren't compatible.
declare function spyOn<T>(object: T, method: keyof T): jasmine.Spy;
/**
* If you call the function pending anywhere in the spec body,
* no matter the expectations, the spec will be marked pending.
*/
declare function pending(reason?: string): void;
/**
* Fails a test when called within one.
*/
declare function fail(error?: any): never;
declare namespace jasmine {
let DEFAULT_TIMEOUT_INTERVAL: number;
function clock(): Clock;
function any(aclass: any): Any;
function anything(): Any;
function arrayContaining(sample: any[]): ArrayContaining;
function objectContaining(sample: any): ObjectContaining;
function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy;
function createSpyObj(baseName: string, methodNames: any[]): any;
// tslint:disable-next-line: no-unnecessary-generics
function createSpyObj<T>(baseName: string, methodNames: any[]): T;
function pp(value: any): string;
function addCustomEqualityTester(equalityTester: CustomEqualityTester): void;
function addMatchers(matchers: CustomMatcherFactories): void;
function stringMatching(value: string | RegExp): Any;
interface Clock {
install(): void;
uninstall(): void;
/**
* Calls to any registered callback are triggered when the clock isticked forward
* via the jasmine.clock().tick function, which takes a number of milliseconds.
*/
tick(ms: number): void;
mockDate(date?: Date): void;
}
interface Any {
new (expectedClass: any): any;
jasmineMatches(other: any): boolean;
jasmineToString(): string;
}
interface ArrayContaining {
new (sample: any[]): any;
asymmetricMatch(other: any): boolean;
jasmineToString(): string;
}
interface ObjectContaining {
new (sample: any): any;
jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean;
jasmineToString(): string;
}
interface Spy {
(...params: any[]): any;
identity: string;
and: SpyAnd;
calls: Calls;
mostRecentCall: { args: any[] };
argsForCall: any[];
wasCalled: boolean;
}
interface SpyAnd {
/**
* By chaining the spy with and.callThrough, the spy will still track all
* calls to it but in addition it will delegate to the actual implementation.
*/
callThrough(): Spy;
/**
* By chaining the spy with and.returnValue, all calls to the function
* will return a specific value.
*/
returnValue(val: any): Spy;
/**
* By chaining the spy with and.returnValues, all calls to the function
* will return specific values in order until it reaches the end of the return values list.
*/
returnValues(...values: any[]): Spy;
/**
* By chaining the spy with and.callFake, all calls to the spy
* will delegate to the supplied function.
*/
callFake(fn: (...args: any[]) => any): Spy;
/**
* By chaining the spy with and.throwError, all calls to the spy
* will throw the specified value.
*/
throwError(msg: string): Spy;
/**
* When a calling strategy is used for a spy, the original stubbing
* behavior can be returned at any time with and.stub.
*/
stub(): Spy;
}
interface Calls {
/**
* By chaining the spy with calls.any(),
* will return false if the spy has not been called at all,
* and then true once at least one call happens.
*/
any(): boolean;
/**
* By chaining the spy with calls.count(),
* will return the number of times the spy was called
*/
count(): number;
/**
* By chaining the spy with calls.argsFor(),
* will return the arguments passed to call number index
*/
argsFor(index: number): any[];
/**
* By chaining the spy with calls.allArgs(),
* will return the arguments to all calls
*/
allArgs(): any[];
/**
* By chaining the spy with calls.all(), will return the
* context (the this) and arguments passed all calls
*/
all(): CallInfo[];
/**
* By chaining the spy with calls.mostRecent(), will return the
* context (the this) and arguments for the most recent call
*/
mostRecent(): CallInfo;
/**
* By chaining the spy with calls.first(), will return the
* context (the this) and arguments for the first call
*/
first(): CallInfo;
/**
* By chaining the spy with calls.reset(), will clears all tracking for a spy
*/
reset(): void;
}
interface CallInfo {
/**
* The context (the this) for the call
*/
object: any;
/**
* All arguments passed to the call
*/
args: any[];
/**
* The return value of the call
*/
returnValue: any;
}
interface CustomMatcherFactories {
[index: string]: CustomMatcherFactory;
}
type CustomMatcherFactory = (util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]) => CustomMatcher;
interface MatchersUtil {
equals(a: any, b: any, customTesters?: CustomEqualityTester[]): boolean;
// tslint:disable-next-line: no-unnecessary-generics
contains<T>(haystack: ArrayLike<T> | string, needle: any, customTesters?: CustomEqualityTester[]): boolean;
buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string;
}
type CustomEqualityTester = (first: any, second: any) => boolean;
interface CustomMatcher {
compare<T>(actual: T, expected: T, ...args: any[]): CustomMatcherResult;
compare(actual: any, ...expected: any[]): CustomMatcherResult;
}
interface CustomMatcherResult {
pass: boolean;
message: string | (() => string);
}
interface ArrayLike<T> {
length: number;
[n: number]: T;
}
}
{
"name": "@types/jest",
"version": "26.0.23",
"description": "TypeScript definitions for Jest",
"license": "MIT",
"contributors": [
{
"name": "Asana (https://asana.com)\n// Ivo Stratev",
"url": "https://github.com/NoHomey",
"githubUsername": "NoHomey"
},
{
"name": "jwbay",
"url": "https://github.com/jwbay",
"githubUsername": "jwbay"
},
{
"name": "Alexey Svetliakov",
"url": "https://github.com/asvetliakov",
"githubUsername": "asvetliakov"
},
{
"name": "Alex Jover Morales",
"url": "https://github.com/alexjoverm",
"githubUsername": "alexjoverm"
},
{
"name": "Allan Lukwago",
"url": "https://github.com/epicallan",
"githubUsername": "epicallan"
},
{
"name": "Ika",
"url": "https://github.com/ikatyang",
"githubUsername": "ikatyang"
},
{
"name": "Waseem Dahman",
"url": "https://github.com/wsmd",
"githubUsername": "wsmd"
},
{
"name": "Jamie Mason",
"url": "https://github.com/JamieMason",
"githubUsername": "JamieMason"
},
{
"name": "Douglas Duteil",
"url": "https://github.com/douglasduteil",
"githubUsername": "douglasduteil"
},
{
"name": "Ahn",
"url": "https://github.com/ahnpnl",
"githubUsername": "ahnpnl"
},
{
"name": "Josh Goldberg",
"url": "https://github.com/joshuakgoldberg",
"githubUsername": "joshuakgoldberg"
},
{
"name": "Jeff Lau",
"url": "https://github.com/UselessPickles",
"githubUsername": "UselessPickles"
},
{
"name": "Andrew Makarov",
"url": "https://github.com/r3nya",
"githubUsername": "r3nya"
},
{
"name": "Martin Hochel",
"url": "https://github.com/hotell",
"githubUsername": "hotell"
},
{
"name": "Sebastian Sebald",
"url": "https://github.com/sebald",
"githubUsername": "sebald"
},
{
"name": "Andy",
"url": "https://github.com/andys8",
"githubUsername": "andys8"
},
{
"name": "Antoine Brault",
"url": "https://github.com/antoinebrault",
"githubUsername": "antoinebrault"
},
{
"name": "Gregor Stamać",
"url": "https://github.com/gstamac",
"githubUsername": "gstamac"
},
{
"name": "ExE Boss",
"url": "https://github.com/ExE-Boss",
"githubUsername": "ExE-Boss"
},
{
"name": "Alex Bolenok",
"url": "https://github.com/quassnoi",
"githubUsername": "quassnoi"
},
{
"name": "Mario Beltrán Alarcón",
"url": "https://github.com/Belco90",
"githubUsername": "Belco90"
},
{
"name": "Tony Hallett",
"url": "https://github.com/tonyhallett",
"githubUsername": "tonyhallett"
},
{
"name": "Jason Yu",
"url": "https://github.com/ycmjason",
"githubUsername": "ycmjason"
},
{
"name": "Devansh Jethmalani",
"url": "https://github.com/devanshj",
"githubUsername": "devanshj"
},
{
"name": "Pawel Fajfer",
"url": "https://github.com/pawfa",
"githubUsername": "pawfa"
},
{
"name": "Regev Brody",
"url": "https://github.com/regevbr",
"githubUsername": "regevbr"
},
{
"name": "Alexandre Germain",
"url": "https://github.com/gerkindev",
"githubUsername": "gerkindev"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/jest"
},
"scripts": {},
"dependencies": {
"jest-diff": "^26.0.0",
"pretty-format": "^26.0.0"
},
"typesPublisherContentHash": "2ba294369468924cf573f064d944f4d4df1a25e8b23a828c75a085ef2452f0c3",
"typeScriptVersion": "3.8"
}
\ No newline at end of file
MIT License
Copyright (c) Microsoft Corporation.
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
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js (http://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details
* Last updated: Sun, 27 Jun 2021 03:01:14 GMT
* Dependencies: none
* Global values: `AbortController`, `AbortSignal`, `Buffer`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout`
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Minh Son Nguyen](https://github.com/nguymin4), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Jason Kwok](https://github.com/JasonHK), [Victor Perin](https://github.com/victorperin), and [Yongsheng Zhang](https://github.com/ZYSzys).
declare module 'assert' {
/** An alias of `assert.ok()`. */
function assert(value: any, message?: string | Error): asserts value;
namespace assert {
class AssertionError extends Error {
actual: any;
expected: any;
operator: string;
generatedMessage: boolean;
code: 'ERR_ASSERTION';
constructor(options?: {
/** If provided, the error message is set to this value. */
message?: string;
/** The `actual` property on the error instance. */
actual?: any;
/** The `expected` property on the error instance. */
expected?: any;
/** The `operator` property on the error instance. */
operator?: string;
/** If provided, the generated stack trace omits frames before this function. */
// tslint:disable-next-line:ban-types
stackStartFn?: Function;
});
}
class CallTracker {
calls(exact?: number): () => void;
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func;
report(): CallTrackerReportInformation[];
verify(): void;
}
interface CallTrackerReportInformation {
message: string;
/** The actual number of times the function was called. */
actual: number;
/** The number of times the function was expected to be called. */
expected: number;
/** The name of the function that is wrapped. */
operator: string;
/** A stack trace of the function. */
stack: object;
}
type AssertPredicate = RegExp | (new () => object) | ((thrown: any) => boolean) | object | Error;
function fail(message?: string | Error): never;
/** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */
function fail(
actual: any,
expected: any,
message?: string | Error,
operator?: string,
// tslint:disable-next-line:ban-types
stackStartFn?: Function,
): never;
function ok(value: any, message?: string | Error): asserts value;
/** @deprecated since v9.9.0 - use strictEqual() instead. */
function equal(actual: any, expected: any, message?: string | Error): void;
/** @deprecated since v9.9.0 - use notStrictEqual() instead. */
function notEqual(actual: any, expected: any, message?: string | Error): void;
/** @deprecated since v9.9.0 - use deepStrictEqual() instead. */
function deepEqual(actual: any, expected: any, message?: string | Error): void;
/** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */
function notDeepEqual(actual: any, expected: any, message?: string | Error): void;
function strictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T;
function notStrictEqual(actual: any, expected: any, message?: string | Error): void;
function deepStrictEqual<T>(actual: any, expected: T, message?: string | Error): asserts actual is T;
function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void;
function throws(block: () => any, message?: string | Error): void;
function throws(block: () => any, error: AssertPredicate, message?: string | Error): void;
function doesNotThrow(block: () => any, message?: string | Error): void;
function doesNotThrow(block: () => any, error: AssertPredicate, message?: string | Error): void;
function ifError(value: any): asserts value is null | undefined;
function rejects(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
function rejects(
block: (() => Promise<any>) | Promise<any>,
error: AssertPredicate,
message?: string | Error,
): Promise<void>;
function doesNotReject(block: (() => Promise<any>) | Promise<any>, message?: string | Error): Promise<void>;
function doesNotReject(
block: (() => Promise<any>) | Promise<any>,
error: AssertPredicate,
message?: string | Error,
): Promise<void>;
function match(value: string, regExp: RegExp, message?: string | Error): void;
function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void;
const strict: Omit<
typeof assert,
| 'equal'
| 'notEqual'
| 'deepEqual'
| 'notDeepEqual'
| 'ok'
| 'strictEqual'
| 'deepStrictEqual'
| 'ifError'
| 'strict'
> & {
(value: any, message?: string | Error): asserts value;
equal: typeof strictEqual;
notEqual: typeof notStrictEqual;
deepEqual: typeof deepStrictEqual;
notDeepEqual: typeof notDeepStrictEqual;
// Mapped types and assertion functions are incompatible?
// TS2775: Assertions require every name in the call target
// to be declared with an explicit type annotation.
ok: typeof ok;
strictEqual: typeof strictEqual;
deepStrictEqual: typeof deepStrictEqual;
ifError: typeof ifError;
strict: typeof strict;
};
}
export = assert;
}
declare module 'assert/strict' {
import { strict } from 'assert';
export = strict;
}
/**
* Async Hooks module: https://nodejs.org/api/async_hooks.html
*/
declare module 'async_hooks' {
/**
* Returns the asyncId of the current execution context.
*/
function executionAsyncId(): number;
/**
* The resource representing the current execution.
* Useful to store data within the resource.
*
* Resource objects returned by `executionAsyncResource()` are most often internal
* Node.js handle objects with undocumented APIs. Using any functions or properties
* on the object is likely to crash your application and should be avoided.
*
* Using `executionAsyncResource()` in the top-level execution context will
* return an empty object as there is no handle or request object to use,
* but having an object representing the top-level can be helpful.
*/
function executionAsyncResource(): object;
/**
* Returns the ID of the resource responsible for calling the callback that is currently being executed.
*/
function triggerAsyncId(): number;
interface HookCallbacks {
/**
* Called when a class is constructed that has the possibility to emit an asynchronous event.
* @param asyncId a unique ID for the async resource
* @param type the type of the async resource
* @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created
* @param resource reference to the resource representing the async operation, needs to be released during destroy
*/
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void;
/**
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
* The before callback is called just before said callback is executed.
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
*/
before?(asyncId: number): void;
/**
* Called immediately after the callback specified in before is completed.
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
*/
after?(asyncId: number): void;
/**
* Called when a promise has resolve() called. This may not be in the same execution id
* as the promise itself.
* @param asyncId the unique id for the promise that was resolve()d.
*/
promiseResolve?(asyncId: number): void;
/**
* Called after the resource corresponding to asyncId is destroyed
* @param asyncId a unique ID for the async resource
*/
destroy?(asyncId: number): void;
}
interface AsyncHook {
/**
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
*/
enable(): this;
/**
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
*/
disable(): this;
}
/**
* Registers functions to be called for different lifetime events of each async operation.
* @param options the callbacks to register
* @return an AsyncHooks instance used for disabling and enabling hooks
*/
function createHook(options: HookCallbacks): AsyncHook;
interface AsyncResourceOptions {
/**
* The ID of the execution context that created this async event.
* @default executionAsyncId()
*/
triggerAsyncId?: number;
/**
* Disables automatic `emitDestroy` when the object is garbage collected.
* This usually does not need to be set (even if `emitDestroy` is called
* manually), unless the resource's `asyncId` is retrieved and the
* sensitive API's `emitDestroy` is called with it.
* @default false
*/
requireManualDestroy?: boolean;
}
/**
* The class AsyncResource was designed to be extended by the embedder's async resources.
* Using this users can easily trigger the lifetime events of their own resources.
*/
class AsyncResource {
/**
* AsyncResource() is meant to be extended. Instantiating a
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
* async_hook.executionAsyncId() is used.
* @param type The type of async event.
* @param triggerAsyncId The ID of the execution context that created
* this async event (default: `executionAsyncId()`), or an
* AsyncResourceOptions object (since 9.3)
*/
constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions);
/**
* Binds the given function to the current execution context.
* @param fn The function to bind to the current execution context.
* @param type An optional name to associate with the underlying `AsyncResource`.
*/
static bind<Func extends (...args: any[]) => any>(fn: Func, type?: string): Func & { asyncResource: AsyncResource };
/**
* Binds the given function to execute to this `AsyncResource`'s scope.
* @param fn The function to bind to the current `AsyncResource`.
*/
bind<Func extends (...args: any[]) => any>(fn: Func): Func & { asyncResource: AsyncResource };
/**
* Call the provided function with the provided arguments in the
* execution context of the async resource. This will establish the
* context, trigger the AsyncHooks before callbacks, call the function,
* trigger the AsyncHooks after callbacks, and then restore the original
* execution context.
* @param fn The function to call in the execution context of this
* async resource.
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result;
/**
* Call AsyncHooks destroy callbacks.
*/
emitDestroy(): this;
/**
* @return the unique ID assigned to this AsyncResource instance.
*/
asyncId(): number;
/**
* @return the trigger ID for this AsyncResource instance.
*/
triggerAsyncId(): number;
}
/**
* When having multiple instances of `AsyncLocalStorage`, they are independent
* from each other. It is safe to instantiate this class multiple times.
*/
class AsyncLocalStorage<T> {
/**
* This method disables the instance of `AsyncLocalStorage`. All subsequent calls
* to `asyncLocalStorage.getStore()` will return `undefined` until
* `asyncLocalStorage.run()` is called again.
*
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the
* instance will be exited.
*
* Calling `asyncLocalStorage.disable()` is required before the
* `asyncLocalStorage` can be garbage collected. This does not apply to stores
* provided by the `asyncLocalStorage`, as those objects are garbage collected
* along with the corresponding async resources.
*
* This method is to be used when the `asyncLocalStorage` is not in use anymore
* in the current process.
*/
disable(): void;
/**
* This method returns the current store. If this method is called outside of an
* asynchronous context initialized by calling `asyncLocalStorage.run`, it will
* return `undefined`.
*/
getStore(): T | undefined;
/**
* This methods runs a function synchronously within a context and return its
* return value. The store is not accessible outside of the callback function or
* the asynchronous operations created within the callback.
*
* Optionally, arguments can be passed to the function. They will be passed to the
* callback function.
*
* I the callback function throws an error, it will be thrown by `run` too. The
* stacktrace will not be impacted by this call and the context will be exited.
*/
// TODO: Apply generic vararg once available
run<R>(store: T, callback: (...args: any[]) => R, ...args: any[]): R;
/**
* This methods runs a function synchronously outside of a context and return its
* return value. The store is not accessible within the callback function or the
* asynchronous operations created within the callback.
*
* Optionally, arguments can be passed to the function. They will be passed to the
* callback function.
*
* If the callback function throws an error, it will be thrown by `exit` too. The
* stacktrace will not be impacted by this call and the context will be
* re-entered.
*/
// TODO: Apply generic vararg once available
exit<R>(callback: (...args: any[]) => R, ...args: any[]): R;
/**
* Calling `asyncLocalStorage.enterWith(store)` will transition into the context
* for the remainder of the current synchronous execution and will persist
* through any following asynchronous calls.
*/
enterWith(store: T): void;
}
}
// NOTE: These definitions support NodeJS and TypeScript 3.7.
// NOTE: TypeScript version-specific augmentations can be found in the following paths:
// - ~/base.d.ts - Shared definitions common to all TypeScript versions
// - ~/index.d.ts - Definitions specific to TypeScript 2.1
// - ~/ts3.7/base.d.ts - Definitions specific to TypeScript 3.7
// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in
// Reference required types from the default lib:
/// <reference lib="es2018" />
/// <reference lib="esnext.asynciterable" />
/// <reference lib="esnext.intl" />
/// <reference lib="esnext.bigint" />
// Base definitions for all NodeJS modules that are not specific to any version of TypeScript:
/// <reference path="ts3.6/base.d.ts" />
// TypeScript 3.7-specific augmentations:
/// <reference path="assert.d.ts" />
declare module 'buffer' {
import { BinaryLike } from 'crypto';
export const INSPECT_MAX_BYTES: number;
export const kMaxLength: number;
export const kStringMaxLength: number;
export const constants: {
MAX_LENGTH: number;
MAX_STRING_LENGTH: number;
};
const BuffType: typeof Buffer;
export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary";
export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer;
export const SlowBuffer: {
/** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */
new(size: number): Buffer;
prototype: Buffer;
};
export { BuffType as Buffer };
/**
* @experimental
*/
export interface BlobOptions {
/**
* @default 'utf8'
*/
encoding?: BufferEncoding;
/**
* The Blob content-type. The intent is for `type` to convey
* the MIME media type of the data, however no validation of the type format
* is performed.
*/
type?: string;
}
/**
* @experimental
*/
export class Blob {
/**
* Returns a promise that fulfills with an {ArrayBuffer} containing a copy of the `Blob` data.
*/
readonly size: number;
/**
* The content-type of the `Blob`.
*/
readonly type: string;
/**
* Creates a new `Blob` object containing a concatenation of the given sources.
*
* {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into
* the 'Blob' and can therefore be safely modified after the 'Blob' is created.
*
* String sources are also copied into the `Blob`.
*/
constructor(sources: Array<(BinaryLike | Blob)>, options?: BlobOptions);
arrayBuffer(): Promise<ArrayBuffer>;
/**
* @param start The starting index.
* @param end The ending index.
* @param type The content-type for the new `Blob`
*/
slice(start?: number, end?: number, type?: string): Blob;
/**
* Returns a promise that resolves the contents of the `Blob` decoded as a UTF-8 string.
*/
text(): Promise<string>;
}
}
declare module 'node:buffer' {
export * from 'buffer';
}
declare module 'child_process' {
import { BaseEncodingOptions } from 'fs';
import { EventEmitter, Abortable } from 'events';
import * as net from 'net';
import { Writable, Readable, Stream, Pipe } from 'stream';
type Serializable = string | object | number | boolean | bigint;
type SendHandle = net.Socket | net.Server;
interface ChildProcess extends EventEmitter {
stdin: Writable | null;
stdout: Readable | null;
stderr: Readable | null;
readonly channel?: Pipe | null;
readonly stdio: [
Writable | null, // stdin
Readable | null, // stdout
Readable | null, // stderr
Readable | Writable | null | undefined, // extra
Readable | Writable | null | undefined // extra
];
readonly killed: boolean;
readonly pid?: number;
readonly connected: boolean;
readonly exitCode: number | null;
readonly signalCode: NodeJS.Signals | null;
readonly spawnargs: string[];
readonly spawnfile: string;
kill(signal?: NodeJS.Signals | number): boolean;
send(message: Serializable, callback?: (error: Error | null) => void): boolean;
send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean;
send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean;
disconnect(): void;
unref(): void;
ref(): void;
/**
* events.EventEmitter
* 1. close
* 2. disconnect
* 3. error
* 4. exit
* 5. message
* 6. spawn
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
addListener(event: "disconnect", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
addListener(event: "spawn", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean;
emit(event: "disconnect"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean;
emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean;
emit(event: "spawn", listener: () => void): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
on(event: "disconnect", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
on(event: "spawn", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
once(event: "disconnect", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
once(event: "spawn", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
prependListener(event: "disconnect", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
prependListener(event: "spawn", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
prependOnceListener(event: "disconnect", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this;
prependOnceListener(event: "spawn", listener: () => void): this;
}
// return this object when stdio option is undefined or not specified
interface ChildProcessWithoutNullStreams extends ChildProcess {
stdin: Writable;
stdout: Readable;
stderr: Readable;
readonly stdio: [
Writable, // stdin
Readable, // stdout
Readable, // stderr
Readable | Writable | null | undefined, // extra, no modification
Readable | Writable | null | undefined // extra, no modification
];
}
// return this object when stdio option is a tuple of 3
interface ChildProcessByStdio<
I extends null | Writable,
O extends null | Readable,
E extends null | Readable,
> extends ChildProcess {
stdin: I;
stdout: O;
stderr: E;
readonly stdio: [
I,
O,
E,
Readable | Writable | null | undefined, // extra, no modification
Readable | Writable | null | undefined // extra, no modification
];
}
interface MessageOptions {
keepOpen?: boolean;
}
type IOType = "overlapped" | "pipe" | "ignore" | "inherit";
type StdioOptions = IOType | Array<(IOType | "ipc" | Stream | number | null | undefined)>;
type SerializationType = 'json' | 'advanced';
interface MessagingOptions extends Abortable {
/**
* Specify the kind of serialization used for sending messages between processes.
* @default 'json'
*/
serialization?: SerializationType;
/**
* The signal value to be used when the spawned process will be killed by the abort signal.
* @default 'SIGTERM'
*/
killSignal?: NodeJS.Signals | number;
}
interface ProcessEnvOptions {
uid?: number;
gid?: number;
cwd?: string;
env?: NodeJS.ProcessEnv;
}
interface CommonOptions extends ProcessEnvOptions {
/**
* @default true
*/
windowsHide?: boolean;
/**
* @default 0
*/
timeout?: number;
}
interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable {
argv0?: string;
stdio?: StdioOptions;
shell?: boolean | string;
windowsVerbatimArguments?: boolean;
}
interface SpawnOptions extends CommonSpawnOptions {
detached?: boolean;
}
interface SpawnOptionsWithoutStdio extends SpawnOptions {
stdio?: StdioPipeNamed | StdioPipe[];
}
type StdioNull = 'inherit' | 'ignore' | Stream;
type StdioPipeNamed = 'pipe' | 'overlapped';
type StdioPipe = undefined | null | StdioPipeNamed;
interface SpawnOptionsWithStdioTuple<
Stdin extends StdioNull | StdioPipe,
Stdout extends StdioNull | StdioPipe,
Stderr extends StdioNull | StdioPipe,
> extends SpawnOptions {
stdio: [Stdin, Stdout, Stderr];
}
// overloads of spawn without 'args'
function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>,
): ChildProcessByStdio<Writable, Readable, Readable>;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>,
): ChildProcessByStdio<Writable, Readable, null>;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>,
): ChildProcessByStdio<Writable, null, Readable>;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,
): ChildProcessByStdio<null, Readable, Readable>;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>,
): ChildProcessByStdio<Writable, null, null>;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>,
): ChildProcessByStdio<null, Readable, null>;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>,
): ChildProcessByStdio<null, null, Readable>;
function spawn(
command: string,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>,
): ChildProcessByStdio<null, null, null>;
function spawn(command: string, options: SpawnOptions): ChildProcess;
// overloads of spawn with 'args'
function spawn(command: string, args?: ReadonlyArray<string>, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>,
): ChildProcessByStdio<Writable, Readable, Readable>;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioNull>,
): ChildProcessByStdio<Writable, Readable, null>;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioPipe>,
): ChildProcessByStdio<Writable, null, Readable>;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,
): ChildProcessByStdio<null, Readable, Readable>;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioPipe, StdioNull, StdioNull>,
): ChildProcessByStdio<Writable, null, null>;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioNull>,
): ChildProcessByStdio<null, Readable, null>;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioPipe>,
): ChildProcessByStdio<null, null, Readable>;
function spawn(
command: string,
args: ReadonlyArray<string>,
options: SpawnOptionsWithStdioTuple<StdioNull, StdioNull, StdioNull>,
): ChildProcessByStdio<null, null, null>;
function spawn(command: string, args: ReadonlyArray<string>, options: SpawnOptions): ChildProcess;
interface ExecOptions extends CommonOptions {
shell?: string;
maxBuffer?: number;
killSignal?: NodeJS.Signals | number;
}
interface ExecOptionsWithStringEncoding extends ExecOptions {
encoding: BufferEncoding;
}
interface ExecOptionsWithBufferEncoding extends ExecOptions {
encoding: BufferEncoding | null; // specify `null`.
}
interface ExecException extends Error {
cmd?: string;
killed?: boolean;
code?: number;
signal?: NodeJS.Signals;
}
// no `options` definitely means stdout/stderr are `string`.
function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
// `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
// `options` with well known `encoding` means stdout/stderr are definitely `string`.
function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
// `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
// There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
function exec(
command: string,
options: { encoding: BufferEncoding } & ExecOptions,
callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
): ChildProcess;
// `options` without an `encoding` means stdout/stderr are definitely `string`.
function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess;
// fallback if nothing else matches. Worst case is always `string | Buffer`.
function exec(
command: string,
options: (BaseEncodingOptions & ExecOptions) | undefined | null,
callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
): ChildProcess;
interface PromiseWithChild<T> extends Promise<T> {
child: ChildProcess;
}
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
namespace exec {
function __promisify__(command: string): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>;
function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(command: string, options?: (BaseEncodingOptions & ExecOptions) | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
}
interface ExecFileOptions extends CommonOptions, Abortable {
maxBuffer?: number;
killSignal?: NodeJS.Signals | number;
windowsVerbatimArguments?: boolean;
shell?: boolean | string;
signal?: AbortSignal;
}
interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {
encoding: BufferEncoding;
}
interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions {
encoding: 'buffer' | null;
}
interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {
encoding: BufferEncoding;
}
type ExecFileException = ExecException & NodeJS.ErrnoException;
function execFile(file: string): ChildProcess;
function execFile(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess;
function execFile(file: string, args?: ReadonlyArray<string> | null): ChildProcess;
function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess;
// no `options` definitely means stdout/stderr are `string`.
function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
function execFile(file: string, args: ReadonlyArray<string> | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
// `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess;
function execFile(
file: string,
args: ReadonlyArray<string> | undefined | null,
options: ExecFileOptionsWithBufferEncoding,
callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void,
): ChildProcess;
// `options` with well known `encoding` means stdout/stderr are definitely `string`.
function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
function execFile(
file: string,
args: ReadonlyArray<string> | undefined | null,
options: ExecFileOptionsWithStringEncoding,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
): ChildProcess;
// `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
// There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
function execFile(
file: string,
options: ExecFileOptionsWithOtherEncoding,
callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
): ChildProcess;
function execFile(
file: string,
args: ReadonlyArray<string> | undefined | null,
options: ExecFileOptionsWithOtherEncoding,
callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
): ChildProcess;
// `options` without an `encoding` means stdout/stderr are definitely `string`.
function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess;
function execFile(
file: string,
args: ReadonlyArray<string> | undefined | null,
options: ExecFileOptions,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void
): ChildProcess;
// fallback if nothing else matches. Worst case is always `string | Buffer`.
function execFile(
file: string,
options: (BaseEncodingOptions & ExecFileOptions) | undefined | null,
callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null,
): ChildProcess;
function execFile(
file: string,
args: ReadonlyArray<string> | undefined | null,
options: (BaseEncodingOptions & ExecFileOptions) | undefined | null,
callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null,
): ChildProcess;
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
namespace execFile {
function __promisify__(file: string): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(file: string, args: ReadonlyArray<string> | undefined | null): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>;
function __promisify__(file: string, args: ReadonlyArray<string> | undefined | null, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>;
function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(file: string, args: ReadonlyArray<string> | undefined | null, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
function __promisify__(
file: string,
args: ReadonlyArray<string> | undefined | null,
options: ExecFileOptionsWithOtherEncoding,
): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
function __promisify__(file: string, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(file: string, args: ReadonlyArray<string> | undefined | null, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>;
function __promisify__(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
function __promisify__(
file: string,
args: ReadonlyArray<string> | undefined | null,
options: (BaseEncodingOptions & ExecFileOptions) | undefined | null,
): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>;
}
interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable {
execPath?: string;
execArgv?: string[];
silent?: boolean;
stdio?: StdioOptions;
detached?: boolean;
windowsVerbatimArguments?: boolean;
}
function fork(modulePath: string, options?: ForkOptions): ChildProcess;
function fork(modulePath: string, args?: ReadonlyArray<string>, options?: ForkOptions): ChildProcess;
interface SpawnSyncOptions extends CommonSpawnOptions {
input?: string | NodeJS.ArrayBufferView;
maxBuffer?: number;
encoding?: BufferEncoding | 'buffer' | null;
}
interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions {
encoding: BufferEncoding;
}
interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions {
encoding?: 'buffer' | null;
}
interface SpawnSyncReturns<T> {
pid: number;
output: string[];
stdout: T;
stderr: T;
status: number | null;
signal: NodeJS.Signals | null;
error?: Error;
}
function spawnSync(command: string): SpawnSyncReturns<Buffer>;
function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;
function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;
function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;
function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;
interface ExecSyncOptions extends CommonOptions {
input?: string | Uint8Array;
stdio?: StdioOptions;
shell?: string;
killSignal?: NodeJS.Signals | number;
maxBuffer?: number;
encoding?: BufferEncoding | 'buffer' | null;
}
interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions {
encoding: BufferEncoding;
}
interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions {
encoding?: 'buffer' | null;
}
function execSync(command: string): Buffer;
function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string;
function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer;
function execSync(command: string, options?: ExecSyncOptions): Buffer;
interface ExecFileSyncOptions extends CommonOptions {
input?: string | NodeJS.ArrayBufferView;
stdio?: StdioOptions;
killSignal?: NodeJS.Signals | number;
maxBuffer?: number;
encoding?: BufferEncoding;
shell?: boolean | string;
}
interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions {
encoding: BufferEncoding;
}
interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions {
encoding: BufferEncoding; // specify `null`.
}
function execFileSync(command: string): Buffer;
function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string;
function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;
function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer;
function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithStringEncoding): string;
function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;
function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptions): Buffer;
}
declare module 'cluster' {
import * as child from 'child_process';
import EventEmitter = require('events');
import * as net from 'net';
// interfaces
interface ClusterSettings {
execArgv?: string[]; // default: process.execArgv
exec?: string;
args?: string[];
silent?: boolean;
stdio?: any[];
uid?: number;
gid?: number;
inspectPort?: number | (() => number);
}
interface Address {
address: string;
port: number;
addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6"
}
class Worker extends EventEmitter {
id: number;
process: child.ChildProcess;
send(message: child.Serializable, sendHandle?: child.SendHandle, callback?: (error: Error | null) => void): boolean;
kill(signal?: string): void;
destroy(signal?: string): void;
disconnect(): void;
isConnected(): boolean;
isDead(): boolean;
exitedAfterDisconnect: boolean;
/**
* events.EventEmitter
* 1. disconnect
* 2. error
* 3. exit
* 4. listening
* 5. message
* 6. online
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "disconnect", listener: () => void): this;
addListener(event: "error", listener: (error: Error) => void): this;
addListener(event: "exit", listener: (code: number, signal: string) => void): this;
addListener(event: "listening", listener: (address: Address) => void): this;
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "disconnect"): boolean;
emit(event: "error", error: Error): boolean;
emit(event: "exit", code: number, signal: string): boolean;
emit(event: "listening", address: Address): boolean;
emit(event: "message", message: any, handle: net.Socket | net.Server): boolean;
emit(event: "online"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "disconnect", listener: () => void): this;
on(event: "error", listener: (error: Error) => void): this;
on(event: "exit", listener: (code: number, signal: string) => void): this;
on(event: "listening", listener: (address: Address) => void): this;
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "disconnect", listener: () => void): this;
once(event: "error", listener: (error: Error) => void): this;
once(event: "exit", listener: (code: number, signal: string) => void): this;
once(event: "listening", listener: (address: Address) => void): this;
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "disconnect", listener: () => void): this;
prependListener(event: "error", listener: (error: Error) => void): this;
prependListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependListener(event: "listening", listener: (address: Address) => void): this;
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: "online", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "disconnect", listener: () => void): this;
prependOnceListener(event: "error", listener: (error: Error) => void): this;
prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependOnceListener(event: "listening", listener: (address: Address) => void): this;
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: "online", listener: () => void): this;
}
interface Cluster extends EventEmitter {
Worker: Worker;
disconnect(callback?: () => void): void;
fork(env?: any): Worker;
isMaster: boolean;
isWorker: boolean;
schedulingPolicy: number;
settings: ClusterSettings;
setupMaster(settings?: ClusterSettings): void;
worker?: Worker;
workers?: NodeJS.Dict<Worker>;
readonly SCHED_NONE: number;
readonly SCHED_RR: number;
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "disconnect", listener: (worker: Worker) => void): this;
addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
addListener(event: "fork", listener: (worker: Worker) => void): this;
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: (worker: Worker) => void): this;
addListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "disconnect", worker: Worker): boolean;
emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
emit(event: "fork", worker: Worker): boolean;
emit(event: "listening", worker: Worker, address: Address): boolean;
emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
emit(event: "online", worker: Worker): boolean;
emit(event: "setup", settings: ClusterSettings): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "disconnect", listener: (worker: Worker) => void): this;
on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
on(event: "fork", listener: (worker: Worker) => void): this;
on(event: "listening", listener: (worker: Worker, address: Address) => void): this;
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: (worker: Worker) => void): this;
on(event: "setup", listener: (settings: ClusterSettings) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "disconnect", listener: (worker: Worker) => void): this;
once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
once(event: "fork", listener: (worker: Worker) => void): this;
once(event: "listening", listener: (worker: Worker, address: Address) => void): this;
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: (worker: Worker) => void): this;
once(event: "setup", listener: (settings: ClusterSettings) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependListener(event: "fork", listener: (worker: Worker) => void): this;
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: "online", listener: (worker: Worker) => void): this;
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependOnceListener(event: "fork", listener: (worker: Worker) => void): this;
prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this;
prependOnceListener(event: "online", listener: (worker: Worker) => void): this;
prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
}
const SCHED_NONE: number;
const SCHED_RR: number;
function disconnect(callback?: () => void): void;
function fork(env?: any): Worker;
const isMaster: boolean;
const isWorker: boolean;
let schedulingPolicy: number;
const settings: ClusterSettings;
function setupMaster(settings?: ClusterSettings): void;
const worker: Worker;
const workers: NodeJS.Dict<Worker>;
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
function addListener(event: string, listener: (...args: any[]) => void): Cluster;
function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function addListener(event: "fork", listener: (worker: Worker) => void): Cluster;
function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
// the handle is a net.Socket or net.Server object, or undefined.
function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
function addListener(event: "online", listener: (worker: Worker) => void): Cluster;
function addListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function emit(event: string | symbol, ...args: any[]): boolean;
function emit(event: "disconnect", worker: Worker): boolean;
function emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
function emit(event: "fork", worker: Worker): boolean;
function emit(event: "listening", worker: Worker, address: Address): boolean;
function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
function emit(event: "online", worker: Worker): boolean;
function emit(event: "setup", settings: ClusterSettings): boolean;
function on(event: string, listener: (...args: any[]) => void): Cluster;
function on(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function on(event: "fork", listener: (worker: Worker) => void): Cluster;
function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
function on(event: "online", listener: (worker: Worker) => void): Cluster;
function on(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function once(event: string, listener: (...args: any[]) => void): Cluster;
function once(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function once(event: "fork", listener: (worker: Worker) => void): Cluster;
function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined.
function once(event: "online", listener: (worker: Worker) => void): Cluster;
function once(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function removeListener(event: string, listener: (...args: any[]) => void): Cluster;
function removeAllListeners(event?: string): Cluster;
function setMaxListeners(n: number): Cluster;
function getMaxListeners(): number;
function listeners(event: string): Function[];
function listenerCount(type: string): number;
function prependListener(event: string, listener: (...args: any[]) => void): Cluster;
function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster;
function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
// the handle is a net.Socket or net.Server object, or undefined.
function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
function prependListener(event: "online", listener: (worker: Worker) => void): Cluster;
function prependListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster;
function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster;
function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster;
function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster;
function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster;
// the handle is a net.Socket or net.Server object, or undefined.
function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster;
function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster;
function prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster;
function eventNames(): string[];
}
declare module 'console' {
import { InspectOptions } from 'util';
global {
// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
interface Console {
Console: NodeJS.ConsoleConstructor;
/**
* A simple assertion test that verifies whether `value` is truthy.
* If it is not, an `AssertionError` is thrown.
* If provided, the error `message` is formatted using `util.format()` and used as the error message.
*/
assert(value: any, message?: string, ...optionalParams: any[]): void;
/**
* When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY.
* When `stdout` is not a TTY, this method does nothing.
*/
clear(): void;
/**
* Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`.
*/
count(label?: string): void;
/**
* Resets the internal counter specific to `label`.
*/
countReset(label?: string): void;
/**
* The `console.debug()` function is an alias for {@link console.log}.
*/
debug(message?: any, ...optionalParams: any[]): void;
/**
* Uses {@link util.inspect} on `obj` and prints the resulting string to `stdout`.
* This function bypasses any custom `inspect()` function defined on `obj`.
*/
dir(obj: any, options?: InspectOptions): void;
/**
* This method calls {@link console.log} passing it the arguments received. Please note that this method does not produce any XML formatting
*/
dirxml(...data: any[]): void;
/**
* Prints to `stderr` with newline.
*/
error(message?: any, ...optionalParams: any[]): void;
/**
* Increases indentation of subsequent lines by two spaces.
* If one or more `label`s are provided, those are printed first without the additional indentation.
*/
group(...label: any[]): void;
/**
* The `console.groupCollapsed()` function is an alias for {@link console.group}.
*/
groupCollapsed(...label: any[]): void;
/**
* Decreases indentation of subsequent lines by two spaces.
*/
groupEnd(): void;
/**
* The {@link console.info} function is an alias for {@link console.log}.
*/
info(message?: any, ...optionalParams: any[]): void;
/**
* Prints to `stdout` with newline.
*/
log(message?: any, ...optionalParams: any[]): void;
/**
* This method does not display anything unless used in the inspector.
* Prints to `stdout` the array `array` formatted as a table.
*/
table(tabularData: any, properties?: ReadonlyArray<string>): void;
/**
* Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`.
*/
time(label?: string): void;
/**
* Stops a timer that was previously started by calling {@link console.time} and prints the result to `stdout`.
*/
timeEnd(label?: string): void;
/**
* For a timer that was previously started by calling {@link console.time}, prints the elapsed time and other `data` arguments to `stdout`.
*/
timeLog(label?: string, ...data: any[]): void;
/**
* Prints to `stderr` the string 'Trace :', followed by the {@link util.format} formatted message and stack trace to the current position in the code.
*/
trace(message?: any, ...optionalParams: any[]): void;
/**
* The {@link console.warn} function is an alias for {@link console.error}.
*/
warn(message?: any, ...optionalParams: any[]): void;
// --- Inspector mode only ---
/**
* This method does not display anything unless used in the inspector.
* Starts a JavaScript CPU profile with an optional label.
*/
profile(label?: string): void;
/**
* This method does not display anything unless used in the inspector.
* Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector.
*/
profileEnd(label?: string): void;
/**
* This method does not display anything unless used in the inspector.
* Adds an event with the label `label` to the Timeline panel of the inspector.
*/
timeStamp(label?: string): void;
}
var console: Console;
namespace NodeJS {
interface ConsoleConstructorOptions {
stdout: WritableStream;
stderr?: WritableStream;
ignoreErrors?: boolean;
colorMode?: boolean | 'auto';
inspectOptions?: InspectOptions;
}
interface ConsoleConstructor {
prototype: Console;
new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console;
new(options: ConsoleConstructorOptions): Console;
}
interface Global {
console: typeof console;
}
}
}
export = console;
}
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */
declare module 'constants' {
import { constants as osConstants, SignalConstants } from 'os';
import { constants as cryptoConstants } from 'crypto';
import { constants as fsConstants } from 'fs';
const exp: typeof osConstants.errno &
typeof osConstants.priority &
SignalConstants &
typeof cryptoConstants &
typeof fsConstants;
export = exp;
}
declare module 'crypto' {
import * as stream from 'stream';
import { PeerCertificate } from 'tls';
interface Certificate {
/**
* @deprecated
* @param spkac
* @returns The challenge component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportChallenge(spkac: BinaryLike): Buffer;
/**
* @deprecated
* @param spkac
* @param encoding The encoding of the spkac string.
* @returns The public key component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* @deprecated
* @param spkac
* @returns `true` if the given `spkac` data structure is valid,
* `false` otherwise.
*/
verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
}
const Certificate: Certificate & {
/** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */
new(): Certificate;
/** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */
(): Certificate;
/**
* @param spkac
* @returns The challenge component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportChallenge(spkac: BinaryLike): Buffer;
/**
* @param spkac
* @param encoding The encoding of the spkac string.
* @returns The public key component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* @param spkac
* @returns `true` if the given `spkac` data structure is valid,
* `false` otherwise.
*/
verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
};
namespace constants {
// https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants
const OPENSSL_VERSION_NUMBER: number;
/** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
const SSL_OP_ALL: number;
/** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
/** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
/** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */
const SSL_OP_CISCO_ANYCONNECT: number;
/** Instructs OpenSSL to turn on cookie exchange. */
const SSL_OP_COOKIE_EXCHANGE: number;
/** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */
const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
/** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */
const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
/** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */
const SSL_OP_EPHEMERAL_RSA: number;
/** Allows initial connection to servers that do not support RI. */
const SSL_OP_LEGACY_SERVER_CONNECT: number;
const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
const SSL_OP_MICROSOFT_SESS_ID_BUG: number;
/** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */
const SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
const SSL_OP_NETSCAPE_CA_DN_BUG: number;
const SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
/** Instructs OpenSSL to disable support for SSL/TLS compression. */
const SSL_OP_NO_COMPRESSION: number;
const SSL_OP_NO_QUERY_MTU: number;
/** Instructs OpenSSL to always start a new session when performing renegotiation. */
const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
const SSL_OP_NO_SSLv2: number;
const SSL_OP_NO_SSLv3: number;
const SSL_OP_NO_TICKET: number;
const SSL_OP_NO_TLSv1: number;
const SSL_OP_NO_TLSv1_1: number;
const SSL_OP_NO_TLSv1_2: number;
const SSL_OP_PKCS1_CHECK_1: number;
const SSL_OP_PKCS1_CHECK_2: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */
const SSL_OP_SINGLE_DH_USE: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */
const SSL_OP_SINGLE_ECDH_USE: number;
const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
const SSL_OP_TLS_BLOCK_PADDING_BUG: number;
const SSL_OP_TLS_D5_BUG: number;
/** Instructs OpenSSL to disable version rollback attack detection. */
const SSL_OP_TLS_ROLLBACK_BUG: number;
const ENGINE_METHOD_RSA: number;
const ENGINE_METHOD_DSA: number;
const ENGINE_METHOD_DH: number;
const ENGINE_METHOD_RAND: number;
const ENGINE_METHOD_EC: number;
const ENGINE_METHOD_CIPHERS: number;
const ENGINE_METHOD_DIGESTS: number;
const ENGINE_METHOD_PKEY_METHS: number;
const ENGINE_METHOD_PKEY_ASN1_METHS: number;
const ENGINE_METHOD_ALL: number;
const ENGINE_METHOD_NONE: number;
const DH_CHECK_P_NOT_SAFE_PRIME: number;
const DH_CHECK_P_NOT_PRIME: number;
const DH_UNABLE_TO_CHECK_GENERATOR: number;
const DH_NOT_SUITABLE_GENERATOR: number;
const ALPN_ENABLED: number;
const RSA_PKCS1_PADDING: number;
const RSA_SSLV23_PADDING: number;
const RSA_NO_PADDING: number;
const RSA_PKCS1_OAEP_PADDING: number;
const RSA_X931_PADDING: number;
const RSA_PKCS1_PSS_PADDING: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */
const RSA_PSS_SALTLEN_DIGEST: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */
const RSA_PSS_SALTLEN_MAX_SIGN: number;
/** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
const RSA_PSS_SALTLEN_AUTO: number;
const POINT_CONVERSION_COMPRESSED: number;
const POINT_CONVERSION_UNCOMPRESSED: number;
const POINT_CONVERSION_HYBRID: number;
/** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
const defaultCoreCipherList: string;
/** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
const defaultCipherList: string;
}
interface HashOptions extends stream.TransformOptions {
/**
* For XOF hash functions such as `shake256`, the
* outputLength option can be used to specify the desired output length in bytes.
*/
outputLength?: number;
}
/** @deprecated since v10.0.0 */
const fips: boolean;
function createHash(algorithm: string, options?: HashOptions): Hash;
function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac;
// https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
type BinaryToTextEncoding = 'base64' | 'hex';
type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1';
type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2';
type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding;
type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid';
class Hash extends stream.Transform {
private constructor();
copy(): Hash;
update(data: BinaryLike): Hash;
update(data: string, input_encoding: Encoding): Hash;
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
class Hmac extends stream.Transform {
private constructor();
update(data: BinaryLike): Hmac;
update(data: string, input_encoding: Encoding): Hmac;
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
type KeyObjectType = 'secret' | 'public' | 'private';
interface KeyExportOptions<T extends KeyFormat> {
type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1';
format: T;
cipher?: string;
passphrase?: string | Buffer;
}
interface JwkKeyExportOptions {
format: 'jwk';
}
interface JsonWebKey {
crv?: string;
d?: string;
dp?: string;
dq?: string;
e?: string;
k?: string;
kty?: string;
n?: string;
p?: string;
q?: string;
qi?: string;
x?: string;
y?: string;
}
interface AsymmetricKeyDetails {
/**
* Key size in bits (RSA, DSA).
*/
modulusLength?: number;
/**
* Public exponent (RSA).
*/
publicExponent?: bigint;
/**
* Size of q in bits (DSA).
*/
divisorLength?: number;
/**
* Name of the curve (EC).
*/
namedCurve?: string;
}
class KeyObject {
private constructor();
asymmetricKeyType?: KeyType;
/**
* For asymmetric keys, this property represents the size of the embedded key in
* bytes. This property is `undefined` for symmetric keys.
*/
asymmetricKeySize?: number;
/**
* This property exists only on asymmetric keys. Depending on the type of the key,
* this object contains information about the key. None of the information obtained
* through this property can be used to uniquely identify a key or to compromise the
* security of the key.
*/
asymmetricKeyDetails?: AsymmetricKeyDetails;
export(options: KeyExportOptions<'pem'>): string | Buffer;
export(options?: KeyExportOptions<'der'>): Buffer;
symmetricKeySize?: number;
type: KeyObjectType;
}
type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305';
type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm';
type BinaryLike = string | NodeJS.ArrayBufferView;
type CipherKey = BinaryLike | KeyObject;
interface CipherCCMOptions extends stream.TransformOptions {
authTagLength: number;
}
interface CipherGCMOptions extends stream.TransformOptions {
authTagLength?: number;
}
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher;
function createCipheriv(
algorithm: CipherCCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options: CipherCCMOptions,
): CipherCCM;
function createCipheriv(
algorithm: CipherGCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options?: CipherGCMOptions,
): CipherGCM;
function createCipheriv(
algorithm: string,
key: CipherKey,
iv: BinaryLike | null,
options?: stream.TransformOptions,
): Cipher;
class Cipher extends stream.Transform {
private constructor();
update(data: BinaryLike): Buffer;
update(data: string, input_encoding: Encoding): Buffer;
update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string;
update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string;
final(): Buffer;
final(output_encoding: BufferEncoding): string;
setAutoPadding(auto_padding?: boolean): this;
// getAuthTag(): Buffer;
// setAAD(buffer: NodeJS.ArrayBufferView): this;
}
interface CipherCCM extends Cipher {
setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this;
getAuthTag(): Buffer;
}
interface CipherGCM extends Cipher {
setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this;
getAuthTag(): Buffer;
}
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher;
function createDecipheriv(
algorithm: CipherCCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options: CipherCCMOptions,
): DecipherCCM;
function createDecipheriv(
algorithm: CipherGCMTypes,
key: CipherKey,
iv: BinaryLike | null,
options?: CipherGCMOptions,
): DecipherGCM;
function createDecipheriv(
algorithm: string,
key: CipherKey,
iv: BinaryLike | null,
options?: stream.TransformOptions,
): Decipher;
class Decipher extends stream.Transform {
private constructor();
update(data: NodeJS.ArrayBufferView): Buffer;
update(data: string, input_encoding: Encoding): Buffer;
update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string;
update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string;
final(): Buffer;
final(output_encoding: BufferEncoding): string;
setAutoPadding(auto_padding?: boolean): this;
// setAuthTag(tag: NodeJS.ArrayBufferView): this;
// setAAD(buffer: NodeJS.ArrayBufferView): this;
}
interface DecipherCCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this;
}
interface DecipherGCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this;
}
interface PrivateKeyInput {
key: string | Buffer;
format?: KeyFormat;
type?: 'pkcs1' | 'pkcs8' | 'sec1';
passphrase?: string | Buffer;
}
interface PublicKeyInput {
key: string | Buffer;
format?: KeyFormat;
type?: 'pkcs1' | 'spki';
}
function generateKey(type: 'hmac' | 'aes', options: {length: number}, callback: (err: Error | null, key: KeyObject) => void): void;
function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject;
function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject;
function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject;
function createSign(algorithm: string, options?: stream.WritableOptions): Signer;
type DSAEncoding = 'der' | 'ieee-p1363';
interface SigningOptions {
/**
* @See crypto.constants.RSA_PKCS1_PADDING
*/
padding?: number;
saltLength?: number;
dsaEncoding?: DSAEncoding;
}
interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions { }
interface SignKeyObjectInput extends SigningOptions {
key: KeyObject;
}
interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions { }
interface VerifyKeyObjectInput extends SigningOptions {
key: KeyObject;
}
type KeyLike = string | Buffer | KeyObject;
class Signer extends stream.Writable {
private constructor();
update(data: BinaryLike): Signer;
update(data: string, input_encoding: Encoding): Signer;
sign(private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer;
sign(
private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
output_format: BinaryToTextEncoding,
): string;
}
function createVerify(algorithm: string, options?: stream.WritableOptions): Verify;
class Verify extends stream.Writable {
private constructor();
update(data: BinaryLike): Verify;
update(data: string, input_encoding: Encoding): Verify;
verify(
object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
signature: NodeJS.ArrayBufferView,
): boolean;
verify(
object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
signature: string,
signature_format?: BinaryToTextEncoding,
): boolean;
// https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format
// The signature field accepts a TypedArray type, but it is only available starting ES2017
}
function createDiffieHellman(prime_length: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman;
function createDiffieHellman(prime: string, prime_encoding: BinaryToTextEncoding): DiffieHellman;
function createDiffieHellman(
prime: string,
prime_encoding: BinaryToTextEncoding,
generator: number | NodeJS.ArrayBufferView,
): DiffieHellman;
function createDiffieHellman(
prime: string,
prime_encoding: BinaryToTextEncoding,
generator: string,
generator_encoding: BinaryToTextEncoding,
): DiffieHellman;
class DiffieHellman {
private constructor();
generateKeys(): Buffer;
generateKeys(encoding: BinaryToTextEncoding): string;
computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer;
computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer;
computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string;
computeSecret(
other_public_key: string,
input_encoding: BinaryToTextEncoding,
output_encoding: BinaryToTextEncoding,
): string;
getPrime(): Buffer;
getPrime(encoding: BinaryToTextEncoding): string;
getGenerator(): Buffer;
getGenerator(encoding: BinaryToTextEncoding): string;
getPublicKey(): Buffer;
getPublicKey(encoding: BinaryToTextEncoding): string;
getPrivateKey(): Buffer;
getPrivateKey(encoding: BinaryToTextEncoding): string;
setPublicKey(public_key: NodeJS.ArrayBufferView): void;
setPublicKey(public_key: string, encoding: BufferEncoding): void;
setPrivateKey(private_key: NodeJS.ArrayBufferView): void;
setPrivateKey(private_key: string, encoding: BufferEncoding): void;
verifyError: number;
}
function getDiffieHellman(group_name: string): DiffieHellman;
function pbkdf2(
password: BinaryLike,
salt: BinaryLike,
iterations: number,
keylen: number,
digest: string,
callback: (err: Error | null, derivedKey: Buffer) => any,
): void;
function pbkdf2Sync(
password: BinaryLike,
salt: BinaryLike,
iterations: number,
keylen: number,
digest: string,
): Buffer;
function randomBytes(size: number): Buffer;
function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
function pseudoRandomBytes(size: number): Buffer;
function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
function randomInt(max: number): number;
function randomInt(min: number, max: number): number;
function randomInt(max: number, callback: (err: Error | null, value: number) => void): void;
function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
function randomFillSync<T extends NodeJS.ArrayBufferView>(buffer: T, offset?: number, size?: number): T;
function randomFill<T extends NodeJS.ArrayBufferView>(
buffer: T,
callback: (err: Error | null, buf: T) => void,
): void;
function randomFill<T extends NodeJS.ArrayBufferView>(
buffer: T,
offset: number,
callback: (err: Error | null, buf: T) => void,
): void;
function randomFill<T extends NodeJS.ArrayBufferView>(
buffer: T,
offset: number,
size: number,
callback: (err: Error | null, buf: T) => void,
): void;
interface ScryptOptions {
cost?: number;
blockSize?: number;
parallelization?: number;
N?: number;
r?: number;
p?: number;
maxmem?: number;
}
function scrypt(
password: BinaryLike,
salt: BinaryLike,
keylen: number,
callback: (err: Error | null, derivedKey: Buffer) => void,
): void;
function scrypt(
password: BinaryLike,
salt: BinaryLike,
keylen: number,
options: ScryptOptions,
callback: (err: Error | null, derivedKey: Buffer) => void,
): void;
function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer;
interface RsaPublicKey {
key: KeyLike;
padding?: number;
}
interface RsaPrivateKey {
key: KeyLike;
passphrase?: string;
/**
* @default 'sha1'
*/
oaepHash?: string;
oaepLabel?: NodeJS.TypedArray;
padding?: number;
}
function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
function getCiphers(): string[];
function getCurves(): string[];
function getFips(): 1 | 0;
function getHashes(): string[];
class ECDH {
private constructor();
static convertKey(
key: BinaryLike,
curve: string,
inputEncoding?: BinaryToTextEncoding,
outputEncoding?: 'latin1' | 'hex' | 'base64',
format?: 'uncompressed' | 'compressed' | 'hybrid',
): Buffer | string;
generateKeys(): Buffer;
generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer;
computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer;
computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string;
computeSecret(
other_public_key: string,
input_encoding: BinaryToTextEncoding,
output_encoding: BinaryToTextEncoding,
): string;
getPrivateKey(): Buffer;
getPrivateKey(encoding: BinaryToTextEncoding): string;
getPublicKey(): Buffer;
getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
setPrivateKey(private_key: NodeJS.ArrayBufferView): void;
setPrivateKey(private_key: string, encoding: BinaryToTextEncoding): void;
}
function createECDH(curve_name: string): ECDH;
function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean;
/** @deprecated since v10.0.0 */
const DEFAULT_ENCODING: BufferEncoding;
type KeyType = 'rsa' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448';
type KeyFormat = 'pem' | 'der';
interface BasePrivateKeyEncodingOptions<T extends KeyFormat> {
format: T;
cipher?: string;
passphrase?: string;
}
interface KeyPairKeyObjectResult {
publicKey: KeyObject;
privateKey: KeyObject;
}
interface ED25519KeyPairKeyObjectOptions {
/**
* No options.
*/
}
interface ED448KeyPairKeyObjectOptions {
/**
* No options.
*/
}
interface X25519KeyPairKeyObjectOptions {
/**
* No options.
*/
}
interface X448KeyPairKeyObjectOptions {
/**
* No options.
*/
}
interface ECKeyPairKeyObjectOptions {
/**
* Name of the curve to use.
*/
namedCurve: string;
}
interface RSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* @default 0x10001
*/
publicExponent?: number;
}
interface DSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
}
interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* @default 0x10001
*/
publicExponent?: number;
publicKeyEncoding: {
type: 'pkcs1' | 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs1' | 'pkcs8';
};
}
interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Name of the curve to use.
*/
namedCurve: string;
publicKeyEncoding: {
type: 'pkcs1' | 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'sec1' | 'pkcs8';
};
}
interface ED25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface ED448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface X25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface X448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: 'spki';
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: 'pkcs8';
};
}
interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> {
publicKey: T1;
privateKey: T2;
}
function generateKeyPairSync(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'pem'>,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'der'>,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'pem'>,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'der'>,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'pem'>,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'der'>,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'pem'>,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'der'>,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: 'ec',
options: ECKeyPairOptions<'pem', 'pem'>,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: 'ec',
options: ECKeyPairOptions<'pem', 'der'>,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: 'ec',
options: ECKeyPairOptions<'der', 'pem'>,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: 'ec',
options: ECKeyPairOptions<'der', 'der'>,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'pem'>,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'der'>,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'pem'>,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'der'>,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'pem'>,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'der'>,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'pem'>,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'der'>,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'pem'>,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'der'>,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'pem'>,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'der'>,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: 'x448',
options: X448KeyPairOptions<'pem', 'pem'>,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: 'x448',
options: X448KeyPairOptions<'pem', 'der'>,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: 'x448',
options: X448KeyPairOptions<'der', 'pem'>,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: 'x448',
options: X448KeyPairOptions<'der', 'der'>,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPair(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'pem'>,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'der'>,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'pem'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'der'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'rsa',
options: RSAKeyPairKeyObjectOptions,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'pem'>,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'der'>,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'pem'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'der'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'dsa',
options: DSAKeyPairKeyObjectOptions,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: 'ec',
options: ECKeyPairOptions<'pem', 'pem'>,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'ec',
options: ECKeyPairOptions<'pem', 'der'>,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'ec',
options: ECKeyPairOptions<'der', 'pem'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'ec',
options: ECKeyPairOptions<'der', 'der'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'ec',
options: ECKeyPairKeyObjectOptions,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'pem'>,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'der'>,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'pem'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'der'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'ed25519',
options: ED25519KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'pem'>,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'der'>,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'pem'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'der'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'ed448',
options: ED448KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'pem'>,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'der'>,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'pem'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'der'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'x25519',
options: X25519KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: 'x448',
options: X448KeyPairOptions<'pem', 'pem'>,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'x448',
options: X448KeyPairOptions<'pem', 'der'>,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'x448',
options: X448KeyPairOptions<'der', 'pem'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: 'x448',
options: X448KeyPairOptions<'der', 'der'>,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: 'x448',
options: X448KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
namespace generateKeyPair {
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'pem'>,
): Promise<{ publicKey: string; privateKey: string }>;
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'pem', 'der'>,
): Promise<{ publicKey: string; privateKey: Buffer }>;
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'pem'>,
): Promise<{ publicKey: Buffer; privateKey: string }>;
function __promisify__(
type: 'rsa',
options: RSAKeyPairOptions<'der', 'der'>,
): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'pem'>,
): Promise<{ publicKey: string; privateKey: string }>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'pem', 'der'>,
): Promise<{ publicKey: string; privateKey: Buffer }>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'pem'>,
): Promise<{ publicKey: Buffer; privateKey: string }>;
function __promisify__(
type: 'dsa',
options: DSAKeyPairOptions<'der', 'der'>,
): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'pem', 'pem'>,
): Promise<{ publicKey: string; privateKey: string }>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'pem', 'der'>,
): Promise<{ publicKey: string; privateKey: Buffer }>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'der', 'pem'>,
): Promise<{ publicKey: Buffer; privateKey: string }>;
function __promisify__(
type: 'ec',
options: ECKeyPairOptions<'der', 'der'>,
): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'pem'>,
): Promise<{ publicKey: string; privateKey: string }>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'pem', 'der'>,
): Promise<{ publicKey: string; privateKey: Buffer }>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'pem'>,
): Promise<{ publicKey: Buffer; privateKey: string }>;
function __promisify__(
type: 'ed25519',
options: ED25519KeyPairOptions<'der', 'der'>,
): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
function __promisify__(
type: 'ed25519',
options?: ED25519KeyPairKeyObjectOptions,
): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'pem'>,
): Promise<{ publicKey: string; privateKey: string }>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'pem', 'der'>,
): Promise<{ publicKey: string; privateKey: Buffer }>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'pem'>,
): Promise<{ publicKey: Buffer; privateKey: string }>;
function __promisify__(
type: 'ed448',
options: ED448KeyPairOptions<'der', 'der'>,
): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'pem'>,
): Promise<{ publicKey: string; privateKey: string }>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'pem', 'der'>,
): Promise<{ publicKey: string; privateKey: Buffer }>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'pem'>,
): Promise<{ publicKey: Buffer; privateKey: string }>;
function __promisify__(
type: 'x25519',
options: X25519KeyPairOptions<'der', 'der'>,
): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
function __promisify__(
type: 'x25519',
options?: X25519KeyPairKeyObjectOptions,
): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'pem', 'pem'>,
): Promise<{ publicKey: string; privateKey: string }>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'pem', 'der'>,
): Promise<{ publicKey: string; privateKey: Buffer }>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'der', 'pem'>,
): Promise<{ publicKey: Buffer; privateKey: string }>;
function __promisify__(
type: 'x448',
options: X448KeyPairOptions<'der', 'der'>,
): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
}
/**
* Calculates and returns the signature for `data` using the given private key and
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
* dependent upon the key type (especially Ed25519 and Ed448).
*
* If `key` is not a `KeyObject`, this function behaves as if `key` had been
* passed to `crypto.createPrivateKey().
*/
function sign(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
): Buffer;
function sign(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
callback: (error: Error | null, data: Buffer) => void
): void;
/**
* Calculates and returns the signature for `data` using the given private key and
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
* dependent upon the key type (especially Ed25519 and Ed448).
*
* If `key` is not a `KeyObject`, this function behaves as if `key` had been
* passed to `crypto.createPublicKey()`.
*/
function verify(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
signature: NodeJS.ArrayBufferView,
): boolean;
function verify(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
signature: NodeJS.ArrayBufferView,
callback: (error: Error | null, result: boolean) => void
): void;
/**
* Computes the Diffie-Hellman secret based on a privateKey and a publicKey.
* Both keys must have the same asymmetricKeyType, which must be one of
* 'dh' (for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).
*/
function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer;
type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts';
interface CipherInfoOptions {
/**
* A test key length.
*/
keyLength?: number;
/**
* A test IV length.
*/
ivLength?: number;
}
interface CipherInfo {
/**
* The name of the cipher.
*/
name: string;
/**
* The nid of the cipher.
*/
nid: number;
/**
* The block size of the cipher in bytes.
* This property is omitted when mode is 'stream'.
*/
blockSize?: number;
/**
* The expected or default initialization vector length in bytes.
* This property is omitted if the cipher does not use an initialization vector.
*/
ivLength?: number;
/**
* The expected or default key length in bytes.
*/
keyLength: number;
/**
* The cipher mode.
*/
mode: CipherMode;
}
/**
* Returns information about a given cipher.
*
* Some ciphers accept variable length keys and initialization vectors.
* By default, the `crypto.getCipherInfo()` method will return the default
* values for these ciphers. To test if a given key length or iv length
* is acceptable for given cipher, use the `keyLenth` and `ivLenth` options.
* If the given values are unacceptable, `undefined` will be returned.
* @param nameOrNid The name or nid of the cipher to query.
*/
function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined;
/**
* HKDF is a simple key derivation function defined in RFC 5869.
* The given `key`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
*
* The supplied `callback` function is called with two arguments: `err` and `derivedKey`.
* If an errors occurs while deriving the key, `err` will be set; otherwise `err` will be `null`.
* The successfully generated `derivedKey` will be passed to the callback as an `ArrayBuffer`.
* An error will be thrown if any of the input aguments specify invalid values or types.
*/
function hkdf(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => any): void;
/**
* Provides a synchronous HKDF key derivation function as defined in RFC 5869.
* The given `key`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
*
* The successfully generated `derivedKey` will be returned as an `ArrayBuffer`.
* An error will be thrown if any of the input aguments specify invalid values or types,
* or if the derived key cannot be generated.
*/
function hkdfSync(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer;
interface SecureHeapUsage {
/**
* The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.
*/
total: number;
/**
* The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.
*/
min: number;
/**
* The total number of bytes currently allocated from the secure heap.
*/
used: number;
/**
* The calculated ratio of `used` to `total` allocated bytes.
*/
utilization: number;
}
function secureHeapUsed(): SecureHeapUsage;
// TODO: X509Certificate
interface RandomUUIDOptions {
/**
* By default, to improve performance,
* Node.js will pre-emptively generate and persistently cache enough
* random data to generate up to 128 random UUIDs. To generate a UUID
* without using the cache, set `disableEntropyCache` to `true`.
*
* @default `false`
*/
disableEntropyCache?: boolean;
}
function randomUUID(options?: RandomUUIDOptions): string;
interface X509CheckOptions {
/**
* @default 'always'
*/
subject: 'always' | 'never';
/**
* @default true
*/
wildcards: boolean;
/**
* @default true
*/
partialWildcards: boolean;
/**
* @default false
*/
multiLabelWildcards: boolean;
/**
* @default false
*/
singleLabelSubdomains: boolean;
}
class X509Certificate {
/**
* Will be `true` if this is a Certificate Authority (ca) certificate.
*/
readonly ca: boolean;
/**
* The SHA-1 fingerprint of this certificate.
*/
readonly fingerprint: string;
/**
* The SHA-256 fingerprint of this certificate.
*/
readonly fingerprint256: string;
/**
* The complete subject of this certificate.
*/
readonly subject: string;
/**
* The subject alternative name specified for this certificate.
*/
readonly subjectAltName: string;
/**
* The information access content of this certificate.
*/
readonly infoAccess: string;
/**
* An array detailing the key usages for this certificate.
*/
readonly keyUsage: string[];
/**
* The issuer identification included in this certificate.
*/
readonly issuer: string;
/**
* The issuer certificate or `undefined` if the issuer certificate is not available.
*/
readonly issuerCertificate?: X509Certificate;
/**
* The public key for this certificate.
*/
readonly publicKey: KeyObject;
/**
* A `Buffer` containing the DER encoding of this certificate.
*/
readonly raw: Buffer;
/**
* The serial number of this certificate.
*/
readonly serialNumber: string;
/**
* Returns the PEM-encoded certificate.
*/
readonly validFrom: string;
/**
* The date/time from which this certificate is considered valid.
*/
readonly validTo: string;
constructor(buffer: BinaryLike);
/**
* Checks whether the certificate matches the given email address.
*
* Returns `email` if the certificate matches,`undefined` if it does not.
*/
checkEmail(email: string, options?: X509CheckOptions): string | undefined;
/**
* Checks whether the certificate matches the given host name.
*
* Returns `name` if the certificate matches, `undefined` if it does not.
*/
checkHost(name: string, options?: X509CheckOptions): string | undefined;
/**
* Checks whether the certificate matches the given IP address (IPv4 or IPv6).
*
* Returns `ip` if the certificate matches, `undefined` if it does not.
*/
checkIP(ip: string, options?: X509CheckOptions): string | undefined;
/**
* Checks whether this certificate was issued by the given `otherCert`.
*/
checkIssued(otherCert: X509Certificate): boolean;
/**
* Checks whether this certificate was issued by the given `otherCert`.
*/
checkPrivateKey(privateKey: KeyObject): boolean;
/**
* There is no standard JSON encoding for X509 certificates. The
* `toJSON()` method returns a string containing the PEM encoded
* certificate.
*/
toJSON(): string;
/**
* Returns information about this certificate using the legacy certificate object encoding.
*/
toLegacyObject(): PeerCertificate;
/**
* Returns the PEM-encoded certificate.
*/
toString(): string;
/**
* Verifies that this certificate was signed by the given public key.
* Does not perform any other validation checks on the certificate.
*/
verify(publicKey: KeyObject): boolean;
}
type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint;
interface GeneratePrimeOptions {
add?: LargeNumberLike;
rem?: LargeNumberLike;
/**
* @default false
*/
safe?: boolean;
bigint?: boolean;
}
interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions {
bigint: true;
}
interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions {
bigint?: false;
}
function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void;
function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void;
function generatePrimeSync(size: number): ArrayBuffer;
function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint;
function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer;
function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint;
interface CheckPrimeOptions {
/**
* The number of Miller-Rabin probabilistic primality iterations to perform.
* When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input.
* Care must be used when selecting a number of checks.
* Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details.
*
* @default 0
*/
checks?: number;
}
/**
* Checks the primality of the candidate.
*/
function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void;
function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void;
/**
* Checks the primality of the candidate.
*/
function checkPrimeSync(value: LargeNumberLike, options?: CheckPrimeOptions): boolean;
}
declare module 'dgram' {
import { AddressInfo } from 'net';
import * as dns from 'dns';
import { EventEmitter, Abortable } from 'events';
interface RemoteInfo {
address: string;
family: 'IPv4' | 'IPv6';
port: number;
size: number;
}
interface BindOptions {
port?: number;
address?: string;
exclusive?: boolean;
fd?: number;
}
type SocketType = "udp4" | "udp6";
interface SocketOptions extends Abortable {
type: SocketType;
reuseAddr?: boolean;
/**
* @default false
*/
ipv6Only?: boolean;
recvBufferSize?: number;
sendBufferSize?: number;
lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void;
}
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
class Socket extends EventEmitter {
addMembership(multicastAddress: string, multicastInterface?: string): void;
address(): AddressInfo;
bind(port?: number, address?: string, callback?: () => void): void;
bind(port?: number, callback?: () => void): void;
bind(callback?: () => void): void;
bind(options: BindOptions, callback?: () => void): void;
close(callback?: () => void): void;
connect(port: number, address?: string, callback?: () => void): void;
connect(port: number, callback: () => void): void;
disconnect(): void;
dropMembership(multicastAddress: string, multicastInterface?: string): void;
getRecvBufferSize(): number;
getSendBufferSize(): number;
ref(): this;
remoteAddress(): AddressInfo;
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array | ReadonlyArray<any>, port?: number, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array | ReadonlyArray<any>, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void;
send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void;
setBroadcast(flag: boolean): void;
setMulticastInterface(multicastInterface: string): void;
setMulticastLoopback(flag: boolean): void;
setMulticastTTL(ttl: number): void;
setRecvBufferSize(size: number): void;
setSendBufferSize(size: number): void;
setTTL(ttl: number): void;
unref(): this;
/**
* Tells the kernel to join a source-specific multicast channel at the given
* `sourceAddress` and `groupAddress`, using the `multicastInterface` with the
* `IP_ADD_SOURCE_MEMBERSHIP` socket option.
* If the `multicastInterface` argument
* is not specified, the operating system will choose one interface and will add
* membership to it.
* To add membership to every available interface, call
* `socket.addSourceSpecificMembership()` multiple times, once per interface.
*/
addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
/**
* Instructs the kernel to leave a source-specific multicast channel at the given
* `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`
* socket option. This method is automatically called by the kernel when the
* socket is closed or the process terminates, so most apps will never have
* reason to call this.
*
* If `multicastInterface` is not specified, the operating system will attempt to
* drop membership on all valid interfaces.
*/
dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
/**
* events.EventEmitter
* 1. close
* 2. connect
* 3. error
* 4. listening
* 5. message
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "connect", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "listening", listener: () => void): this;
addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "connect"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "listening"): boolean;
emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "connect", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "connect", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "listening", listener: () => void): this;
once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "connect", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "listening", listener: () => void): this;
prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "connect", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "listening", listener: () => void): this;
prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
}
}
/**
* @experimental
*/
declare module 'diagnostic_channel' {
/**
* Returns wether a named channel has subscribers or not.
*/
function hasSubscribers(name: string): boolean;
/**
* Gets or create a diagnostic channel by name.
*/
function channel(name: string): Channel;
type ChannelListener = (name: string, message: unknown) => void;
/**
* Simple diagnostic channel that allows
*/
class Channel {
readonly name: string;
readonly hashSubscribers: boolean;
private constructor(name: string);
/**
* Add a listener to the message channel.
*/
subscribe(listener: ChannelListener): void;
/**
* Removes a previously registered listener.
*/
unsubscribe(listener: ChannelListener): void;
}
}
declare module 'dns' {
import * as dnsPromises from "dns/promises";
// Supported getaddrinfo flags.
export const ADDRCONFIG: number;
export const V4MAPPED: number;
/**
* If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
* well as IPv4 mapped IPv6 addresses.
*/
export const ALL: number;
export interface LookupOptions {
family?: number;
hints?: number;
all?: boolean;
verbatim?: boolean;
}
export interface LookupOneOptions extends LookupOptions {
all?: false;
}
export interface LookupAllOptions extends LookupOptions {
all: true;
}
export interface LookupAddress {
address: string;
family: number;
}
export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void;
export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void;
export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
export namespace lookup {
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;
function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
}
export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void;
export namespace lookupService {
function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>;
}
export interface ResolveOptions {
ttl: boolean;
}
export interface ResolveWithTtlOptions extends ResolveOptions {
ttl: true;
}
export interface RecordWithTtl {
address: string;
ttl: number;
}
/** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */
export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;
export interface AnyARecord extends RecordWithTtl {
type: "A";
}
export interface AnyAaaaRecord extends RecordWithTtl {
type: "AAAA";
}
export interface CaaRecord {
critial: number;
issue?: string;
issuewild?: string;
iodef?: string;
contactemail?: string;
contactphone?: string;
}
export interface MxRecord {
priority: number;
exchange: string;
}
export interface AnyMxRecord extends MxRecord {
type: "MX";
}
export interface NaptrRecord {
flags: string;
service: string;
regexp: string;
replacement: string;
order: number;
preference: number;
}
export interface AnyNaptrRecord extends NaptrRecord {
type: "NAPTR";
}
export interface SoaRecord {
nsname: string;
hostmaster: string;
serial: number;
refresh: number;
retry: number;
expire: number;
minttl: number;
}
export interface AnySoaRecord extends SoaRecord {
type: "SOA";
}
export interface SrvRecord {
priority: number;
weight: number;
port: number;
name: string;
}
export interface AnySrvRecord extends SrvRecord {
type: "SRV";
}
export interface AnyTxtRecord {
type: "TXT";
entries: string[];
}
export interface AnyNsRecord {
type: "NS";
value: string;
}
export interface AnyPtrRecord {
type: "PTR";
value: string;
}
export interface AnyCnameRecord {
type: "CNAME";
value: string;
}
export type AnyRecord = AnyARecord |
AnyAaaaRecord |
AnyCnameRecord |
AnyMxRecord |
AnyNaptrRecord |
AnyNsRecord |
AnyPtrRecord |
AnySoaRecord |
AnySrvRecord |
AnyTxtRecord;
export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;
export function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;
export function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;
export function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void;
export function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;
export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;
export function resolve(
hostname: string,
rrtype: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void,
): void;
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
export namespace resolve {
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
}
export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;
export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
export namespace resolve4 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void;
export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void;
// NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime.
export namespace resolve6 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export namespace resolveCname {
function __promisify__(hostname: string): Promise<string[]>;
}
export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void;
export namespace resolveCaa {
function __promisify__(hostname: string): Promise<CaaRecord[]>;
}
export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void;
export namespace resolveMx {
function __promisify__(hostname: string): Promise<MxRecord[]>;
}
export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void;
export namespace resolveNaptr {
function __promisify__(hostname: string): Promise<NaptrRecord[]>;
}
export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export namespace resolveNs {
function __promisify__(hostname: string): Promise<string[]>;
}
export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void;
export namespace resolvePtr {
function __promisify__(hostname: string): Promise<string[]>;
}
export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void;
export namespace resolveSoa {
function __promisify__(hostname: string): Promise<SoaRecord>;
}
export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void;
export namespace resolveSrv {
function __promisify__(hostname: string): Promise<SrvRecord[]>;
}
export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void;
export namespace resolveTxt {
function __promisify__(hostname: string): Promise<string[][]>;
}
export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void;
export namespace resolveAny {
function __promisify__(hostname: string): Promise<AnyRecord[]>;
}
export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void;
export function setServers(servers: ReadonlyArray<string>): void;
export function getServers(): string[];
// Error codes
export const NODATA: string;
export const FORMERR: string;
export const SERVFAIL: string;
export const NOTFOUND: string;
export const NOTIMP: string;
export const REFUSED: string;
export const BADQUERY: string;
export const BADNAME: string;
export const BADFAMILY: string;
export const BADRESP: string;
export const CONNREFUSED: string;
export const TIMEOUT: string;
export const EOF: string;
export const FILE: string;
export const NOMEM: string;
export const DESTRUCTION: string;
export const BADSTR: string;
export const BADFLAGS: string;
export const NONAME: string;
export const BADHINTS: string;
export const NOTINITIALIZED: string;
export const LOADIPHLPAPI: string;
export const ADDRGETNETWORKPARAMS: string;
export const CANCELLED: string;
export interface ResolverOptions {
timeout?: number;
}
export class Resolver {
constructor(options?: ResolverOptions);
cancel(): void;
getServers: typeof getServers;
resolve: typeof resolve;
resolve4: typeof resolve4;
resolve6: typeof resolve6;
resolveAny: typeof resolveAny;
resolveCname: typeof resolveCname;
resolveMx: typeof resolveMx;
resolveNaptr: typeof resolveNaptr;
resolveNs: typeof resolveNs;
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
setLocalAddress(ipv4?: string, ipv6?: string): void;
setServers: typeof setServers;
}
export { dnsPromises as promises };
}
declare module "dns/promises" {
import {
LookupAddress,
LookupOneOptions,
LookupAllOptions,
LookupOptions,
AnyRecord,
CaaRecord,
MxRecord,
NaptrRecord,
SoaRecord,
SrvRecord,
ResolveWithTtlOptions,
RecordWithTtl,
ResolveOptions,
ResolverOptions,
} from "dns";
function getServers(): string[];
function lookup(hostname: string, family: number): Promise<LookupAddress>;
function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>;
function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
function lookup(hostname: string): Promise<LookupAddress>;
function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>;
function resolve(hostname: string): Promise<string[]>;
function resolve(hostname: string, rrtype: "A"): Promise<string[]>;
function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>;
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>;
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function resolve(hostname: string, rrtype: "NS"): Promise<string[]>;
function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>;
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function resolve(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
function resolve4(hostname: string): Promise<string[]>;
function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
function resolve6(hostname: string): Promise<string[]>;
function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
function resolveAny(hostname: string): Promise<AnyRecord[]>;
function resolveCaa(hostname: string): Promise<CaaRecord[]>;
function resolveCname(hostname: string): Promise<string[]>;
function resolveMx(hostname: string): Promise<MxRecord[]>;
function resolveNaptr(hostname: string): Promise<NaptrRecord[]>;
function resolveNs(hostname: string): Promise<string[]>;
function resolvePtr(hostname: string): Promise<string[]>;
function resolveSoa(hostname: string): Promise<SoaRecord>;
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
function resolveTxt(hostname: string): Promise<string[][]>;
function reverse(ip: string): Promise<string[]>;
function setServers(servers: ReadonlyArray<string>): void;
class Resolver {
constructor(options?: ResolverOptions);
cancel(): void;
getServers: typeof getServers;
resolve: typeof resolve;
resolve4: typeof resolve4;
resolve6: typeof resolve6;
resolveAny: typeof resolveAny;
resolveCname: typeof resolveCname;
resolveMx: typeof resolveMx;
resolveNaptr: typeof resolveNaptr;
resolveNs: typeof resolveNs;
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
setLocalAddress(ipv4?: string, ipv6?: string): void;
setServers: typeof setServers;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment