From 9e13e02ace794fba00f44bcf70f41cdca1a56b4e Mon Sep 17 00:00:00 2001 From: Konstantin Burkalev Date: Wed, 15 Jun 2016 15:59:48 +0300 Subject: [PATCH 001/306] Updated definitions for wampy.js v3.0.x --- wampy/wampy-tests.ts | 5 +++-- wampy/wampy.d.ts | 22 +++++++++++++++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/wampy/wampy-tests.ts b/wampy/wampy-tests.ts index f7dcf9fe52..c0ac8d6656 100644 --- a/wampy/wampy-tests.ts +++ b/wampy/wampy-tests.ts @@ -13,7 +13,8 @@ ws.options({ onConnect: function () { console.log('Yahoo! We are online!'); }, onClose: function () { console.log('See you next time!'); }, onError: function () { console.log('Breakdown happened'); }, - onReconnect: function () { console.log('Reconnecting...'); } + onReconnect: function () { console.log('Reconnecting...'); }, + onReconnectSuccess: function () { console.log('Successfully reconnected!'); } }); ws.connect(); @@ -93,7 +94,7 @@ var status = ws.getOpStatus(); ws.cancel(status.reqId); -var sqrt_f = function (x: number) { return x*x; }; +var sqrt_f = function (x: number, y: any) { return [{}, x*x]; }; ws.register('sqrt.value', sqrt_f); diff --git a/wampy/wampy.d.ts b/wampy/wampy.d.ts index 650a8a91a5..e068b97a25 100644 --- a/wampy/wampy.d.ts +++ b/wampy/wampy.d.ts @@ -1,4 +1,4 @@ -// Type definitions for wampy.js v2.0.1 +// Type definitions for wampy.js v3.0.x // Project: https://github.com/KSDaemon/wampy.js // Definitions by: Konstantin Burkalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,10 +12,13 @@ declare module "wampy" { transportEncoding?: string; realm?: string; helloCustomDetails?: any; + onChallenge?: (auth_method: string, challenge_details: string) => string; + authid?: string; onConnect?: () => void; onClose?: () => void; onError?: () => void; onReconnect?: () => void; + onReconnectSuccess?: () => void; ws?: any; msgpackCoder?: any; } @@ -36,7 +39,7 @@ declare module "wampy" { } interface RegisterCallbacksHash extends SuccessErrorCallbacksHash { - rpc: (data: any) => any; + rpc: (data: any, options: any) => any[]; } interface CallSuccessErrorCallbacksHash { @@ -51,8 +54,17 @@ declare module "wampy" { disclose_me?: boolean; } - interface CallAdvancedOptions extends AdvancedOptions { + interface PublishAdvancedOptions extends AdvancedOptions { + exclude_authid?: string | string[]; + exclude_authrole?: string | string[]; + eligible_authid?: string | string[]; + eligible_authrole?: string | string[]; + } + + interface CallAdvancedOptions { + disclose_me?: boolean; receive_progress?: boolean; + timeout?: number; } interface CancelAdvancedOptions { @@ -71,7 +83,7 @@ declare module "wampy" { publish(topicURI: string, payload?: any, callbacks?: SuccessErrorCallbacksHash, - advancedOptions?: AdvancedOptions): Wampy; + advancedOptions?: PublishAdvancedOptions): Wampy; call(topicURI: string, payload?: any, callbacks?: (((data: any) => void) | CallSuccessErrorCallbacksHash), @@ -79,7 +91,7 @@ declare module "wampy" { cancel(reqId: number, callbacks?: ((() => void) | SuccessErrorCallbacksHash), advancedOptions?: CancelAdvancedOptions): Wampy; - register(topicURI: string, callbacks: (((data: any) => any) | RegisterCallbacksHash)): Wampy; + register(topicURI: string, callbacks: (((data: any, options: any) => any[]) | RegisterCallbacksHash)): Wampy; unregister(topicURI: string, callbacks?: ((() => void) | SuccessErrorCallbacksHash)): Wampy; } From b2e1844aba38db3f4181205cf4d49c7b769a56c5 Mon Sep 17 00:00:00 2001 From: efokschaner Date: Sat, 6 Aug 2016 23:26:19 -0700 Subject: [PATCH 002/306] Update definitions for msgpack-lite --- msgpack-lite/index.d.ts | 130 ++++++++++++++++++++++++----- msgpack-lite/msgpack-lite-tests.ts | 76 ++++++++++++++++- msgpack-lite/tsconfig.json | 2 +- 3 files changed, 183 insertions(+), 25 deletions(-) diff --git a/msgpack-lite/index.d.ts b/msgpack-lite/index.d.ts index 400d22b2e7..53ed592afa 100644 --- a/msgpack-lite/index.d.ts +++ b/msgpack-lite/index.d.ts @@ -1,14 +1,72 @@ -// Type definitions for msgpack-lite 0.1.20 +// Type definitions for msgpack-lite v0.1.26 // Project: https://github.com/kawanet/msgpack-lite -// Definitions by: Endel Dreyer +// Definitions by: Endel Dreyer , Edmund Fokschaner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module "msgpack-lite" { - import { Transform } from "stream"; +declare module 'msgpack-lite' { + import * as stream from 'stream'; namespace MsgpackLite { - interface BufferOptions { codec: any; } + /** + * encode from JS Object to MessagePack + */ + function encode(input: any, options?: EncoderOptions): Buffer; + + /** + * decode from MessagePack to JS Object + */ + function decode(input: Buffer | Uint8Array | Array, options?: DecoderOptions): any; + + /** + * create a stream that encodes from JS Object to MessagePack + */ + function createEncodeStream(options?: EncoderOptions & stream.TransformOptions ): EncodeStream; + + /** + * create a stream that decodes from MessagePack (Buffer) to JS Object + */ + function createDecodeStream(options?: DecoderOptions & stream.TransformOptions): DecodeStream; + + /** + * Codecs allow for Custom Extension Types + * Register a custom extension type number to serialize/deserialize your own class instances. + * https://github.com/kawanet/msgpack-lite#custom-extension-types-codecs + * If you wish to modify the default built-in codec, you can access it at msgpack.codec.preset + */ + function createCodec(options?: CodecOptions): Codec; + + /** + * The default built-in codec + */ + var codec: { + /** + * The default built-in codec + */ + preset: Codec; + }; + + interface Codec { + /** + * Register a custom extension to serialize your own class instances + * + * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) + * @param Class the constructor of the type you wish to serialize + * @param packer a function that converts an instance of T to bytes + */ + addExtPacker( + etype: number, + Class: new(...args: any[]) => T, + packer: (t: T) => Buffer | Uint8Array): void; + + /** + * Register a custom extension to deserialize your own class instances + * + * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) + * @param unpacker a function that converts bytes to an instance of T + */ + addExtUnpacker(etype: number, unpacker: (data: Buffer | Uint8Array) => T): void; + } interface Encoder { bufferish: any; @@ -42,29 +100,59 @@ declare module "msgpack-lite" { end: (chunk: any) => void; } - interface EncodeStream extends Transform { + interface EncodeStream extends stream.Transform { encoder: Encoder; } - interface DecodeStream extends Transform { + + interface DecodeStream extends stream.Transform { decoder: Decoder; } - interface Codec { - new (options?: any): Codec; - options: any; - init (): void; - addExtPacker (etype: number, Class: any, packer: (value: any) => any): void; - getExtPacker (value: any): (value: any) => any; - addExtUnpacker (etype: number, unpacker: (value: any) => any): void; - getExtUnpacker (etype: number): (value: any) => any; + interface CodecOptions { + /** + * It includes the preset extensions for JavaScript native objects. + * @see https://github.com/kawanet/msgpack-lite#extension-types + * @default false + */ + preset?: boolean; + /** + * It runs a validation of the value before writing it into buffer. + * This is the default behavior for some old browsers which do not support ArrayBuffer object. + * @default varies + */ + safe?: boolean; + /** + * It uses raw formats instead of bin and str. + * Set true for compatibility with msgpack's old spec. + * @see https://github.com/kawanet/msgpack-lite#compatibility-mode + * @default false + */ + raw?: boolean; + /** + * It decodes msgpack's int64/uint64 formats with int64-buffer object. + * int64-buffer is a cutom integer type with 64 bits of precision instead + * of the built-in IEEE-754 53 bits. See https://github.com/kawanet/int64-buffer + * @default false + */ + int64?: boolean; + /** + * It ties msgpack's bin format with ArrayBuffer object, instead of Buffer object. + * @default false + */ + binarraybuffer?: boolean; + /** + * It returns Uint8Array object when encoding, instead of Buffer object. + */ + uint8array?: boolean; } - export function encode(input: any, options?: BufferOptions): any; - export function decode(input: Buffer | Uint8Array | Array, options?: BufferOptions): any; - export function createEncodeStream (): EncodeStream; - export function createDecodeStream (): DecodeStream; - export function createCodec (options?: any): Codec; - export function codec (): { preset: Codec }; + interface EncoderOptions { + codec?: Codec + } + + interface DecoderOptions { + codec?: Codec + } } export = MsgpackLite; diff --git a/msgpack-lite/msgpack-lite-tests.ts b/msgpack-lite/msgpack-lite-tests.ts index f6d8725754..3608e6bfd9 100644 --- a/msgpack-lite/msgpack-lite-tests.ts +++ b/msgpack-lite/msgpack-lite-tests.ts @@ -1,5 +1,75 @@ +import * as msgpack from 'msgpack-lite'; -import * as msgpack from "msgpack-lite"; +// https://github.com/kawanet/msgpack-lite#encoding-and-decoding-messagepack +function encodingAndDecoding() { + // encode from JS Object to MessagePack (Buffer) + var buffer = msgpack.encode({"foo": "bar"}); -var encoded = msgpack.encode(""); -msgpack.decode(encoded); + // decode from MessagePack (Buffer) to JS Object + var data = msgpack.decode(buffer); // => {"foo": "bar"} +} + +// https://github.com/kawanet/msgpack-lite#writing-to-messagepack-stream +function writingToStream() { + var fs = require("fs"); + + var writeStream = fs.createWriteStream("test.msp"); + var encodeStream = msgpack.createEncodeStream(); + encodeStream.pipe(writeStream); + + // send multiple objects to stream + encodeStream.write({foo: "bar"}); + encodeStream.write({baz: "qux"}); + + // call this once you're done writing to the stream. + encodeStream.end(); +} + +// https://github.com/kawanet/msgpack-lite#reading-from-messagepack-stream +function readingFromStream() { + var fs = require("fs"); + var msgpack = require("msgpack-lite"); + + var readStream = fs.createReadStream("test.msp"); + var decodeStream = msgpack.createDecodeStream(); + + // show multiple objects decoded from stream + readStream.pipe(decodeStream).on("data", console.warn); +} + +// https://github.com/kawanet/msgpack-lite#decoding-messagepack-bytes-array +function decodingBytesArray() { + // decode() accepts Buffer instance per default + msgpack.decode(new Buffer([0x81, 0xA3, 0x66, 0x6F, 0x6F, 0xA3, 0x62, 0x61, 0x72])); + + // decode() also accepts Array instance + msgpack.decode([0x81, 0xA3, 0x66, 0x6F, 0x6F, 0xA3, 0x62, 0x61, 0x72]); + + // decode() accepts raw Uint8Array instance as well + msgpack.decode(new Uint8Array([0x81, 0xA3, 0x66, 0x6F, 0x6F, 0xA3, 0x62, 0x61, 0x72])); +} + +// https://github.com/kawanet/msgpack-lite#custom-extension-types-codecs +function customExtensionTypes() { + var codec = msgpack.createCodec(); + codec.addExtPacker(0x3F, MyVector, myVectorPacker); + codec.addExtUnpacker(0x3F, myVectorUnpacker); + + var data = new MyVector(1, 2); + var encoded = msgpack.encode(data, {codec: codec}); + var decoded = msgpack.decode(encoded, {codec: codec}); + + class MyVector { + constructor(public x: number, public y: number) {} + } + + function myVectorPacker(vector: MyVector) { + var array = [vector.x, vector.y]; + return msgpack.encode(array); // return Buffer serialized + } + + function myVectorUnpacker(buffer: Buffer | Uint8Array): MyVector { + var array = msgpack.decode(buffer); + return new MyVector(array[0], array[1]); // return Object deserialized + } +} diff --git a/msgpack-lite/tsconfig.json b/msgpack-lite/tsconfig.json index 39588c1eef..6070c69ece 100644 --- a/msgpack-lite/tsconfig.json +++ b/msgpack-lite/tsconfig.json @@ -4,7 +4,7 @@ "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From 0c28d885a4109aa79bff1267eeaf85297807e24d Mon Sep 17 00:00:00 2001 From: efokschaner Date: Sun, 1 Jan 2017 18:14:21 -0800 Subject: [PATCH 003/306] Add tslint.json to msgpack-lite --- msgpack-lite/index.d.ts | 8 ++++---- msgpack-lite/tslint.json | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 msgpack-lite/tslint.json diff --git a/msgpack-lite/index.d.ts b/msgpack-lite/index.d.ts index 53ed592afa..128be7fad1 100644 --- a/msgpack-lite/index.d.ts +++ b/msgpack-lite/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for msgpack-lite v0.1.26 +// Type definitions for msgpack-lite 0.1 // Project: https://github.com/kawanet/msgpack-lite // Definitions by: Endel Dreyer , Edmund Fokschaner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -16,7 +16,7 @@ declare module 'msgpack-lite' { /** * decode from MessagePack to JS Object */ - function decode(input: Buffer | Uint8Array | Array, options?: DecoderOptions): any; + function decode(input: Buffer | Uint8Array | number[], options?: DecoderOptions): any; /** * create a stream that encodes from JS Object to MessagePack @@ -147,11 +147,11 @@ declare module 'msgpack-lite' { } interface EncoderOptions { - codec?: Codec + codec?: Codec; } interface DecoderOptions { - codec?: Codec + codec?: Codec; } } diff --git a/msgpack-lite/tslint.json b/msgpack-lite/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/msgpack-lite/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file From 16b909b10fbaed9f6d8cd7e145a8d33201cf0d97 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sat, 7 Jan 2017 02:54:53 +0300 Subject: [PATCH 004/306] Node api fix according to official API --- node/index.d.ts | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index a52b0424de..e9b120cc2b 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -281,9 +281,9 @@ declare namespace NodeJS { readable: boolean; isTTY?: boolean; read(size?: number): string | Buffer; - setEncoding(encoding: string | null): void; - pause(): ReadableStream; - resume(): ReadableStream; + setEncoding(encoding: string | null): this; + pause(): this; + resume(): this; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: string): void; @@ -302,10 +302,7 @@ declare namespace NodeJS { end(str: string, encoding?: string, cb?: Function): void; } - export interface ReadWriteStream extends ReadableStream, WritableStream { - pause(): ReadWriteStream; - resume(): ReadWriteStream; - } + export interface ReadWriteStream extends ReadableStream, WritableStream { } export interface Events extends EventEmitter { } @@ -1845,11 +1842,11 @@ declare module "net" { connect(port: number, host?: string, connectionListener?: Function): void; connect(path: string, connectionListener?: Function): void; bufferSize: number; - setEncoding(encoding?: string): void; + setEncoding(encoding?: string): this; write(data: any, encoding?: string, callback?: Function): void; destroy(): void; - pause(): Socket; - resume(): Socket; + pause(): this; + resume(): this; setTimeout(timeout: number, callback?: Function): void; setNoDelay(noDelay?: boolean): void; setKeepAlive(enable?: boolean, initialDelay?: number): void; @@ -3339,9 +3336,9 @@ declare module "stream" { constructor(opts?: ReadableOptions); protected _read(size: number): void; read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Readable; - resume(): Readable; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: any): void; @@ -3502,8 +3499,8 @@ declare module "stream" { // Note: Duplex extends both Readable and Writable. export class Duplex extends Readable implements NodeJS.ReadWriteStream { // Readable - pause(): Duplex; - resume(): Duplex; + pause(): this; + resume(): this; // Writeable writable: boolean; constructor(opts?: DuplexOptions); @@ -3528,9 +3525,9 @@ declare module "stream" { protected _transform(chunk: any, encoding: string, callback: Function): void; protected _flush(callback: Function): void; read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Transform; - resume(): Transform; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: any): void; From 261edf6ed5faf327a9f7977ee0c40a4277dd775c Mon Sep 17 00:00:00 2001 From: efokschaner Date: Sat, 7 Jan 2017 06:17:23 -0800 Subject: [PATCH 005/306] Fix no-single-declare-module lint error --- msgpack-lite/index.d.ts | 282 ++++++++++++++--------------- msgpack-lite/msgpack-lite-tests.ts | 1 - 2 files changed, 138 insertions(+), 145 deletions(-) diff --git a/msgpack-lite/index.d.ts b/msgpack-lite/index.d.ts index 128be7fad1..e451267dbc 100644 --- a/msgpack-lite/index.d.ts +++ b/msgpack-lite/index.d.ts @@ -4,156 +4,150 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module 'msgpack-lite' { - import * as stream from 'stream'; +import * as stream from 'stream'; - namespace MsgpackLite { - /** - * encode from JS Object to MessagePack - */ - function encode(input: any, options?: EncoderOptions): Buffer; +/** + * encode from JS Object to MessagePack + */ +export function encode(input: any, options?: EncoderOptions): Buffer; - /** - * decode from MessagePack to JS Object - */ - function decode(input: Buffer | Uint8Array | number[], options?: DecoderOptions): any; +/** + * decode from MessagePack to JS Object + */ +export function decode(input: Buffer | Uint8Array | number[], options?: DecoderOptions): any; - /** - * create a stream that encodes from JS Object to MessagePack - */ - function createEncodeStream(options?: EncoderOptions & stream.TransformOptions ): EncodeStream; +/** + * create a stream that encodes from JS Object to MessagePack + */ +export function createEncodeStream(options?: EncoderOptions & stream.TransformOptions ): EncodeStream; - /** - * create a stream that decodes from MessagePack (Buffer) to JS Object - */ - function createDecodeStream(options?: DecoderOptions & stream.TransformOptions): DecodeStream; +/** + * create a stream that decodes from MessagePack (Buffer) to JS Object + */ +export function createDecodeStream(options?: DecoderOptions & stream.TransformOptions): DecodeStream; - /** - * Codecs allow for Custom Extension Types - * Register a custom extension type number to serialize/deserialize your own class instances. - * https://github.com/kawanet/msgpack-lite#custom-extension-types-codecs - * If you wish to modify the default built-in codec, you can access it at msgpack.codec.preset - */ - function createCodec(options?: CodecOptions): Codec; +/** + * Codecs allow for Custom Extension Types + * Register a custom extension type number to serialize/deserialize your own class instances. + * https://github.com/kawanet/msgpack-lite#custom-extension-types-codecs + * If you wish to modify the default built-in codec, you can access it at msgpack.codec.preset + */ +export function createCodec(options?: CodecOptions): Codec; - /** - * The default built-in codec - */ - var codec: { - /** - * The default built-in codec - */ - preset: Codec; - }; +/** + * The default built-in codec + */ +export var codec: { + /** + * The default built-in codec + */ + preset: Codec; +}; - interface Codec { - /** - * Register a custom extension to serialize your own class instances - * - * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) - * @param Class the constructor of the type you wish to serialize - * @param packer a function that converts an instance of T to bytes - */ - addExtPacker( - etype: number, - Class: new(...args: any[]) => T, - packer: (t: T) => Buffer | Uint8Array): void; +export interface Codec { + /** + * Register a custom extension to serialize your own class instances + * + * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) + * @param Class the constructor of the type you wish to serialize + * @param packer a function that converts an instance of T to bytes + */ + addExtPacker( + etype: number, + Class: new(...args: any[]) => T, + packer: (t: T) => Buffer | Uint8Array): void; - /** - * Register a custom extension to deserialize your own class instances - * - * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) - * @param unpacker a function that converts bytes to an instance of T - */ - addExtUnpacker(etype: number, unpacker: (data: Buffer | Uint8Array) => T): void; - } - - interface Encoder { - bufferish: any; - maxBufferSize: number; - minBufferSize: number; - offset: number; - start: number; - write: (chunk: any) => void; - fetch: () => void; - flush: () => void; - push: (chunk: any) => void; - pull: () => number; - read: () => number; - reserve: (length: number) => number; - send: (buffer: Buffer) => void; - encode: (chunk: any) => void; - end: (chunk: any) => void; - } - - interface Decoder { - bufferish: any; - offset: number; - fetch: () => void; - flush: () => void; - pull: () => number; - read: () => number; - write: (chunk: any) => void; - reserve: (length: number) => number; - decode: (chunk: any) => void; - push: (chunk: any) => void; - end: (chunk: any) => void; - } - - interface EncodeStream extends stream.Transform { - encoder: Encoder; - } - - interface DecodeStream extends stream.Transform { - decoder: Decoder; - } - - interface CodecOptions { - /** - * It includes the preset extensions for JavaScript native objects. - * @see https://github.com/kawanet/msgpack-lite#extension-types - * @default false - */ - preset?: boolean; - /** - * It runs a validation of the value before writing it into buffer. - * This is the default behavior for some old browsers which do not support ArrayBuffer object. - * @default varies - */ - safe?: boolean; - /** - * It uses raw formats instead of bin and str. - * Set true for compatibility with msgpack's old spec. - * @see https://github.com/kawanet/msgpack-lite#compatibility-mode - * @default false - */ - raw?: boolean; - /** - * It decodes msgpack's int64/uint64 formats with int64-buffer object. - * int64-buffer is a cutom integer type with 64 bits of precision instead - * of the built-in IEEE-754 53 bits. See https://github.com/kawanet/int64-buffer - * @default false - */ - int64?: boolean; - /** - * It ties msgpack's bin format with ArrayBuffer object, instead of Buffer object. - * @default false - */ - binarraybuffer?: boolean; - /** - * It returns Uint8Array object when encoding, instead of Buffer object. - */ - uint8array?: boolean; - } - - interface EncoderOptions { - codec?: Codec; - } - - interface DecoderOptions { - codec?: Codec; - } - } - - export = MsgpackLite; + /** + * Register a custom extension to deserialize your own class instances + * + * @param etype an integer within the range of 0 and 127 (0x0 and 0x7F) + * @param unpacker a function that converts bytes to an instance of T + */ + addExtUnpacker(etype: number, unpacker: (data: Buffer | Uint8Array) => T): void; } + +export interface Encoder { + bufferish: any; + maxBufferSize: number; + minBufferSize: number; + offset: number; + start: number; + write: (chunk: any) => void; + fetch: () => void; + flush: () => void; + push: (chunk: any) => void; + pull: () => number; + read: () => number; + reserve: (length: number) => number; + send: (buffer: Buffer) => void; + encode: (chunk: any) => void; + end: (chunk: any) => void; +} + +export interface Decoder { + bufferish: any; + offset: number; + fetch: () => void; + flush: () => void; + pull: () => number; + read: () => number; + write: (chunk: any) => void; + reserve: (length: number) => number; + decode: (chunk: any) => void; + push: (chunk: any) => void; + end: (chunk: any) => void; +} + +export interface EncodeStream extends stream.Transform { + encoder: Encoder; +} + +export interface DecodeStream extends stream.Transform { + decoder: Decoder; +} + +export interface CodecOptions { + /** + * It includes the preset extensions for JavaScript native objects. + * @see https://github.com/kawanet/msgpack-lite#extension-types + * @default false + */ + preset?: boolean; + /** + * It runs a validation of the value before writing it into buffer. + * This is the default behavior for some old browsers which do not support ArrayBuffer object. + * @default varies + */ + safe?: boolean; + /** + * It uses raw formats instead of bin and str. + * Set true for compatibility with msgpack's old spec. + * @see https://github.com/kawanet/msgpack-lite#compatibility-mode + * @default false + */ + raw?: boolean; + /** + * It decodes msgpack's int64/uint64 formats with int64-buffer object. + * int64-buffer is a cutom integer type with 64 bits of precision instead + * of the built-in IEEE-754 53 bits. See https://github.com/kawanet/int64-buffer + * @default false + */ + int64?: boolean; + /** + * It ties msgpack's bin format with ArrayBuffer object, instead of Buffer object. + * @default false + */ + binarraybuffer?: boolean; + /** + * It returns Uint8Array object when encoding, instead of Buffer object. + */ + uint8array?: boolean; +} + +export interface EncoderOptions { + codec?: Codec; +} + +export interface DecoderOptions { + codec?: Codec; +} \ No newline at end of file diff --git a/msgpack-lite/msgpack-lite-tests.ts b/msgpack-lite/msgpack-lite-tests.ts index 3608e6bfd9..033fde060c 100644 --- a/msgpack-lite/msgpack-lite-tests.ts +++ b/msgpack-lite/msgpack-lite-tests.ts @@ -28,7 +28,6 @@ function writingToStream() { // https://github.com/kawanet/msgpack-lite#reading-from-messagepack-stream function readingFromStream() { var fs = require("fs"); - var msgpack = require("msgpack-lite"); var readStream = fs.createReadStream("test.msp"); var decodeStream = msgpack.createDecodeStream(); From bbc7449794201aaa4a8c34363068e2a2e70c5321 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sat, 7 Jan 2017 19:57:33 +0300 Subject: [PATCH 006/306] Mongodb-node reconciliation --- mongodb/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index 82f8f0dcce..26d1656baf 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1185,7 +1185,7 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption setCursorOption(field: string, value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding - setEncoding(encoding: string): void; + setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId @@ -1271,7 +1271,7 @@ export interface AggregationCursor extends Readable { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind rewind(): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding - setEncoding(encoding: string): void; + setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip skip(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort @@ -1312,7 +1312,7 @@ export interface CommandCursor extends Readable { //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind rewind(): CommandCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding - setEncoding(encoding: string): void; + setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray From 6c25f377ff8bbaf1cf1f9d39b22f5350b8eca55e Mon Sep 17 00:00:00 2001 From: Hinell Date: Sat, 7 Jan 2017 23:13:39 +0300 Subject: [PATCH 007/306] Fixed @node/node interface accroding to official NodeJS API. Closing #13782 --- node/index.d.ts | 7243 ++++++++++++++++++++++------------------------- 1 file changed, 3445 insertions(+), 3798 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index e9b120cc2b..e6333dd7d1 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -8,37 +8,162 @@ * Node.js v6.x API * * * ************************************************/ +interface NodeError { + /** + * Returns a string describing the point in the code at which the Error was instantiated. + * + * For example: + * + * ``` + * Error: Things keep happening! + * at /home/gbusey/file.js:525:2 + * at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) + * at Actor. (/home/gbusey/actors.js:400:8) + * at increaseSynergy (/home/gbusey/actors.js:701:6) + * ``` + * + * The first line is formatted as : , and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses. + */ + stack?: string; -// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build -interface Console { - Console: typeof NodeJS.Console; - assert(value: any, message?: string, ...optionalParams: any[]): void; - dir(obj: any, options?: {showHidden?: boolean, depth?: number, colors?: boolean}): void; - error(message?: any, ...optionalParams: any[]): void; - info(message?: any, ...optionalParams: any[]): void; - log(message?: any, ...optionalParams: any[]): void; - time(label: string): void; - timeEnd(label: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; + /** + * Returns the string description of error as set by calling new Error(message). The message passed to the constructor will also appear in the first line of the stack trace of the Error, however changing this property after the Error object is created may not change the first line of the stack trace. + * + * ``` + * const err = new Error('The message'); + * console.log(err.message); + * // Prints: The message + * ``` + */ + message: string; } -interface Error { - stack?: string; -} +interface Error extends NodeError { } interface ErrorConstructor { - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - stackTraceLimit: number; + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()`` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack // similar to `new Error().stack` + * ``` + * + * The first line of the trace, instead of being prefixed with `ErrorType : message`, will be the result of calling `targetObject.toString()``. + * + * The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace. + * + * The constructorOpt argument is useful for hiding implementation details of error generation from an end user. For instance: + * + * ```js + * function MyError() { + * Error.captureStackTrace(this, MyError); + * } + * + * // Without passing MyError to captureStackTrace, the MyError + * // frame would should up in the .stack property. by passing + * // the constructor, we omit that frame and all frames above it. + * new MyError().stack + * ``` + */ + captureStackTrace(targetObject: T, constructorOpt?: new () => T): void; + + /** + * The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj))``. + * + * The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will not capture any frames. + */ + stackTraceLimit: number; } -// compat for TypeScript 1.8 -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } +// ES2015 collection types +interface NodeCollection { + size: number; +} + +interface NodeWeakCollection {} + +interface IterableIterator {} + +interface NodeCollectionConstructor { + prototype: T; +} + +interface Map extends NodeCollection { + clear(): void; + delete(key: K): boolean; + entries(): Array<[K, V]>; + forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; + get(key: K): V; + has(key: K): boolean; + keys(): Array; + set(key: K, value?: V): Map; + values(): Array; + // [Symbol.iterator]():Array<[K,V]>; + // [Symbol.toStringTag]: "Map"; +} + +interface MapConstructor extends NodeCollectionConstructor> { + new (): Map; + new (): Map; +} + +declare var Map: MapConstructor; + +interface WeakMap extends NodeWeakCollection { + clear(): void; + delete(key: K): boolean; + get(key: K): V | void; + has(key: K): boolean; + set(key: K, value?: V): WeakMap; +} + +interface WeakMapConstructor extends NodeCollectionConstructor> { + new (): WeakMap; + new (): WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface Set extends NodeCollection { + add(value: T): Set; + clear(): void; + delete(value: T): boolean; + entries(): Array<[T, T]>; + forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; + has(value: T): boolean; + keys(): Array; + values(): Array; + // [Symbol.iterator]():Array; + // [Symbol.toStringTag]: "Set"; +} + +interface SetConstructor extends NodeCollectionConstructor> { + new (): Set; + new (): Set; + new (iterable: Array): Set; +} + +declare var Set: SetConstructor; + +interface WeakSet extends NodeWeakCollection { + add(value: T): WeakSet; + clear(): void; + delete(value: T): boolean; + has(value: T): boolean; + // [Symbol.toStringTag]: "WeakSet"; +} + +interface WeakSetConstructor extends NodeCollectionConstructor> { + new (): WeakSet; + new (): WeakSet; + new (iterable: Array): WeakSet; +} + +declare var WeakSet: WeakSetConstructor; /************************************************ * * @@ -47,7 +172,6 @@ interface WeakSetConstructor { } ************************************************/ declare var process: NodeJS.Process; declare var global: NodeJS.Global; -declare var console: Console; declare var __filename: string; declare var __dirname: string; @@ -60,26 +184,44 @@ declare function setImmediate(callback: (...args: any[]) => void, ...args: any[] declare function clearImmediate(immediateId: any): void; interface NodeRequireFunction { - (id: string): any; + (id: string): any; } interface NodeRequire extends NodeRequireFunction { - resolve(id: string): string; - cache: any; - extensions: any; - main: NodeModule | undefined; + resolve(id: string): string; + cache: { [filename: string]: NodeModule }; + extensions: NodeExtensions; + main: any; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; } declare var require: NodeRequire; -interface NodeModule { - exports: any; - require: NodeRequireFunction; - id: string; - filename: string; - loaded: boolean; - parent: NodeModule | null; - children: NodeModule[]; +declare class NodeModule { + static runMain(): void; + static wrap(code: string): string; + static _nodeModulePaths(path: string): string[]; + static _load(request: string, parent?: NodeModule, isMain?: boolean): any; + static _resolveFilename(request: string, parent?: NodeModule, isMain?: boolean): string; + static _extensions: NodeExtensions; + + constructor(filename: string); + _compile(code: string, filename: string): string; + + id: string; + parent: NodeModule; + filename: string; + paths: string[]; + children: NodeModule[]; + exports: any; + loaded: boolean; + require: NodeRequireFunction; } declare var module: NodeModule; @@ -87,159 +229,209 @@ declare var module: NodeModule; // Same as module.exports declare var exports: any; declare var SlowBuffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; }; +// Console class (compatible with TypeScript `lib.d.ts`). +declare interface Console { + log(msg: any, ...params: any[]): void; + info(msg: any, ...params: any[]): void; + warn(msg: any, ...params: any[]): void; + error(msg: any, ...params: any[]): void; + dir(value: any, ...params: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; + trace(msg: any, ...params: any[]): void; + assert(test?: boolean, msg?: string, ...params: any[]): void; -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer { } + Console: new (stdout: NodeJS.WritableStream) => Console; +} -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - */ -declare var Buffer: { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - new (str: string, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - new (size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new (array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - new (arrayBuffer: ArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new (array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - new (buffer: Buffer): Buffer; - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafeSlow(size: number): Buffer; -}; +declare var console: Console; + +declare class Buffer extends Uint8Array { + [index: number]: number; + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor(str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor(size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor(array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor(arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor(array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor(buffer: Buffer); + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be _zero-filled_. + * + * @param size The desired length of the new `Buffer` + * @param fill A value to pre-fill the new `Buffer` with. Default: `0` + * @param encoding If `fill` is a string, this is its encoding. Default: `'utf8'` + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new _non-zero-filled_ `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `buffer.kMaxLength`. Otherwise, a `RangeError` is thrown. A zero-length `Buffer` will be created if `size <= 0`. + * + * The underlying memory for `Buffer` instances created in this way is not initialized. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize such `Buffer` instances to zeroes. + * + * @param size The desired length of the new `Buffer` + */ + static allocUnsafe(size: number): Buffer; + /** + * Returns `true` if `obj` is a Buffer, `false` otherwise. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` contains a supported character encoding, or `false` otherwise. + * + * @param encoding A character encoding name to check. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + swap16(): this; + swap32(): this; + swap64(): this; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + entries(): IterableIterator<[number, number]>; + keys(): IterableIterator; + values(): IterableIterator; +} /************************************************ * * @@ -247,301 +439,244 @@ declare var Buffer: { * * ************************************************/ declare namespace NodeJS { - export var Console: { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream): Console; - } + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } - export interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } + export interface EventEmitter { + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + prependListener(event: string, listener: Function): this; + prependOnceListener(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + eventNames(): string[]; + listenerCount(type: string): number; + } - export class EventEmitter { - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - listenerCount(type: string | symbol): number; - // Added in Node 6... - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; - eventNames(): (string | symbol)[]; - } + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + isPaused(): boolean; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } - export interface ReadableStream extends EventEmitter { - readable: boolean; - isTTY?: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string | null): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - } + export interface WritableStream extends EventEmitter { + writable: boolean; + setDefaultEncoding(encoding: string): this; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } - export interface WritableStream extends EventEmitter { - writable: boolean; - isTTY?: boolean; - write(buffer: Buffer | string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } + export interface ReadWriteStream extends ReadableStream, WritableStream { } - export interface ReadWriteStream extends ReadableStream, WritableStream { } + export interface Events extends EventEmitter { } - export interface Events extends EventEmitter { } + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - } + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - } + export interface Env { + PATH: string; + [key: string]: string; + } - export interface CpuUsage { - user: number; - system: number; - } + export interface Versions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } - export interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + argv0: string; + /** + * The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. + */ + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: Env; + exit(code?: number): void; + exitCode?: number; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: Versions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): MemoryUsage; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; - export interface Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: any; - exit(code?: number): void; - exitCode: number; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: ProcessVersions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string | number): void; - pid: number; - title: string; - arch: string; - platform: string; - mainModule?: NodeModule; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?: [number, number]): [number, number]; - domain: Domain; + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - } + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } + export interface Timer { + ref(): void; + unref(): void; + _called: boolean; + _onTimeout: Function; + _timerArgs?: any[]; + } - export interface Timer { - ref(): void; - unref(): void; - } -} - -interface IterableIterator { } - -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; + export interface Immediate { + _argv?: any[]; + _callback: Function; + _onImmediate: Function; + } } /************************************************ @@ -550,3566 +685,3078 @@ interface NodeBuffer extends Uint8Array { * * ************************************************/ declare module "buffer" { - export var INSPECT_MAX_BYTES: number; - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + export var INSPECT_MAX_BYTES: number; + export var kMaxLength: number; + + export type Encoding = "ascii" | "latin1" | "binary" | "utf8" | "utf-8" | "ucs2" | "ucs-2" | "utf16le" | "utf-16le" | "hex" | "base64"; + + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } + export interface StringifyOptions { + encodeURIComponent?: Function; + } - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { - class internal extends NodeJS.EventEmitter { } + export class EventEmitter implements NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static defaultMaxListeners: number; - namespace internal { - export class EventEmitter extends internal { - static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated - static defaultMaxListeners: number; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Array<(...args: any[]) => void>; + listenerCount(event: string): number; + emit(event: string, ...args: any[]): boolean; + eventNames(): string[]; + } - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - eventNames(): (string | symbol)[]; - listenerCount(type: string | symbol): number; - } - } - - export = internal; + export interface Listener { + on(event: E, listener: L): this; + once(event: E, listener: L): this; + addListener(event: E, listener: L): this; + removeListener(event: E, listener: L): this; + listeners(event: E): L[]; + } } declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; - export interface RequestOptions { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: { [key: string]: any }; - auth?: string; - agent?: Agent | boolean; - } + export interface OutgoingHeaders { + [header: string]: number | string | string[]; + } - export interface Server extends net.Server { - setTimeout(msecs: number, callback: Function): void; - maxHeadersCount: number; - timeout: number; - listening: boolean; - } + export interface IncomingHeaders { + [header: string]: string | string[]; + } + + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHeaders; + auth?: string; + agent?: Agent | boolean; + } + + export class Server extends net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + listening: boolean; + } + + export class ServerResponse extends stream.Writable { + finished: boolean; + headersSent: boolean; + statusCode: number; + statusMessage: string; + sendDate: boolean; + + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, statusText?: string, headers?: OutgoingHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHeaders): void; + setHeader(name: string, value: string | string[]): void; + setTimeout(msecs: number, callback: () => void): this; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: OutgoingHeaders): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export class ClientRequest extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export class IncomingMessage extends stream.Readable { + httpVersion: string; + headers: IncomingHeaders; + rawHeaders: string[]; + trailers: IncomingHeaders; + rawTrailers: string[]; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + destroy(error?: Error): void; /** - * @deprecated Use IncomingMessage + * Only valid for request obtained from http.Server. */ - export interface ServerRequest extends IncomingMessage { - connection: net.Socket; - } - export interface ServerResponse extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; - writeHead(statusCode: number, headers?: any): void; - statusCode: number; - statusMessage: string; - headersSent: boolean; - setHeader(name: string, value: string | string[]): void; - setTimeout(msecs: number, callback: Function): ServerResponse; - sendDate: boolean; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: any): void; - finished: boolean; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface ClientRequest extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - export interface IncomingMessage extends stream.Readable { - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - connection: net.Socket; - headers: any; - rawHeaders: string[]; - trailers: any; - rawTrailers: any; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; - /** - * Only valid for request obtained from http.Server. - */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - destroy(error?: Error): void; - } + method?: string; /** - * @deprecated Use IncomingMessage + * Only valid for request obtained from http.Server. */ - export interface ClientResponse extends IncomingMessage { } + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + } - export interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } - export class Agent { - maxSockets: number; - sockets: any; - requests: any; + export class Agent { + maxSockets: number; + sockets: any; + requests: any; - constructor(opts?: AgentOptions); + constructor(opts?: AgentOptions); - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } - export var METHODS: string[]; + export var METHODS: string[]; - export var STATUS_CODES: { - [errorCode: number]: string; - [errorCode: string]: string; - }; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; - export var globalAgent: Agent; + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; } declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - import * as net from "net"; + import * as child from "child_process"; + import * as events from "events"; - // interfaces - export interface ClusterSettings { - execArgv?: string[]; // default: process.execArgv - exec?: string; - args?: string[]; - silent?: boolean; - stdio?: any[]; - uid?: number; - gid?: number; - } + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } - export interface ClusterSetupMasterSettings { - exec?: string; // default: process.argv[1] - args?: string[]; // default: process.argv.slice(2) - silent?: boolean; // default: false - stdio?: any[]; - } + export interface Address { + address: string; + port: number; + addressType: string; + } - export interface Address { - address: string; - port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" - } + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + } - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): boolean; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - exitedAfterDisconnect: boolean; + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: { + [index: string]: Worker + }; - /** - * events.EventEmitter - * 1. disconnect - * 2. error - * 3. exit - * 4. listening - * 5. message - * 6. online - */ - addListener(event: string, listener: Function): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (code: number, signal: string) => 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, listener: Function): boolean - emit(event: "disconnect", listener: () => void): boolean - emit(event: "error", listener: (code: number, signal: string) => void): boolean - emit(event: "exit", listener: (code: number, signal: string) => void): boolean - emit(event: "listening", listener: (address: Address) => void): boolean - emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean - emit(event: "online", listener: () => void): boolean - - on(event: string, listener: Function): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (code: number, signal: string) => 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: Function): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (code: number, signal: string) => 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: Function): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (code: number, signal: string) => 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: Function): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (code: number, signal: string) => 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; - } - - export interface Cluster extends events.EventEmitter { - Worker: Worker; - disconnect(callback?: Function): void; - fork(env?: any): Worker; - isMaster: boolean; - isWorker: boolean; - // TODO: cluster.schedulingPolicy - settings: ClusterSettings; - setupMaster(settings?: ClusterSetupMasterSettings): void; - worker: Worker; - workers: { - [index: string]: Worker - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - addListener(event: string, listener: Function): 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: any) => void): this; - - emit(event: string, listener: Function): boolean; - emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - emit(event: "fork", listener: (worker: Worker) => void): boolean; - emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - emit(event: "online", listener: (worker: Worker) => void): boolean; - emit(event: "setup", listener: (settings: any) => void): boolean; - - on(event: string, listener: Function): 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: any) => void): this; - - once(event: string, listener: Function): 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: any) => void): this; - - prependListener(event: string, listener: Function): 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: any) => void): this; - - prependOnceListener(event: string, listener: Function): 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; - prependOnceListener(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. - prependOnceListener(event: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: any) => void): this; - - } - - export function disconnect(callback?: Function): void; - export function fork(env?: any): Worker; - export var isMaster: boolean; - export var isWorker: boolean; - // TODO: cluster.schedulingPolicy - export var settings: ClusterSettings; - export function setupMaster(settings?: ClusterSetupMasterSettings): void; - export var worker: Worker; - export var workers: { - [index: string]: Worker - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - export function addListener(event: string, listener: Function): Cluster; - export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function addListener(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. - export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function emit(event: string, listener: Function): boolean; - export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - export function emit(event: "fork", listener: (worker: Worker) => void): boolean; - export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - export function emit(event: "online", listener: (worker: Worker) => void): boolean; - export function emit(event: "setup", listener: (settings: any) => void): boolean; - - export function on(event: string, listener: Function): Cluster; - export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function on(event: "fork", listener: (worker: Worker) => void): Cluster; - export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export 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. - export function on(event: "online", listener: (worker: Worker) => void): Cluster; - export function on(event: "setup", listener: (settings: any) => void): Cluster; - - export function once(event: string, listener: Function): Cluster; - export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function once(event: "fork", listener: (worker: Worker) => void): Cluster; - export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export 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. - export function once(event: "online", listener: (worker: Worker) => void): Cluster; - export function once(event: "setup", listener: (settings: any) => void): Cluster; - - export function removeListener(event: string, listener: Function): Cluster; - export function removeAllListeners(event?: string): Cluster; - export function setMaxListeners(n: number): Cluster; - export function getMaxListeners(): number; - export function listeners(event: string): Function[]; - export function listenerCount(type: string): number; - - export function prependListener(event: string, listener: Function): Cluster; - export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependListener(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. - export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function prependOnceListener(event: string, listener: Function): Cluster; - export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependOnceListener(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. - export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function eventNames(): string[]; + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: "disconnect", listener: (worker: Worker) => void): void; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; + export function on(event: "fork", listener: (worker: Worker) => void): void; + export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; + export function on(event: "message", listener: (worker: Worker, message: any) => void): void; + export function on(event: "online", listener: (worker: Worker) => void): void; + export function on(event: "setup", listener: (settings: any) => void): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; } declare module "zlib" { - import * as stream from "stream"; - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; finishFlush?: number } + import * as stream from "stream"; - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + export interface ZlibCallback { (error: Error, result: any): void } - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } - export function deflate(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; - export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function deflateRaw(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; - export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; - export function gzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function gzipSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function gunzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function gunzipSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function inflate(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function inflateSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function inflateRawSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function unzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; - export function unzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; + export function deflate(buf: Buffer | string, callback?: ZlibCallback): void; + export function deflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function deflateSync(buf: Buffer | string, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; + export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; + export function gzip(buf: Buffer | string, callback?: ZlibCallback): void; + export function gzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function gzipSync(buf: Buffer | string, options?: ZlibOptions): any; + export function gunzip(buf: Buffer | string, callback?: ZlibCallback): void; + export function gunzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function gunzipSync(buf: Buffer | string, options?: ZlibOptions): any; + export function inflate(buf: Buffer | string, callback?: ZlibCallback): void; + export function inflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function inflateSync(buf: Buffer | string, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; + export function inflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function inflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; + export function unzip(buf: Buffer | string, callback?: ZlibCallback): void; + export function unzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; + export function unzipSync(buf: Buffer | string, options?: ZlibOptions): any; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; } declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - export interface NetworkInterfaceInfo { - address: string; - netmask: string; - family: string; - mac: string; - internal: boolean; - } - - export function hostname(): string; - export function loadavg(): number[]; - export function uptime(): number; - export function freemem(): number; - export function totalmem(): number; - export function cpus(): CpuInfo[]; - export function type(): string; - export function release(): string; - export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - export function homedir(): string; - export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } - export var constants: { - UV_UDP_REUSEADDR: number, - errno: { - SIGHUP: number; - SIGINT: number; - SIGQUIT: number; - SIGILL: number; - SIGTRAP: number; - SIGABRT: number; - SIGIOT: number; - SIGBUS: number; - SIGFPE: number; - SIGKILL: number; - SIGUSR1: number; - SIGSEGV: number; - SIGUSR2: number; - SIGPIPE: number; - SIGALRM: number; - SIGTERM: number; - SIGCHLD: number; - SIGSTKFLT: number; - SIGCONT: number; - SIGSTOP: number; - SIGTSTP: number; - SIGTTIN: number; - SIGTTOU: number; - SIGURG: number; - SIGXCPU: number; - SIGXFSZ: number; - SIGVTALRM: number; - SIGPROF: number; - SIGWINCH: number; - SIGIO: number; - SIGPOLL: number; - SIGPWR: number; - SIGSYS: number; - SIGUNUSED: number; - }, - signals: { - E2BIG: number; - EACCES: number; - EADDRINUSE: number; - EADDRNOTAVAIL: number; - EAFNOSUPPORT: number; - EAGAIN: number; - EALREADY: number; - EBADF: number; - EBADMSG: number; - EBUSY: number; - ECANCELED: number; - ECHILD: number; - ECONNABORTED: number; - ECONNREFUSED: number; - ECONNRESET: number; - EDEADLK: number; - EDESTADDRREQ: number; - EDOM: number; - EDQUOT: number; - EEXIST: number; - EFAULT: number; - EFBIG: number; - EHOSTUNREACH: number; - EIDRM: number; - EILSEQ: number; - EINPROGRESS: number; - EINTR: number; - EINVAL: number; - EIO: number; - EISCONN: number; - EISDIR: number; - ELOOP: number; - EMFILE: number; - EMLINK: number; - EMSGSIZE: number; - EMULTIHOP: number; - ENAMETOOLONG: number; - ENETDOWN: number; - ENETRESET: number; - ENETUNREACH: number; - ENFILE: number; - ENOBUFS: number; - ENODATA: number; - ENODEV: number; - ENOENT: number; - ENOEXEC: number; - ENOLCK: number; - ENOLINK: number; - ENOMEM: number; - ENOMSG: number; - ENOPROTOOPT: number; - ENOSPC: number; - ENOSR: number; - ENOSTR: number; - ENOSYS: number; - ENOTCONN: number; - ENOTDIR: number; - ENOTEMPTY: number; - ENOTSOCK: number; - ENOTSUP: number; - ENOTTY: number; - ENXIO: number; - EOPNOTSUPP: number; - EOVERFLOW: number; - EPERM: number; - EPIPE: number; - EPROTO: number; - EPROTONOSUPPORT: number; - EPROTOTYPE: number; - ERANGE: number; - EROFS: number; - ESPIPE: number; - ESRCH: number; - ESTALE: number; - ETIME: number; - ETIMEDOUT: number; - ETXTBSY: number; - EWOULDBLOCK: number; - EXDEV: number; - }, + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; }; - export function arch(): string; - export function platform(): string; - export function tmpdir(): string; - export var EOL: string; - export function endianness(): "BE" | "LE"; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + + export function tmpdir(): string; + export function homedir(): string; + export function endianness(): "BE" | "LE"; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): CpuInfo[]; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function userInfo(options?: { encoding: 'buffer' }): { username: Buffer, uid: number, gid: number, shell: Buffer | null, homedir: Buffer } + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: string | null, homedir: string } + export var EOL: string; } declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; - } + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } - export interface RequestOptions extends http.RequestOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - } + export interface RequestOptions extends http.RequestOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer | string[] | Buffer[]; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } - export interface Agent extends http.Agent { } + export interface AgentOptions extends http.AgentOptions { + /** + * Certificate, Private key and CA certificates to use for SSL. Default `null`. + */ + pfx?: string | Buffer; + /** + * Private key to use for SSL. Default `null`. + */ + key?: string | Buffer | string[] | Buffer[]; + /** + * A string of passphrase for the private key or pfx. Default `null`. + */ + passphrase?: string; + /** + * Public x509 certificate to use. Default `null`. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. + */ + ciphers?: string; + /** + * If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default `true`. + */ + rejectUnauthorized?: boolean; + /** + * Servername for SNI (Server Name Indication) TLS extension. + */ + servername?: string; + /** + * The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS. + */ + secureProtocol?: string; + maxCachedSessions?: number; + } - export interface AgentOptions extends http.AgentOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - maxCachedSessions?: number; - } + export class Agent extends http.Agent { + constructor(options?: AgentOptions); + } - export var Agent: { - new (options?: AgentOptions): Agent; - }; - export interface Server extends tls.Server { } - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export var globalAgent: Agent; + export class Server extends tls.Server { } + + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export var globalAgent: Agent; } declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - export var version: any; + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; } declare module "repl" { - import * as stream from "stream"; - import * as readline from "readline"; + import { EventEmitter } from "events"; + import { Interface } from "readline"; - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - completer?: Function; - replMode?: any; - breakEvalOnSigint?: any; - } + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + completer?: Function; + replMode?: symbol; + breakEvalOnSigint?: boolean; + } - export interface REPLServer extends readline.ReadLine { - defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; - displayPrompt(preserveCursor?: boolean): void; + export function start(options: ReplOptions): REPLServer; - /** - * events.EventEmitter - * 1. exit - * 2. reset - **/ + export type REPLCommand = (this: REPLServer, rest: string) => void; - addListener(event: string, listener: Function): this; - addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: Function): this; + export class REPLServer extends Interface { + inputStream: NodeJS.ReadableStream; + outputStream: NodeJS.WritableStream; + useColors: boolean; + commands: { + [command: string]: REPLCommand; + }; + defineCommand(keyword: string, cmd: REPLCommand | { help: string, action: REPLCommand }): void; + displayPrompt(preserveCursor?: boolean): void; + setPrompt(prompt: string): void; + turnOffEditorMode(): void; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "exit"): boolean; - emit(event: "reset", context: any): boolean; - - on(event: string, listener: Function): this; - on(event: "exit", listener: () => void): this; - on(event: "reset", listener: Function): this; - - once(event: string, listener: Function): this; - once(event: "exit", listener: () => void): this; - once(event: "reset", listener: Function): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: Function): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: Function): this; - } - - export function start(options: ReplOptions): REPLServer; + export class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } } declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; + import * as events from "events"; + import * as stream from "stream"; - export interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } - export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): ReadLine; - resume(): ReadLine; - close(): void; - write(data: string | Buffer, key?: Key): void; + export class Interface extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + } - /** - * events.EventEmitter - * 1. close - * 2. line - * 3. pause - * 4. resume - * 5. SIGCONT - * 6. SIGINT - * 7. SIGTSTP - **/ + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: any) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; + export interface CompleterResult { + completions: string[]; + line: string; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: any): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; + export interface InterfaceOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer; + terminal?: boolean; + historySize?: number; + } - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: any) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): Interface; + export function createInterface(options: InterfaceOptions): Interface; - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: any) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: any) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: any) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - } - - export interface Completer { - (line: string): CompleterResult; - (line: string, callback: (err: any, result: CompleterResult) => void): any; - } - - export type CompleterResult = [string[], string]; - - export interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer; - terminal?: boolean; - historySize?: number; - } - - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; - export function createInterface(options: ReadLineOptions): ReadLine; - - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { - export interface Context { } - export interface ScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - export interface RunningScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - } - export class Script { - constructor(code: string, options?: ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; - runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; - runInThisContext(options?: RunningScriptOptions): any; - } - export function createContext(sandbox?: Context): Context; - export function isContext(sandbox: Context): boolean; - export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; - export function runInDebugContext(code: string): any; - export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; - export function runInThisContext(code: string, options?: RunningScriptOptions): any; + export interface Context { } + + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + + export interface RunInNewContextOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + + export interface RunInContextOptions extends RunInNewContextOptions { + breakOnSigint?: boolean; + } + + export class Script { + constructor(code: string, options?: string | ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunInContextOptions): any; + runInNewContext(sandbox?: Context, options?: RunInNewContextOptions): any; + runInThisContext(options?: RunInNewContextOptions): any; + } + + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: string | RunInNewContextOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: string | RunInNewContextOptions): any; + export function runInThisContext(code: string, options?: string | RunInNewContextOptions): any; + /** + * @deprecated + */ + export function createScript(code: string, options?: string | ScriptOptions): Script; } declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - import * as net from "net"; + import * as events from "events"; + import * as stream from "stream"; + import * as buffer from "buffer"; + import * as net from "net"; - export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle?: any): boolean; - connected: boolean; - disconnect(): void; - unref(): void; - ref(): void; + export class ChildProcess extends events.EventEmitter implements + events.Listener<'close', (code: number, signal: string) => void>, + events.Listener<'error', (error: Error) => void>, + events.Listener<'exit', ((code: number, signal: string | null) => void) | ((code: number | null, signal: string) => void)>, + events.Listener<'message', (message: any, sendHandle?: net.Socket | net.Server) => void>, + events.Listener<'disconnect', () => void> { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + } - /** - * events.EventEmitter - * 1. close - * 2. disconnet - * 3. error - * 4. exit - * 5. message - **/ + export interface SpawnOptions { + cwd?: string; + env?: any; + stdio?: any; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + } - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: (code: number, signal: string) => void): this; - addListener(event: "disconnet", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; - emit(event: string, ...args: any[]): boolean; - emit(event: "close", code: number, signal: string): boolean; - emit(event: "disconnet"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + export interface ExecOptions { + cwd?: string; + env?: any; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + encoding?: buffer.Encoding | 'buffer'; + } - on(event: string, listener: Function): this; - on(event: "close", listener: (code: number, signal: string) => void): this; - on(event: "disconnet", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - once(event: string, listener: Function): this; - once(event: "close", listener: (code: number, signal: string) => void): this; - once(event: "disconnet", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export interface ExecFileOptions { + cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + encoding?: buffer.Encoding | 'buffer'; + } - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: (code: number, signal: string) => void): this; - prependListener(event: "disconnet", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "disconnet", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - } + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } - export interface SpawnOptions { - cwd?: string; - env?: any; - stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - export interface ExecOptions { - cwd?: string; - env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - export interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string; // specify `null`. - } - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); - export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + shell?: boolean | string; + encoding?: buffer.Encoding | 'buffer'; + } - export interface ExecFileOptions { - cwd?: string; - env?: any; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: string; // specify `null`. - } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - export interface ForkOptions { - cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - uid?: number; - gid?: number; - } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: buffer.Encoding | 'buffer'; + } - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - shell?: boolean | string; - } - export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding: string; // specify `null`. - } - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptions & { encoding: 'buffer' }): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding: string; // specify `null`. - } - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: buffer.Encoding | 'buffer'; + } - export interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: string; // specify `null`. - } - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; } declare module "url" { - export interface Url { - href?: string; - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: string | any; - slashes?: boolean; - hash?: string; - path?: string; - } + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: string | any; + slashes?: boolean; + hash?: string; + path?: string; + } - export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; - export function format(url: Url): string; - export function resolve(from: string, to: string): string; + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(url: Url | string): string; + export function resolve(from: string, to: string): string; } declare module "dns" { - export interface MxRecord { - exchange: string, - priority: number - } + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; - export function setServers(servers: string[]): void; - - //Error codes - export var NODATA: string; - export var FORMERR: string; - export var SERVFAIL: string; - export var NOTFOUND: string; - export var NOTIMP: string; - export var REFUSED: string; - export var BADQUERY: string; - export var BADNAME: string; - export var BADFAMILY: string; - export var BADRESP: string; - export var CONNREFUSED: string; - export var TIMEOUT: string; - export var EOF: string; - export var FILE: string; - export var NOMEM: string; - export var DESTRUCTION: string; - export var BADSTR: string; - export var BADFLAGS: string; - export var NONAME: string; - export var BADHINTS: string; - export var NOTINITIALIZED: string; - export var LOADIPHLPAPI: string; - export var ADDRGETNETWORKPARAMS: string; - export var CANCELLED: string; + export const NODATA: 'ENODATA'; + export const FORMERR: 'EFORMERR'; + export const SERVFAIL: 'ESERVFAIL'; + export const NOTFOUND: 'ENOTFOUND'; + export const NOTIMP: 'ENOTIMP'; + export const REFUSED: 'EREFUSED'; + export const BADQUERY: 'EBADQUERY'; + export const BADNAME: 'EBADNAME'; + export const BADFAMILY: 'EBADFAMILY'; + export const BADRESP: 'EBADRESP'; + export const CONNREFUSED: 'ECONNREFUSED'; + export const TIMEOUT: 'ETIMEOUT'; + export const EOF: 'EOF'; + export const FILE: 'EFILE'; + export const NOMEM: 'ENOMEM'; + export const DESTRUCTION: 'EDESTRUCTION'; + export const BADSTR: 'EBADSTR'; + export const BADFLAGS: 'EBADFLAGS'; + export const NONAME: 'ENONAME'; + export const BADHINTS: 'EBADHINTS'; + export const NOTINITIALIZED: 'ENOTINITIALIZED'; + export const LOADIPHLPAPI: 'ELOADIPHLPAPI'; + export const ADDRGETNETWORKPARAMS: 'EADDRGETNETWORKPARAMS'; + export const CANCELLED: 'ECANCELLED'; } declare module "net" { - import * as stream from "stream"; - import * as events from "events"; + import * as stream from "stream"; - export interface Socket extends stream.Duplex { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; + export class Socket extends stream.Duplex { + constructor(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }); - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - setEncoding(encoding?: string): this; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - pause(): this; - resume(): this; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - unref(): void; - ref(): void; + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; - remoteAddress: string; - remoteFamily: string; - remotePort: number; - localAddress: string; - localPort: number; - bytesRead: number; - bytesWritten: number; - destroyed: boolean; + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: (had_error: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - addListener(event: "timeout", listener: () => void): this; + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "close", had_error: boolean): boolean; - emit(event: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "timeout"): boolean; + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } - on(event: string, listener: Function): this; - on(event: "close", listener: (had_error: boolean) => void): this; - on(event: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - on(event: "timeout", listener: () => void): this; + export class Server extends Socket { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): this; + listen(port: number, hostname?: string, listeningListener?: Function): this; + listen(port: number, backlog?: number, listeningListener?: Function): this; + listen(port: number, listeningListener?: Function): this; + listen(path: string, backlog?: number, listeningListener?: Function): this; + listen(path: string, listeningListener?: Function): this; + listen(handle: any, backlog?: number, listeningListener?: Function): this; + listen(handle: any, listeningListener?: Function): this; + listen(options: ListenOptions, listeningListener?: Function): this; + close(callback?: () => void): this; + address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + } - once(event: string, listener: Function): this; - once(event: "close", listener: (had_error: boolean) => void): this; - once(event: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: (had_error: boolean) => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; - }; - - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } - - export interface Server extends events.EventEmitter { - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; - listen(port: number, hostname?: string, listeningListener?: Function): Server; - listen(port: number, backlog?: number, listeningListener?: Function): Server; - listen(port: number, listeningListener?: Function): Server; - listen(path: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(options: ListenOptions, listeningListener?: Function): Server; - listen(handle: any, backlog?: number, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - close(callback?: Function): Server; - address(): { port: number; family: string; address: string; }; - getConnections(cb: (error: Error, count: number) => void): void; - ref(): Server; - unref(): Server; - maxConnections: number; - connections: number; - - /** - * events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - } - export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; - export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; } declare module "dgram" { - import * as events from "events"; + import * as events from "events"; - interface RemoteInfo { - address: string; - family: string; - port: number; - } + export interface RemoteInfo { + address: string; + port: number; + size: number; + } - interface AddressInfo { - address: string; - family: string; - port: number; - } + export interface AddressInfo { + address: string; + family: string; + port: number; + } - interface BindOptions { - port: number; - address?: string; - exclusive?: boolean; - } + export interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } - interface SocketOptions { - type: "udp4" | "udp6"; - reuseAddr?: boolean; - } + export interface SocketOptions { + type: string; + reuseAddr?: boolean; + } - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(type: string | SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export interface Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port?: number, address?: string, callback?: () => void): void; - bind(options: BindOptions, callback?: Function): void; - close(callback?: any): void; - address(): AddressInfo; - setBroadcast(flag: boolean): void; - setTTL(ttl: number): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - ref(): this; - unref(): this; - - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - **/ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; - } + export class Socket extends events.EventEmitter { + send(msg: Buffer | string | Array, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(msg: Buffer | string | Array, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + bind(options: BindOptions, callback?: () => void): void; + close(callback?: () => void): void; + setTTL(ttl: number): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): void; + unref(): void; + } } declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - - interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: Function): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (code: number, signal: string) => void): this; - - on(event: string, listener: Function): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (code: number, signal: string) => void): this; - - once(event: string, listener: Function): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (code: number, signal: string) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (code: number, signal: string) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; - } - - export interface ReadStream extends stream.Readable { - close(): void; - destroy(): void; - bytesRead: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: Function): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: Function): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - export interface WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: Function): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: Function): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } + import * as stream from "stream"; + import * as events from "events"; + import * as buffer from "buffer"; + /** + * Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their synchronous counterparts are of this type. + */ + export class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; /** - * Asynchronous rename. - * @param oldPath - * @param newPath - * @param callback No arguments other than a possible exception are given to the completion callback. + * "Access Time" - Time when file data last accessed. Changed by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls. */ - export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + atime: Date; /** - * Synchronous rename - * @param oldPath - * @param newPath + * "Modified Time" - Time when file data last modified. Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls. */ - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string | Buffer, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string | Buffer, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string | Buffer, uid: number, gid: number): void; - export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string | Buffer, mode: number): void; - export function chmodSync(path: string | Buffer, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string | Buffer, mode: number): void; - export function lchmodSync(path: string | Buffer, mode: string): void; - export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string | Buffer): Stats; - export function lstatSync(path: string | Buffer): Stats; - export function fstatSync(fd: number): Stats; - export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; - export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; - export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string | Buffer): string; - export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; - /* - * Asynchronous unlink - deletes the file specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + mtime: Date; + /** + * "Change Time" - Time when file status was last changed (inode data modification). Changed by the `chmod(2)`, `chown(2)`, `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`,` utimes(2)`, `read(2)`, and `write(2)` system calls. */ - export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous unlink - deletes the file specified in {path} - * - * @param path + ctime: Date; + /** + * "Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either the `ctime` or `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). Note that this value may be greater than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants, also set if the `atime` is explicitly set to an earlier value than the current `birthtime` using the `utimes(2)` system call. */ - export function unlinkSync(path: string | Buffer): void; - /* - * Asynchronous rmdir - removes the directory specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + birthtime: Date; + } + + export type WatchListener = (eventType: string, filename?: string | Buffer) => void; + + /** + * Objects returned from fs.watch() are of this type. + */ + export class FSWatcher extends events.EventEmitter implements + events.Listener<'change', WatchListener> { + close(): void; + } + + export class ReadStream extends stream.Readable implements + events.Listener<'open', (fd: number) => void>, + events.Listener<'close', () => void> { + bytesRead: number; + path: string | Buffer; + close(): void; + destroy(): void; + } + + export class WriteStream extends stream.Writable implements + events.Listener<'open', (fd: number) => void>, + events.Listener<'close', () => void> { + close(): void; + bytesWritten: number; + path: string | Buffer; + } + + export const F_OK: number; + export const R_OK: number; + export const W_OK: number; + export const X_OK: number; + + export const constants: { + O_RDONLY: number; + O_WRONLY: number; + O_RDWR: number; + S_IFMT: number; + S_IFREG: number; + S_IFDIR: number; + S_IFCHR: number; + S_IFBLK: number; + S_IFIFO: number; + S_IFLNK: number; + S_IFSOCK: number; + O_CREAT: number; + O_EXCL: number; + O_NOCTTY: number; + O_TRUNC: number; + O_APPEND: number; + O_DIRECTORY: number; + O_NOFOLLOW: number; + O_SYNC: number; + O_SYMLINK: number; + O_NONBLOCK: number; + S_IRWXU: number; + S_IRUSR: number; + S_IWUSR: number; + S_IXUSR: number; + S_IRWXG: number; + S_IRGRP: number; + S_IWGRP: number; + S_IXGRP: number; + S_IRWXO: number; + S_IROTH: number; + S_IWOTH: number; + S_IXOTH: number; + F_OK: number; + R_OK: number; + W_OK: number; + X_OK: number; + [key: string]: number; + } + + /** + * Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. The following constants define the possible values of `mode`. It is possible to create a mask consisting of the bitwise OR of two or more values. + */ + export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous version of `fs.access()`. This throws if any accessibility checks fail, and does nothing otherwise. + */ + export function accessSync(path: string | Buffer, mode?: number): void; + + export interface AppendFileOptions { + encoding?: buffer.Encoding; + mode?: number; + flag?: string; + } + + /** + * Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a buffer. + */ + export function appendFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function appendFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | AppendFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * The synchronous version of `fs.appendFile()`. + */ + export function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: AppendFileOptions | null): void; + + /** + * Asynchronous chmod(2). + */ + export function chmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous chmod(2). + */ + export function chmodSync(path: string | Buffer, mode: number): void; + + /** + * Asynchronous chown(2). + */ + export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous chown(2). + */ + export function chownSync(path: string | Buffer, uid: number, gid: number): void; + + /** + * Asynchronous close(2). + */ + export function close(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous close(2). + */ + export function closeSync(fd: number): void; + + export interface ReadStreamOptions { + flags?: string; + encoding?: buffer.Encoding; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + } + + /** + * Returns a new ReadStream object. + * + * Be aware that, unlike the default value set for `highWaterMark` on a readable stream (16 kb), the stream returned by this method has a default value of 64 kb for the same parameter. + */ + export function createReadStream(path: string | Buffer, options?: ReadStreamOptions | null): ReadStream; + + export interface WriteStreamOptions { + flags?: string; + defaultEncoding?: buffer.Encoding; + fd?: number; + mode?: number; + autoClose?: boolean; + start: number; + end: number; + } + + /** + * Returns a new WriteStream object. + */ + export function createWriteStream(path: string | Buffer, options?: WriteStreamOptions | null): WriteStream; + + /** + * Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false. + * + * @deprecated + */ + export function exists(path: string | Buffer, callback: (exists: boolean) => void): void; + + /** + * Synchronous version of `fs.exists()`. Returns true if the file exists, false otherwise. + */ + export function existsSync(path: string | Buffer): boolean; + + /** + * Asynchronous fchmod(2). + */ + export function fchmod(fd: number, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fchmod(2). + */ + export function fchmodSync(fd: number, mode: number): void; + + /** + * Asynchronous fchown(2). + */ + export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fchown(2). + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous fdatasync(2). + */ + export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fdatasync(2). + */ + export function fdatasyncSync(fd: number): void; + + /** + * Asynchronous fstat(2). + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + /** + * Synchronous fstat(2). + */ + export function fstatSync(fd: number): Stats; + + /** + * Asynchronous fsync(2). + */ + export function fsync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous fsync(2). + */ + export function fsyncSync(fd: number): void; + + /** + * Asynchronous ftruncate(2). + * + * If the file referred to by the file descriptor was larger than `len` bytes, only the first `len` bytes will be retained in the file. + * + * If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes ('\0'). + */ + export function ftruncate(fd: number, len: number | null | undefined, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous ftruncate(2). + */ + export function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Change the file timestamps of a file referenced by the supplied file descriptor. + */ + export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous version of `fs.futimes()`. + */ + export function futimesSync(fd: number, atime: number, mtime: number): void; + + /** + * Asynchronous lchmod(2). + * + * Only available on Mac OS X. + * + * @deprecated + */ + export function lchmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous lchmod(2). + * + * @deprecated + */ + export function lchmodSync(path: string | Buffer, mode: number): void; + + /** + * Asynchronous lchown(2). + * + * @deprecated + */ + export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous lchown(2). + * + * @deprecated + */ + export function lchownSync(path: string | Buffer, uid: number, gid: number): void; + + /** + * Asynchronous link(2). + */ + export function link(existingPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous link(2). + */ + export function linkSync(existingPath: string | Buffer, newPath: string | Buffer): void; + + /** + * Asynchronous lstat(2). `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to. + */ + export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + /** + * Synchronous lstat(2). + */ + export function lstatSync(path: string | Buffer): Stats; + + /** + * Asynchronous mkdir(2). `mode` defaults to `0o777`. + */ + export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function mkdir(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous mkdir(2). + */ + export function mkdirSync(path: string | Buffer, mode?: number): void; + + export interface MkdtempOptions { + encoding: buffer.Encoding; + } + + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * The created folder path is passed as a string to the callback's second parameter. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; + export function mkdtemp(prefix: string, options: buffer.Encoding | MkdtempOptions | null, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; + + /** + * The synchronous version of fs.mkdtemp(). Returns the created folder path. + */ + export function mkdtempSync(prefix: string, options?: buffer.Encoding | MkdtempOptions | null): string; + + /** + * Asynchronous file open. See open(2). `flags` can be: + * + * 'r' - Open file for reading. An exception occurs if the file does not exist. + * + * 'r+' - Open file for reading and writing. An exception occurs if the file does not exist. + * + * 'rs+' - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. + * + * This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. + * + * Note that this doesn't turn `fs.open()` into a synchronous blocking call. If that's what you want then you should be using `fs.openSync()` + * + * 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists). + * + * 'wx' - Like `'w'` but fails if `path` exists. + * + * 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). + * + * 'wx+' - Like `'w+'` but fails if `path` exists. + * + * 'a' - Open file for appending. The file is created if it does not exist. + * + * 'ax' - Like 'a' but fails if `path` exists. + * + * 'a+' - Open file for reading and appending. The file is created if it does not exist. + * + * 'ax+' - Like 'a+' but fails if `path` exists. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was created. It defaults to `0666`, readable and writable. + */ + export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + /** + * Synchronous version of `fs.open()`. + */ + export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; + + /** + * Read data from the file specified by fd. + * + * @param buffer is the buffer that the data will be written to. + * @param offset is the offset in the buffer to start writing at. + * @param length is an integer specifying the number of bytes to read. + * @param position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. + */ + export function read(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void; + + export interface ReaddirOptions { + encoding?: buffer.Encoding | 'buffer'; + } + + /** + * Asynchronous readdir(3). Reads the contents of a directory. + * + * @param files is an array of the names of the files in the directory excluding '.' and '..'. + */ + export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + export function readdir(path: string | Buffer, options: 'buffer' | (ReadFileOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; + export function readdir(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + + /** + * Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'. + */ + export function readdirSync(path: string | Buffer): string[]; + export function readdirSync(path: string | Buffer, options: 'buffer' | (ReaddirOptions & { encoding: 'buffer' })): Buffer[]; + export function readdirSync(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null): string[]; + + export interface ReadFileOptions { + encoding?: buffer.Encoding | 'buffer'; + flag?: string; + } + + /** + * Asynchronously reads the entire contents of a file. + */ + export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + export function readFile(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding }), callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; + export function readFile(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + /** + * Synchronous version of `fs.readFile`. + */ + export function readFileSync(file: string | Buffer | number): Buffer; + export function readFileSync(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding })): string; + export function readFileSync(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null): Buffer; + + export interface ReadlinkOptions { + encoding?: buffer.Encoding | 'buffer'; + } + + /** + * Asynchronous readlink(2). + */ + export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + export function readlink(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + export function readlink(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + + /** + * Synchronous readlink(2). + */ + export function readlinkSync(path: string | Buffer): string; + export function readlinkSync(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' })): Buffer; + export function readlinkSync(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null): string; + + /** + * Synchronous version of `fs.read()`. + */ + export function readSync(fd: number, buffer: string | Buffer, offset: number, length: number, position: number): number; + + export interface RealpathOptions { + encoding?: buffer.Encoding | 'buffer'; + } + + /** + * Asynchronous realpath(3). May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + */ + export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + export function realpath(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + export function realpath(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + + /** + * Synchronous realpath(3). Returns the resolved path. + * + * Only paths that can be converted to UTF8 strings are supported. + */ + export function realpathSync(path: string | Buffer): string; + export function realpathSync(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' })): Buffer; + export function realpathSync(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null): string; + + /** + * Asynchronous rename(2). + */ + export function rename(oldPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous rename(2). + */ + export function renameSync(oldPath: string | Buffer, newPath: string | Buffer): void; + + /** + * Asynchronous rmdir(2). + */ + export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous rmdir(2). + */ + export function rmdirSync(path: string | Buffer): void; + + /** + * Asynchronous stat(2). + * + * In case of an error, the `err.code` will be one of Common System Errors. + * + * Using `fs.stat()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, `fs.access()` is recommended. + */ + export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + /** + * Synchronous stat(2). + */ + export function statSync(path: string | Buffer): Stats; + + /** + * Asynchronous symlink(2). The type argument is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using `'junction'`, the target argument will automatically be normalized to absolute path. + */ + export function symlink(target: string | Buffer, path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function symlink(target: string | Buffer, path: string | Buffer, type: 'dir' | 'file' | 'junction', callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous symlink(2). + */ + export function symlinkSync(target: string | Buffer, path: string | Buffer, type?: 'dir' | 'file' | 'junction'): void; + + /** + * Asynchronous truncate(2). + */ + export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous truncate(2). + */ + export function truncateSync(path: string | Buffer, len?: number): void; + + /** + * Asynchronous unlink(2). + */ + export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous unlink(2). + */ + export function unlinkSync(path: string | Buffer): void; + + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, _all_ listeners are removed and you have effectively stopped watching `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error. + * + * Note: `fs.watch()` is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + */ + export function unwatchFile(filename: string | Buffer, listener?: WatchListener): void; + + /** + * Change file timestamps of the file referenced by the supplied path. + * + * Note: the arguments `atime` and `mtime` of the following related functions follow these rules: + * + * - The value should be a Unix timestamp in seconds. For example, `Date.now()` returns milliseconds, so it should be divided by 1000 before passing it in. + * If the value is a numeric string like `'123456789'`, the value will get converted to the corresponding number. + * If the value is `NaN` or `Infinity`, the value will get converted to `Date.now() / 1000`. + */ + export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Synchronous version of `fs.utimes()`. + */ + export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; + + export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. default = `true`. */ - export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous rmdir - removes the directory specified in {path} - * - * @param path + persistent?: boolean; + /** + * Indicates whether all subdirectories should be watched, or only the current directory. The applies when a directory is specified, and only on supported platforms (See Caveats). default = `false`. */ - export function rmdirSync(path: string | Buffer): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + recursive?: boolean; + /** + * Specifies the character encoding to be used for the filename passed to the listener. default = `'utf8'`. */ - export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + encoding?: buffer.Encoding; + } + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory. The returned object is a `fs.FSWatcher`. + * + * Please note the listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but they are not the same thing. + */ + export function watch(filename: string | Buffer): FSWatcher; + export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null): FSWatcher; + export function watch(filename: string | Buffer, listener: WatchListener): FSWatcher; + export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null, listener: WatchListener): FSWatcher; + + export interface WatchFileOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched */ - export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + persistent: boolean; + /** + * Indicates how often the target should be polled in milliseconds. The default is `5007`. */ - export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: number): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: string): void; - /* - * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @param callback The created folder path is passed as a string to the callback's second parameter. - */ - export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; - /* - * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @returns Returns the created folder path. - */ - export function mkdtempSync(prefix: string): string; - export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string | Buffer): string[]; - export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function closeSync(fd: number): void; - export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; - export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; - export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function futimesSync(fd: number, atime: Date, mtime: Date): void; - export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; - export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; - export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - */ - export function readFileSync(filename: string, encoding: string): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ - export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; - export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; - export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; - export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; - export function existsSync(path: string | Buffer): boolean; + interval: number; + } - export namespace constants { - // File Access Constants + /** + * Watch for changes on filename. The callback listener will be called each time the file is accessed. + * + * Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. + * + * Note: `fs.watch()` is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + */ + export function watchFile(filename: string | Buffer, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string | Buffer, options: WatchFileOptions | null, listener: (curr: Stats, prev: Stats) => void): void; - /** Constant for fs.access(). File is visible to the calling process. */ - export const F_OK: number; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` and `length` determine the part of the buffer to be written. + * + * `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. See pwrite(2). + * + * Note that it is unsafe to use `fs.write` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. + */ + export function write(fd: number, buffer: string | Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; + export function write(fd: number, data: string | Buffer, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; + export function write(fd: number, data: string | Buffer, position: number, encoding: buffer.Encoding, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; - /** Constant for fs.access(). File can be read by the calling process. */ - export const R_OK: number; + export interface WriteFileOptions { + encoding?: buffer.Encoding; + mode?: number; + flag?: string; + } - /** Constant for fs.access(). File can be written by the calling process. */ - export const W_OK: number; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * + * Note that it is unsafe to use `fs.writeFile` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. + * + * Note: If a file descriptor is specified as the `file`, it will not be closed automatically. + */ + export function writeFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; + export function writeFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | WriteFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; - /** Constant for fs.access(). File can be executed by the calling process. */ - export const X_OK: number; + /** + * The synchronous version of `fs.writeFile()`. + */ + export function writeFileSync(file: string | Buffer | number, data: string | Buffer, options?: buffer.Encoding | WriteFileOptions | null): void; - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - export const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - export const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - export const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - export const O_CREAT: number; - - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ - export const O_EXCL: number; - - /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ - export const O_NOCTTY: number; - - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ - export const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - export const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - export const O_DIRECTORY: number; - - /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ - export const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - export const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - export const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - export const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - export const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - export const O_NONBLOCK: number; - - // File Type Constants - - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ - export const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - export const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - export const S_IFDIR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - export const S_IFCHR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - export const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - export const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - export const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - export const S_IFSOCK: number; - - // File Mode Constants - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ - export const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - export const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - export const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - export const S_IXUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ - export const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - export const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - export const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - export const S_IXGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ - export const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - export const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - export const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - export const S_IXOTH: number; - } - - /** Tests a user's permissions for the file specified by path. */ - export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; - export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; - /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string | Buffer, mode?: number): void; - export function createReadStream(path: string | Buffer, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - end?: number; - }): ReadStream; - export function createWriteStream(path: string | Buffer, options?: { - flags?: string; - encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - }): WriteStream; - export function fdatasync(fd: number, callback: Function): void; - export function fdatasyncSync(fd: number): void; + /** + * Synchronous `fs.write`. + */ + export function writeSync(fd: number, buffer: string | Buffer, offset: number, length: number, position?: number): void; + export function writeSync(fd: number, data: string | Buffer, position?: number, encoding?: buffer.Encoding): void; } declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export interface ParsedPath { /** - * A parsed path object generated by path.parse() or consumed by path.format(). + * The root of the path such as '/' or 'c:\' */ - export interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ + export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; + + export module posix { export function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths paths to join. - */ export function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - export function resolve(...pathSegments: any[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to - */ + export function resolve(...pathSegments: string[]): string; + export function isAbsolute(p: string): boolean; export function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ export function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ export function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ export var sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ export var delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pathObject: ParsedPath): string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } - export module posix { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } - - export module win32 { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } + export module win32 { + export function normalize(p: string): string; + export function join(...paths: string[]): string; + export function resolve(...pathSegments: string[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } } declare module "string_decoder" { - export interface NodeStringDecoder { - write(buffer: Buffer): string; - end(buffer?: Buffer): string; - } - export var StringDecoder: { - new (encoding?: string): NodeStringDecoder; - }; + import * as buffer from "buffer"; + + export class StringDecoder { + /** + * @param encoding The character encoding the `StringDecoder` will use. Defaults to `'utf8'`. + */ + constructor(encoding?: buffer.Encoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the `Buffer` are omitted from the returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * + * @param buffer A `Buffer` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * + * @param buffer A `Buffer` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } } declare module "tls" { - import * as crypto from "crypto"; - import * as net from "net"; - import * as stream from "stream"; + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; - var CLIENT_RENEG_LIMIT: number; - var CLIENT_RENEG_WINDOW: number; + export var CLIENT_RENEG_LIMIT: number; + export var CLIENT_RENEG_WINDOW: number; + export var SLAB_BUFFER_SIZE: number; + export var DEFAULT_CIPHERS: string; + export var DEFAULT_ECDH_CURVE: string; - export interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } + export class Server extends net.Server { + /** + * The `server.addContext()` method adds a secure context that will be used if the client request's SNS hostname matches the supplied `hostname` (or wildcard). + * + * @param hostname A SNI hostname or wildcard (e.g. `'*'`) + * @param options An object containing any of the possible properties from the `tls.createSecureContext()` options arguments + */ + addContext(hostName: string, options: SecureContextOptions): void; + /** + * Returns a `Buffer` instance holding the keys currently used for encryption/decryption of the TLS Session Tickets. + */ + getTicketKeys(): Buffer; + /** + * Updates the keys for encryption/decryption of the TLS Session Tickets. + * + * Note: The key's Buffer should be 48 bytes long. See ticketKeys option in tls.createServer for more information on how it is used. + * + * Note: Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * Returns the current number of concurrent connections on the server. + */ + connections: number; + } - export interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - } + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } - export class TLSSocket extends stream.Duplex { - /** - * Construct a new tls.TLSSocket object from an existing TCP socket. - */ - constructor(socket:net.Socket, options?: { - /** - * An optional TLS context object from tls.createSecureContext() - */ - secureContext?: SecureContext, - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean, - /** - * An optional net.Server instance. - */ - server?: net.Server, - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean, - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. Defaults to false. - */ - rejectUnauthorized?: boolean, - /** - * An array of strings or a Buffer naming possible NPN protocols. - * (Protocols should be ordered by their priority.) - */ - NPNProtocols?: string[] | Buffer, - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) When the server - * receives both NPN and ALPN extensions from the client, ALPN takes - * precedence over NPN and the server does not send an NPN extension - * to the client. - */ - ALPNProtocols?: string[] | Buffer, - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * SecureContext.) If SNICallback wasn't provided the default callback - * with high-level API will be used (see below). - */ - SNICallback?: Function, - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer, - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean - }); - /** - * Returns the bound address, the address family name and port of the underlying socket as reported by - * the operating system. - * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. - */ - address(): { port: number; family: string; address: string }; - /** - * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. - */ - authorized: boolean; - /** - * The reason why the peer's certificate has not been verified. - * This property becomes available only when tlsSocket.authorized === false. - */ - authorizationError: Error; - /** - * Static boolean value, always true. - * May be used to distinguish TLS sockets from regular ones. - */ - encrypted: boolean; - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. - */ - getCipher(): CipherNameAndProtocol; - /** - * Returns an object representing the peer's certificate. - * The returned object has some properties corresponding to the field of the certificate. - * If detailed argument is true the full chain with issuer property will be returned, - * if false only the top certificate without issuer property. - * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {any} - An object representing the peer's certificate. - */ - getPeerCertificate(detailed?: boolean): { - subject: Certificate; - issuerInfo: Certificate; - issuer: Certificate; - raw: any; - valid_from: string; - valid_to: string; - fingerprint: string; - serialNumber: string; - }; - /** - * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. - */ - getSession(): any; - /** - * NOTE: Works only with client TLS sockets. - * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns {any} - TLS session ticket or undefined if none was negotiated. - */ - getTLSTicket(): any; - /** - * The string representation of the local IP address. - */ - localAddress: string; - /** - * The numeric representation of the local port. - */ - localPort: string; - /** - * The string representation of the remote IP address. - * For example, '74.125.127.100' or '2001:4860:a005::68'. - */ - remoteAddress: string; - /** - * The string representation of the remote IP family. 'IPv4' or 'IPv6'. - */ - remoteFamily: string; - /** - * The numeric representation of the remote port. For example, 443. - */ - remotePort: number; - /** - * Initiate TLS renegotiation process. - * - * NOTE: Can be used to request peer's certificate after the secure connection has been established. - * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, - * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation - * is successfully completed. - */ - renegotiate(options: TlsOptions, callback: (err: Error) => any): any; - /** - * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by - * the TLS layer until the entire fragment is received and its integrity is verified; - * large fragments can span multiple roundtrips, and their processing can be delayed due to packet - * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, - * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. - */ - setMaxSendFragment(size: number): boolean; + export interface Cipher { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } - /** - * events.EventEmitter - * 1. OCSPResponse - * 2. secureConnect - **/ - addListener(event: string, listener: Function): this; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; + export interface EphemeralKeyInfo { + type: 'DH' | 'ECDH'; + name?: string; + size: number; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; + export interface PeerCertificate { + subject: Certificate; + issuerInfo: Certificate; + issuer: Certificate; + raw: Buffer; + valid_from: string; + valid_to: string; + fingerprint: string; + serialNumber: string; + } - on(event: string, listener: Function): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; + export interface TLSSocketOptions { + /** + * An optional TLS context object from `tls.createSecureContext()`. + */ + secureContext?: SecureContext; + /** + * If true the TLS socket will be instantiated in server-mode. Defaults to `false`. + */ + isServer?: boolean; + /** + * An optional net.Server instance. + */ + server?: net.Server; + /** + * Optional, see `tls.createServer()`. + */ + requestCert?: boolean; + /** + * Optional, see `tls.createServer()`. + */ + rejectUnauthorized?: boolean; + /** + * Optional, see `tls.createServer()`. + */ + NPNProtocols?: string[] | Buffer; + /** + * Optional, see `tls.createServer()`. + */ + ALPNProtocols?: string[] | Buffer; + /** + * Optional, see `tls.createServer()`. + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer; + /** + * If `true`, specifies that the OCSP status request extension will be added to the client hello and an 'OCSPResponse' event will be emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean; + } - once(event: string, listener: Function): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; + export interface RenegotiateOptions { + rejectUnauthorized?: boolean; + requestCert?: boolean; + } - prependListener(event: string, listener: Function): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; + export class TLSSocket extends net.Socket { + /** + * Construct a new `tls.TLSSocket` object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`. + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`. + */ + authorizationError?: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances. + */ + encrypted: true; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version that first defined the cipher. + */ + getCipher(): Cipher; + /** + * Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in Perfect Forward Secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; `null` is returned if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + */ + getEphemeralKeyInfo(): EphemeralKeyInfo; + /** + * Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate. + * + * @param detailed Specify `true` to request that the full certificate chain with the `issuer` property be returned; false to return only the top certificate without the `issuer` property. + */ + getPeerCertificate(detailed?: boolean): PeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. The value `null` will be returned for server sockets or disconnected client sockets. + */ + getProtocol(): string | null; + /** + * Returns the ASN.1 encoded TLS session or `undefined` if no session was negotiated. Can be used to speed up handshake establishment when reconnecting to the server. + */ + getSession(): Buffer | undefined; + /** + * Returns the TLS session ticket or `undefined` if no session was negotiated. + * + * Note: This only works with client TLS sockets. Useful only for debugging, for session reuse `provide` session option to `tls.connect()`. + */ + getTLSTicket(): Buffer | undefined; + /** + * Returns the string representation of the local IP address. + */ + localAddress: string; + /** + * Returns the numeric representation of the local port. + */ + localPort: number; + /** + * Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. + */ + remoteAddress: string; + /** + * Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + */ + remoteFamily: string; + /** + * The numeric representation of the remote port. For example, 443. + */ + remotePort: number; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * + * Note: This method can be used to request a peer's certificate after the secure connection has been established. + * + * Note: When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + */ + renegotiate(options: RenegotiateOptions, callback: (err: Error | null) => any): any; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. Returns `true` if setting the limit succeeded; false otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. + * + * @param size The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + } - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - } + export interface ConnectOptions { + /** + * Host the client should connect to. + */ + host?: string; + /** + * Port the client should connect to. + */ + port?: number | string; + /** + * Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `host` and `port` are ignored. + */ + socket?: net.Socket; + /** + * Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + */ + path?: string; + /** + * A `string` or `Buffer` containing the private key, certificate, and CA certs of the client in PFX or PKCS12 format. + */ + pfx?: string | Buffer; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s containing the private key of the client in PEM format. + */ + key?: string | Buffer | string[] | Buffer[]; + /** + * A string containing the passphrase for the private key or pfx. + */ + passphrase?: string; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s containing the certificate key of the client in PEM format. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * A string describing the ciphers to use or exclude, separated by `:`. Uses the same default cipher suite as `tls.createServer()`. + */ + ciphers?: string; + /** + * If true, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`. + */ + rejectUnauthorized?: boolean; + /** + * An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. + */ + NPNProtocols?: string[] | Buffer[]; + /** + * An array of strings or `Buffer`s containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler: `['hello', 'world']`.) + */ + ALPNProtocols?: string[] | Buffer[]; + /** + * Server name for the SNI (Server Name Indication) TLS extension. + */ + servername?: string; + /** + * A callback function to be used when checking the server's hostname against the certificate. This should throw an error if verification fails. The method should return `undefined` if the `servername` and `cert` are verified. + */ + checkServerIdentity?: (servername: string, cert: Buffer) => void; + /** + * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. + */ + secureProtocol?: string; + /** + * An optional TLS context object as returned by from `tls.createSecureContext( ... )`. It can be used for caching client certificates, keys, and CA certificates. + */ + secureContext?: SecureContext; + /** + * A `Buffer` instance, containing TLS session. + */ + session?: Buffer; + /** + * Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`. + */ + minDHSize?: number; + } - export interface TlsOptions { - host?: string; - port?: number; - pfx?: string | Buffer[]; - key?: string | string[] | Buffer | any[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | string[] | Buffer | Buffer[]; - crl?: string | string[]; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: string[] | Buffer; - SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; - ecdhCurve?: string; - dhparam?: string | Buffer; - handshakeTimeout?: number; - ALPNProtocols?: string[] | Buffer; - sessionTimeout?: number; - ticketKeys?: any; - sessionIdContext?: string; - secureProtocol?: string; - } + export interface SecureContextOptions { + /** + * A string or `Buffer` holding the PFX or PKCS12 encoded private key, certificate, and CA certificates. + */ + pfx?: string | Buffer; + /** + * The private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided either as an array of key strings or as an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. + */ + key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; + /** + * A string containing the passphrase for the private key or pfx. + */ + passphrase?: string; + /** + * A string containing the PEM encoded certificate. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). + */ + crl?: string | string[]; + /** + * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. + */ + ciphers?: string; + /** + * If `true`, when a cipher is being selected, the server's preferences will be used instead of the client preferences. + */ + honorCipherOrder?: boolean; + } - export interface ConnectionOptions { - host?: string; - port?: number; - socket?: net.Socket; - pfx?: string | Buffer - key?: string | string[] | Buffer | Buffer[]; - passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | Buffer | (string | Buffer)[]; - rejectUnauthorized?: boolean; - NPNProtocols?: (string | Buffer)[]; - servername?: string; - path?: string; - ALPNProtocols?: (string | Buffer)[]; - checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; - secureProtocol?: string; - secureContext?: Object; - session?: Buffer; - minDHSize?: number; - } + export interface CreateServerOptions { + /** + * A `string` or `Buffer` containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the `key`, `cert`, and `ca` options.) + */ + pfx?: string | Buffer; + /** + * The private key of the server in PEM format. To support multiple keys using different algorithms an array can be provided either as a plain array of key strings or an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. + */ + key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; + /** + * A string containing the passphrase for the private key or pfx. + */ + passphrase?: string; + /** + * A string containing the PEM encoded certificate. + */ + cert?: string | Buffer | string[] | Buffer[]; + /** + * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. + */ + ca?: string | Buffer | string[] | Buffer[]; + /** + * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). + */ + crl?: string | string[]; + /** + * A string describing the ciphers to use or exclude, separated by `:`. + */ + ciphers?: string; + /** + * A string describing a named curve to use for ECDH key agreement or false to disable ECDH. Defaults to `prime256v1` (NIST P-256). Use crypto.getCurves() to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. + */ + ecdhCurve?: string; + /** + * A string or `Buffer` containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer; + /** + * Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out. + */ + handshakeTimeout?: number; + /** + * When choosing a cipher, use the server's preferences instead of the client preferences. Defaults to `true`. + */ + honorCipherOrder?: boolean; + /** + * If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`. + */ + requestCert?: boolean; + /** + * If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `false`. + */ + rejectUnauthorized?: boolean; + /** + * An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer; + /** + * An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client. + */ + ALPNProtocols?: string[] | Buffer; + /** + * A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + /** + * An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See SSL_CTX_set_timeout for more details. + */ + sessionTimeout?: number; + /** + * A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. Note that this is automatically shared between `cluster` module workers. + */ + ticketKeys?: Buffer; + /** + * A string containing an opaque identifier for session resumption. If `requestCert` is true, the default is a 128 bit truncated SHA1 hash value generated from the command-line. Otherwise, a default is not provided. + */ + sessionIdContext?: string; + /** + * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. + */ + secureProtocol?: string; + } - export interface Server extends net.Server { - close(callback?: Function): Server; - address(): { port: number; family: string; address: string; }; - addContext(hostName: string, credentials: { - key: string; - cert: string; - ca: string; - }): void; - maxConnections: number; - connections: number; + export interface SecureContext { + context: any; + } - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - **/ - addListener(event: string, listener: Function): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + /** + * Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the `'secureConnection'` event. + */ + export function createServer(options: CreateServerOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; - emit(event: string, ...args: any[]): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; - emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; - emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; - emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; - emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + /** + * Creates a new client connection to the given `port` and `host` or `options.port` and `options.host`. (If `host` is omitted, it defaults to `localhost`.) + */ + export function connect(options: ConnectOptions, callback?: () => void): TLSSocket; + export function connect(port: number, options?: ConnectOptions, callback?: () => void): TLSSocket; + export function connect(port: number, host?: string, options?: ConnectOptions, callback?: () => void): TLSSocket; - on(event: string, listener: Function): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + /** + * The `tls.createSecureContext()` method creates a credentials object. + * + * If the `'ca'` option is not given, then Node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt. + */ + export function createSecureContext(options: SecureContextOptions): SecureContext; - once(event: string, listener: Function): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - } - - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - - export interface SecurePair { - encrypted: any; - cleartext: any; - } - - export interface SecureContextOptions { - pfx?: string | Buffer; - key?: string | Buffer; - passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer; - crl?: string | string[] - ciphers?: string; - honorCipherOrder?: boolean; - } - - export interface SecureContext { - context: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; - export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; - export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - export function createSecureContext(details: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported SSL ciphers. + */ + export function getCiphers(): string[]; } declare module "crypto" { - export interface Certificate { - exportChallenge(spkac: string | Buffer): Buffer; - exportPublicKey(spkac: string | Buffer): Buffer; - verifySpkac(spkac: Buffer): boolean; - } - export var Certificate: { - new (): Certificate; - (): Certificate; - } + import * as stream from "stream"; - export var fips: boolean; + export var constants: { + defaultCipherList: string; + defaultCoreCipherList: string; + [key: string]: string | number; + } - export interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: string | string[]; - crl: string | string[]; - ciphers: string; - } - export interface Credentials { context?: any; } - export function createCredentials(details: CredentialDetails): Credentials; - export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string | Buffer): Hmac; + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; - type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; - type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; - type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; - type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; - type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + export class Certificate { + constructor(); + exportChallenge(spkac: string | Buffer, encoding?: string): string; + exportPublicKey(spkac: string | Buffer, encoding?: string): Buffer; + verifySpkac(spkac: Buffer): boolean; + } - export interface Hash extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hash; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - export interface Hmac extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hmac; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - export function createCipher(algorithm: string, password: any): Cipher; - export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - export interface Cipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): void; - getAuthTag(): Buffer; - setAAD(buffer: Buffer): void; - } - export function createDecipher(algorithm: string, password: any): Decipher; - export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - export interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer): Buffer; - update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; - update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; - final(): Buffer; - final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): void; - setAuthTag(tag: Buffer): void; - setAAD(buffer: Buffer): void; - } - export function createSign(algorithm: string): Signer; - export interface Signer extends NodeJS.WritableStream { - update(data: string | Buffer): Signer; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; - } - export function createVerify(algorith: string): Verify; - export interface Verify extends NodeJS.WritableStream { - update(data: string | Buffer): Verify; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; - verify(object: string, signature: Buffer): boolean; - verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; - } - export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; - export function createDiffieHellman(prime: Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; - export interface DiffieHellman { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrime(): Buffer; - getPrime(encoding: HexBase64Latin1Encoding): string; - getGenerator(): Buffer; - getGenerator(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - setPublicKey(public_key: Buffer): void; - setPublicKey(public_key: string, encoding: string): void; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: string): void; - verifyError: number; - } - export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - export interface RsaPublicKey { - key: string; - padding?: number; - } - export interface RsaPrivateKey { - key: string; - passphrase?: string, - padding?: number; - } - export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer - export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer - export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer - export function getCiphers(): string[]; - export function getCurves(): string[]; - export function getHashes(): string[]; - export interface ECDH { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; - } - export function createECDH(curve_name: string): ECDH; - export function timingSafeEqual(a: Buffer, b: Buffer): boolean; - export var DEFAULT_ENCODING: string; + export function createHash(algorithm: string): Hash; + + export class Hash extends stream.Transform { + update(data: string | Buffer, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): string; + digest(): Buffer; + } + + export function createHmac(algorithm: string, key: string | Buffer): Hmac; + + export class Hmac extends stream.Transform { + update(data: string | Buffer, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): string; + digest(): Buffer; + } + + export function createCipher(algorithm: string, password: string | Buffer): Cipher; + export function createCipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Cipher; + + export class Cipher extends stream.Transform { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary" | "latin1" | "base64" | "hex"): string; + update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1", output_encoding: "binary" | "latin1" | "base64" | "hex"): string; + final(): Buffer; + final(output_encoding: string): string; + setAAD(buffer: Buffer): void; + setAutoPadding(auto_padding: boolean): void; + getAuthTag(): Buffer; + } + + export function createDecipher(algorithm: string, password: string | Buffer): Decipher; + export function createDecipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Decipher; + + export class Decipher extends stream.Transform { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; + update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; + final(): Buffer; + final(output_encoding: string): string; + setAAD(buffer: Buffer): void; + setAutoPadding(auto_padding: boolean): void; + setAuthTag(tag: Buffer): void; + } + + export function createSign(algorithm: string): Signer; + + export class Signer extends stream.Writable { + update(data: string | Buffer): void; + sign(private_key: string): Buffer; + sign(private_key: string, output_format: string): string; + } + + export function createVerify(algorith: string): Verify; + + export class Verify extends stream.Writable { + update(data: string | Buffer): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + + export function createDiffieHellman(prime: number, prime_encoding?: string, generator?: number | string | Buffer, generator_encoding?: string): DiffieHellman; + export function createDiffieHellman(prime_length: number, generator?: number | string | Buffer): DiffieHellman; + export function getDiffieHellman(group_name: string): DiffieHellman; + + export class DiffieHellman { + verifyError: number; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + generateKeys(encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding?: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + + export function createECDH(curve_name: string): ECDH; + + export class ECDH { + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + generateKeys(encoding?: string, format?: string): string; + getPrivateKey(encoding?: string): string; + getPublicKey(encoding?: string, format?: string): string; + setPrivateKey(private_key: string, encoding?: string): void; + } + + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => void): void; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => void): void; + + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; + + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + + export interface RsaKey { + key: string; + passphrase?: string, + padding?: number; + } + + export function timingSafeEqual(a: Buffer, b: Buffer): boolean; + export function publicEncrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; + export function privateEncrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; + export function publicDecrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; + export function privateDecrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; + + export function setEngine(engine: string, flags?: number): void; } declare module "stream" { - import * as events from "events"; + import * as events from "events"; - class internal extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - namespace internal { + export class Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } - export class Stream extends internal { } + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (this: Readable, size?: number) => any; + } - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (size?: number) => any; - } + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + isPaused(): boolean; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - protected _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. readable - * 5. error - **/ - addListener(event: string, listener: Function): this; - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + setDefaultEncoding(encoding: string): this; + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements Writable { + writable: boolean; + constructor(opts?: DuplexOptions); + setDefaultEncoding(encoding: string): this; + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; + export interface TransformOptions extends ReadableOptions, WritableOptions { + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; + export class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + } - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - - removeListener(event: string, listener: Function): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - } - - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; - } - - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - protected _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - **/ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "drain", chunk: Buffer | string): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - - removeListener(event: string, listener: Function): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - } - - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } - - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - // Readable - pause(): this; - resume(): this; - // Writeable - writable: boolean; - constructor(opts?: DuplexOptions); - protected _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export interface TransformOptions extends DuplexOptions { - transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - flush?: (callback: Function) => any; - } - - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - protected _transform(chunk: any, encoding: string, callback: Function): void; - protected _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } - - export class PassThrough extends Transform { } - } - - export = internal; + export class PassThrough extends Transform { } } declare module "util" { - export interface InspectOptions { - showHidden?: boolean; - depth?: number; - colors?: boolean; - customInspect?: boolean; + /** + * The `util.debuglog()` method is used to create a function that conditionally writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` environment variable. If the `section` name appears within the value of that environment variable, then the returned function operates similar to console.error(). If not, then the returned function is a no-op. + */ + export function debuglog(section: string): (msg: any, ...args: any[]) => void; + + export interface InspectOptions { + /** + * If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`. + */ + showHidden?: boolean; + /** + * Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`. + */ + depth?: number | null; + /** + * If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see "Customizing util.inspect colors". + */ + colors?: boolean; + /** + * If `false`, then custom `inspect(depth, opts)` functions exported on the object being inspected will not be called. Defaults to `true`. + */ + customInspect?: boolean; + /** + * If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`. + */ + showProxy?: boolean; + /** + * Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements. + */ + maxArrayLength?: number | null; + /** + * The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to `60` for legacy compatibility. + */ + breakLength?: number; + } + + /** + * The `util.inspect()` method returns a string representation of object that is primarily useful for debugging. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + + export namespace inspect { + export var colors: { + bold: [number, number]; + italic: [number, number]; + underline: [number, number]; + inverse: [number, number]; + white: [number, number]; + grey: [number, number]; + black: [number, number]; + blue: [number, number]; + cyan: [number, number]; + green: [number, number]; + magenta: [number, number]; + red: [number, number]; + yellow: [number, number]; } - export function format(format: any, ...param: any[]): string; - export function debug(string: string): void; - export function error(...param: any[]): void; - export function puts(...param: any[]): void; - export function print(...param: any[]): void; - export function log(string: string): void; - export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - export function isArray(object: any): boolean; - export function isRegExp(object: any): boolean; - export function isDate(object: any): boolean; - export function isError(object: any): boolean; - export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key: string): (msg: string, ...param: any[]) => void; - export function isBoolean(object: any): boolean; - export function isBuffer(object: any): boolean; - export function isFunction(object: any): boolean; - export function isNull(object: any): boolean; - export function isNullOrUndefined(object: any): boolean; - export function isNumber(object: any): boolean; - export function isObject(object: any): boolean; - export function isPrimitive(object: any): boolean; - export function isString(object: any): boolean; - export function isSymbol(object: any): boolean; - export function isUndefined(object: any): boolean; - export function deprecate(fn: Function, message: string): Function; + export var styles: { + special: string; + number: string; + boolean: string; + undefined: string; + null: string; + string: string; + symbol: string; + date: string; + regexp: string; + }; + + export var custom: symbol; + } + + /** + * The `util.deprecate()` method wraps the given function or class in such a way that it is marked as deprecated. + */ + export function deprecate(fn: T, string: string): T; + + /** + * The `util.format()` method returns a formatted string using the first argument as a printf-like format. + */ + export function format(format: any, ...param: any[]): string; + + /** + * Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor. + */ + export function inherits(constructor: any, superConstructor: any): void; + + /** + * Deprecated predecessor of `console.error`. + * + * @deprecated + */ + export function debug(string: string): void; + + /** + * Deprecated predecessor of `console.error`. + * + * @deprecated + */ + export function error(...strings: string[]): void; + + /** + * Internal alias for `Array.isArray`. + * + * @deprecated + */ + export function isArray(object: any): object is any[]; + + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isBoolean(object: any): object is boolean; + + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isBuffer(object: any): object is Buffer; + + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isDate(object: any): object is Date; + + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isError(object: any): object is Error; + + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isFunction(object: any): object is Function; + + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isNull(object: any): object is null; + + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isNullOrUndefined(object: any): object is null | undefined; + + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isNumber(object: any): object is number; + + /** + * Returns true if the given `object` is strictly an `Object` and not a `Function`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isObject(object: any): object is Object; + + /** + * Returns true if the given `object` is a primitive type. Otherwise, returns `false`. + * + * @deprecated + */ + export function isPrimitive(object: any): object is string | number | boolean | null | undefined; + + /** + * Returns true if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isRegExp(object: any): object is RegExp; + + /** + * Returns true if the given `object` is a `String`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isString(object: any): object is string; + + /** + * Returns true if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isSymbol(object: any): object is symbol; + + /** + * Returns true if the given `object` is `undefined`. Otherwise, returns `false`. + * + * @deprecated + */ + export function isUndefined(object: any): object is symbol; + + /** + * The `util.log()` method prints the given `string` to `stdout` with an included timestamp. + * + * @deprecated + */ + export function log(string: string): void; + + /** + * Deprecated predecessor of `console.log`. + * + * @deprecated + */ + export function print(strings: string[]): void; + + /** + * Deprecated predecessor of `console.log`. + * + * @deprecated + */ + export function puts(strings: string[]): void; + + /** + * The `util._extend()` method was never intended to be used outside of internal Node.js modules. The community found and used it anyway. + * + * It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through `Object.assign()`. + * + * @deprecated + */ + export function _extend(target: T, source: U): T & U; } declare module "assert" { - function internal(value: any, message?: string): void; - namespace internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; + function internal(value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; - constructor(options?: { - message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function - }); - } - - export function fail(actual: any, expected: any, message: string, operator: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export function ifError(value: any): void; + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); } - export = internal; + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; } declare module "tty" { - import * as net from "net"; + import * as net from "net"; - export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - export interface WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } } declare module "domain" { - import * as events from "events"; + import * as events from "events"; - export class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - members: any[]; - enter(): void; - exit(): void; - } + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + members: any[]; + enter(): void; + exit(): void; + } - export function create(): Domain; + export function create(): Domain; } declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFBLK: number; - export var S_IFIFO: number; - export var S_IFSOCK: number; - export var S_IRWXU: number; - export var S_IRUSR: number; - export var S_IWUSR: number; - export var S_IXUSR: number; - export var S_IRWXG: number; - export var S_IRGRP: number; - export var S_IWGRP: number; - export var S_IXGRP: number; - export var S_IRWXO: number; - export var S_IROTH: number; - export var S_IWOTH: number; - export var S_IXOTH: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_NOCTTY: number; - export var O_DIRECTORY: number; - export var O_NOATIME: number; - export var O_NOFOLLOW: number; - export var O_SYNC: number; - export var O_SYMLINK: number; - export var O_DIRECT: number; - export var O_NONBLOCK: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; - export var SIGQUIT: number; - export var SIGTRAP: number; - export var SIGIOT: number; - export var SIGBUS: number; - export var SIGUSR1: number; - export var SIGUSR2: number; - export var SIGPIPE: number; - export var SIGALRM: number; - export var SIGCHLD: number; - export var SIGSTKFLT: number; - export var SIGCONT: number; - export var SIGSTOP: number; - export var SIGTSTP: number; - export var SIGTTIN: number; - export var SIGTTOU: number; - export var SIGURG: number; - export var SIGXCPU: number; - export var SIGXFSZ: number; - export var SIGVTALRM: number; - export var SIGPROF: number; - export var SIGIO: number; - export var SIGPOLL: number; - export var SIGPWR: number; - export var SIGSYS: number; - export var SIGUNUSED: number; - export var defaultCoreCipherList: string; - export var defaultCipherList: string; - export var ENGINE_METHOD_RSA: number; - export var ALPN_ENABLED: number; + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; +} + +declare module "module" { + export = NodeModule; } declare module "process" { - export = process; -} - -declare module "v8" { - interface HeapSpaceInfo { - space_name: string; - space_size: number; - space_used_size: number; - space_available_size: number; - physical_space_size: number; - } - - const enum DoesZapCodeSpaceFlag { - Disabled = 0, - Enabled = 1 - } - - interface HeapInfo { - total_heap_size: number; - total_heap_size_executable: number; - total_physical_size: number; - total_available_size: number; - used_heap_size: number; - heap_size_limit: number; - malloced_memory: number; - peak_malloced_memory: number; - does_zap_garbage: DoesZapCodeSpaceFlag; - } - - export function getHeapStatistics(): HeapInfo; - export function getHeapSpaceStatistics(): HeapSpaceInfo[]; - export function setFlagsFromString(flags: string): void; + export = process; } declare module "timers" { - export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function clearTimeout(timeoutId: NodeJS.Timer): void; - export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function clearInterval(intervalId: NodeJS.Timer): void; - export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; - export function clearImmediate(immediateId: any): void; -} - -declare module "console" { - export = console; -} - -/** - * _debugger module is not documented. - * Source code is at https://github.com/nodejs/node/blob/master/lib/_debugger.js - */ -declare module "_debugger" { - export interface Packet { - raw: string; - headers: string[]; - body: Message; - } - - export interface Message { - seq: number; - type: string; - } - - export interface RequestInfo { - command: string; - arguments: any; - } - - export interface Request extends Message, RequestInfo { - } - - export interface Event extends Message { - event: string; - body?: any; - } - - export interface Response extends Message { - request_seq: number; - success: boolean; - /** Contains error message if success === false. */ - message?: string; - /** Contains message body if success === true. */ - body?: any; - } - - export interface BreakpointMessageBody { - type: string; - target: number; - line: number; - } - - export class Protocol { - res: Packet; - state: string; - execute(data: string): void; - serialize(rq: Request): string; - onResponse: (pkt: Packet) => void; - } - - export var NO_FRAME: number; - export var port: number; - - export interface ScriptDesc { - name: string; - id: number; - isNative?: boolean; - handle?: number; - type: string; - lineOffset?: number; - columnOffset?: number; - lineCount?: number; - } - - export interface Breakpoint { - id: number; - scriptId: number; - script: ScriptDesc; - line: number; - condition?: string; - scriptReq?: string; - } - - export interface RequestHandler { - (err: boolean, body: Message, res: Packet): void; - request_seq?: number; - } - - export interface ResponseBodyHandler { - (err: boolean, body?: any): void; - request_seq?: number; - } - - export interface ExceptionInfo { - text: string; - } - - export interface BreakResponse { - script?: ScriptDesc; - exception?: ExceptionInfo; - sourceLine: number; - sourceLineText: string; - sourceColumn: number; - } - - export function SourceInfo(body: BreakResponse): string; - - export interface ClientInstance extends NodeJS.EventEmitter { - protocol: Protocol; - scripts: ScriptDesc[]; - handles: ScriptDesc[]; - breakpoints: Breakpoint[]; - currentSourceLine: number; - currentSourceColumn: number; - currentSourceLineText: string; - currentFrame: number; - currentScript: string; - - connect(port: number, host: string): void; - req(req: any, cb: RequestHandler): void; - reqFrameEval(code: string, frame: number, cb: RequestHandler): void; - mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; - setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; - clearBreakpoint(rq: Request, cb: RequestHandler): void; - listbreakpoints(cb: RequestHandler): void; - reqSource(from: number, to: number, cb: RequestHandler): void; - reqScripts(cb: any): void; - reqContinue(cb: RequestHandler): void; - } - - export var Client : { - new (): ClientInstance - } + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function clearImmediate(immediateId: NodeJS.Immediate): void; } From 41da5eb070a6578eb8cbef441d8bc474908d91e7 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sun, 8 Jan 2017 01:30:51 +0300 Subject: [PATCH 008/306] Fixed @node/node interface according to official API. Resolving #13782 Changed api: stream.Readable, Renamed: NodeJS.Console to NodeJS.ConsoleConstructor Reconciled all consequent interfaces, like writeStream etc. --- node/index.d.ts | 7241 +++++++++++++++++++++++++---------------------- 1 file changed, 3797 insertions(+), 3444 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index e6333dd7d1..0620b9df9a 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -8,162 +8,37 @@ * Node.js v6.x API * * * ************************************************/ -interface NodeError { - /** - * Returns a string describing the point in the code at which the Error was instantiated. - * - * For example: - * - * ``` - * Error: Things keep happening! - * at /home/gbusey/file.js:525:2 - * at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) - * at Actor. (/home/gbusey/actors.js:400:8) - * at increaseSynergy (/home/gbusey/actors.js:701:6) - * ``` - * - * The first line is formatted as : , and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses. - */ - stack?: string; - /** - * Returns the string description of error as set by calling new Error(message). The message passed to the constructor will also appear in the first line of the stack trace of the Error, however changing this property after the Error object is created may not change the first line of the stack trace. - * - * ``` - * const err = new Error('The message'); - * console.log(err.message); - * // Prints: The message - * ``` - */ - message: string; +// 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; + assert(value: any, message?: string, ...optionalParams: any[]): void; + dir(obj: any, options?: {showHidden?: boolean, depth?: number, colors?: boolean}): void; + error(message?: any, ...optionalParams: any[]): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + time(label: string): void; + timeEnd(label: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; } -interface Error extends NodeError { } +interface Error { + stack?: string; +} interface ErrorConstructor { - /** - * Creates a `.stack` property on `targetObject`, which when accessed returns a string representing the location in the code at which `Error.captureStackTrace()`` was called. - * - * ```js - * const myObject = {}; - * Error.captureStackTrace(myObject); - * myObject.stack // similar to `new Error().stack` - * ``` - * - * The first line of the trace, instead of being prefixed with `ErrorType : message`, will be the result of calling `targetObject.toString()``. - * - * The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace. - * - * The constructorOpt argument is useful for hiding implementation details of error generation from an end user. For instance: - * - * ```js - * function MyError() { - * Error.captureStackTrace(this, MyError); - * } - * - * // Without passing MyError to captureStackTrace, the MyError - * // frame would should up in the .stack property. by passing - * // the constructor, we omit that frame and all frames above it. - * new MyError().stack - * ``` - */ - captureStackTrace(targetObject: T, constructorOpt?: new () => T): void; - - /** - * The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj))``. - * - * The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. - * - * If set to a non-number value, or set to a negative number, stack traces will not capture any frames. - */ - stackTraceLimit: number; + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + stackTraceLimit: number; } -// ES2015 collection types -interface NodeCollection { - size: number; -} - -interface NodeWeakCollection {} - -interface IterableIterator {} - -interface NodeCollectionConstructor { - prototype: T; -} - -interface Map extends NodeCollection { - clear(): void; - delete(key: K): boolean; - entries(): Array<[K, V]>; - forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; - get(key: K): V; - has(key: K): boolean; - keys(): Array; - set(key: K, value?: V): Map; - values(): Array; - // [Symbol.iterator]():Array<[K,V]>; - // [Symbol.toStringTag]: "Map"; -} - -interface MapConstructor extends NodeCollectionConstructor> { - new (): Map; - new (): Map; -} - -declare var Map: MapConstructor; - -interface WeakMap extends NodeWeakCollection { - clear(): void; - delete(key: K): boolean; - get(key: K): V | void; - has(key: K): boolean; - set(key: K, value?: V): WeakMap; -} - -interface WeakMapConstructor extends NodeCollectionConstructor> { - new (): WeakMap; - new (): WeakMap; -} - -declare var WeakMap: WeakMapConstructor; - -interface Set extends NodeCollection { - add(value: T): Set; - clear(): void; - delete(value: T): boolean; - entries(): Array<[T, T]>; - forEach(callbackfn: (value: T, index: T, set: Set) => void, thisArg?: any): void; - has(value: T): boolean; - keys(): Array; - values(): Array; - // [Symbol.iterator]():Array; - // [Symbol.toStringTag]: "Set"; -} - -interface SetConstructor extends NodeCollectionConstructor> { - new (): Set; - new (): Set; - new (iterable: Array): Set; -} - -declare var Set: SetConstructor; - -interface WeakSet extends NodeWeakCollection { - add(value: T): WeakSet; - clear(): void; - delete(value: T): boolean; - has(value: T): boolean; - // [Symbol.toStringTag]: "WeakSet"; -} - -interface WeakSetConstructor extends NodeCollectionConstructor> { - new (): WeakSet; - new (): WeakSet; - new (iterable: Array): WeakSet; -} - -declare var WeakSet: WeakSetConstructor; +// compat for TypeScript 1.8 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } /************************************************ * * @@ -172,6 +47,7 @@ declare var WeakSet: WeakSetConstructor; ************************************************/ declare var process: NodeJS.Process; declare var global: NodeJS.Global; +declare var console: Console; declare var __filename: string; declare var __dirname: string; @@ -184,44 +60,26 @@ declare function setImmediate(callback: (...args: any[]) => void, ...args: any[] declare function clearImmediate(immediateId: any): void; interface NodeRequireFunction { - (id: string): any; + (id: string): any; } interface NodeRequire extends NodeRequireFunction { - resolve(id: string): string; - cache: { [filename: string]: NodeModule }; - extensions: NodeExtensions; - main: any; -} - -interface NodeExtensions { - '.js': (m: NodeModule, filename: string) => any; - '.json': (m: NodeModule, filename: string) => any; - '.node': (m: NodeModule, filename: string) => any; - [ext: string]: (m: NodeModule, filename: string) => any; + resolve(id: string): string; + cache: any; + extensions: any; + main: NodeModule | undefined; } declare var require: NodeRequire; -declare class NodeModule { - static runMain(): void; - static wrap(code: string): string; - static _nodeModulePaths(path: string): string[]; - static _load(request: string, parent?: NodeModule, isMain?: boolean): any; - static _resolveFilename(request: string, parent?: NodeModule, isMain?: boolean): string; - static _extensions: NodeExtensions; - - constructor(filename: string); - _compile(code: string, filename: string): string; - - id: string; - parent: NodeModule; - filename: string; - paths: string[]; - children: NodeModule[]; - exports: any; - loaded: boolean; - require: NodeRequireFunction; +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; } declare var module: NodeModule; @@ -229,209 +87,159 @@ declare var module: NodeModule; // Same as module.exports declare var exports: any; declare var SlowBuffer: { - new (str: string, encoding?: string): Buffer; - new (size: number): Buffer; - new (size: Uint8Array): Buffer; - new (array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; }; -// Console class (compatible with TypeScript `lib.d.ts`). -declare interface Console { - log(msg: any, ...params: any[]): void; - info(msg: any, ...params: any[]): void; - warn(msg: any, ...params: any[]): void; - error(msg: any, ...params: any[]): void; - dir(value: any, ...params: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - trace(msg: any, ...params: any[]): void; - assert(test?: boolean, msg?: string, ...params: any[]): void; - Console: new (stdout: NodeJS.WritableStream) => Console; -} +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; +interface Buffer extends NodeBuffer { } -declare var console: Console; - -declare class Buffer extends Uint8Array { - [index: number]: number; - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor(str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor(size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor(array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor(arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor(array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor(buffer: Buffer); - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be _zero-filled_. - * - * @param size The desired length of the new `Buffer` - * @param fill A value to pre-fill the new `Buffer` with. Default: `0` - * @param encoding If `fill` is a string, this is its encoding. Default: `'utf8'` - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new _non-zero-filled_ `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `buffer.kMaxLength`. Otherwise, a `RangeError` is thrown. A zero-length `Buffer` will be created if `size <= 0`. - * - * The underlying memory for `Buffer` instances created in this way is not initialized. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize such `Buffer` instances to zeroes. - * - * @param size The desired length of the new `Buffer` - */ - static allocUnsafe(size: number): Buffer; - /** - * Returns `true` if `obj` is a Buffer, `false` otherwise. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns `true` if `encoding` contains a supported character encoding, or `false` otherwise. - * - * @param encoding A character encoding name to check. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Buffer, buf2: Buffer): number; - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - swap16(): this; - swap32(): this; - swap64(): this; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - entries(): IterableIterator<[number, number]>; - keys(): IterableIterator; - values(): IterableIterator; -} +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + new (str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + new (arrayBuffer: ArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + new (buffer: Buffer): Buffer; + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; +}; /************************************************ * * @@ -439,244 +247,301 @@ declare class Buffer extends Uint8Array { * * ************************************************/ declare namespace NodeJS { - export interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } + export interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream): Console; + } - export interface EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - eventNames(): string[]; - listenerCount(type: string): number; - } + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } - export interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: string): this; - isPaused(): boolean; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: ReadableStream): ReadableStream; - } + export class EventEmitter { + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + eventNames(): (string | symbol)[]; + } - export interface WritableStream extends EventEmitter { - writable: boolean; - setDefaultEncoding(encoding: string): this; - write(buffer: Buffer | string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } + export interface ReadableStream extends EventEmitter { + readable: boolean; + isTTY?: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string | null): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): this; + unpipe(destination?: T): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } - export interface ReadWriteStream extends ReadableStream, WritableStream { } + export interface WritableStream extends EventEmitter { + writable: boolean; + isTTY?: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } - export interface Events extends EventEmitter { } + export interface ReadWriteStream extends ReadableStream, WritableStream { } - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; + export interface Events extends EventEmitter { } - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - } + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - } + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } - export interface Env { - PATH: string; - [key: string]: string; - } + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } - export interface Versions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } + export interface CpuUsage { + user: number; + system: number; + } - export interface Process extends EventEmitter { - stdout: WritableStream; - stderr: WritableStream; - stdin: ReadableStream; - argv: string[]; - argv0: string; - /** - * The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. - */ - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - env: Env; - exit(code?: number): void; - exitCode?: number; - getgid(): number; - setgid(id: number): void; - setgid(id: string): void; - getuid(): number; - setuid(id: number): void; - setuid(id: string): void; - version: string; - versions: Versions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string | number): void; - pid: number; - title: string; - arch: string; - platform: string; - memoryUsage(): MemoryUsage; - nextTick(callback: Function): void; - umask(mask?: number): number; - uptime(): number; - hrtime(time?: [number, number]): [number, number]; - domain: Domain; + export interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } - // Worker - send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - } + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + exitCode: number; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + title: string; + arch: string; + platform: string; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } - export interface Timer { - ref(): void; - unref(): void; - _called: boolean; - _onTimeout: Function; - _timerArgs?: any[]; - } + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } - export interface Immediate { - _argv?: any[]; - _callback: Function; - _onImmediate: Function; - } + export interface Timer { + ref(): void; + unref(): void; + } +} + +interface IterableIterator { } + +/** + * @deprecated + */ +interface NodeBuffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; } /************************************************ @@ -685,3078 +550,3566 @@ declare namespace NodeJS { * * ************************************************/ declare module "buffer" { - export var INSPECT_MAX_BYTES: number; - export var kMaxLength: number; - - export type Encoding = "ascii" | "latin1" | "binary" | "utf8" | "utf-8" | "ucs2" | "ucs-2" | "utf16le" | "utf-16le" | "hex" | "base64"; - - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + export var INSPECT_MAX_BYTES: number; + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } + export interface StringifyOptions { + encodeURIComponent?: Function; + } - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { - export class EventEmitter implements NodeJS.EventEmitter { - static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated - static defaultMaxListeners: number; + class internal extends NodeJS.EventEmitter { } - addListener(event: string, listener: (...args: any[]) => void): this; - on(event: string, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Array<(...args: any[]) => void>; - listenerCount(event: string): number; - emit(event: string, ...args: any[]): boolean; - eventNames(): string[]; - } + namespace internal { + export class EventEmitter extends internal { + static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated + static defaultMaxListeners: number; - export interface Listener { - on(event: E, listener: L): this; - once(event: E, listener: L): this; - addListener(event: E, listener: L): this; - removeListener(event: E, listener: L): this; - listeners(event: E): L[]; - } + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): (string | symbol)[]; + listenerCount(type: string | symbol): number; + } + } + + export = internal; } declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; - export interface OutgoingHeaders { - [header: string]: number | string | string[]; - } + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: { [key: string]: any }; + auth?: string; + agent?: Agent | boolean; + } - export interface IncomingHeaders { - [header: string]: string | string[]; - } - - export interface RequestOptions { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number | string; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: OutgoingHeaders; - auth?: string; - agent?: Agent | boolean; - } - - export class Server extends net.Server { - setTimeout(msecs: number, callback: Function): void; - maxHeadersCount: number; - timeout: number; - listening: boolean; - } - - export class ServerResponse extends stream.Writable { - finished: boolean; - headersSent: boolean; - statusCode: number; - statusMessage: string; - sendDate: boolean; - - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - writeContinue(): void; - writeHead(statusCode: number, statusText?: string, headers?: OutgoingHeaders): void; - writeHead(statusCode: number, headers?: OutgoingHeaders): void; - setHeader(name: string, value: string | string[]): void; - setTimeout(msecs: number, callback: () => void): this; - getHeader(name: string): string; - removeHeader(name: string): void; - write(chunk: any, encoding?: string): any; - addTrailers(headers: OutgoingHeaders): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } - - export class ClientRequest extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - write(chunk: any, encoding?: string): void; - abort(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } - - export class IncomingMessage extends stream.Readable { - httpVersion: string; - headers: IncomingHeaders; - rawHeaders: string[]; - trailers: IncomingHeaders; - rawTrailers: string[]; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; - destroy(error?: Error): void; + export interface Server extends net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + listening: boolean; + } /** - * Only valid for request obtained from http.Server. + * @deprecated Use IncomingMessage */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - } + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; - export interface AgentOptions { + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + statusMessage: string; + headersSent: boolean; + setHeader(name: string, value: string | string[]): void; + setTimeout(msecs: number, callback: Function): ServerResponse; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + finished: boolean; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface IncomingMessage extends stream.Readable { + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: any; + rawHeaders: string[]; + trailers: any; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false + * @deprecated Use IncomingMessage */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } + export interface ClientResponse extends IncomingMessage { } - export class Agent { - maxSockets: number; - sockets: any; - requests: any; + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } - constructor(opts?: AgentOptions); + export class Agent { + maxSockets: number; + sockets: any; + requests: any; - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } + constructor(opts?: AgentOptions); - export var METHODS: string[]; + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } - export var STATUS_CODES: { - [errorCode: number]: string; - [errorCode: string]: string; - }; + export var METHODS: string[]; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; - export function createClient(port?: number, host?: string): any; - export function request(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: string | RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export var globalAgent: Agent; + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; } declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; - export interface ClusterSettings { - exec?: string; - args?: string[]; - silent?: boolean; - } + // interfaces + export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } - export interface Address { - address: string; - port: number; - addressType: string; - } + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; + } - export class Worker extends events.EventEmitter { - id: string; - process: child.ChildProcess; - suicide: boolean; - send(message: any, sendHandle?: any): boolean; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - } + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } - export var settings: ClusterSettings; - export var isMaster: boolean; - export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; - export var worker: Worker; - export var workers: { - [index: string]: Worker - }; + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; - export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (code: number, signal: string) => 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, listener: Function): boolean + emit(event: "disconnect", listener: () => void): boolean + emit(event: "error", listener: (code: number, signal: string) => void): boolean + emit(event: "exit", listener: (code: number, signal: string) => void): boolean + emit(event: "listening", listener: (address: Address) => void): boolean + emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean + emit(event: "online", listener: () => void): boolean + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (code: number, signal: string) => 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: Function): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (code: number, signal: string) => 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: Function): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => 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: Function): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => 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; + } + + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): 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: any) => void): this; + + emit(event: string, listener: Function): boolean; + emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + emit(event: "fork", listener: (worker: Worker) => void): boolean; + emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + emit(event: "online", listener: (worker: Worker) => void): boolean; + emit(event: "setup", listener: (settings: any) => void): boolean; + + on(event: string, listener: Function): 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: any) => void): this; + + once(event: string, listener: Function): 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: any) => void): this; + + prependListener(event: string, listener: Function): 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: any) => void): this; + + prependOnceListener(event: string, listener: Function): 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; + prependOnceListener(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. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback?: Function): void; + export function fork(env?: any): Worker; + export var isMaster: boolean; + export var isWorker: boolean; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; + export var worker: Worker; + export var workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(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. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function emit(event: string, listener: Function): boolean; + export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + export function emit(event: "fork", listener: (worker: Worker) => void): boolean; + export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + export function emit(event: "online", listener: (worker: Worker) => void): boolean; + export function emit(event: "setup", listener: (settings: any) => void): boolean; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export 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. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export 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. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; + export function listeners(event: string): Function[]; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(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. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(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. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { - import * as stream from "stream"; + import * as stream from "stream"; + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; finishFlush?: number } - export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } - export interface ZlibCallback { (error: Error, result: any): void } + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } - export interface Gzip extends stream.Transform { } - export interface Gunzip extends stream.Transform { } - export interface Deflate extends stream.Transform { } - export interface Inflate extends stream.Transform { } - export interface DeflateRaw extends stream.Transform { } - export interface InflateRaw extends stream.Transform { } - export interface Unzip extends stream.Transform { } + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; - export function createGzip(options?: ZlibOptions): Gzip; - export function createGunzip(options?: ZlibOptions): Gunzip; - export function createDeflate(options?: ZlibOptions): Deflate; - export function createInflate(options?: ZlibOptions): Inflate; - export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - export function createInflateRaw(options?: ZlibOptions): InflateRaw; - export function createUnzip(options?: ZlibOptions): Unzip; + export function deflate(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function deflateRaw(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function gzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function gunzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflate(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function unzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): Buffer; - export function deflate(buf: Buffer | string, callback?: ZlibCallback): void; - export function deflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function deflateSync(buf: Buffer | string, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; - export function deflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; - export function gzip(buf: Buffer | string, callback?: ZlibCallback): void; - export function gzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function gzipSync(buf: Buffer | string, options?: ZlibOptions): any; - export function gunzip(buf: Buffer | string, callback?: ZlibCallback): void; - export function gunzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function gunzipSync(buf: Buffer | string, options?: ZlibOptions): any; - export function inflate(buf: Buffer | string, callback?: ZlibCallback): void; - export function inflate(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function inflateSync(buf: Buffer | string, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer | string, callback?: ZlibCallback): void; - export function inflateRaw(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function inflateRawSync(buf: Buffer | string, options?: ZlibOptions): any; - export function unzip(buf: Buffer | string, callback?: ZlibCallback): void; - export function unzip(buf: Buffer | string, options: ZlibOptions, callback?: ZlibCallback): void; - export function unzipSync(buf: Buffer | string, options?: ZlibOptions): any; - - // Constants - export var Z_NO_FLUSH: number; - export var Z_PARTIAL_FLUSH: number; - export var Z_SYNC_FLUSH: number; - export var Z_FULL_FLUSH: number; - export var Z_FINISH: number; - export var Z_BLOCK: number; - export var Z_TREES: number; - export var Z_OK: number; - export var Z_STREAM_END: number; - export var Z_NEED_DICT: number; - export var Z_ERRNO: number; - export var Z_STREAM_ERROR: number; - export var Z_DATA_ERROR: number; - export var Z_MEM_ERROR: number; - export var Z_BUF_ERROR: number; - export var Z_VERSION_ERROR: number; - export var Z_NO_COMPRESSION: number; - export var Z_BEST_SPEED: number; - export var Z_BEST_COMPRESSION: number; - export var Z_DEFAULT_COMPRESSION: number; - export var Z_FILTERED: number; - export var Z_HUFFMAN_ONLY: number; - export var Z_RLE: number; - export var Z_FIXED: number; - export var Z_DEFAULT_STRATEGY: number; - export var Z_BINARY: number; - export var Z_TEXT: number; - export var Z_ASCII: number; - export var Z_UNKNOWN: number; - export var Z_DEFLATED: number; - export var Z_NULL: number; + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; } declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + + export function hostname(): string; + export function loadavg(): number[]; + export function uptime(): number; + export function freemem(): number; + export function totalmem(): number; + export function cpus(): CpuInfo[]; + export function type(): string; + export function release(): string; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function homedir(): string; + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } + export var constants: { + UV_UDP_REUSEADDR: number, + errno: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }, + signals: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }, }; - } - - export interface NetworkInterfaceInfo { - address: string; - netmask: string; - family: string; - mac: string; - internal: boolean; - } - - export function tmpdir(): string; - export function homedir(): string; - export function endianness(): "BE" | "LE"; - export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; - export function loadavg(): number[]; - export function totalmem(): number; - export function freemem(): number; - export function cpus(): CpuInfo[]; - export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - export function userInfo(options?: { encoding: 'buffer' }): { username: Buffer, uid: number, gid: number, shell: Buffer | null, homedir: Buffer } - export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: string | null, homedir: string } - export var EOL: string; + export function arch(): string; + export function platform(): string; + export function tmpdir(): string; + export var EOL: string; + export function endianness(): "BE" | "LE"; } declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; - export interface ServerOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - crl?: any; - ciphers?: string; - honorCipherOrder?: boolean; - requestCert?: boolean; - rejectUnauthorized?: boolean; - NPNProtocols?: any; - SNICallback?: (servername: string) => any; - } + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; + } - export interface RequestOptions extends http.RequestOptions { - pfx?: string | Buffer; - key?: string | Buffer; - passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer | string[] | Buffer[]; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - } + export interface RequestOptions extends http.RequestOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } - export interface AgentOptions extends http.AgentOptions { - /** - * Certificate, Private key and CA certificates to use for SSL. Default `null`. - */ - pfx?: string | Buffer; - /** - * Private key to use for SSL. Default `null`. - */ - key?: string | Buffer | string[] | Buffer[]; - /** - * A string of passphrase for the private key or pfx. Default `null`. - */ - passphrase?: string; - /** - * Public x509 certificate to use. Default `null`. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. - */ - ciphers?: string; - /** - * If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default `true`. - */ - rejectUnauthorized?: boolean; - /** - * Servername for SNI (Server Name Indication) TLS extension. - */ - servername?: string; - /** - * The SSL method to use, e.g. `SSLv3_method` to force SSL version 3. The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS. - */ - secureProtocol?: string; - maxCachedSessions?: number; - } + export interface Agent extends http.Agent { } - export class Agent extends http.Agent { - constructor(options?: AgentOptions); - } + export interface AgentOptions extends http.AgentOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + maxCachedSessions?: number; + } - export class Server extends tls.Server { } - - export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export function get(options: string | RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export var globalAgent: Agent; + export var Agent: { + new (options?: AgentOptions): Agent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export var globalAgent: Agent; } declare module "punycode" { - export function decode(string: string): string; - export function encode(string: string): string; - export function toUnicode(domain: string): string; - export function toASCII(domain: string): string; - export var ucs2: ucs2; - interface ucs2 { - decode(string: string): number[]; - encode(codePoints: number[]): string; - } - export var version: any; + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; } declare module "repl" { - import { EventEmitter } from "events"; - import { Interface } from "readline"; + import * as stream from "stream"; + import * as readline from "readline"; - export interface ReplOptions { - prompt?: string; - input?: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - terminal?: boolean; - eval?: Function; - useColors?: boolean; - useGlobal?: boolean; - ignoreUndefined?: boolean; - writer?: Function; - completer?: Function; - replMode?: symbol; - breakEvalOnSigint?: boolean; - } + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + completer?: Function; + replMode?: any; + breakEvalOnSigint?: any; + } - export function start(options: ReplOptions): REPLServer; + export interface REPLServer extends readline.ReadLine { + defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + displayPrompt(preserveCursor?: boolean): void; - export type REPLCommand = (this: REPLServer, rest: string) => void; + /** + * events.EventEmitter + * 1. exit + * 2. reset + **/ - export class REPLServer extends Interface { - inputStream: NodeJS.ReadableStream; - outputStream: NodeJS.WritableStream; - useColors: boolean; - commands: { - [command: string]: REPLCommand; - }; - defineCommand(keyword: string, cmd: REPLCommand | { help: string, action: REPLCommand }): void; - displayPrompt(preserveCursor?: boolean): void; - setPrompt(prompt: string): void; - turnOffEditorMode(): void; - } + addListener(event: string, listener: Function): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: Function): this; - export class Recoverable extends SyntaxError { - err: Error; - constructor(err: Error); - } + emit(event: string, ...args: any[]): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: any): boolean; + + on(event: string, listener: Function): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: Function): this; + + once(event: string, listener: Function): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: Function): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: Function): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: Function): this; + } + + export function start(options: ReplOptions): REPLServer; } declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; + import * as events from "events"; + import * as stream from "stream"; - export interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } - export class Interface extends events.EventEmitter { - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): this; - resume(): this; - close(): void; - write(data: string | Buffer, key?: Key): void; - } + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; + close(): void; + write(data: string | Buffer, key?: Key): void; - export interface Completer { - (line: string): CompleterResult; - (line: string, callback: (err: any, result: CompleterResult) => void): any; - } + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + **/ - export interface CompleterResult { - completions: string[]; - line: string; - } + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: any) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; - export interface InterfaceOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer; - terminal?: boolean; - historySize?: number; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: any): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): Interface; - export function createInterface(options: InterfaceOptions): Interface; + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: any) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: any) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: any) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: any) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + } + + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } + + export type CompleterResult = [string[], string]; + + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer; + terminal?: boolean; + historySize?: number; + } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; + export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { - export interface Context { } - - export interface ScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - - export interface RunInNewContextOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - } - - export interface RunInContextOptions extends RunInNewContextOptions { - breakOnSigint?: boolean; - } - - export class Script { - constructor(code: string, options?: string | ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunInContextOptions): any; - runInNewContext(sandbox?: Context, options?: RunInNewContextOptions): any; - runInThisContext(options?: RunInNewContextOptions): any; - } - - export function createContext(sandbox?: Context): Context; - export function isContext(sandbox: Context): boolean; - export function runInContext(code: string, contextifiedSandbox: Context, options?: string | RunInNewContextOptions): any; - export function runInDebugContext(code: string): any; - export function runInNewContext(code: string, sandbox?: Context, options?: string | RunInNewContextOptions): any; - export function runInThisContext(code: string, options?: string | RunInNewContextOptions): any; - /** - * @deprecated - */ - export function createScript(code: string, options?: string | ScriptOptions): Script; + export interface Context { } + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + export interface RunningScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + export class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; + export function runInThisContext(code: string, options?: RunningScriptOptions): any; } declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; - import * as buffer from "buffer"; - import * as net from "net"; + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; - export class ChildProcess extends events.EventEmitter implements - events.Listener<'close', (code: number, signal: string) => void>, - events.Listener<'error', (error: Error) => void>, - events.Listener<'exit', ((code: number, signal: string | null) => void) | ((code: number | null, signal: string) => void)>, - events.Listener<'message', (message: any, sendHandle?: net.Socket | net.Server) => void>, - events.Listener<'disconnect', () => void> { - stdin: stream.Writable; - stdout: stream.Readable; - stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; - pid: number; - kill(signal?: string): void; - send(message: any, sendHandle?: any): boolean; - connected: boolean; - disconnect(): void; - unref(): void; - } + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; - export interface SpawnOptions { - cwd?: string; - env?: any; - stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - } + /** + * events.EventEmitter + * 1. close + * 2. disconnet + * 3. error + * 4. exit + * 5. message + **/ - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnet", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export interface ExecOptions { - cwd?: string; - env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - encoding?: buffer.Encoding | 'buffer'; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnet"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function exec(command: string, options: ExecOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + on(event: string, listener: Function): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnet", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export interface ExecFileOptions { - cwd?: string; - env?: any; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - encoding?: buffer.Encoding | 'buffer'; - } + once(event: string, listener: Function): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnet", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions & { encoding: 'buffer' }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnet", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; - export interface ForkOptions { - cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - uid?: number; - gid?: number; - } + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnet", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + export interface SpawnOptions { + cwd?: string; + env?: any; + stdio?: any; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + } + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - shell?: boolean | string; - encoding?: buffer.Encoding | 'buffer'; - } + export interface ExecOptions { + cwd?: string; + env?: any; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + export interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string; // specify `null`. + } + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); + export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions & { encoding: 'buffer' }): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + export interface ExecFileOptions { + cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: string; // specify `null`. + } + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: buffer.Encoding | 'buffer'; - } + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptions & { encoding: 'buffer' }): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + } + export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - export interface ExecFileSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; - encoding?: buffer.Encoding | 'buffer'; - } + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions & { encoding: 'buffer' }): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; } declare module "url" { - export interface Url { - href?: string; - protocol?: string; - auth?: string; - hostname?: string; - port?: string; - host?: string; - pathname?: string; - search?: string; - query?: string | any; - slashes?: boolean; - hash?: string; - path?: string; - } + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: string | any; + slashes?: boolean; + hash?: string; + path?: string; + } - export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; - export function format(url: Url | string): string; - export function resolve(from: string, to: string): string; + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(url: Url): string; + export function resolve(from: string, to: string): string; } declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export interface MxRecord { + exchange: string, + priority: number + } - export const NODATA: 'ENODATA'; - export const FORMERR: 'EFORMERR'; - export const SERVFAIL: 'ESERVFAIL'; - export const NOTFOUND: 'ENOTFOUND'; - export const NOTIMP: 'ENOTIMP'; - export const REFUSED: 'EREFUSED'; - export const BADQUERY: 'EBADQUERY'; - export const BADNAME: 'EBADNAME'; - export const BADFAMILY: 'EBADFAMILY'; - export const BADRESP: 'EBADRESP'; - export const CONNREFUSED: 'ECONNREFUSED'; - export const TIMEOUT: 'ETIMEOUT'; - export const EOF: 'EOF'; - export const FILE: 'EFILE'; - export const NOMEM: 'ENOMEM'; - export const DESTRUCTION: 'EDESTRUCTION'; - export const BADSTR: 'EBADSTR'; - export const BADFLAGS: 'EBADFLAGS'; - export const NONAME: 'ENONAME'; - export const BADHINTS: 'EBADHINTS'; - export const NOTINITIALIZED: 'ENOTINITIALIZED'; - export const LOADIPHLPAPI: 'ELOADIPHLPAPI'; - export const ADDRGETNETWORKPARAMS: 'EADDRGETNETWORKPARAMS'; - export const CANCELLED: 'ECANCELLED'; + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export function setServers(servers: string[]): void; + + //Error codes + export var NODATA: string; + export var FORMERR: string; + export var SERVFAIL: string; + export var NOTFOUND: string; + export var NOTIMP: string; + export var REFUSED: string; + export var BADQUERY: string; + export var BADNAME: string; + export var BADFAMILY: string; + export var BADRESP: string; + export var CONNREFUSED: string; + export var TIMEOUT: string; + export var EOF: string; + export var FILE: string; + export var NOMEM: string; + export var DESTRUCTION: string; + export var BADSTR: string; + export var BADFLAGS: string; + export var NONAME: string; + export var BADHINTS: string; + export var NOTINITIALIZED: string; + export var LOADIPHLPAPI: string; + export var ADDRGETNETWORKPARAMS: string; + export var CANCELLED: string; } declare module "net" { - import * as stream from "stream"; + import * as stream from "stream"; + import * as events from "events"; - export class Socket extends stream.Duplex { - constructor(options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }); + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): this; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; - connect(port: number, host?: string, connectionListener?: Function): void; - connect(path: string, connectionListener?: Function): void; - bufferSize: number; - write(data: any, encoding?: string, callback?: Function): void; - destroy(): void; - setTimeout(timeout: number, callback?: Function): void; - setNoDelay(noDelay?: boolean): void; - setKeepAlive(enable?: boolean, initialDelay?: number): void; - address(): { port: number; family: string; address: string; }; - unref(): void; - ref(): void; + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + destroyed: boolean; - remoteAddress: string; - remoteFamily: string; - remotePort: number; - localAddress: string; - localPort: number; - bytesRead: number; - bytesWritten: number; + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; - } + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; - export class Server extends Socket { - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): this; - listen(port: number, hostname?: string, listeningListener?: Function): this; - listen(port: number, backlog?: number, listeningListener?: Function): this; - listen(port: number, listeningListener?: Function): this; - listen(path: string, backlog?: number, listeningListener?: Function): this; - listen(path: string, listeningListener?: Function): this; - listen(handle: any, backlog?: number, listeningListener?: Function): this; - listen(handle: any, listeningListener?: Function): this; - listen(options: ListenOptions, listeningListener?: Function): this; - close(callback?: () => void): this; - address(): { port: number; family: string; address: string; }; - getConnections(cb: (error: Error, count: number) => void): void; - ref(): this; - unref(): this; - maxConnections: number; - connections: number; - } + on(event: string, listener: Function): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; - export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; - export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function connect(port: number, host?: string, connectionListener?: Function): Socket; - export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; - export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; - export function createConnection(path: string, connectionListener?: Function): Socket; - export function isIP(input: string): number; - export function isIPv4(input: string): boolean; - export function isIPv6(input: string): boolean; + once(event: string, listener: Function): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } + + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; + listen(port: number, hostname?: string, listeningListener?: Function): Server; + listen(port: number, backlog?: number, listeningListener?: Function): Server; + listen(port: number, listeningListener?: Function): Server; + listen(path: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(options: ListenOptions, listeningListener?: Function): Server; + listen(handle: any, backlog?: number, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): Server; + unref(): Server; + maxConnections: number; + connections: number; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; } declare module "dgram" { - import * as events from "events"; + import * as events from "events"; - export interface RemoteInfo { - address: string; - port: number; - size: number; - } + interface RemoteInfo { + address: string; + family: string; + port: number; + } - export interface AddressInfo { - address: string; - family: string; - port: number; - } + interface AddressInfo { + address: string; + family: string; + port: number; + } - export interface BindOptions { - port: number; - address?: string; - exclusive?: boolean; - } + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } - export interface SocketOptions { - type: string; - reuseAddr?: boolean; - } + interface SocketOptions { + type: "udp4" | "udp6"; + reuseAddr?: boolean; + } - export function createSocket(type: string | SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export class Socket extends events.EventEmitter { - send(msg: Buffer | string | Array, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - send(msg: Buffer | string | Array, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; - bind(options: BindOptions, callback?: () => void): void; - close(callback?: () => void): void; - setTTL(ttl: number): void; - address(): AddressInfo; - setBroadcast(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setMulticastLoopback(flag: boolean): void; - addMembership(multicastAddress: string, multicastInterface?: string): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - ref(): void; - unref(): void; - } + export interface Socket extends events.EventEmitter { + send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: any): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + } } declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import * as buffer from "buffer"; + import * as stream from "stream"; + import * as events from "events"; + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: Function): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + + on(event: string, listener: Function): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + + once(event: string, listener: Function): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + } + + export interface ReadStream extends stream.Readable { + close(): void; + destroy(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } - /** - * Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their synchronous counterparts are of this type. - */ - export class Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; /** - * "Access Time" - Time when file data last accessed. Changed by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls. + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. */ - atime: Date; + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /** - * "Modified Time" - Time when file data last modified. Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls. + * Synchronous rename + * @param oldPath + * @param newPath */ - mtime: Date; - /** - * "Change Time" - Time when file status was last changed (inode data modification). Changed by the `chmod(2)`, `chown(2)`, `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`,` utimes(2)`, `read(2)`, and `write(2)` system calls. + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string | Buffer, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string | Buffer, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string | Buffer, uid: number, gid: number): void; + export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string | Buffer, mode: number): void; + export function chmodSync(path: string | Buffer, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string | Buffer, mode: number): void; + export function lchmodSync(path: string | Buffer, mode: string): void; + export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string | Buffer): Stats; + export function lstatSync(path: string | Buffer): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; + export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; + export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string | Buffer): string; + export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; + /* + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. */ - ctime: Date; - /** - * "Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either the `ctime` or `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). Note that this value may be greater than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants, also set if the `atime` is explicitly set to an earlier value than the current `birthtime` using the `utimes(2)` system call. + export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path */ - birthtime: Date; - } - - export type WatchListener = (eventType: string, filename?: string | Buffer) => void; - - /** - * Objects returned from fs.watch() are of this type. - */ - export class FSWatcher extends events.EventEmitter implements - events.Listener<'change', WatchListener> { - close(): void; - } - - export class ReadStream extends stream.Readable implements - events.Listener<'open', (fd: number) => void>, - events.Listener<'close', () => void> { - bytesRead: number; - path: string | Buffer; - close(): void; - destroy(): void; - } - - export class WriteStream extends stream.Writable implements - events.Listener<'open', (fd: number) => void>, - events.Listener<'close', () => void> { - close(): void; - bytesWritten: number; - path: string | Buffer; - } - - export const F_OK: number; - export const R_OK: number; - export const W_OK: number; - export const X_OK: number; - - export const constants: { - O_RDONLY: number; - O_WRONLY: number; - O_RDWR: number; - S_IFMT: number; - S_IFREG: number; - S_IFDIR: number; - S_IFCHR: number; - S_IFBLK: number; - S_IFIFO: number; - S_IFLNK: number; - S_IFSOCK: number; - O_CREAT: number; - O_EXCL: number; - O_NOCTTY: number; - O_TRUNC: number; - O_APPEND: number; - O_DIRECTORY: number; - O_NOFOLLOW: number; - O_SYNC: number; - O_SYMLINK: number; - O_NONBLOCK: number; - S_IRWXU: number; - S_IRUSR: number; - S_IWUSR: number; - S_IXUSR: number; - S_IRWXG: number; - S_IRGRP: number; - S_IWGRP: number; - S_IXGRP: number; - S_IRWXO: number; - S_IROTH: number; - S_IWOTH: number; - S_IXOTH: number; - F_OK: number; - R_OK: number; - W_OK: number; - X_OK: number; - [key: string]: number; - } - - /** - * Tests a user's permissions for the file or directory specified by `path`. The `mode` argument is an optional integer that specifies the accessibility checks to be performed. The following constants define the possible values of `mode`. It is possible to create a mask consisting of the bitwise OR of two or more values. - */ - export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous version of `fs.access()`. This throws if any accessibility checks fail, and does nothing otherwise. - */ - export function accessSync(path: string | Buffer, mode?: number): void; - - export interface AppendFileOptions { - encoding?: buffer.Encoding; - mode?: number; - flag?: string; - } - - /** - * Asynchronously append data to a file, creating the file if it does not yet exist. `data` can be a string or a buffer. - */ - export function appendFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function appendFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | AppendFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * The synchronous version of `fs.appendFile()`. - */ - export function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: AppendFileOptions | null): void; - - /** - * Asynchronous chmod(2). - */ - export function chmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous chmod(2). - */ - export function chmodSync(path: string | Buffer, mode: number): void; - - /** - * Asynchronous chown(2). - */ - export function chown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous chown(2). - */ - export function chownSync(path: string | Buffer, uid: number, gid: number): void; - - /** - * Asynchronous close(2). - */ - export function close(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous close(2). - */ - export function closeSync(fd: number): void; - - export interface ReadStreamOptions { - flags?: string; - encoding?: buffer.Encoding; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; - end?: number; - } - - /** - * Returns a new ReadStream object. - * - * Be aware that, unlike the default value set for `highWaterMark` on a readable stream (16 kb), the stream returned by this method has a default value of 64 kb for the same parameter. - */ - export function createReadStream(path: string | Buffer, options?: ReadStreamOptions | null): ReadStream; - - export interface WriteStreamOptions { - flags?: string; - defaultEncoding?: buffer.Encoding; - fd?: number; - mode?: number; - autoClose?: boolean; - start: number; - end: number; - } - - /** - * Returns a new WriteStream object. - */ - export function createWriteStream(path: string | Buffer, options?: WriteStreamOptions | null): WriteStream; - - /** - * Test whether or not the given path exists by checking with the file system. Then call the `callback` argument with either true or false. - * - * @deprecated - */ - export function exists(path: string | Buffer, callback: (exists: boolean) => void): void; - - /** - * Synchronous version of `fs.exists()`. Returns true if the file exists, false otherwise. - */ - export function existsSync(path: string | Buffer): boolean; - - /** - * Asynchronous fchmod(2). - */ - export function fchmod(fd: number, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fchmod(2). - */ - export function fchmodSync(fd: number, mode: number): void; - - /** - * Asynchronous fchown(2). - */ - export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fchown(2). - */ - export function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous fdatasync(2). - */ - export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fdatasync(2). - */ - export function fdatasyncSync(fd: number): void; - - /** - * Asynchronous fstat(2). - */ - export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - /** - * Synchronous fstat(2). - */ - export function fstatSync(fd: number): Stats; - - /** - * Asynchronous fsync(2). - */ - export function fsync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous fsync(2). - */ - export function fsyncSync(fd: number): void; - - /** - * Asynchronous ftruncate(2). - * - * If the file referred to by the file descriptor was larger than `len` bytes, only the first `len` bytes will be retained in the file. - * - * If the file previously was shorter than `len` bytes, it is extended, and the extended part is filled with null bytes ('\0'). - */ - export function ftruncate(fd: number, len: number | null | undefined, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous ftruncate(2). - */ - export function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Change the file timestamps of a file referenced by the supplied file descriptor. - */ - export function futimes(fd: number, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous version of `fs.futimes()`. - */ - export function futimesSync(fd: number, atime: number, mtime: number): void; - - /** - * Asynchronous lchmod(2). - * - * Only available on Mac OS X. - * - * @deprecated - */ - export function lchmod(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous lchmod(2). - * - * @deprecated - */ - export function lchmodSync(path: string | Buffer, mode: number): void; - - /** - * Asynchronous lchown(2). - * - * @deprecated - */ - export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous lchown(2). - * - * @deprecated - */ - export function lchownSync(path: string | Buffer, uid: number, gid: number): void; - - /** - * Asynchronous link(2). - */ - export function link(existingPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous link(2). - */ - export function linkSync(existingPath: string | Buffer, newPath: string | Buffer): void; - - /** - * Asynchronous lstat(2). `lstat()` is identical to `stat()`, except that if `path` is a symbolic link, then the link itself is stat-ed, not the file that it refers to. - */ - export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - /** - * Synchronous lstat(2). - */ - export function lstatSync(path: string | Buffer): Stats; - - /** - * Asynchronous mkdir(2). `mode` defaults to `0o777`. - */ - export function mkdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function mkdir(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous mkdir(2). - */ - export function mkdirSync(path: string | Buffer, mode?: number): void; - - export interface MkdtempOptions { - encoding: buffer.Encoding; - } - - /** - * Creates a unique temporary directory. - * - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * The created folder path is passed as a string to the callback's second parameter. - */ - export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; - export function mkdtemp(prefix: string, options: buffer.Encoding | MkdtempOptions | null, callback: (err: NodeJS.ErrnoException | null, dir: string) => void): void; - - /** - * The synchronous version of fs.mkdtemp(). Returns the created folder path. - */ - export function mkdtempSync(prefix: string, options?: buffer.Encoding | MkdtempOptions | null): string; - - /** - * Asynchronous file open. See open(2). `flags` can be: - * - * 'r' - Open file for reading. An exception occurs if the file does not exist. - * - * 'r+' - Open file for reading and writing. An exception occurs if the file does not exist. - * - * 'rs+' - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. - * - * This is primarily useful for opening files on NFS mounts as it allows you to skip the potentially stale local cache. It has a very real impact on I/O performance so don't use this flag unless you need it. - * - * Note that this doesn't turn `fs.open()` into a synchronous blocking call. If that's what you want then you should be using `fs.openSync()` - * - * 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists). - * - * 'wx' - Like `'w'` but fails if `path` exists. - * - * 'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). - * - * 'wx+' - Like `'w+'` but fails if `path` exists. - * - * 'a' - Open file for appending. The file is created if it does not exist. - * - * 'ax' - Like 'a' but fails if `path` exists. - * - * 'a+' - Open file for reading and appending. The file is created if it does not exist. - * - * 'ax+' - Like 'a+' but fails if `path` exists. - * - * `mode` sets the file mode (permission and sticky bits), but only if the file was created. It defaults to `0666`, readable and writable. - */ - export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - /** - * Synchronous version of `fs.open()`. - */ - export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; - - /** - * Read data from the file specified by fd. - * - * @param buffer is the buffer that the data will be written to. - * @param offset is the offset in the buffer to start writing at. - * @param length is an integer specifying the number of bytes to read. - * @param position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position. - */ - export function read(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: Buffer) => void): void; - - export interface ReaddirOptions { - encoding?: buffer.Encoding | 'buffer'; - } - - /** - * Asynchronous readdir(3). Reads the contents of a directory. - * - * @param files is an array of the names of the files in the directory excluding '.' and '..'. - */ - export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - export function readdir(path: string | Buffer, options: 'buffer' | (ReadFileOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; - export function readdir(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - - /** - * Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'. - */ - export function readdirSync(path: string | Buffer): string[]; - export function readdirSync(path: string | Buffer, options: 'buffer' | (ReaddirOptions & { encoding: 'buffer' })): Buffer[]; - export function readdirSync(path: string | Buffer, options: buffer.Encoding | ReaddirOptions | null): string[]; - - export interface ReadFileOptions { - encoding?: buffer.Encoding | 'buffer'; - flag?: string; - } - - /** - * Asynchronously reads the entire contents of a file. - */ - export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - export function readFile(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding }), callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; - export function readFile(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - /** - * Synchronous version of `fs.readFile`. - */ - export function readFileSync(file: string | Buffer | number): Buffer; - export function readFileSync(file: string | Buffer | number, options: buffer.Encoding | (ReadFileOptions & { encoding: buffer.Encoding })): string; - export function readFileSync(file: string | Buffer | number, options: 'buffer' | ReadFileOptions | null): Buffer; - - export interface ReadlinkOptions { - encoding?: buffer.Encoding | 'buffer'; - } - - /** - * Asynchronous readlink(2). - */ - export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; - export function readlink(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - export function readlink(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - - /** - * Synchronous readlink(2). - */ - export function readlinkSync(path: string | Buffer): string; - export function readlinkSync(path: string | Buffer, options: 'buffer' | (ReadlinkOptions & { encoding: 'buffer' })): Buffer; - export function readlinkSync(path: string | Buffer, options: buffer.Encoding | ReadlinkOptions | null): string; - - /** - * Synchronous version of `fs.read()`. - */ - export function readSync(fd: number, buffer: string | Buffer, offset: number, length: number, position: number): number; - - export interface RealpathOptions { - encoding?: buffer.Encoding | 'buffer'; - } - - /** - * Asynchronous realpath(3). May use `process.cwd` to resolve relative paths. - * - * Only paths that can be converted to UTF8 strings are supported. - */ - export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - export function realpath(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' }), callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - export function realpath(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - - /** - * Synchronous realpath(3). Returns the resolved path. - * - * Only paths that can be converted to UTF8 strings are supported. - */ - export function realpathSync(path: string | Buffer): string; - export function realpathSync(path: string | Buffer, options: 'buffer' | (RealpathOptions & { encoding: 'buffer' })): Buffer; - export function realpathSync(path: string | Buffer, options: buffer.Encoding | RealpathOptions | null): string; - - /** - * Asynchronous rename(2). - */ - export function rename(oldPath: string | Buffer, newPath: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous rename(2). - */ - export function renameSync(oldPath: string | Buffer, newPath: string | Buffer): void; - - /** - * Asynchronous rmdir(2). - */ - export function rmdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous rmdir(2). - */ - export function rmdirSync(path: string | Buffer): void; - - /** - * Asynchronous stat(2). - * - * In case of an error, the `err.code` will be one of Common System Errors. - * - * Using `fs.stat()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available. - * - * To check if a file exists without manipulating it afterwards, `fs.access()` is recommended. - */ - export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - /** - * Synchronous stat(2). - */ - export function statSync(path: string | Buffer): Stats; - - /** - * Asynchronous symlink(2). The type argument is only available on Windows (ignored on other platforms). Note that Windows junction points require the destination path to be absolute. When using `'junction'`, the target argument will automatically be normalized to absolute path. - */ - export function symlink(target: string | Buffer, path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function symlink(target: string | Buffer, path: string | Buffer, type: 'dir' | 'file' | 'junction', callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous symlink(2). - */ - export function symlinkSync(target: string | Buffer, path: string | Buffer, type?: 'dir' | 'file' | 'junction'): void; - - /** - * Asynchronous truncate(2). - */ - export function truncate(path: string | Buffer, len: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous truncate(2). - */ - export function truncateSync(path: string | Buffer, len?: number): void; - - /** - * Asynchronous unlink(2). - */ - export function unlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous unlink(2). - */ - export function unlinkSync(path: string | Buffer): void; - - /** - * Stop watching for changes on `filename`. If `listener` is specified, only that particular listener is removed. Otherwise, _all_ listeners are removed and you have effectively stopped watching `filename`. - * - * Calling `fs.unwatchFile()` with a filename that is not being watched is a no-op, not an error. - * - * Note: `fs.watch()` is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. - */ - export function unwatchFile(filename: string | Buffer, listener?: WatchListener): void; - - /** - * Change file timestamps of the file referenced by the supplied path. - * - * Note: the arguments `atime` and `mtime` of the following related functions follow these rules: - * - * - The value should be a Unix timestamp in seconds. For example, `Date.now()` returns milliseconds, so it should be divided by 1000 before passing it in. - * If the value is a numeric string like `'123456789'`, the value will get converted to the corresponding number. - * If the value is `NaN` or `Infinity`, the value will get converted to `Date.now() / 1000`. - */ - export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err: NodeJS.ErrnoException | null) => void): void; - - /** - * Synchronous version of `fs.utimes()`. - */ - export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; - - export interface WatchOptions { - /** - * Indicates whether the process should continue to run as long as files are being watched. default = `true`. + export function unlinkSync(path: string | Buffer): void; + /* + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. */ - persistent?: boolean; - /** - * Indicates whether all subdirectories should be watched, or only the current directory. The applies when a directory is specified, and only on supported platforms (See Caveats). default = `false`. + export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path */ - recursive?: boolean; - /** - * Specifies the character encoding to be used for the filename passed to the listener. default = `'utf8'`. + export function rmdirSync(path: string | Buffer): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. */ - encoding?: buffer.Encoding; - } - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory. The returned object is a `fs.FSWatcher`. - * - * Please note the listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but they are not the same thing. - */ - export function watch(filename: string | Buffer): FSWatcher; - export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null): FSWatcher; - export function watch(filename: string | Buffer, listener: WatchListener): FSWatcher; - export function watch(filename: string | Buffer, options: buffer.Encoding | WatchOptions | null, listener: WatchListener): FSWatcher; - - export interface WatchFileOptions { - /** - * Indicates whether the process should continue to run as long as files are being watched + export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. */ - persistent: boolean; - /** - * Indicates how often the target should be polled in milliseconds. The default is `5007`. + export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. */ - interval: number; - } + export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: number): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: string): void; + /* + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ + export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; + /* + * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @returns Returns the created folder path. + */ + export function mkdtempSync(prefix: string): string; + export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string | Buffer): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; + export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; + export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; + export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + */ + export function readFileSync(filename: string, encoding: string): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; + export function existsSync(path: string | Buffer): boolean; - /** - * Watch for changes on filename. The callback listener will be called each time the file is accessed. - * - * Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. - * - * Note: `fs.watch()` is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. - */ - export function watchFile(filename: string | Buffer, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string | Buffer, options: WatchFileOptions | null, listener: (curr: Stats, prev: Stats) => void): void; + export namespace constants { + // File Access Constants - /** - * Write `buffer` to the file specified by `fd`. - * - * `offset` and `length` determine the part of the buffer to be written. - * - * `position` refers to the offset from the beginning of the file where this data should be written. If `typeof position !== 'number'`, the data will be written at the current position. See pwrite(2). - * - * Note that it is unsafe to use `fs.write` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. - * - * On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. - */ - export function write(fd: number, buffer: string | Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: string | Buffer, offset: number, length: number, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; - export function write(fd: number, data: string | Buffer, position: number, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; - export function write(fd: number, data: string | Buffer, position: number, encoding: buffer.Encoding, callback: (err: NodeJS.ErrnoException | null, written: number, string: string) => void): void; + /** Constant for fs.access(). File is visible to the calling process. */ + export const F_OK: number; - export interface WriteFileOptions { - encoding?: buffer.Encoding; - mode?: number; - flag?: string; - } + /** Constant for fs.access(). File can be read by the calling process. */ + export const R_OK: number; - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * - * Note that it is unsafe to use `fs.writeFile` multiple times on the same file without waiting for the callback. For this scenario, `fs.createWriteStream` is strongly recommended. - * - * Note: If a file descriptor is specified as the `file`, it will not be closed automatically. - */ - export function writeFile(file: string | Buffer | number, data: string | Buffer, callback: (err: NodeJS.ErrnoException | null) => void): void; - export function writeFile(file: string | Buffer | number, data: string | Buffer, options: buffer.Encoding | WriteFileOptions | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** Constant for fs.access(). File can be written by the calling process. */ + export const W_OK: number; - /** - * The synchronous version of `fs.writeFile()`. - */ - export function writeFileSync(file: string | Buffer | number, data: string | Buffer, options?: buffer.Encoding | WriteFileOptions | null): void; + /** Constant for fs.access(). File can be executed by the calling process. */ + export const X_OK: number; - /** - * Synchronous `fs.write`. - */ - export function writeSync(fd: number, buffer: string | Buffer, offset: number, length: number, position?: number): void; - export function writeSync(fd: number, data: string | Buffer, position?: number, encoding?: buffer.Encoding): void; + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + export const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + export const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + export const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + export const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + export const O_EXCL: number; + + /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ + export const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + export const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + export const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + export const O_DIRECTORY: number; + + /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ + export const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + export const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + export const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + export const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + export const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + export const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + export const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + export const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + export const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + export const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + export const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + export const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + export const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + export const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + export const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + export const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + export const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + export const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + export const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + export const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + export const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + export const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + export const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + export const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + export const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + export const S_IXOTH: number; + } + + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string | Buffer, mode?: number): void; + export function createReadStream(path: string | Buffer, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + }): ReadStream; + export function createWriteStream(path: string | Buffer, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + export function fdatasync(fd: number, callback: Function): void; + export function fdatasyncSync(fd: number): void; } declare module "path" { - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - export interface ParsedPath { /** - * The root of the path such as '/' or 'c:\' + * A parsed path object generated by path.parse() or consumed by path.format(). */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } + export interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ - export function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths string paths to join. - */ - export function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - export function resolve(...pathSegments: string[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to - */ - export function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ - export function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ - export function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ - export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - export var sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - export var delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pathObject: ParsedPath): string; - - export module posix { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ export function join(...paths: string[]): string; - export function resolve(...pathSegments: string[]): string; - export function isAbsolute(p: string): boolean; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: any[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; - export module win32 { - export function normalize(p: string): string; - export function join(...paths: string[]): string; - export function resolve(...pathSegments: string[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } } declare module "string_decoder" { - import * as buffer from "buffer"; - - export class StringDecoder { - /** - * @param encoding The character encoding the `StringDecoder` will use. Defaults to `'utf8'`. - */ - constructor(encoding?: buffer.Encoding); - /** - * Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the `Buffer` are omitted from the returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. - * - * @param buffer A `Buffer` containing the bytes to decode. - */ - write(buffer: Buffer): string; - /** - * Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character encoding. - * - * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. - * - * @param buffer A `Buffer` containing the bytes to decode. - */ - end(buffer?: Buffer): string; - } + export interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + export var StringDecoder: { + new (encoding?: string): NodeStringDecoder; + }; } declare module "tls" { - import * as crypto from "crypto"; - import * as net from "net"; - import * as stream from "stream"; + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; - export var CLIENT_RENEG_LIMIT: number; - export var CLIENT_RENEG_WINDOW: number; - export var SLAB_BUFFER_SIZE: number; - export var DEFAULT_CIPHERS: string; - export var DEFAULT_ECDH_CURVE: string; + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; - export class Server extends net.Server { - /** - * The `server.addContext()` method adds a secure context that will be used if the client request's SNS hostname matches the supplied `hostname` (or wildcard). - * - * @param hostname A SNI hostname or wildcard (e.g. `'*'`) - * @param options An object containing any of the possible properties from the `tls.createSecureContext()` options arguments - */ - addContext(hostName: string, options: SecureContextOptions): void; - /** - * Returns a `Buffer` instance holding the keys currently used for encryption/decryption of the TLS Session Tickets. - */ - getTicketKeys(): Buffer; - /** - * Updates the keys for encryption/decryption of the TLS Session Tickets. - * - * Note: The key's Buffer should be 48 bytes long. See ticketKeys option in tls.createServer for more information on how it is used. - * - * Note: Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys. - */ - setTicketKeys(keys: Buffer): void; - /** - * Returns the current number of concurrent connections on the server. - */ - connections: number; - } + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } - export interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } + export interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } - export interface Cipher { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - } + export class TLSSocket extends stream.Duplex { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket:net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: Function, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + /** + * Returns the bound address, the address family name and port of the underlying socket as reported by + * the operating system. + * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + */ + address(): { port: number; family: string; address: string }; + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param {boolean} detailed - If true; the full chain with issuer property will be returned. + * @returns {any} - An object representing the peer's certificate. + */ + getPeerCertificate(detailed?: boolean): { + subject: Certificate; + issuerInfo: Certificate; + issuer: Certificate; + raw: any; + valid_from: string; + valid_to: string; + fingerprint: string; + serialNumber: string; + }; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns {any} - TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * The string representation of the local IP address. + */ + localAddress: string; + /** + * The numeric representation of the local port. + */ + localPort: string; + /** + * The string representation of the remote IP address. + * For example, '74.125.127.100' or '2001:4860:a005::68'. + */ + remoteAddress: string; + /** + * The string representation of the remote IP family. 'IPv4' or 'IPv6'. + */ + remoteFamily: string; + /** + * The numeric representation of the remote port. For example, 443. + */ + remotePort: number; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: TlsOptions, callback: (err: Error) => any): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns {boolean} - Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; - export interface EphemeralKeyInfo { - type: 'DH' | 'ECDH'; - name?: string; - size: number; - } + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + **/ + addListener(event: string, listener: Function): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; - export interface PeerCertificate { - subject: Certificate; - issuerInfo: Certificate; - issuer: Certificate; - raw: Buffer; - valid_from: string; - valid_to: string; - fingerprint: string; - serialNumber: string; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; - export interface TLSSocketOptions { - /** - * An optional TLS context object from `tls.createSecureContext()`. - */ - secureContext?: SecureContext; - /** - * If true the TLS socket will be instantiated in server-mode. Defaults to `false`. - */ - isServer?: boolean; - /** - * An optional net.Server instance. - */ - server?: net.Server; - /** - * Optional, see `tls.createServer()`. - */ - requestCert?: boolean; - /** - * Optional, see `tls.createServer()`. - */ - rejectUnauthorized?: boolean; - /** - * Optional, see `tls.createServer()`. - */ - NPNProtocols?: string[] | Buffer; - /** - * Optional, see `tls.createServer()`. - */ - ALPNProtocols?: string[] | Buffer; - /** - * Optional, see `tls.createServer()`. - */ - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer; - /** - * If `true`, specifies that the OCSP status request extension will be added to the client hello and an 'OCSPResponse' event will be emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean; - } + on(event: string, listener: Function): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; - export interface RenegotiateOptions { - rejectUnauthorized?: boolean; - requestCert?: boolean; - } + once(event: string, listener: Function): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; - export class TLSSocket extends net.Socket { - /** - * Construct a new `tls.TLSSocket` object from an existing TCP socket. - */ - constructor(socket: net.Socket, options?: TLSSocketOptions); - /** - * Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`. - */ - authorized: boolean; - /** - * Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`. - */ - authorizationError?: Error; - /** - * Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances. - */ - encrypted: true; - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version that first defined the cipher. - */ - getCipher(): Cipher; - /** - * Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in Perfect Forward Secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; `null` is returned if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. - */ - getEphemeralKeyInfo(): EphemeralKeyInfo; - /** - * Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate. - * - * @param detailed Specify `true` to request that the full certificate chain with the `issuer` property be returned; false to return only the top certificate without the `issuer` property. - */ - getPeerCertificate(detailed?: boolean): PeerCertificate; - /** - * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. The value `null` will be returned for server sockets or disconnected client sockets. - */ - getProtocol(): string | null; - /** - * Returns the ASN.1 encoded TLS session or `undefined` if no session was negotiated. Can be used to speed up handshake establishment when reconnecting to the server. - */ - getSession(): Buffer | undefined; - /** - * Returns the TLS session ticket or `undefined` if no session was negotiated. - * - * Note: This only works with client TLS sockets. Useful only for debugging, for session reuse `provide` session option to `tls.connect()`. - */ - getTLSTicket(): Buffer | undefined; - /** - * Returns the string representation of the local IP address. - */ - localAddress: string; - /** - * Returns the numeric representation of the local port. - */ - localPort: number; - /** - * Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. - */ - remoteAddress: string; - /** - * Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. - */ - remoteFamily: string; - /** - * The numeric representation of the remote port. For example, 443. - */ - remotePort: number; - /** - * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. - * - * Note: This method can be used to request a peer's certificate after the secure connection has been established. - * - * Note: When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. - */ - renegotiate(options: RenegotiateOptions, callback: (err: Error | null) => any): any; - /** - * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. Returns `true` if setting the limit succeeded; false otherwise. - * - * Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. - * - * @param size The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`. - */ - setMaxSendFragment(size: number): boolean; - } + prependListener(event: string, listener: Function): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; - export interface ConnectOptions { - /** - * Host the client should connect to. - */ - host?: string; - /** - * Port the client should connect to. - */ - port?: number | string; - /** - * Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `host` and `port` are ignored. - */ - socket?: net.Socket; - /** - * Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. - */ - path?: string; - /** - * A `string` or `Buffer` containing the private key, certificate, and CA certs of the client in PFX or PKCS12 format. - */ - pfx?: string | Buffer; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s containing the private key of the client in PEM format. - */ - key?: string | Buffer | string[] | Buffer[]; - /** - * A string containing the passphrase for the private key or pfx. - */ - passphrase?: string; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s containing the certificate key of the client in PEM format. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If this is omitted several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * A string describing the ciphers to use or exclude, separated by `:`. Uses the same default cipher suite as `tls.createServer()`. - */ - ciphers?: string; - /** - * If true, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`. - */ - rejectUnauthorized?: boolean; - /** - * An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. - */ - NPNProtocols?: string[] | Buffer[]; - /** - * An array of strings or `Buffer`s containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler: `['hello', 'world']`.) - */ - ALPNProtocols?: string[] | Buffer[]; - /** - * Server name for the SNI (Server Name Indication) TLS extension. - */ - servername?: string; - /** - * A callback function to be used when checking the server's hostname against the certificate. This should throw an error if verification fails. The method should return `undefined` if the `servername` and `cert` are verified. - */ - checkServerIdentity?: (servername: string, cert: Buffer) => void; - /** - * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. - */ - secureProtocol?: string; - /** - * An optional TLS context object as returned by from `tls.createSecureContext( ... )`. It can be used for caching client certificates, keys, and CA certificates. - */ - secureContext?: SecureContext; - /** - * A `Buffer` instance, containing TLS session. - */ - session?: Buffer; - /** - * Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`. - */ - minDHSize?: number; - } + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } - export interface SecureContextOptions { - /** - * A string or `Buffer` holding the PFX or PKCS12 encoded private key, certificate, and CA certificates. - */ - pfx?: string | Buffer; - /** - * The private key of the server in PEM format. To support multiple keys using different algorithms, an array can be provided either as an array of key strings or as an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. - */ - key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; - /** - * A string containing the passphrase for the private key or pfx. - */ - passphrase?: string; - /** - * A string containing the PEM encoded certificate. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). - */ - crl?: string | string[]; - /** - * A string describing the ciphers to use or exclude. Consult https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT for details on the format. - */ - ciphers?: string; - /** - * If `true`, when a cipher is being selected, the server's preferences will be used instead of the client preferences. - */ - honorCipherOrder?: boolean; - } + export interface TlsOptions { + host?: string; + port?: number; + pfx?: string | Buffer[]; + key?: string | string[] | Buffer | any[]; + passphrase?: string; + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | string[] | Buffer | Buffer[]; + crl?: string | string[]; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer; + SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; + ecdhCurve?: string; + dhparam?: string | Buffer; + handshakeTimeout?: number; + ALPNProtocols?: string[] | Buffer; + sessionTimeout?: number; + ticketKeys?: any; + sessionIdContext?: string; + secureProtocol?: string; + } - export interface CreateServerOptions { - /** - * A `string` or `Buffer` containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with the `key`, `cert`, and `ca` options.) - */ - pfx?: string | Buffer; - /** - * The private key of the server in PEM format. To support multiple keys using different algorithms an array can be provided either as a plain array of key strings or an array of objects in the format `{pem: key, passphrase: passphrase}`. This option is required for ciphers that make use of private keys. - */ - key?: string | string[] | Buffer | Array<{ pem: string | string[] | Buffer, passphrase: string }>; - /** - * A string containing the passphrase for the private key or pfx. - */ - passphrase?: string; - /** - * A string containing the PEM encoded certificate. - */ - cert?: string | Buffer | string[] | Buffer[]; - /** - * A string, `Buffer`, array of strings, or array of `Buffer`s of trusted certificates in PEM format. If omitted, several well known "root" CAs (like VeriSign) will be used. These are used to authorize connections. - */ - ca?: string | Buffer | string[] | Buffer[]; - /** - * Either a string or array of strings of PEM encoded CRLs (Certificate Revocation List). - */ - crl?: string | string[]; - /** - * A string describing the ciphers to use or exclude, separated by `:`. - */ - ciphers?: string; - /** - * A string describing a named curve to use for ECDH key agreement or false to disable ECDH. Defaults to `prime256v1` (NIST P-256). Use crypto.getCurves() to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. - */ - ecdhCurve?: string; - /** - * A string or `Buffer` containing Diffie Hellman parameters, required for Perfect Forward Secrecy. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. - */ - dhparam?: string | Buffer; - /** - * Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out. - */ - handshakeTimeout?: number; - /** - * When choosing a cipher, use the server's preferences instead of the client preferences. Defaults to `true`. - */ - honorCipherOrder?: boolean; - /** - * If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`. - */ - requestCert?: boolean; - /** - * If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `false`. - */ - rejectUnauthorized?: boolean; - /** - * An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.) - */ - NPNProtocols?: string[] | Buffer; - /** - * An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client. - */ - ALPNProtocols?: string[] | Buffer; - /** - * A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below). - */ - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - /** - * An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See SSL_CTX_set_timeout for more details. - */ - sessionTimeout?: number; - /** - * A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. Note that this is automatically shared between `cluster` module workers. - */ - ticketKeys?: Buffer; - /** - * A string containing an opaque identifier for session resumption. If `requestCert` is true, the default is a 128 bit truncated SHA1 hash value generated from the command-line. Otherwise, a default is not provided. - */ - sessionIdContext?: string; - /** - * The SSL method to use, e.g., `SSLv3_method` to force SSL version 3. The possible values depend on the version of OpenSSL installed in the environment and are defined in the constant SSL_METHODS. - */ - secureProtocol?: string; - } + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: string | Buffer + key?: string | string[] | Buffer | Buffer[]; + passphrase?: string; + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | Buffer | (string | Buffer)[]; + rejectUnauthorized?: boolean; + NPNProtocols?: (string | Buffer)[]; + servername?: string; + path?: string; + ALPNProtocols?: (string | Buffer)[]; + checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; + secureProtocol?: string; + secureContext?: Object; + session?: Buffer; + minDHSize?: number; + } - export interface SecureContext { - context: any; - } + export interface Server extends net.Server { + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; - /** - * Creates a new tls.Server. The secureConnectionListener, if provided, is automatically set as a listener for the `'secureConnection'` event. - */ - export function createServer(options: CreateServerOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + addListener(event: string, listener: Function): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - /** - * Creates a new client connection to the given `port` and `host` or `options.port` and `options.host`. (If `host` is omitted, it defaults to `localhost`.) - */ - export function connect(options: ConnectOptions, callback?: () => void): TLSSocket; - export function connect(port: number, options?: ConnectOptions, callback?: () => void): TLSSocket; - export function connect(port: number, host?: string, options?: ConnectOptions, callback?: () => void): TLSSocket; + emit(event: string, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - /** - * The `tls.createSecureContext()` method creates a credentials object. - * - * If the `'ca'` option is not given, then Node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt. - */ - export function createSecureContext(options: SecureContextOptions): SecureContext; + on(event: string, listener: Function): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - /** - * Returns an array with the names of the supported SSL ciphers. - */ - export function getCiphers(): string[]; + once(event: string, listener: Function): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer; + crl?: string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; } declare module "crypto" { - import * as stream from "stream"; + export interface Certificate { + exportChallenge(spkac: string | Buffer): Buffer; + exportPublicKey(spkac: string | Buffer): Buffer; + verifySpkac(spkac: Buffer): boolean; + } + export var Certificate: { + new (): Certificate; + (): Certificate; + } - export var constants: { - defaultCipherList: string; - defaultCoreCipherList: string; - [key: string]: string | number; - } + export var fips: boolean; - export function getCiphers(): string[]; - export function getCurves(): string[]; - export function getHashes(): string[]; + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string | Buffer): Hmac; - export class Certificate { - constructor(); - exportChallenge(spkac: string | Buffer, encoding?: string): string; - exportPublicKey(spkac: string | Buffer, encoding?: string): Buffer; - verifySpkac(spkac: Buffer): boolean; - } + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; - export function createHash(algorithm: string): Hash; - - export class Hash extends stream.Transform { - update(data: string | Buffer, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): string; - digest(): Buffer; - } - - export function createHmac(algorithm: string, key: string | Buffer): Hmac; - - export class Hmac extends stream.Transform { - update(data: string | Buffer, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): string; - digest(): Buffer; - } - - export function createCipher(algorithm: string, password: string | Buffer): Cipher; - export function createCipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Cipher; - - export class Cipher extends stream.Transform { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary" | "latin1" | "base64" | "hex"): string; - update(data: string, input_encoding: "utf8" | "ascii" | "binary" | "latin1", output_encoding: "binary" | "latin1" | "base64" | "hex"): string; - final(): Buffer; - final(output_encoding: string): string; - setAAD(buffer: Buffer): void; - setAutoPadding(auto_padding: boolean): void; - getAuthTag(): Buffer; - } - - export function createDecipher(algorithm: string, password: string | Buffer): Decipher; - export function createDecipheriv(algorithm: string, key: string | Buffer, iv: string | Buffer): Decipher; - - export class Decipher extends stream.Transform { - update(data: Buffer): Buffer; - update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; - update(data: string, input_encoding: "binary" | "latin1" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary" | "latin1"): string; - final(): Buffer; - final(output_encoding: string): string; - setAAD(buffer: Buffer): void; - setAutoPadding(auto_padding: boolean): void; - setAuthTag(tag: Buffer): void; - } - - export function createSign(algorithm: string): Signer; - - export class Signer extends stream.Writable { - update(data: string | Buffer): void; - sign(private_key: string): Buffer; - sign(private_key: string, output_format: string): string; - } - - export function createVerify(algorith: string): Verify; - - export class Verify extends stream.Writable { - update(data: string | Buffer): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - - export function createDiffieHellman(prime: number, prime_encoding?: string, generator?: number | string | Buffer, generator_encoding?: string): DiffieHellman; - export function createDiffieHellman(prime_length: number, generator?: number | string | Buffer): DiffieHellman; - export function getDiffieHellman(group_name: string): DiffieHellman; - - export class DiffieHellman { - verifyError: number; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - generateKeys(encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding?: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; - } - - export function createECDH(curve_name: string): ECDH; - - export class ECDH { - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - generateKeys(encoding?: string, format?: string): string; - getPrivateKey(encoding?: string): string; - getPublicKey(encoding?: string, format?: string): string; - setPrivateKey(private_key: string, encoding?: string): void; - } - - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => void): void; - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => void): void; - - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; - - export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - - export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - - export interface RsaKey { - key: string; - passphrase?: string, - padding?: number; - } - - export function timingSafeEqual(a: Buffer, b: Buffer): boolean; - export function publicEncrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; - export function privateEncrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; - export function publicDecrypt(public_key: string | RsaKey, buffer: Buffer): Buffer; - export function privateDecrypt(private_key: string | RsaKey, buffer: Buffer): Buffer; - - export function setEngine(engine: string, flags?: number): void; + export interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hash; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hmac; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + export interface Cipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): void; + getAuthTag(): Buffer; + setAAD(buffer: Buffer): void; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + export interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): void; + setAuthTag(tag: Buffer): void; + setAAD(buffer: Buffer): void; + } + export function createSign(algorithm: string): Signer; + export interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer): Signer; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase: string }): Buffer; + sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + } + export function createVerify(algorith: string): Verify; + export interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer): Verify; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string, signature: Buffer): boolean; + verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + } + export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; + export function createDiffieHellman(prime: Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + export interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export interface RsaPublicKey { + key: string; + padding?: number; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: number; + } + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; + export interface ECDH { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + export function createECDH(curve_name: string): ECDH; + export function timingSafeEqual(a: Buffer, b: Buffer): boolean; + export var DEFAULT_ENCODING: string; } declare module "stream" { - import * as events from "events"; + import * as events from "events"; - export class Stream extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } + class internal extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + namespace internal { - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (this: Readable, size?: number) => any; - } + export class Stream extends internal { } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - isPaused(): boolean; - setEncoding(encoding: string): this; - pause(): this; - resume(): this; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (size?: number) => any; + } - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; - } + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + protected _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): this; + unpipe(destination?: T): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - setDefaultEncoding(encoding: string): this; - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + **/ + addListener(event: string, listener: Function): this; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements Writable { - writable: boolean; - constructor(opts?: DuplexOptions); - setDefaultEncoding(encoding: string): this; - _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; - export interface TransformOptions extends ReadableOptions, WritableOptions { - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; - } + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; - export class Transform extends Duplex { - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: string, callback: Function): void; - } + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; - export class PassThrough extends Transform { } + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + // Readable + pause(): this; + resume(): this; + // Writeable + writable: boolean; + constructor(opts?: DuplexOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends DuplexOptions { + transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + flush?: (callback: Function) => any; + } + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + protected _transform(chunk: any, encoding: string, callback: Function): void; + protected _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + pipe(destination: T, options?: { end?: boolean; }): this; + unpipe(destination?: T): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform { } + } + + export = internal; } declare module "util" { - /** - * The `util.debuglog()` method is used to create a function that conditionally writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` environment variable. If the `section` name appears within the value of that environment variable, then the returned function operates similar to console.error(). If not, then the returned function is a no-op. - */ - export function debuglog(section: string): (msg: any, ...args: any[]) => void; - - export interface InspectOptions { - /** - * If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`. - */ - showHidden?: boolean; - /** - * Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`. - */ - depth?: number | null; - /** - * If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see "Customizing util.inspect colors". - */ - colors?: boolean; - /** - * If `false`, then custom `inspect(depth, opts)` functions exported on the object being inspected will not be called. Defaults to `true`. - */ - customInspect?: boolean; - /** - * If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`. - */ - showProxy?: boolean; - /** - * Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements. - */ - maxArrayLength?: number | null; - /** - * The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to `60` for legacy compatibility. - */ - breakLength?: number; - } - - /** - * The `util.inspect()` method returns a string representation of object that is primarily useful for debugging. - */ - export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - export function inspect(object: any, options: InspectOptions): string; - - export namespace inspect { - export var colors: { - bold: [number, number]; - italic: [number, number]; - underline: [number, number]; - inverse: [number, number]; - white: [number, number]; - grey: [number, number]; - black: [number, number]; - blue: [number, number]; - cyan: [number, number]; - green: [number, number]; - magenta: [number, number]; - red: [number, number]; - yellow: [number, number]; + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; } - export var styles: { - special: string; - number: string; - boolean: string; - undefined: string; - null: string; - string: string; - symbol: string; - date: string; - regexp: string; - }; - - export var custom: symbol; - } - - /** - * The `util.deprecate()` method wraps the given function or class in such a way that it is marked as deprecated. - */ - export function deprecate(fn: T, string: string): T; - - /** - * The `util.format()` method returns a formatted string using the first argument as a printf-like format. - */ - export function format(format: any, ...param: any[]): string; - - /** - * Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor. - */ - export function inherits(constructor: any, superConstructor: any): void; - - /** - * Deprecated predecessor of `console.error`. - * - * @deprecated - */ - export function debug(string: string): void; - - /** - * Deprecated predecessor of `console.error`. - * - * @deprecated - */ - export function error(...strings: string[]): void; - - /** - * Internal alias for `Array.isArray`. - * - * @deprecated - */ - export function isArray(object: any): object is any[]; - - /** - * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isBoolean(object: any): object is boolean; - - /** - * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isBuffer(object: any): object is Buffer; - - /** - * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isDate(object: any): object is Date; - - /** - * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isError(object: any): object is Error; - - /** - * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isFunction(object: any): object is Function; - - /** - * Returns `true` if the given `object` is strictly `null`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isNull(object: any): object is null; - - /** - * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isNullOrUndefined(object: any): object is null | undefined; - - /** - * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isNumber(object: any): object is number; - - /** - * Returns true if the given `object` is strictly an `Object` and not a `Function`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isObject(object: any): object is Object; - - /** - * Returns true if the given `object` is a primitive type. Otherwise, returns `false`. - * - * @deprecated - */ - export function isPrimitive(object: any): object is string | number | boolean | null | undefined; - - /** - * Returns true if the given `object` is a `RegExp`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isRegExp(object: any): object is RegExp; - - /** - * Returns true if the given `object` is a `String`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isString(object: any): object is string; - - /** - * Returns true if the given `object` is a `Symbol`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isSymbol(object: any): object is symbol; - - /** - * Returns true if the given `object` is `undefined`. Otherwise, returns `false`. - * - * @deprecated - */ - export function isUndefined(object: any): object is symbol; - - /** - * The `util.log()` method prints the given `string` to `stdout` with an included timestamp. - * - * @deprecated - */ - export function log(string: string): void; - - /** - * Deprecated predecessor of `console.log`. - * - * @deprecated - */ - export function print(strings: string[]): void; - - /** - * Deprecated predecessor of `console.log`. - * - * @deprecated - */ - export function puts(strings: string[]): void; - - /** - * The `util._extend()` method was never intended to be used outside of internal Node.js modules. The community found and used it anyway. - * - * It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through `Object.assign()`. - * - * @deprecated - */ - export function _extend(target: T, source: U): T & U; + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; + export function isBoolean(object: any): boolean; + export function isBuffer(object: any): boolean; + export function isFunction(object: any): boolean; + export function isNull(object: any): boolean; + export function isNullOrUndefined(object: any): boolean; + export function isNumber(object: any): boolean; + export function isObject(object: any): boolean; + export function isPrimitive(object: any): boolean; + export function isString(object: any): boolean; + export function isSymbol(object: any): boolean; + export function isUndefined(object: any): boolean; + export function deprecate(fn: Function, message: string): Function; } declare module "assert" { - function internal(value: any, message?: string): void; - namespace internal { - export class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; + function internal(value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; - constructor(options?: { - message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function - }); + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); + } + + export function fail(actual: any, expected: any, message: string, operator: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; } - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - - export function ifError(value: any): void; - } - - export = internal; + export = internal; } declare module "tty" { - import * as net from "net"; + import * as net from "net"; - export function isatty(fd: number): boolean; - export interface ReadStream extends net.Socket { - isRaw: boolean; - setRawMode(mode: boolean): void; - isTTY: boolean; - } - export interface WriteStream extends net.Socket { - columns: number; - rows: number; - isTTY: boolean; - } + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } } declare module "domain" { - import * as events from "events"; + import * as events from "events"; - export class Domain extends events.EventEmitter implements NodeJS.Domain { - run(fn: Function): void; - add(emitter: events.EventEmitter): void; - remove(emitter: events.EventEmitter): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - members: any[]; - enter(): void; - exit(): void; - } + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + members: any[]; + enter(): void; + exit(): void; + } - export function create(): Domain; + export function create(): Domain; } declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFBLK: number; - export var S_IFIFO: number; - export var S_IFSOCK: number; - export var S_IRWXU: number; - export var S_IRUSR: number; - export var S_IWUSR: number; - export var S_IXUSR: number; - export var S_IRWXG: number; - export var S_IRGRP: number; - export var S_IWGRP: number; - export var S_IXGRP: number; - export var S_IRWXO: number; - export var S_IROTH: number; - export var S_IWOTH: number; - export var S_IXOTH: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_NOCTTY: number; - export var O_DIRECTORY: number; - export var O_NOATIME: number; - export var O_NOFOLLOW: number; - export var O_SYNC: number; - export var O_SYMLINK: number; - export var O_DIRECT: number; - export var O_NONBLOCK: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; -} - -declare module "module" { - export = NodeModule; + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; + export var SIGQUIT: number; + export var SIGTRAP: number; + export var SIGIOT: number; + export var SIGBUS: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGPIPE: number; + export var SIGALRM: number; + export var SIGCHLD: number; + export var SIGSTKFLT: number; + export var SIGCONT: number; + export var SIGSTOP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGURG: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var SIGVTALRM: number; + export var SIGPROF: number; + export var SIGIO: number; + export var SIGPOLL: number; + export var SIGPWR: number; + export var SIGSYS: number; + export var SIGUNUSED: number; + export var defaultCoreCipherList: string; + export var defaultCipherList: string; + export var ENGINE_METHOD_RSA: number; + export var ALPN_ENABLED: number; } declare module "process" { - export = process; + export = process; +} + +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + const enum DoesZapCodeSpaceFlag { + Disabled = 0, + Enabled = 1 + } + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + export function getHeapStatistics(): HeapInfo; + export function getHeapSpaceStatistics(): HeapSpaceInfo[]; + export function setFlagsFromString(flags: string): void; } declare module "timers" { - export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; - export function clearTimeout(timeoutId: NodeJS.Timer): void; - export function clearInterval(intervalId: NodeJS.Timer): void; - export function clearImmediate(immediateId: NodeJS.Immediate): void; + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + export function clearImmediate(immediateId: any): void; +} + +declare module "console" { + export = console; +} + +/** + * _debugger module is not documented. + * Source code is at https://github.com/nodejs/node/blob/master/lib/_debugger.js + */ +declare module "_debugger" { + export interface Packet { + raw: string; + headers: string[]; + body: Message; + } + + export interface Message { + seq: number; + type: string; + } + + export interface RequestInfo { + command: string; + arguments: any; + } + + export interface Request extends Message, RequestInfo { + } + + export interface Event extends Message { + event: string; + body?: any; + } + + export interface Response extends Message { + request_seq: number; + success: boolean; + /** Contains error message if success === false. */ + message?: string; + /** Contains message body if success === true. */ + body?: any; + } + + export interface BreakpointMessageBody { + type: string; + target: number; + line: number; + } + + export class Protocol { + res: Packet; + state: string; + execute(data: string): void; + serialize(rq: Request): string; + onResponse: (pkt: Packet) => void; + } + + export var NO_FRAME: number; + export var port: number; + + export interface ScriptDesc { + name: string; + id: number; + isNative?: boolean; + handle?: number; + type: string; + lineOffset?: number; + columnOffset?: number; + lineCount?: number; + } + + export interface Breakpoint { + id: number; + scriptId: number; + script: ScriptDesc; + line: number; + condition?: string; + scriptReq?: string; + } + + export interface RequestHandler { + (err: boolean, body: Message, res: Packet): void; + request_seq?: number; + } + + export interface ResponseBodyHandler { + (err: boolean, body?: any): void; + request_seq?: number; + } + + export interface ExceptionInfo { + text: string; + } + + export interface BreakResponse { + script?: ScriptDesc; + exception?: ExceptionInfo; + sourceLine: number; + sourceLineText: string; + sourceColumn: number; + } + + export function SourceInfo(body: BreakResponse): string; + + export interface ClientInstance extends NodeJS.EventEmitter { + protocol: Protocol; + scripts: ScriptDesc[]; + handles: ScriptDesc[]; + breakpoints: Breakpoint[]; + currentSourceLine: number; + currentSourceColumn: number; + currentSourceLineText: string; + currentFrame: number; + currentScript: string; + + connect(port: number, host: string): void; + req(req: any, cb: RequestHandler): void; + reqFrameEval(code: string, frame: number, cb: RequestHandler): void; + mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; + setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; + clearBreakpoint(rq: Request, cb: RequestHandler): void; + listbreakpoints(cb: RequestHandler): void; + reqSource(from: number, to: number, cb: RequestHandler): void; + reqScripts(cb: any): void; + reqContinue(cb: RequestHandler): void; + } + + export var Client : { + new (): ClientInstance + } } From 03e2e599c5c0781b383744d9b954f4a6b226ec35 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sun, 8 Jan 2017 02:00:20 +0300 Subject: [PATCH 009/306] node/node-test.ts Console testing update, mongodb reconciliation with node api --- mongodb/index.d.ts | 12 ++++++------ node/node-tests.ts | 5 +++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index 26d1656baf..f96c699a6f 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1173,7 +1173,7 @@ export interface Cursor extends Readable { next(): Promise; next(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe - pipe(destination: Writable, options?: Object): void; + pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read @@ -1202,7 +1202,7 @@ export interface Cursor extends Readable { toArray(): Promise; toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe - unpipe(destination?: Writable): void; + unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift unshift(stream: Buffer | string): void; } @@ -1261,7 +1261,7 @@ export interface AggregationCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out out(destination: string): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe - pipe(destination: Writable, options?: Object): void; + pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project project(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read @@ -1280,7 +1280,7 @@ export interface AggregationCursor extends Readable { toArray(): Promise; toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe - unpipe(destination?: Writable): void; + unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift unshift(stream: Buffer | string): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind @@ -1306,7 +1306,7 @@ export interface CommandCursor extends Readable { next(): Promise; next(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe - pipe(destination: Writable, options?: Object): void; + pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind @@ -1319,7 +1319,7 @@ export interface CommandCursor extends Readable { toArray(): Promise; toArray(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe - unpipe(destination?: Writable): void; + unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift unshift(stream: Buffer | string): void; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 706e8b37f6..e34a67a41e 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1630,6 +1630,11 @@ namespace console_tests { var _c: Console = console; _c = c; } + { + var writeStream = fs.createWriteStream('./index.d.ts'); + var consoleInstance = new console.Console(writeStream) + + } } /////////////////////////////////////////////////// From 1e18f44d5c2f6d46c8ae5b9b6461d49fbdb254e9 Mon Sep 17 00:00:00 2001 From: Hinell Date: Sun, 8 Jan 2017 03:09:50 +0300 Subject: [PATCH 010/306] mongodb/ methods duplication removal --- mongodb/index.d.ts | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index f96c699a6f..58b3d7aa0c 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -1172,8 +1172,6 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe - pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read @@ -1184,8 +1182,6 @@ export interface Cursor extends Readable { rewind(): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setCursorOption setCursorOption(field: string, value: Object): Cursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setEncoding - setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#showRecordId @@ -1201,8 +1197,6 @@ export interface Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unpipe - unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift unshift(stream: Buffer | string): void; } @@ -1260,8 +1254,6 @@ export interface AggregationCursor extends Readable { next(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out out(destination: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe - pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project project(document: Object): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#read @@ -1271,16 +1263,12 @@ export interface AggregationCursor extends Readable { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind rewind(): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding - setEncoding(encoding: string): this; - // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#skip skip(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#sort sort(document: Object): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unpipe - unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unshift unshift(stream: Buffer | string): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind @@ -1305,21 +1293,15 @@ export interface CommandCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe - pipe(destination: Writable, options?: Object): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind rewind(): CommandCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding - setEncoding(encoding: string): this; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setReadPreference setReadPreference(readPreference: string | ReadPreference): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#toArray toArray(): Promise; toArray(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unpipe - unpipe(destination?: Writable): this; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift unshift(stream: Buffer | string): void; } From b4fc6f27dc2bcf91c31d536539fe4f48becd18d1 Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Mon, 9 Jan 2017 05:24:31 +0100 Subject: [PATCH 011/306] Jest update --- jest/index.d.ts | 68 +++++++++++++++++++++++++++++++++++---- jest/jest-tests.ts | 79 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 140 insertions(+), 7 deletions(-) diff --git a/jest/index.d.ts b/jest/index.d.ts index fda6c66404..6e3d5381a8 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Jest 16.0.0 +// Type definitions for Jest 18.0.0 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev , jwbay +// Definitions by: Asana , Ivo Stratev , jwbay , Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare var beforeAll: jest.Lifecycle; declare var beforeEach: jest.Lifecycle; @@ -16,7 +17,7 @@ declare var xit: jest.It; declare var test: jest.It; declare var xtest: jest.It; -declare function expect(actual: any): jest.Matchers; +declare const expect: jest.Expect; interface NodeRequire { /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ @@ -31,8 +32,10 @@ declare namespace jest { 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. */ + /** @deprecated */ function clearAllMocks(): typeof jest; + /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */ + function resetAllMocks(): 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; /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ @@ -111,6 +114,41 @@ declare namespace jest { skip: Describe; } + interface MatcherUtils { + readonly isNot: boolean; + utils: { + readonly EXPECTED_COLOR: string; + readonly RECEIVED_COLOR: string; + ensureActualIsNumber(actual: any, matcherName?: string): void; + ensureExpectedIsNumber(actual: any, matcherName?: string): void; + ensureNoExpected(actual: any, matcherName?: string): void; + ensureNumbers(actual: any, expected: any, matcherName?: string): void; + /** get the type of a value with handling the edge cases like `typeof []` and `typeof null` */ + getType(value: any): string; + matcherHint(matcherName: string, received?: string, expected?: string, options?: { secondArgument?: string, isDirectExpectCall?: boolean }): string; + pluralize(word: string, count: number): string; + printExpected(value: any): string; + printReceived(value: any): string; + printWithType(name: string, received: any, print: (value: any) => string): string; + stringify(object: {}, maxDepth?: number): string; + } + } + + interface ExpectExtendMap { + [key: string]: (this: MatcherUtils, received: any, actual: any) => { message: () => string, pass: boolean }; + } + + interface Expect { + (actual: any): Matchers; + anything(): void; + any(cs: any): void; + arrayContaining(arr: any[]): void; + assertions(num: number): void; + extend(obj: ExpectExtendMap): void; + objectContaining(obj: {}): void; + stringMatching(str: string | RegExp): void; + } + interface Matchers { not: Matchers; lastCalledWith(...args: any[]): void; @@ -135,9 +173,11 @@ declare namespace jest { toHaveBeenCalledTimes(expected: number): boolean; toHaveBeenCalledWith(...params: any[]): boolean; toHaveBeenLastCalledWith(...params: any[]): boolean; + toHaveLength(expected: number): void; + toHaveProperty(propertyPath: string, value?: any): void; toMatch(expected: string | RegExp): void; toMatchObject(expected: {}): void; - toMatchSnapshot(): void; + toMatchSnapshot(snapshotName?: string): void; toThrow(): void; toThrowError(error?: string | Constructable | RegExp): void; toThrowErrorMatchingSnapshot(): void; @@ -147,9 +187,25 @@ declare namespace jest { new (...args: any[]): any } - interface Mock extends Function { + interface Mock extends Function, MockInstance { new (): T; (...args: any[]): any; + } + + /** + * Wrap module with mock definitions + * @example + * jest.mock("../api"); + * import { Api } from "../api"; + * + * const myApi: jest.Mocked = new Api() as any; + * myApi.myApiMethod.mockImplementation(() => "test"); + */ + type Mocked = T & { + [P in keyof T]: T[P] & MockInstance; + } & MockInstance; + + interface MockInstance { mock: MockContext; mockClear(): void; mockImplementation(fn: Function): Mock; diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index 913a671fa1..e1f8fb120f 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -171,6 +171,60 @@ describe('toThrow API', function () { }); }); +describe('Assymetric matchers', function () { + it('works', function () { + expect({ + timestamp: 1480807810388, + text: 'Some text content, but we care only about *this part*' + }).toEqual({ + timestamp: expect.any(Number), + text: expect.stringMatching('*this part*') + }); + + const callback = jest.fn(); + expect(callback).toEqual(expect.any(Function)); + callback(5, "test"); + expect(callback).toBeCalledWith(expect.any(Number), expect.any(String)) + const obj = { + items: [1] + }; + expect(obj).toEqual(expect.objectContaining({ + items: expect.arrayContaining([ + expect.any(Number) + ]) + })); + + expect.assertions(4); + }); +}); + +describe('Extending extend', function () { + it('works', function () { + expect.extend({ + toBeNumber(received: any, actual: any) { + const pass = received === actual; + const message = + () => `expected ${received} ${pass ? 'not ' : ''} to be ${actual}`; + return { message, pass }; + }, + toBeTest(received: any, actual: any) { + this.utils.ensureNoExpected(received); + this.utils.ensureActualIsNumber(received); + this.utils.ensureExpectedIsNumber(actual); + this.utils.ensureNumbers(received, actual); + + return { + message: () => ` + ${this.utils.getType(received).toLowerCase()} \n\n + ${this.utils.matcherHint(".not.toBe")} ${this.utils.printExpected(actual)} ${this.utils.printReceived(received)}\n\n + `, + pass: true + }; + } + }); + }); +}); + describe('missing tests', function () { it('creates closures', function () { class Closure { @@ -208,7 +262,7 @@ describe('missing tests', function () { expect(getFruits()).toContain('Orange'); mock.mockReturnValueOnce(['Apple', 'Plum']); expect(mock()).not.toContain('Orange'); - const myBeverage: any = {delicious: true, sour: false}; + const myBeverage: any = {delicious: true, sour: false}; expect(myBeverage).toContainEqual({delicious: true, sour: false}); mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. mock.mockClear(); @@ -248,6 +302,10 @@ describe('toMatchSnapshot', function () { it('compares snapshots', function () { expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); }); + + it('can give name to snapshot', function () { + expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot('given name'); + }); }); describe('toThrowErrorMatchingSnapshot', function () { @@ -367,3 +425,22 @@ describe('strictNullChecks', function () { done(); }) }); + +interface TestApi { + testProp: boolean; + testMethod(a: number): void; +} + +describe("Mocked type", function () { + it("Works", function () { + const mock: jest.Mocked = jest.fn(() => ({ + testProp: true, + testMethod1: jest.fn(), + testMethod2: jest.fn() + })) as any; + mock.testProp; + mock.testMethod.mockImplementation(() => "test"); + mock.testMethod(5); + mock.mockClear(); + }); +}); From f2581e2b98d07073207ab3e5685dc44c5435ca32 Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Mon, 9 Jan 2017 06:59:08 +0100 Subject: [PATCH 012/306] Added one more example for jest.Mocked --- jest/index.d.ts | 5 +++++ jest/jest-tests.ts | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/jest/index.d.ts b/jest/index.d.ts index 6e3d5381a8..2f246f2bfe 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -200,6 +200,11 @@ declare namespace jest { * * const myApi: jest.Mocked = new Api() as any; * myApi.myApiMethod.mockImplementation(() => "test"); + * + * jest.mock("./func"); + * const myFuncMock: jest.Mocked = require("./func"); + * myFuncMock.mockImplementation(() => 5); + * myFuncMock(); */ type Mocked = T & { [P in keyof T]: T[P] & MockInstance; diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index e1f8fb120f..f2866d1689 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -431,6 +431,8 @@ interface TestApi { testMethod(a: number): void; } +declare function mockedFunc(a: number): string; + describe("Mocked type", function () { it("Works", function () { const mock: jest.Mocked = jest.fn(() => ({ @@ -442,5 +444,9 @@ describe("Mocked type", function () { mock.testMethod.mockImplementation(() => "test"); mock.testMethod(5); mock.mockClear(); + + const funcMock: jest.Mocked = require("./mockedFunc"); + funcMock.mockImplementation(() => "test"); + funcMock(5).toUpperCase(); }); }); From a0a9fe2efe4aa8a9c6ad765d6ccc471341964332 Mon Sep 17 00:00:00 2001 From: Rafael Salguero Iturrios Date: Sun, 8 Jan 2017 23:08:31 -0700 Subject: [PATCH 013/306] Update index.d.ts --- rx-lite/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rx-lite/index.d.ts b/rx-lite/index.d.ts index fb5056c478..7e085031aa 100644 --- a/rx-lite/index.d.ts +++ b/rx-lite/index.d.ts @@ -232,7 +232,7 @@ declare namespace Rx { withLatestFrom(souces: (Observable | IPromise)[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; concat(...sources: (Observable | IPromise)[]): Observable; concat(sources: (Observable | IPromise)[]): Observable; - concatAll(): Observable; + concatAll(): T; concatObservable(): Observable; // alias for concatAll concatMap(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat concatMap(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; // alias for selectConcat From 3e757ce66287de54c45ecb30945c869ce7ad9809 Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Mon, 9 Jan 2017 20:26:28 +0100 Subject: [PATCH 014/306] Infer type for jest.fn() for subtypes of object --- jest/index.d.ts | 1 + jest/jest-tests.ts | 43 ++++++++++++++++++++++++++++++++++++++----- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/jest/index.d.ts b/jest/index.d.ts index 2f246f2bfe..e81a08c1ca 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -49,6 +49,7 @@ declare namespace jest { /** Enables automatic mocking in the module loader. */ function enableAutomock(): typeof jest; /** Creates a mock function. Optionally takes a mock implementation. */ + function fn(implementation: (...args: any[]) => T): Mock; function fn(implementation?: Function): Mock; /** Use the automatic mocking system to generate a mocked version of the given module. */ function genMockFromModule(moduleName: string): T; diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index f2866d1689..c42df8fef4 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -433,20 +433,53 @@ interface TestApi { declare function mockedFunc(a: number): string; -describe("Mocked type", function () { - it("Works", function () { +describe('Mocked type', function () { + it('Works', function () { const mock: jest.Mocked = jest.fn(() => ({ testProp: true, testMethod1: jest.fn(), testMethod2: jest.fn() })) as any; mock.testProp; - mock.testMethod.mockImplementation(() => "test"); + mock.testMethod.mockImplementation(() => 'test'); mock.testMethod(5); mock.mockClear(); - const funcMock: jest.Mocked = require("./mockedFunc"); - funcMock.mockImplementation(() => "test"); + const funcMock: jest.Mocked = require('./mockedFunc'); + funcMock.mockImplementation(() => 'test'); funcMock(5).toUpperCase(); }); }); + +describe('Mocks', function () { + it('jest.fn() without args is a function type', function () { + const test = jest.fn(); + test(); + new test(); + test.mock.instances[0]; + test.mockImplementation(() => { }); + }); + + it('jest.fn() with returned object infers type', function () { + const testMock = jest.fn(() => ({ a: 5, test: jest.fn() })); + + testMock(5, 5, 'a'); + testMock.mockImplementation(() => { }); + testMock.caller; + + const ins = new testMock(); + ins.a; + ins.test(); + ins.test.mockImplementation(() => 5); + ins.test.mock.calls; + + const anotherMock = jest.fn(() => { + const api: Partial = { + testMethod: jest.fn() + }; + return api; + }); + const anotherIns: jest.Mocked = new anotherMock() as any; + anotherIns.testMethod.mockImplementation(() => 1); + }); +}); From 654c2b4e117145df33183ebb67a9f9938e2937e6 Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Wed, 11 Jan 2017 06:36:08 +0100 Subject: [PATCH 015/306] Fix Mocked type --- jest/index.d.ts | 7 +------ jest/jest-tests.ts | 18 +++++------------- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/jest/index.d.ts b/jest/index.d.ts index e81a08c1ca..020376004b 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -201,15 +201,10 @@ declare namespace jest { * * const myApi: jest.Mocked = new Api() as any; * myApi.myApiMethod.mockImplementation(() => "test"); - * - * jest.mock("./func"); - * const myFuncMock: jest.Mocked = require("./func"); - * myFuncMock.mockImplementation(() => 5); - * myFuncMock(); */ type Mocked = T & { [P in keyof T]: T[P] & MockInstance; - } & MockInstance; + }; interface MockInstance { mock: MockContext; diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index c42df8fef4..d2fcd6d007 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -426,28 +426,20 @@ describe('strictNullChecks', function () { }) }); -interface TestApi { +class TestApi { + constructor() { }; testProp: boolean; - testMethod(a: number): void; + testMethod(a: number): string { return ""; } } declare function mockedFunc(a: number): string; describe('Mocked type', function () { it('Works', function () { - const mock: jest.Mocked = jest.fn(() => ({ - testProp: true, - testMethod1: jest.fn(), - testMethod2: jest.fn() - })) as any; + const mock: jest.Mocked = new TestApi() as any; mock.testProp; mock.testMethod.mockImplementation(() => 'test'); - mock.testMethod(5); - mock.mockClear(); - - const funcMock: jest.Mocked = require('./mockedFunc'); - funcMock.mockImplementation(() => 'test'); - funcMock(5).toUpperCase(); + mock.testMethod(5).toUpperCase(); }); }); From 1c1fc8eea20aafce4605999732c282380d8cc1d9 Mon Sep 17 00:00:00 2001 From: Hinell Date: Thu, 12 Jan 2017 02:00:56 +0300 Subject: [PATCH 016/306] [Archiver] reconciliation with [node] --- archiver/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/archiver/index.d.ts b/archiver/index.d.ts index ea117239ac..665624143e 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -31,7 +31,6 @@ declare namespace archiver { } export interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; append(source: STREAM.Readable | Buffer | string, name: nameInterface): void; directory(dirpath: string, destpath: nameInterface | string): void; From b29bba797511449ee8f6bbd8fac2cdda56d0caef Mon Sep 17 00:00:00 2001 From: Hinell Date: Thu, 12 Jan 2017 02:44:29 +0300 Subject: [PATCH 017/306] [node] Rolled back node stream.readable.pipe() method according to official API Read here: https://github.com/nodejs/node/blob/master/lib/_stream_readable.js#L612 --- node/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/node/index.d.ts b/node/index.d.ts index ea1c42aad9..606276e9a6 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -285,7 +285,7 @@ declare namespace NodeJS { pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): this; + pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): this; unshift(chunk: string): void; unshift(chunk: Buffer): void; @@ -3341,7 +3341,7 @@ declare module "stream" { pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): this; + pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): this; unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; @@ -3531,7 +3531,7 @@ declare module "stream" { pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): this; + pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): this; unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; From 99a7b5915bc1dad725ef9759a68ba05b7633e798 Mon Sep 17 00:00:00 2001 From: Hinell Date: Thu, 12 Jan 2017 02:55:06 +0300 Subject: [PATCH 018/306] [bufferstream] reconciliation with [node] --- bufferstream/index.d.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/bufferstream/index.d.ts b/bufferstream/index.d.ts index 69a16d98e0..9b2b15d525 100644 --- a/bufferstream/index.d.ts +++ b/bufferstream/index.d.ts @@ -109,10 +109,6 @@ declare module 'bufferstream/postbuffer' { set a callback to get all post data from a http server request */ onEnd(callback: (data: any) => void): void; - /* - pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe - */ - pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream; } export = PostBuffer; From 6de3e0630cd2bf63fd4b01b4d5d97931c3715ebf Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 00:23:25 +0100 Subject: [PATCH 019/306] updated Definitions for Raven-JS --- raven-js/index.d.ts | 393 +++++++++++++++++++++++++++++--------------- 1 file changed, 256 insertions(+), 137 deletions(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index 6ecb6a0cdd..fda465c30d 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,209 +1,302 @@ // Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Original Definitions by: Santi Albo , Benjamin Pannell +// ; DefinitelyTyped +// Updated by: Ben Vinegar , Ilya Pirogov +// , Eli White , David Cramer +// , Connor Peet , comaz +// , Luca Vazzano + declare var Raven: RavenStatic; - -declare module 'raven-js' { - export default Raven; -} - -interface RavenOptions { - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** The release version of the application you are monitoring with Sentry */ - release?: string; - - /** The environment in which the application is running. */ - environment?: string; - - /** The name of the server or device that the client is running on */ - serverName?: string; - - /** List of messages to be fitlered out before being sent to Sentry. */ - ignoreErrors?: string[]; - - /** Similar to ignoreErrors, but will ignore errors from whole urls patching a regex pattern. */ - ignoreUrls?: RegExp[]; - - /** The inverse of ignoreUrls. Only report errors from whole urls matching a regex pattern. */ - whitelistUrls?: RegExp[]; - - /** An array of regex patterns to indicate which urls are a part of your app. */ - includePaths?: RegExp[]; - - /** Additional data to be tagged onto the error. */ - tags?: { - [id: string]: string; - }; - - /** A function which allows mutation of the data payload right before being sent to Sentry */ - dataCallback?: (data: any) => any; - - /** A callback function that allows you to apply your own filters to determine if the message should be sent to Sentry. */ - shouldSendCallback?: (data: any) => boolean; - - /** By default, Raven does not truncate messages. If you need to truncate characters for whatever reason, you may set this to limit the length. */ - maxMessageLength?: number; - - /** Enables/disables automatic collection of breadcrumbs. Default: true. */ - autoBreadcrumbs?: any; - - /** The max number of breadcrumb captures. Default: 100. */ - maxBreadcrumbs?: number; - - /** Override the default HTTP data transport handler. */ - transport?: (options: RavenTransportOptions) => void; - - /** Allow the use of a Sentry DSN with a private key. Default: false. */ - allowSecretKey?: boolean; -} - -interface RavenAdditionalData { - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** The log level associated with this event. Default: error */ - level?: string; - - /** Additional data to be tagged onto the error. */ - tags?: { - [id: string]: string; - }; - - extra?: any; -} +export = Raven; interface RavenStatic { - /** Raven.js version. */ VERSION: string; + /** A list of currently active plugins. */ Plugins: { [id: string]: RavenPlugin }; - /* - * Allow Raven to be configured as soon as it is loaded + /** + * Allow Raven to be configured as soon as it is loaded. * It uses a global RavenConfig = {dsn: '...', config: {}} - * - * @return undefined */ afterLoad(): void; - /* + /** * Allow multiple versions of Raven to be installed. * Strip Raven from the global context and returns the instance. - * - * @return {Raven} */ noConflict(): RavenStatic; - /* + /** * Configure Raven with a DSN and extra options * - * @param {string} dsn The public Sentry DSN - * @param {object} options Optional set of of global options [optional] - * @return {Raven} + * @param dsn The public Sentry DSN + * @param options Optional set of of global options */ - config(dsn: string, options?: RavenOptions): RavenStatic; + config(dsn: string, options?: RavenGlobalOptions): RavenStatic; - /* - * Installs a global window.onerror error handler - * to capture and report uncaught exceptions. - * At this point, install() is required to be called due - * to the way TraceKit is set up. + /** + * Set the DSN (can be called multiple times, unlike config) * - * @return {Raven} + * @param dsn The public Sentry DSN + */ + setDSN(dsn: string); + + /** + * Installs a global window.onerror error handler to capture and report uncaught exceptions. + * At this point, install() is required to be called due to the way TraceKit is set up. */ install(): RavenStatic; - /* + /** * Adds a plugin to Raven - * - * @return {Raven} */ addPlugin(plugin: RavenPlugin, ...pluginArgs: any[]): RavenStatic; - /* - * Wrap code within a context so Raven can capture errors - * reliably across domains that is executed immediately. + /** + * Wrap code within a context so Raven can capture errors reliably across domains that is + * executed immediately. * - * @param {object} options A specific set of options for this context [optional] - * @param {function} func The callback to be immediately executed within the context - * @param {array} args An array of arguments to be called with the callback [optional] + * @param options A specific set of options for this context + * @param func The callback to be immediately executed within the context + * @param args An array of arguments to be called with the callback */ context(func: Function, ...args: any[]): void; - context(options: RavenAdditionalData, func: Function, ...args: any[]): void; + context(options: RavenWrapOptions, func: Function, ...args: any[]): void; - /* + /** * Wrap code within a context and returns back a new function to be executed * - * @param {object} options A specific set of options for this context [optional] - * @param {function} func The function to be wrapped in a new context - * @return {function} The newly wrapped functions with a context + * @param options A specific set of options for this context + * @param func The function to be wrapped in a new context + * @return The newly wrapped functions with a context */ wrap(func: Function): Function; - wrap(options: RavenAdditionalData, func: Function): Function; + wrap(options: RavenWrapOptions, func: Function): Function; wrap(func: T): T; - wrap(options: RavenAdditionalData, func: T): T; + wrap(options: RavenWrapOptions, func: T): T; - /* + /** * Uninstalls the global error handler. - * - * @return {Raven} */ uninstall(): RavenStatic; - /* + /** * Manually capture an exception and send it over to Sentry * - * @param {error} ex An exception to be logged - * @param {object} options A specific set of options for this error [optional] - * @return {Raven} + * @param ex An exception to be logged + * @param options A specific set of options for this error */ - captureException(ex: Error, options?: RavenAdditionalData): RavenStatic; + captureException(ex: Error, options?: RavenOptions): RavenStatic; /* * Manually send a message to Sentry * - * @param {string} msg A plain message to be captured in Sentry - * @param {object} options A specific set of options for this message [optional] - * @return {Raven} + * @param msg A plain message to be captured in Sentry + * @param options A specific set of options for this message */ - captureMessage(msg: string, options?: RavenAdditionalData): RavenStatic; + captureMessage(msg: string, options?: RavenOptions): RavenStatic; + + /** + * Add a breadcrumb + * @param crumb The trail which should be added to the trail + */ + captureBreadcrumb(crumb: RavenBreadcrumb): RavenStatic; + + /** + * Set a user to be sent along with payloads. + * + * @param user The definition of the currently active user's unique identity + */ + setUserContext(user: RavenUserContext): RavenStatic; /** * Clear the user context, removing the user data that would be sent to Sentry. */ setUserContext(): RavenStatic; - /* - * Set a user to be sent along with the payload. - * - * @param {object} user An object representing user data [optional] - * @return {Raven} + /** + * Add arbitrary data to be sent along with the payload. + * @param extra data of an arbitrary, nested type which will be added */ - setUserContext(user: { - id?: string; - username?: string; - email?: string; - }): RavenStatic; + setExtraContext(extra: { [prop: string]: any }): RavenStatic; - /** Override the default HTTP data transport handler. */ - setTransport(transportFunction: (options: RavenTransportOptions) => void): RavenStatic; + /** + * Add additional tags to be sent along with payloads. + * @param tags A key/value-pair which will be added + */ + setTagsContext(tags: { [id: string]: string }): RavenStatic; - /** An event id is a globally unique id for the event that was just sent. This event id can be used to find the exact event from within Sentry. */ + /** + * Clear the whole currently set context. + */ + clearContext(): RavenStatic; + + /** + * Get a copy of the current context. + */ + getContext(): Object; + + /** + * Set environment of application + * @param environment Typically something like 'production' + */ + setEnvironment(environment: string): RavenStatic; + + /** + * Set release version of application + * @param release Typically something like a git SHA to identify the current version + */ + setRelease(release: string): RavenStatic; + + /** + * Specify a function that can mutate the payload right before it is being sent to Sentry. + * @param callback The function which can mutate the data + */ + setDataCallback(callback: (data: any, orig?: string) => any): RavenStatic; + + /** + * Specify a callback function that can mutate or filter breadcrumbs when they are captured. + * @param callback The function which applies the filter + */ + setBreadcrumbCallback(callback :(data: any, orig?: string) => any): RavenStatic; + + /** + * Specify a callback function that determines if the given message should be sent to Sentry. + * @param callback The function which determines if the given blob should be sent + */ + setShouldSendCallback(callback: (data: any, orig?: string) => boolean): RavenStatic; + + /** + * Override the default HTTP data transport handler. + * @param transport The function which will be invoked to handle the data transmission + */ + setTransport(transport: (options: RavenTransportOptions) => void): RavenStatic; + + /** + * Get the latest raw exception that was captured by Raven. + */ + lastException(): Error; + + /** + * Get the ID of the last Event captured by Raven. + */ lastEventId(): string; - /** If you need to conditionally check if raven needs to be initialized or not, you can use the isSetup function. It will return true if Raven is already initialized. */ + /** + * Determine if Raven is setup and ready to go. + */ isSetup(): boolean; - showReportDialog(options: RavenOptions): void; + /** + * Show the User Feedback Dialog of Sentry + * @param RavenReportDialogOptions Optional Options to set for the User Feedback + */ + showReportDialog(options?: RavenReportDialogOptions): void; +} - setTagsContext(tags: { [id: string]: string; }): void; - setExtraContext(context: any): void; +// --- Helper Interfaces for Options -------------- +interface RavenBreadcrumOptions { + /** Whether to collect XHR calls, defaults to true */ + xhr?: boolean; + + /** Whether to collect console logs, defaults to true */ + console?: boolean; + + /** Whether to collect dom events, defaults to true */ + dom?: boolean; + + /** Whether to record window location and navigation, defaults to true */ + location?: boolean; +} + +interface CommonRavenOptions { + /** The environment of the application you are monitoring with Sentry */ + environment?: string; + + /** The release version of the application you are monitoring with Sentry */ + release?: string; + + /** Additional key/value-data to be tagged onto the error. */ + tags?: { [id: string]: string }; + + /** Additional, arbitrary metadata to collect */ + extra?: { [prop: string]: any }; + + /** The name of the logger used by Sentry. Default: javascript */ + logger?: string; + + /** set to true to get the strack trace of your message */ + stacktrace?: boolean; +} + +interface RavenOptions extends CommonRavenOptions { + /** The name of the server or device that the client is running on */ + server_name?: string; + + /** The log level associated with this event. Default: error */ + level?: string; + + /** In some cases you may see issues where Sentry groups multiple events together when they + * should be separate entities. In other cases, Sentry simply doesn’t group events together + * because they’re so sporadic that they never look the same. */ + fingerprint?: string[]; + + /** Number of frames to trim off the stacktrace. Default: 1 */ + trimHeadFrames?: number; + + /** The name of the device platform. Default: "javascript" */ + platform?: string; +} + +interface RavenGlobalOptions extends CommonRavenOptions { + /** The name of the server or device that the client is running on */ + serverName?: string; + + /** Configures which breadcrumbs are collected automatically */ + autoBreadcrumbs?: boolean | RavenBreadcrumOptions; + + /** Whether to collect errors on the window via TraceKit.collectWindowErrors. Default: true. */ + collectWindowErrors?: boolean; + + /** Max number of breadcrumbs to collect. Default: 100 */ + maxBreadcrumbs?: number; + + /** Exclude messages which match one of the given RegEx-Patterns from being sent to Sentry. */ + ignoreErrors?: (RegExp | string)[]; + + /** Exclude messages which come from whole urls matching one of the given RegEx patterns. */ + ignoreUrls?: (RegExp | string)[]; + + /** Only report messages which come from whole urls matching one of the given RegEx patterns. */ + whitelistUrls?: (RegExp | string)[]; + + /** An array of RegEx patterns to indicate which urls are a part of your app. */ + includePaths?: (RegExp | string)[]; + + /** Maximum amount of stack frames to collect. Default: Infinity */ + stackTraceLimit?: number; + + /** Override the default HTTP data transport handler. */ + transport?: (options: RavenTransportOptions) => void; + + /** Limit the maxium length of a message to this number of characters. Default: Infinity */ + maxMessageLength?: number; + + /** Allows you to apply your own filters to determine if the message should be sent to Sentry. */ + shouldSendCallback?: (data: any) => boolean; + + /** A function which allows mutation of the data payload right before being sent to Sentry */ + dataCallback?: (data: any) => any; +} + +interface RavenWrapOptions extends RavenOptions { + /** Whether to run the wrap recursively. Default: false. */ + deep?: boolean; } interface RavenTransportOptions { @@ -218,6 +311,32 @@ interface RavenTransportOptions { onFailure: () => void; } +interface RavenReportDialogOptions { + eventId?: number, + dsn?: string, + user?: { + name?: string, + email?: string + } +} + + +// --- Helper Interfaces for complex Data Structures -------------- interface RavenPlugin { (raven: RavenStatic, ...args: any[]): RavenStatic; } + +interface RavenUserContext { + id?: string; + username?: string; + email?: string; + ip_address?: string; + extra?: { [prop: string]: any }; +} + +interface RavenBreadcrumb { + message: string; + data: { [id: string]: string }; + category: string; + level: string; +} From 861c2abc61efdc93cebc5387233e226dead003e3 Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 00:46:01 +0100 Subject: [PATCH 020/306] fixed tests --- raven-js/index.d.ts | 28 ++++++++-------- raven-js/raven-js-tests.ts | 67 +++++++++++++++++++++----------------- 2 files changed, 51 insertions(+), 44 deletions(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index fda465c30d..ddb5e8503d 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Raven.js +// Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js // Original Definitions by: Santi Albo , Benjamin Pannell // ; DefinitelyTyped @@ -8,8 +8,8 @@ // , Luca Vazzano -declare var Raven: RavenStatic; -export = Raven; +declare let Raven: RavenStatic; +export default Raven; interface RavenStatic { /** Raven.js version. */ @@ -43,7 +43,7 @@ interface RavenStatic { * * @param dsn The public Sentry DSN */ - setDSN(dsn: string); + setDSN(dsn: string): RavenStatic; /** * Installs a global window.onerror error handler to capture and report uncaught exceptions. @@ -200,7 +200,7 @@ interface RavenStatic { // --- Helper Interfaces for Options -------------- -interface RavenBreadcrumOptions { +export interface RavenBreadcrumOptions { /** Whether to collect XHR calls, defaults to true */ xhr?: boolean; @@ -214,7 +214,7 @@ interface RavenBreadcrumOptions { location?: boolean; } -interface CommonRavenOptions { +export interface CommonRavenOptions { /** The environment of the application you are monitoring with Sentry */ environment?: string; @@ -234,7 +234,7 @@ interface CommonRavenOptions { stacktrace?: boolean; } -interface RavenOptions extends CommonRavenOptions { +export interface RavenOptions extends CommonRavenOptions { /** The name of the server or device that the client is running on */ server_name?: string; @@ -253,7 +253,7 @@ interface RavenOptions extends CommonRavenOptions { platform?: string; } -interface RavenGlobalOptions extends CommonRavenOptions { +export interface RavenGlobalOptions extends CommonRavenOptions { /** The name of the server or device that the client is running on */ serverName?: string; @@ -294,12 +294,12 @@ interface RavenGlobalOptions extends CommonRavenOptions { dataCallback?: (data: any) => any; } -interface RavenWrapOptions extends RavenOptions { +export interface RavenWrapOptions extends RavenOptions { /** Whether to run the wrap recursively. Default: false. */ deep?: boolean; } -interface RavenTransportOptions { +export interface RavenTransportOptions { url: string; data: any; auth: { @@ -311,7 +311,7 @@ interface RavenTransportOptions { onFailure: () => void; } -interface RavenReportDialogOptions { +export interface RavenReportDialogOptions { eventId?: number, dsn?: string, user?: { @@ -322,11 +322,11 @@ interface RavenReportDialogOptions { // --- Helper Interfaces for complex Data Structures -------------- -interface RavenPlugin { +export interface RavenPlugin { (raven: RavenStatic, ...args: any[]): RavenStatic; } -interface RavenUserContext { +export interface RavenUserContext { id?: string; username?: string; email?: string; @@ -334,7 +334,7 @@ interface RavenUserContext { extra?: { [prop: string]: any }; } -interface RavenBreadcrumb { +export interface RavenBreadcrumb { message: string; data: { [id: string]: string }; category: string; diff --git a/raven-js/raven-js-tests.ts b/raven-js/raven-js-tests.ts index 9608e41322..bbd3285e1e 100644 --- a/raven-js/raven-js-tests.ts +++ b/raven-js/raven-js-tests.ts @@ -1,24 +1,24 @@ - - import RavenJS from 'raven-js'; RavenJS.config('https://public@getsentry.com/1').install(); -var options: RavenOptions = { - logger: 'my-logger', - ignoreUrls: [ - /graph\.facebook\.com/i - ], - ignoreErrors: [ - 'fb_xd_fragment' - ], - includePaths: [ - /https?:\/\/(www\.)?getsentry\.com/, - /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ - ] -}; -Raven.config('https://public@getsentry.com/1', options).install(); +RavenJS.config( + 'https://public@getsentry.com/1', + { + logger: 'my-logger', + ignoreUrls: [ + /graph\.facebook\.com/i + ], + ignoreErrors: [ + 'fb_xd_fragment' + ], + includePaths: [ + /https?:\/\/(www\.)?getsentry\.com/, + /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ + ] + } +).install(); var throwsError = () => { throw new Error('broken'); @@ -27,28 +27,35 @@ var throwsError = () => { try { throwsError(); } catch(e) { - Raven.captureException(e); - Raven.captureException(e, {tags: { key: "value" }}); + RavenJS.captureException(e); + RavenJS.captureException(e, {tags: { key: "value" }}); } -Raven.context(throwsError); -Raven.context({tags: { key: "value" }}, throwsError); -Raven.context({extra: {planet: {name: 'Earth'}}}, throwsError); +RavenJS.context(throwsError); +RavenJS.context({tags: { key: "value" }}, throwsError); +RavenJS.context({extra: {planet: {name: 'Earth'}}}, throwsError); -setTimeout(Raven.wrap(throwsError), 1000); -Raven.wrap({logger: "my.module"}, throwsError)(); -Raven.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); +setTimeout(RavenJS.wrap(throwsError), 1000); +RavenJS.wrap({logger: "my.module"}, throwsError)(); +RavenJS.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); -Raven.setUserContext({ +RavenJS.setUserContext({ email: 'matt@example.com', id: '123' }); -Raven.captureMessage('Broken!'); -Raven.captureMessage('Broken!', {tags: { key: "value" }}); +RavenJS.captureMessage('Broken!'); +RavenJS.captureMessage('Broken!', {tags: { key: "value" }}); -Raven.showReportDialog(options); +RavenJS.showReportDialog({ + eventId: 0815, + dsn:'1337asdf', + user: { + name: 'DefenitelyTyped', + email: 'df@ts.ms' + } +}); -Raven.setTagsContext({ key: "value" }); +RavenJS.setTagsContext({ key: "value" }); -Raven.setExtraContext({ foo: "bar" }); +RavenJS.setExtraContext({ foo: "bar" }); From 9ef1ed01256fc403e35fb4cb756310d3df2e658c Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 00:54:16 +0100 Subject: [PATCH 021/306] fixed BOM --- raven-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index ddb5e8503d..b264b9d786 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Raven.js +// Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js // Original Definitions by: Santi Albo , Benjamin Pannell // ; DefinitelyTyped From e1bd300cd1d205dbcf4709c0f3d25d2413123cd6 Mon Sep 17 00:00:00 2001 From: Luca Vazzano Date: Fri, 13 Jan 2017 01:20:04 +0100 Subject: [PATCH 022/306] fixed 'Definitions:'/'Definitions by:' comment at the top of raven-js/index.d.ts --- raven-js/index.d.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts index b264b9d786..7b54ec7372 100644 --- a/raven-js/index.d.ts +++ b/raven-js/index.d.ts @@ -1,11 +1,7 @@ // Type definitions for Raven.js // Project: https://github.com/getsentry/raven-js -// Original Definitions by: Santi Albo , Benjamin Pannell -// ; DefinitelyTyped -// Updated by: Ben Vinegar , Ilya Pirogov -// , Eli White , David Cramer -// , Connor Peet , comaz -// , Luca Vazzano +// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout , Ben Vinegar , Ilya Pirogov , Eli White , David Cramer , Connor Peet , comaz , Luca Vazzano +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare let Raven: RavenStatic; From 004db1e2c6dd5795264b2e98e67f0a579f44d42d Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Fri, 13 Jan 2017 05:09:16 +0100 Subject: [PATCH 023/306] Added mockReset() --- jest/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jest/index.d.ts b/jest/index.d.ts index 020376004b..acfe70a0f6 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -209,6 +209,7 @@ declare namespace jest { interface MockInstance { mock: MockContext; mockClear(): void; + mockReset(): void; mockImplementation(fn: Function): Mock; mockImplementationOnce(fn: Function): Mock; mockReturnThis(): Mock; From 771ef63514fb41176875407fb93a540c162e9e33 Mon Sep 17 00:00:00 2001 From: scippio Date: Sat, 14 Jan 2017 00:31:01 +0100 Subject: [PATCH 024/306] added new option parameter added new option parameter for new package version compatibility --- cron/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cron/index.d.ts b/cron/index.d.ts index e962a9eb27..79a5b96a01 100644 --- a/cron/index.d.ts +++ b/cron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cron 1.0.9 +// Type definitions for cron 1.2.1 // Project: https://www.npmjs.com/package/cron // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,9 +6,9 @@ interface CronJobStatic { - new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob; + new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any, runOnInit?: boolean): CronJob; new (options: { - cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any + cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any; runOnInit?: boolean }): CronJob; } interface CronJob { From ee373b10745c1324ebc30d6c302ccc10cc6d6786 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Sat, 14 Jan 2017 21:13:18 +0100 Subject: [PATCH 025/306] Add definitions for shipit, shipit-utils and express-rate-limit. --- .../express-rate-limit-tests.ts | 25 ++++++++ express-rate-limit/index.d.ts | 37 +++++++++++ express-rate-limit/tsconfig.json | 20 ++++++ shipit-utils/index.d.ts | 22 +++++++ shipit-utils/shipit-utils-tests.ts | 11 ++++ shipit-utils/tsconfig.json | 20 ++++++ shipit/index.d.ts | 61 +++++++++++++++++++ shipit/shipit-cli-tests.ts | 50 +++++++++++++++ shipit/tsconfig.json | 20 ++++++ 9 files changed, 266 insertions(+) create mode 100644 express-rate-limit/express-rate-limit-tests.ts create mode 100644 express-rate-limit/index.d.ts create mode 100644 express-rate-limit/tsconfig.json create mode 100644 shipit-utils/index.d.ts create mode 100644 shipit-utils/shipit-utils-tests.ts create mode 100644 shipit-utils/tsconfig.json create mode 100644 shipit/index.d.ts create mode 100644 shipit/shipit-cli-tests.ts create mode 100644 shipit/tsconfig.json diff --git a/express-rate-limit/express-rate-limit-tests.ts b/express-rate-limit/express-rate-limit-tests.ts new file mode 100644 index 0000000000..761a6d23f8 --- /dev/null +++ b/express-rate-limit/express-rate-limit-tests.ts @@ -0,0 +1,25 @@ +import RateLimit = require("express-rate-limit"); + +var apiLimiter = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + delayMs: 0 // disabled +}); + +var createAccountLimiter = new RateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour window + delayAfter: 1, // begin slowing down responses after the first request + delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request + max: 5, // start blocking after 5 requests + message: "Too many accounts created from this IP, please try again after an hour" +}); + +class SomeStore implements RateLimit.Store { + incr(key: string, cb: RateLimit.StoreIncrementCallback) { } + resetAll() { } + resetKey(key: string) { }; +}; + +var limiterWithStore = new RateLimit({ + store: new SomeStore() +}); diff --git a/express-rate-limit/index.d.ts b/express-rate-limit/index.d.ts new file mode 100644 index 0000000000..57eb003694 --- /dev/null +++ b/express-rate-limit/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for express-rate-limit 2.6.0 +// Project: https://github.com/nfriedly/express-rate-limit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import express = require("express"); + +declare namespace RateLimit { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + export interface Store { + incr: (key: string, cb: StoreIncrementCallback) => void; + resetAll: () => void; + resetKey: (key: string) => void; + } + + export interface Options { + delayAfter?: number; + delayMs?: number; + headers?: boolean; + keyGenerator?: Function; + max?: number; + message?: string; + statusCode?: number; + store?: Store; + windowMs?: number; + } +} + +interface RateLimitStatic { + new(options: RateLimit.Options): express.RequestHandler; +} + +declare var RateLimit: RateLimitStatic; +export = RateLimit; diff --git a/express-rate-limit/tsconfig.json b/express-rate-limit/tsconfig.json new file mode 100644 index 0000000000..560edfef9d --- /dev/null +++ b/express-rate-limit/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-rate-limit-tests.ts" + ] +} diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts new file mode 100644 index 0000000000..a66b681c37 --- /dev/null +++ b/shipit-utils/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for shipit-utils 1.4.0 +// Project: https://github.com/shipitjs/shipit-utils +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "shipit-utils" { + import shipit = require("shipit-cli"); + + type GruntOrShipit = typeof shipit | {}; + + export function equalValues(value: any[]): void; + + export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; + export function getShipit(gruntOrShipit: GruntOrShipit): typeof shipit; + + export function registerTask(gruntOrShipit: GruntOrShipit, name: string, task: Function): typeof shipit; + export function registerTask(gruntOrShipit: GruntOrShipit, name: string, dependencies: string[]): typeof shipit; + + export function runTask(gruntOrShipit: {}): void; +} diff --git a/shipit-utils/shipit-utils-tests.ts b/shipit-utils/shipit-utils-tests.ts new file mode 100644 index 0000000000..15f0d5547b --- /dev/null +++ b/shipit-utils/shipit-utils-tests.ts @@ -0,0 +1,11 @@ +import shipit = require("shipit-cli"); +import utils = require("shipit-utils"); + +var originalShipit = utils.getShipit(shipit); + +var task = () => { + return shipit.local("sleep 10s"); +}; + +utils.registerTask(originalShipit, "myTask", task); +utils.registerTask(originalShipit, "myTask", ["some", "other", "tasks"]); diff --git a/shipit-utils/tsconfig.json b/shipit-utils/tsconfig.json new file mode 100644 index 0000000000..fa4b1ce3b6 --- /dev/null +++ b/shipit-utils/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-utils-tests.ts" + ] +} diff --git a/shipit/index.d.ts b/shipit/index.d.ts new file mode 100644 index 0000000000..e0a528a2f2 --- /dev/null +++ b/shipit/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for shipit 1.5.1 +// Project: https://github.com/shipitjs/shipit +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "shipit-cli" { + import shipit = require("shipit-cli"); + + import * as fs from "fs"; + import * as child_process from "child_process"; + + type LocalOrRemoteCommand = (command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void) => PromiseLike; + type TaskExecution = (name: string, depsOrFn: string[] | Function, fn: Function) => any; + + export interface Options { + environment: string; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + export interface ShipitLocal { + child: child_process.ChildProcess; + stderr: fs.WriteStream; + stdout: fs.WriteStream; + } + + export interface Tasks { + [name: string]: Task; + } + + export interface Task { + blocking: boolean; + dep: string[]; + fn: Function; + name: string; + } + + export function blTask(name: string, depsOrFn: string[] | Function, fn?: Function): any; + export function emit(name: string): any; + export function initConfig(config: {}): typeof shipit; + export function local(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function log(log: any): void; + export function log(...log: any[]): void; + export function on(name: string, callback: Function): any; + export function remote(command: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function remoteCopy(src: string, dest: string, options?: child_process.ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): PromiseLike; + export function start(tasks: string): typeof shipit; + export function start(tasks: string[]): typeof shipit; + export function start(...tasks: string[]): typeof shipit; + export function task(name: string, depsOrFn: string[] | Function, fn?: Function): typeof shipit; + + export var config: {}; + export var domain: any; + export var doneCallback: any; + export var environment: string; + export var seq: any[]; + export var tasks: Tasks; + export var isRunning: boolean; +} diff --git a/shipit/shipit-cli-tests.ts b/shipit/shipit-cli-tests.ts new file mode 100644 index 0000000000..50dff54978 --- /dev/null +++ b/shipit/shipit-cli-tests.ts @@ -0,0 +1,50 @@ +import shipit = require("shipit-cli"); + +shipit.initConfig({ + default: { + workspace: "/tmp/github-monitor", + deployTo: "/tmp/deploy_to", + repositoryUrl: "https://github.com/user/repo.git", + ignores: [".git", "node_modules"], + rsync: ["--del"], + keepReleases: 2, + key: "/path/to/key", + shallowClone: true + }, + staging: { + servers: "user@myserver.com" + } +}); + +shipit.task("build", () => { + shipit.emit("built"); +}); + +shipit.on("built", () => { + shipit.start("start-server"); +}); + +shipit.task("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.blTask("pwd", () => { + return shipit.remote("pwd"); +}); + +shipit.start("task"); +shipit.start("task1", "task2"); +shipit.start(["task1", "task2"]); + +shipit.local("ls -lah", {cwd: "/tmp/deploy/workspace"}).then((res: any) => { + console.log(res.stdout); + console.log(res.stderr); +}); + +shipit.remote("ls -lah").then((res: any) => { + console.log(res[0].stdout); + console.log(res[0].stderr); +}); + +shipit.remoteCopy("/tmp/workspace", "/opt/web/myapp").then(() => {}); +shipit.log("hello %s", "world"); diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json new file mode 100644 index 0000000000..da7bec35d8 --- /dev/null +++ b/shipit/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-cli-tests.ts" + ] +} From d4044f0ce56b80c6ed0403ff17305678a85423b2 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Sat, 14 Jan 2017 21:18:20 +0100 Subject: [PATCH 026/306] Fix definition header for shipit-cli. --- shipit/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shipit/index.d.ts b/shipit/index.d.ts index e0a528a2f2..ab44d7abd8 100644 --- a/shipit/index.d.ts +++ b/shipit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for shipit 1.5.1 +// Type definitions for shipit-cli 1.5.1 // Project: https://github.com/shipitjs/shipit // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 6c7cd1ed7b83005c26891581f6cffb54eafa63d7 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Sat, 14 Jan 2017 21:19:11 +0100 Subject: [PATCH 027/306] Rename "shipit-cli-tests" to "shipit-tests". --- shipit/{shipit-cli-tests.ts => shipit-tests.ts} | 0 shipit/tsconfig.json | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename shipit/{shipit-cli-tests.ts => shipit-tests.ts} (100%) diff --git a/shipit/shipit-cli-tests.ts b/shipit/shipit-tests.ts similarity index 100% rename from shipit/shipit-cli-tests.ts rename to shipit/shipit-tests.ts diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json index da7bec35d8..254ac2d9a5 100644 --- a/shipit/tsconfig.json +++ b/shipit/tsconfig.json @@ -15,6 +15,6 @@ }, "files": [ "index.d.ts", - "shipit-cli-tests.ts" + "shipit-tests.ts" ] } From 040c1365bc12314f7ce49799cd2cdcb8e6c295f5 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Tue, 17 Jan 2017 12:32:34 +0900 Subject: [PATCH 028/306] Update react-router-redux to user history 4.5.x --- react-router-redux/index.d.ts | 111 ++++++++---------- .../react-router-redux-tests.ts | 20 +++- react-router-redux/tsconfig.json | 17 ++- react-router-redux/tslint.json | 1 + 4 files changed, 76 insertions(+), 73 deletions(-) create mode 100644 react-router-redux/tslint.json diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index 16438f9452..a6d3bd8c00 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -1,65 +1,58 @@ -// Type definitions for react-router-redux v4.0.0 +// Type definitions for react-router-redux 4.0 // Project: https://github.com/rackt/react-router-redux -// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg +// Definitions by: Isman Usoh , Noah Shipley , Dimitri Rosenberg , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Action, Middleware, Store } from "redux"; +import { History, Location, LocationDescriptor } from "history"; -import * as Redux from "redux"; -import * as History from "history"; +export const CALL_HISTORY_METHOD: string; +export const LOCATION_CHANGE: string; -export = ReactRouterRedux; - -declare namespace ReactRouterRedux { - import R = Redux; - - const CALL_HISTORY_METHOD: string; - const LOCATION_CHANGE: string; - - const push: PushAction; - const replace: ReplaceAction; - const go: GoAction; - const goBack: GoForwardAction; - const goForward: GoBackAction; - const routerActions: RouteActions; - - type LocationDescriptor = History.LocationDescriptor; - type PushAction = (nextLocation: LocationDescriptor) => RouterAction; - type ReplaceAction = (nextLocation: LocationDescriptor) => RouterAction; - type GoAction = (n: number) => RouterAction; - type GoForwardAction = () => RouterAction; - type GoBackAction = () => RouterAction; - - type RouterAction = { - type: string - payload?: LocationDescriptor - } - - interface RouteActions { - push: PushAction; - replace: ReplaceAction; - go: GoAction; - goForward: GoForwardAction; - goBack: GoBackAction; - } - interface ReactRouterReduxHistory extends History.History { - unsubscribe(): void; - } - - interface DefaultSelectLocationState extends Function { - (state: any): any; - } - - interface SyncHistoryWithStoreOptions { - selectLocationState?: DefaultSelectLocationState; - adjustUrlOnReplay?: boolean; - } - - interface RouterState { - locationBeforeTransitions: History.Location - } - - function routerReducer(state?: RouterState, action?: R.Action): RouterState; - function syncHistoryWithStore(history: History.History, store: R.Store, options?: SyncHistoryWithStoreOptions): ReactRouterReduxHistory; - function routerMiddleware(history: History.History): R.Middleware; +export interface LocationActionPayload { + method: string; + args?: any[]; } + +export interface RouterAction extends Action { + payload?: LocationActionPayload; +} + +type LocationAction = (nextLocation: LocationDescriptor) => RouterAction; +type GoAction = (n: number) => RouterAction; +type NavigateAction = () => RouterAction; + +export const push: LocationAction; +export const replace: LocationAction; +export const go: GoAction; +export const goBack: NavigateAction; +export const goForward: NavigateAction; + +interface RouteActions { + push: typeof push; + replace: typeof replace; + go: typeof go; + goForward: typeof goForward; + goBack: typeof goBack; +} + +export const routerActions: RouteActions; + +export interface RouterState { + locationBeforeTransitions: Location +} + +export type DefaultSelectLocationState = (state: any) => RouterState + +export interface SyncHistoryWithStoreOptions { + selectLocationState?: DefaultSelectLocationState; + adjustUrlOnReplay?: boolean; +} + +export interface HistoryUnsubscribe { + unsubscribe(): void; +} + +export function routerReducer(state?: RouterState, action?: Action): RouterState; +export function syncHistoryWithStore(history: History, store: Store, options?: SyncHistoryWithStoreOptions): History & HistoryUnsubscribe; +export function routerMiddleware(history: History): Middleware; diff --git a/react-router-redux/react-router-redux-tests.ts b/react-router-redux/react-router-redux-tests.ts index 1d73706c4e..87b99b2a69 100644 --- a/react-router-redux/react-router-redux-tests.ts +++ b/react-router-redux/react-router-redux-tests.ts @@ -1,9 +1,16 @@ -/// -/// - import { createStore, combineReducers, applyMiddleware } from 'redux'; import { browserHistory } from 'react-router'; -import { syncHistoryWithStore, routerReducer, routerMiddleware, push, replace, go, goForward, goBack } from 'react-router-redux'; +import { + syncHistoryWithStore, + routerReducer, + routerMiddleware, + push, + replace, + go, + goForward, + goBack, + routerActions +} from 'react-router-redux'; const reducer = combineReducers({ routing: routerReducer }); @@ -25,3 +32,8 @@ store.dispatch(replace('/foo')); store.dispatch(go(1)); store.dispatch(goForward()); store.dispatch(goBack()); +store.dispatch(routerActions.push('/foo')); +store.dispatch(routerActions.replace('/foo')); +store.dispatch(routerActions.go(1)); +store.dispatch(routerActions.goForward()); +store.dispatch(routerActions.goBack()); diff --git a/react-router-redux/tsconfig.json b/react-router-redux/tsconfig.json index b2efdcc111..64b2c38849 100644 --- a/react-router-redux/tsconfig.json +++ b/react-router-redux/tsconfig.json @@ -1,23 +1,20 @@ { - "files": [ - "index.d.ts", - "react-router-redux-tests.ts" - ], "compilerOptions": { "module": "commonjs", "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ - "../" + "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "react-router-redux-tests.ts" + ] } diff --git a/react-router-redux/tslint.json b/react-router-redux/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-router-redux/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 69a9f6d6718fba210ab007541572ff8459c6d1ce Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Tue, 17 Jan 2017 18:29:47 +0900 Subject: [PATCH 029/306] Update react-router definitions to 3.0.x --- react-router/index.d.ts | 137 +++++------ react-router/lib/IndexLink.d.ts | 16 +- react-router/lib/IndexRedirect.d.ts | 25 +-- react-router/lib/IndexRoute.d.ts | 44 ++-- react-router/lib/Link.d.ts | 22 +- react-router/lib/PatternUtils.d.ts | 4 +- react-router/lib/PropTypes.d.ts | 35 +-- react-router/lib/Redirect.d.ts | 27 +-- react-router/lib/Route.d.ts | 50 +++-- react-router/lib/RouteUtils.d.ts | 9 +- react-router/lib/Router.d.ts | 212 +++++++++--------- react-router/lib/RouterContext.d.ts | 27 +-- react-router/lib/applyRouterMiddleware.d.ts | 12 +- react-router/lib/browserHistory.d.ts | 4 +- react-router/lib/createMemoryHistory.d.ts | 6 +- react-router/lib/hashHistory.d.ts | 4 +- react-router/lib/match.d.ts | 25 +-- react-router/lib/useRouterHistory.d.ts | 8 +- react-router/lib/withRouter.d.ts | 11 +- react-router/react-router-tests.tsx | 33 ++- react-router/tsconfig.json | 3 - react-router/v2/index.d.ts | 91 ++++++++ react-router/v2/lib/IndexLink.d.ts | 5 + react-router/v2/lib/IndexRedirect.d.ts | 17 ++ react-router/v2/lib/IndexRoute.d.ts | 20 ++ react-router/{ => v2}/lib/Lifecycle.d.ts | 0 react-router/v2/lib/Link.d.ts | 19 ++ react-router/v2/lib/PatternUtils.d.ts | 1 + react-router/v2/lib/PropTypes.d.ts | 19 ++ react-router/v2/lib/Redirect.d.ts | 19 ++ react-router/v2/lib/Route.d.ts | 25 +++ react-router/{ => v2}/lib/RouteContext.d.ts | 0 react-router/v2/lib/RouteUtils.d.ts | 8 + react-router/v2/lib/Router.d.ts | 116 ++++++++++ react-router/v2/lib/RouterContext.d.ts | 25 +++ .../v2/lib/applyRouterMiddleware.d.ts | 9 + react-router/v2/lib/browserHistory.d.ts | 3 + react-router/v2/lib/createMemoryHistory.d.ts | 3 + react-router/v2/lib/hashHistory.d.ts | 3 + react-router/v2/lib/match.d.ts | 17 ++ react-router/{ => v2}/lib/routerHistory.d.ts | 0 react-router/v2/lib/useRouterHistory.d.ts | 7 + react-router/{ => v2}/lib/useRoutes.d.ts | 0 react-router/v2/lib/withRouter.d.ts | 4 + 44 files changed, 749 insertions(+), 376 deletions(-) create mode 100644 react-router/v2/index.d.ts create mode 100644 react-router/v2/lib/IndexLink.d.ts create mode 100644 react-router/v2/lib/IndexRedirect.d.ts create mode 100644 react-router/v2/lib/IndexRoute.d.ts rename react-router/{ => v2}/lib/Lifecycle.d.ts (100%) create mode 100644 react-router/v2/lib/Link.d.ts create mode 100644 react-router/v2/lib/PatternUtils.d.ts create mode 100644 react-router/v2/lib/PropTypes.d.ts create mode 100644 react-router/v2/lib/Redirect.d.ts create mode 100644 react-router/v2/lib/Route.d.ts rename react-router/{ => v2}/lib/RouteContext.d.ts (100%) create mode 100644 react-router/v2/lib/RouteUtils.d.ts create mode 100644 react-router/v2/lib/Router.d.ts create mode 100644 react-router/v2/lib/RouterContext.d.ts create mode 100644 react-router/v2/lib/applyRouterMiddleware.d.ts create mode 100644 react-router/v2/lib/browserHistory.d.ts create mode 100644 react-router/v2/lib/createMemoryHistory.d.ts create mode 100644 react-router/v2/lib/hashHistory.d.ts create mode 100644 react-router/v2/lib/match.d.ts rename react-router/{ => v2}/lib/routerHistory.d.ts (100%) create mode 100644 react-router/v2/lib/useRouterHistory.d.ts rename react-router/{ => v2}/lib/useRoutes.d.ts (100%) create mode 100644 react-router/v2/lib/withRouter.d.ts diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 59f33e1960..8398838aef 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -1,91 +1,56 @@ -// Type definitions for react-router v2.0.0 +// Type definitions for react-router 3.0 // Project: https://github.com/rackt/react-router -// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov +// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -export as namespace ReactRouter; - -import * as React from 'react'; - -export const routerShape: React.Requireable - -export const locationShape: React.Requireable - -import Router from "./lib/Router"; -import Link from "./lib/Link"; -import IndexLink from "./lib/IndexLink"; -import IndexRedirect from "./lib/IndexRedirect"; -import IndexRoute from "./lib/IndexRoute"; -import Redirect from "./lib/Redirect"; -import Route from "./lib/Route"; -import * as History from "./lib/routerHistory"; -import Lifecycle from "./lib/Lifecycle"; -import RouteContext from "./lib/RouteContext"; -import browserHistory from "./lib/browserHistory"; -import hashHistory from "./lib/hashHistory"; -import useRoutes from "./lib/useRoutes"; -import { createRoutes } from "./lib/RouteUtils"; -import { formatPattern } from "./lib/PatternUtils"; -import RouterContext from "./lib/RouterContext"; -import PropTypes from "./lib/PropTypes"; -import match from "./lib/match"; -import useRouterHistory from "./lib/useRouterHistory"; -import createMemoryHistory from "./lib/createMemoryHistory"; -import withRouter from "./lib/withRouter"; -import applyRouterMiddleware from "./lib/applyRouterMiddleware"; - -// PlainRoute is defined in the API documented at: -// https://github.com/rackt/react-router/blob/master/docs/API.md -// but not included in any of the .../lib modules above. -export type PlainRoute = Router.PlainRoute; - -// The following definitions are also very useful to export -// because by using these types lots of potential type errors -// can be exposed: -export type EnterHook = Router.EnterHook; -export type LeaveHook = Router.LeaveHook; -export type ParseQueryString = Router.ParseQueryString; -export type LocationDescriptor = Router.LocationDescriptor; -export type RedirectFunction = Router.RedirectFunction; -export type RouteComponent = Router.RouteComponent; -export type RouteComponentProps = Router.RouteComponentProps; -export type RouteConfig = Router.RouteConfig; -export type RouteHook = Router.RouteHook; -export type StringifyQuery = Router.StringifyQuery; -export type RouterListener = Router.RouterListener; -export type RouterState = Router.RouterState; -export type InjectedRouter = Router.InjectedRouter; - -export type HistoryBase = History.HistoryBase; -export type RouterOnContext = Router.RouterOnContext; -export type RouteProps = Route.RouteProps; -export type LinkProps = Link.LinkProps; - export { - Router, - Link, - IndexLink, - IndexRedirect, - IndexRoute, - Redirect, - Route, - History, - browserHistory, - hashHistory, - Lifecycle, - RouteContext, - useRoutes, - createRoutes, - formatPattern, - RouterContext, - PropTypes, - match, - useRouterHistory, - createMemoryHistory, - withRouter, - applyRouterMiddleware -}; + Basename, + ChangeHook, + EnterHook, + InjectedRouter, + LeaveHook, + Location, + LocationDescriptor, + ParseQueryString, + RouteComponent, + RouteComponents, + RouteComponentProps, + RouteConfig, + RoutePattern, + RouterProps, + RouterState, + StringifyQuery, + Query +} from "react-router/lib/Router"; +export { LinkProps } from "react-router/lib/Link"; +export { IndexLinkProps } from "react-router/lib/IndexLink"; +export { RouteProps, PlainRoute } from "react-router/lib/Route"; +export { IndexRouteProps } from "react-router/lib/IndexRoute"; +export { RedirectProps } from "react-router/lib/Redirect"; +export { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -export default Router; +/* components */ +export { default as Router } from "react-router/lib/Router"; +export { default as Link } from "react-router/lib/Link"; +export { default as IndexLink } from "react-router/lib/IndexLink"; +export { default as withRouter } from "react-router/lib/withRouter"; + +/* components (configuration) */ +export { default as IndexRedirect } from "react-router/lib/IndexRedirect"; +export { default as IndexRoute } from "react-router/lib/IndexRoute"; +export { default as Redirect } from "react-router/lib/Redirect"; +export { default as Route } from "react-router/lib/Route"; + +/* utils */ +export { createRoutes } from "react-router/lib/RouteUtils"; +export { default as RouterContext } from "react-router/lib/RouterContext"; +export { routerShape, locationShape } from "react-router/lib/PropTypes"; +export { default as match } from "react-router/lib/match"; +export { default as useRouterHistory } from "react-router/lib/useRouterHistory"; +export { formatPattern } from "react-router/lib/PatternUtils"; +export { default as applyRouterMiddleware } from "react-router/lib/applyRouterMiddleware"; + +/* histories */ +export { default as browserHistory } from "react-router/lib/browserHistory"; +export { default as hashHistory } from "react-router/lib/hashHistory"; +export { default as createMemoryHistory } from "react-router/lib/createMemoryHistory"; diff --git a/react-router/lib/IndexLink.d.ts b/react-router/lib/IndexLink.d.ts index 56ecf82c1d..0c62010262 100644 --- a/react-router/lib/IndexLink.d.ts +++ b/react-router/lib/IndexLink.d.ts @@ -1,5 +1,15 @@ -import Link from './Link'; +import { ComponentClass, CSSProperties, HTMLProps } from "react"; +import { Location, LocationDescriptor } from "react-router/lib/Router"; + +type ToLocationFunction = (location: Location) => LocationDescriptor; + +export interface IndexLinkProps extends HTMLProps { + to: LocationDescriptor | ToLocationFunction; + activeClassName?: string; + activeStyle?: CSSProperties; +} + +type IndexLink = ComponentClass; +declare const IndexLink: IndexLink; -declare const IndexLink: Link; export default IndexLink; - diff --git a/react-router/lib/IndexRedirect.d.ts b/react-router/lib/IndexRedirect.d.ts index 41dab299c8..3b8187d09b 100644 --- a/react-router/lib/IndexRedirect.d.ts +++ b/react-router/lib/IndexRedirect.d.ts @@ -1,17 +1,12 @@ -import Router from './Router'; -import * as React from 'react'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { RoutePattern, Query } from "react-router"; -declare const self: self.IndexRedirect; -type self = self.IndexRedirect; -export default self; - -declare namespace self { - interface IndexRedirectProps extends React.Props { - to: Router.RoutePattern; - query?: H.Query; - state?: H.LocationState; - } - interface IndexRedirectElement extends React.ReactElement { } - interface IndexRedirect extends React.ComponentClass { } +export interface IndexRedirectProps extends ClassAttributes { + to: RoutePattern; + query?: Query; } + +type IndexRedirect = ComponentClass; +declare const IndexRedirect: IndexRedirect; + +export default IndexRedirect; diff --git a/react-router/lib/IndexRoute.d.ts b/react-router/lib/IndexRoute.d.ts index b11b16d0e2..b0574df26a 100644 --- a/react-router/lib/IndexRoute.d.ts +++ b/react-router/lib/IndexRoute.d.ts @@ -1,20 +1,28 @@ -import * as React from 'react'; -import Router from './Router'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { LocationState } from "history"; +import { + EnterHook, + ChangeHook, + LeaveHook, + RouteComponent, + RouteComponents, + RouterState +} from "react-router"; -declare const self: self.IndexRoute; -type self = self.IndexRoute; -export default self; +type ComponentCallback = (err: any, component: RouteComponent) => void; +type ComponentsCallback = (err: any, components: RouteComponents) => void; -declare namespace self { - interface IndexRouteProps extends React.Props { - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (location: H.Location, cb: (error: any, component?: Router.RouteComponent) => void) => void; - getComponents?: (location: H.Location, cb: (error: any, components?: Router.RouteComponents) => void) => void; - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - } - interface IndexRoute extends React.ComponentClass { } - interface IndexRouteElement extends React.ReactElement { } -} \ No newline at end of file +export interface IndexRouteProps { + component?: RouteComponent; + components?: RouteComponents; + getComponent?(nextState: RouterState, callback: ComponentCallback): void; + getComponents?(nextState: RouterState, callback: ComponentsCallback): void; + onEnter?: EnterHook; + onChange?: ChangeHook; + onLeave?: LeaveHook; +} + +type IndexRoute = ComponentClass; +declare const IndexRoute: IndexRoute; + +export default IndexRoute; diff --git a/react-router/lib/Link.d.ts b/react-router/lib/Link.d.ts index d90578b9f9..eca6e66abd 100644 --- a/react-router/lib/Link.d.ts +++ b/react-router/lib/Link.d.ts @@ -1,19 +1,11 @@ -import * as React from 'react'; -import Router from './Router'; +import { ComponentClass, CSSProperties, HTMLProps } from "react"; +import { IndexLinkProps } from "react-router/lib/IndexLink"; +export interface LinkProps extends IndexLinkProps { + onlyActiveOnIndex?: boolean; +} + +type Link = ComponentClass; declare const Link: Link; -type Link = Link.Link; export default Link; - -declare namespace Link { - interface LinkProps extends React.HTMLAttributes { - activeStyle?: React.CSSProperties; - activeClassName?: string; - onlyActiveOnIndex?: boolean; - to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); - } - - interface Link extends React.ComponentClass {} - interface LinkElement extends React.ReactElement {} -} diff --git a/react-router/lib/PatternUtils.d.ts b/react-router/lib/PatternUtils.d.ts index 50e90f6e49..2c32b2a286 100644 --- a/react-router/lib/PatternUtils.d.ts +++ b/react-router/lib/PatternUtils.d.ts @@ -1 +1,3 @@ -export function formatPattern(pattern: string, params: {}): string; +import { RoutePattern } from "react-router"; + +export function formatPattern(pattern: RoutePattern, params: any): string; diff --git a/react-router/lib/PropTypes.d.ts b/react-router/lib/PropTypes.d.ts index bbd6431070..c9140777cb 100644 --- a/react-router/lib/PropTypes.d.ts +++ b/react-router/lib/PropTypes.d.ts @@ -1,19 +1,22 @@ -import * as React from 'react'; +import { Requireable, Validator } from "react"; -export function falsy(props: any, propName: string, componentName: string): Error; -export const history: React.Requireable; -export const location: React.Requireable; -export const component: React.Requireable; -export const components: React.Requireable; -export const route: React.Requireable; -export const routes: React.Requireable; +export interface RouterShape extends Validator { + push: Requireable; + replace: Requireable; + go: Requireable; + goBack: Requireable; + goForward: Requireable; + setRouteLeaveHook: Requireable; + isActive: Requireable; +} -export default { - falsy, - history, - location, - component, - components, - route -}; +export interface LocationShape extends Validator { + pathname: Requireable; + search: Requireable; + state: any; + action: Requireable; + key: any; +} +export const routerShape: RouterShape; +export const locationShape: LocationShape; diff --git a/react-router/lib/Redirect.d.ts b/react-router/lib/Redirect.d.ts index e09b576d53..bb8254b4f5 100644 --- a/react-router/lib/Redirect.d.ts +++ b/react-router/lib/Redirect.d.ts @@ -1,19 +1,12 @@ -import * as React from 'react'; -import Router from './Router'; -import * as H from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { RoutePattern, Query } from "react-router"; +import { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -declare const self: self.Redirect; -type self = typeof self; -export default self; - -declare namespace self { - interface RedirectProps extends React.Props { - path?: Router.RoutePattern; - from?: Router.RoutePattern; // alias for path - to: Router.RoutePattern; - query?: H.Query; - state?: H.LocationState; - } - interface Redirect extends React.ComponentClass { } - interface RedirectElement extends React.ReactElement { } +export interface RedirectProps extends IndexRedirectProps { + from: RoutePattern; } + +type Redirect = ComponentClass; +declare const Redirect: Redirect; + +export default Redirect; diff --git a/react-router/lib/Route.d.ts b/react-router/lib/Route.d.ts index 2f5425b55a..15aafebc75 100644 --- a/react-router/lib/Route.d.ts +++ b/react-router/lib/Route.d.ts @@ -1,25 +1,31 @@ -import * as React from 'react'; -import Router from './Router'; -import { Location } from 'history'; +import { ComponentClass, ClassAttributes } from "react"; +import { LocationState } from "history"; +import { + EnterHook, + ChangeHook, + LeaveHook, + RouteComponent, + RouteComponents, + RoutePattern, + RouterState +} from "react-router"; +import { IndexRouteProps } from "react-router/lib/IndexRoute"; -declare const self: self.Route; -type self = self.Route; -export default self; +export interface RouteProps extends IndexRouteProps { + path?: RoutePattern; +} -declare namespace self { +type Route = ComponentClass; +declare const Route: Route; - interface RouteProps extends React.Props { - path?: Router.RoutePattern; - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void - getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - onChange?: Router.ChangeHook; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; - } - interface Route extends React.ComponentClass {} - interface RouteElement extends React.ReactElement {} -} \ No newline at end of file +export default Route; + +type RouteCallback = (err: any, route: PlainRoute) => void; +type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; + +export interface PlainRoute extends RouteProps { + childRoutes?: PlainRoute[]; + getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; + indexRoute?: PlainRoute; + getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): void; +} diff --git a/react-router/lib/RouteUtils.d.ts b/react-router/lib/RouteUtils.d.ts index 7065056ff5..6304f5d7bf 100644 --- a/react-router/lib/RouteUtils.d.ts +++ b/react-router/lib/RouteUtils.d.ts @@ -1,8 +1,3 @@ -import * as React from 'react'; -import Router from './Router'; +import { RouteConfig, PlainRoute } from "react-router"; -type E = React.ReactElement; -export function isReactChildren(object: E | E[]): boolean; -export function createRouteFromReactElement(element: E): Router.PlainRoute; -export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[]; -export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[]; +export function createRoutes(routes: RouteConfig): PlainRoute[]; diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index a9c5417f47..160694953f 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -1,116 +1,106 @@ -import * as React from 'react'; -import RouterContext from './RouterContext'; +import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; import { - QueryString, Query, - Location, LocationDescriptor, LocationState as HLocationState, - History, Href, - Pathname, Path } from 'history'; + Hash, + History, + Href, + LocationKey, + LocationState, + Path, + Pathname, + Search +} from "history"; +import { PlainRoute } from "react-router"; +export type Basename = string; +export type Query = any; +export type Action = "PUSH" | "REPLACE" | "POP"; +export interface Params { + [key: string]: string; +} +export type RoutePattern = string; +export type RouteComponent = ComponentClass | StatelessComponent; +export interface RouteComponents { + [name: string]: RouteComponent; +} +export type RouteConfig = ReactNode | PlainRoute | PlainRoute[]; + +export type ParseQueryString = (queryString: Search) => Query; +export type StringifyQuery = (queryObject: Query) => Search; + +type AnyFunction = (...args: any[]) => any; + +export type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; +export type LeaveHook = (prevState: RouterState) => any; +export type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; +export type RouteHook = (nextLocation?: Location) => any; + +export interface Location { + patname: Pathname; + search: Search; + query: Query; + state: LocationState; + action: Action; + key: LocationKey; +} + +export interface LocationDescriptorObject { + pathname?: Pathname; + query?: Query; + hash?: Hash; + state?: LocationState; +} + +export type LocationDescriptor = Path | LocationDescriptorObject; + +export interface RedirectFunction { + (location: LocationDescriptor): void; + (state: LocationState, pathname: Pathname | Path, query?: Query): void; +} + +export interface RouterState { + location: Location; + routes: PlainRoute[]; + params: Params; + components: RouteComponent[]; +} + +type LocationFunction = (location: LocationDescriptor) => void; +type GoFunction = (n: number) => void; +type NavigateFunction = () => void; +type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean; +type LeaveHookFunction = (route: any, callback: RouteHook) => void; +type CreatePartFunction = (path: Path, query?: any) => Part; + +export interface InjectedRouter { + push: LocationFunction; + replace: LocationFunction; + go: GoFunction; + goBack: NavigateFunction; + goForward: NavigateFunction; + setRouteLeaveHook: LeaveHookFunction; + createPath: CreatePartFunction; + createHref: CreatePartFunction; + isActive: ActiveFunction; +} + +export interface RouteComponentProps { + location?: Location; + params?: P & R; + route?: PlainRoute; + router?: InjectedRouter; + routeParams?: R; +} + +export interface RouterProps extends ClassAttributes { + routes?: RouteConfig; + history?: History; + createElement?(component: RouteComponent, props: any): any; + onError?(error: any): any; + onUpdate?(): any; + render?(props: any): ReactNode; +} + +type Router = ComponentClass; declare const Router: Router; -interface Router extends React.ComponentClass { } export default Router; - -// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md - -declare namespace Router { - type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; - type RoutePattern = string; - type RouteComponents = { [key: string]: RouteComponent }; - - type ParseQueryString = (queryString: QueryString) => Query; - type StringifyQuery = (queryObject: Query) => QueryString; - - type Component = React.ReactType; - type RouteComponent = Component; - - type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; - type LeaveHook = () => void; - type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; - type RouteHook = (nextLocation?: Location) => any; - - type Params = { [param: string]: string }; - - type RouterListener = (error: Error, nextState: RouterState) => void; - - type LocationDescriptor = { - pathname?: Pathname - query?: Query - hash?: Href - state?: HLocationState - } - - interface RedirectFunction { - (location: LocationDescriptor): void; - /** - * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated - */ - (state: HLocationState, pathname: Pathname | Path, query?: Query): void; - } - - interface RouterState { - location: Location; - routes: PlainRoute[]; - params: Params; - components: RouteComponent[]; - } - - interface RouterProps extends React.Props { - history?: History; - routes?: RouteConfig; // alias for children - createElement?: (component: RouteComponent, props: Object) => any; - onError?: (error: any) => any; - onUpdate?: () => any; - parseQueryString?: ParseQueryString; - stringifyQuery?: StringifyQuery; - basename?: string; - render?: (renderProps: React.Props<{}>) => RouterContext; - } - - interface PlainRoute { - path?: RoutePattern; - component?: RouteComponent; - components?: RouteComponents; - getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; - getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; - onEnter?: EnterHook; - onLeave?: LeaveHook; - indexRoute?: PlainRoute; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; - childRoutes?: PlainRoute[]; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; - } - - interface RouteComponentProps { - history?: History; - location?: Location; - params?: P; - route?: PlainRoute; - routeParams?: R; - routes?: PlainRoute[]; - children?: React.ReactElement; - } - - interface RouterOnContext extends History { - setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; - isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; - } - - // Wrap a component using withRouter(Component) to provide a router object - // to the Component's props, allowing the Component to programmatically call - // push and other functions. - // - // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md - - interface InjectedRouter { - push: (pathOrLoc: Path | LocationDescriptor) => void - replace: (pathOrLoc: Path | LocationDescriptor) => void - go: (n: number) => void - goBack: () => void - goForward: () => void - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void - createPath(path: History.Path, query?: History.Query): History.Path - createHref(path: History.Path, query?: History.Query): History.Href - isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean - } -} diff --git a/react-router/lib/RouterContext.d.ts b/react-router/lib/RouterContext.d.ts index b6eab5831c..b04e6e01ae 100644 --- a/react-router/lib/RouterContext.d.ts +++ b/react-router/lib/RouterContext.d.ts @@ -1,25 +1,6 @@ -import * as React from 'react'; -import * as H from 'history'; -import Router from './Router'; +import { ComponentClass } from "react"; -declare const self: self.RouterContext; -type self = self.RouterContext; -export default self; +type RouterContext = ComponentClass; +declare const RouterContext: RouterContext; -declare namespace self { - interface RouterContextProps extends React.Props { - history?: H.History; - router: Router; - createElement: (component: Router.RouteComponent, props: Object) => any; - location: H.Location; - routes: Router.RouteConfig; - params: Router.Params; - components?: Router.RouteComponent[]; - } - interface RouterContext extends React.ComponentClass {} - interface RouterContextElement extends React.ReactElement { - history?: H.History; - location: H.Location; - router?: Router; - } -} \ No newline at end of file +export default RouterContext; diff --git a/react-router/lib/applyRouterMiddleware.d.ts b/react-router/lib/applyRouterMiddleware.d.ts index ed87d815db..e4d023a792 100644 --- a/react-router/lib/applyRouterMiddleware.d.ts +++ b/react-router/lib/applyRouterMiddleware.d.ts @@ -1,9 +1,9 @@ -import * as React from 'react'; -import Router from './Router'; -import RouterContext from './RouterContext'; +import { RouteComponent } from "react-router"; +import RouterContext from "react-router/lib/RouterContext"; export interface Middleware { - renderRouterContext?: (previous: RouterContext, props: React.Props<{}>) => RouterContext; - renderRouteComponent?: (previous: Router.RouteComponent, props: React.Props<{}>) => Router.RouteComponent; + renderRouterContext?: (previous: RouterContext, props: any) => RouterContext; + renderRouteComponent?: (previous: RouteComponent, props: any) => RouteComponent; } -export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => RouterContext; + +export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: any) => RouterContext; diff --git a/react-router/lib/browserHistory.d.ts b/react-router/lib/browserHistory.d.ts index aabbdc23f9..8f45db6412 100644 --- a/react-router/lib/browserHistory.d.ts +++ b/react-router/lib/browserHistory.d.ts @@ -1,3 +1,5 @@ -import { History } from './routerHistory'; +import { History } from "history"; + declare const browserHistory: History; + export default browserHistory; diff --git a/react-router/lib/createMemoryHistory.d.ts b/react-router/lib/createMemoryHistory.d.ts index 5df481bfa1..bb2fed561b 100644 --- a/react-router/lib/createMemoryHistory.d.ts +++ b/react-router/lib/createMemoryHistory.d.ts @@ -1,3 +1,5 @@ -import * as H from 'history'; +import { History, CreateHistory } from "history"; -export default function createMemoryHistory(options?: H.HistoryOptions): H.History; \ No newline at end of file +declare const createMemoryHistory: CreateHistory; + +export default createMemoryHistory; diff --git a/react-router/lib/hashHistory.d.ts b/react-router/lib/hashHistory.d.ts index 79f89c2f1a..6a17e65af9 100644 --- a/react-router/lib/hashHistory.d.ts +++ b/react-router/lib/hashHistory.d.ts @@ -1,3 +1,5 @@ -import { History } from './routerHistory'; +import { History } from "history"; + declare const hashHistory: History; + export default hashHistory; diff --git a/react-router/lib/match.d.ts b/react-router/lib/match.d.ts index e311ea69df..bc5af4fda8 100644 --- a/react-router/lib/match.d.ts +++ b/react-router/lib/match.d.ts @@ -1,17 +1,16 @@ -import * as H from 'history'; -import Router from './Router'; +import { History } from "history"; +import { Basename, LocationDescriptor, ParseQueryString, RouteConfig, StringifyQuery } from "react-router"; interface MatchArgs { - routes?: Router.RouteConfig; - history?: H.History; - location?: H.Location | string; - parseQueryString?: Router.ParseQueryString; - stringifyQuery?: Router.StringifyQuery; + routes: RouteConfig; + location: LocationDescriptor; + history?: History; + basename?: Basename; + parseQueryString?: ParseQueryString; + stringifyQuery?: StringifyQuery; } -interface MatchState extends Router.RouterState { - history: H.History; - router: Router; - createElement: (component: Router.RouteComponent, props: Object) => any; -} -export default function match(args: MatchArgs, cb: (error: any, nextLocation: H.Location, nextState: MatchState) => void): void; + +export type MatchCallback = (error: any, redirectLocation: Location, renderProps: any) => void; + +export default function match(args: MatchArgs, cb: MatchCallback): void; diff --git a/react-router/lib/useRouterHistory.d.ts b/react-router/lib/useRouterHistory.d.ts index d3e043b609..1371baa07b 100644 --- a/react-router/lib/useRouterHistory.d.ts +++ b/react-router/lib/useRouterHistory.d.ts @@ -1,7 +1,5 @@ -import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; +import { History, CreateHistoryEnhancer } from "history"; -interface CreateRouterHistory { - (options?: HistoryOptions): History & HistoryQueries; -} +declare const useRouterHistory: CreateHistoryEnhancer; -export default function useRouterHistory(createHistory: CreateHistory): CreateRouterHistory; +export default useRouterHistory; diff --git a/react-router/lib/withRouter.d.ts b/react-router/lib/withRouter.d.ts index f698d94fd0..25f9d357c7 100644 --- a/react-router/lib/withRouter.d.ts +++ b/react-router/lib/withRouter.d.ts @@ -1,4 +1,9 @@ -import * as React from 'react'; +import { ComponentClass, StatelessComponent } from "react"; -declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C -export default withRouter; +interface Options { + withRef?: boolean; +} + +type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export default function withRouter

(component: ComponentConstructor

, options?: Options): ComponentClass

; diff --git a/react-router/react-router-tests.tsx b/react-router/react-router-tests.tsx index 6c83ca180a..dda05ef9d8 100644 --- a/react-router/react-router-tests.tsx +++ b/react-router/react-router-tests.tsx @@ -1,22 +1,39 @@ -import * as React from "react" -import * as ReactDOM from "react-dom" -import {renderToString} from "react-dom/server"; +import * as React from "react"; +import { Component, ValidationMap } from "react"; +import * as ReactDOM from "react-dom"; +import { renderToString } from "react-dom/server"; -import { applyRouterMiddleware, browserHistory, hashHistory, match, createMemoryHistory, withRouter, routerShape, Router, Route, IndexRoute, InjectedRouter, Link, RouterOnContext, RouterContext, LinkProps} from "react-router"; +import { + applyRouterMiddleware, + browserHistory, + hashHistory, + match, + createMemoryHistory, + withRouter, + routerShape, + Router, + Route, + IndexRoute, + InjectedRouter, + Link, + RouterContext, + LinkProps +} from "react-router"; const NavLink = (props: LinkProps) => ( ) interface MasterContext { - router: RouterOnContext; + router: InjectedRouter; } -class Master extends React.Component, {}> { +class Master extends Component { - static contextTypes: React.ValidationMap = { - router: routerShape + static contextTypes: ValidationMap = { + "router": routerShape }; + context: MasterContext; navigate() { diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index d887e5e5ec..47b5b439bf 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -11,9 +11,6 @@ "strictNullChecks": false, "jsx": "react", "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], diff --git a/react-router/v2/index.d.ts b/react-router/v2/index.d.ts new file mode 100644 index 0000000000..59f33e1960 --- /dev/null +++ b/react-router/v2/index.d.ts @@ -0,0 +1,91 @@ +// Type definitions for react-router v2.0.0 +// Project: https://github.com/rackt/react-router +// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export as namespace ReactRouter; + +import * as React from 'react'; + +export const routerShape: React.Requireable + +export const locationShape: React.Requireable + +import Router from "./lib/Router"; +import Link from "./lib/Link"; +import IndexLink from "./lib/IndexLink"; +import IndexRedirect from "./lib/IndexRedirect"; +import IndexRoute from "./lib/IndexRoute"; +import Redirect from "./lib/Redirect"; +import Route from "./lib/Route"; +import * as History from "./lib/routerHistory"; +import Lifecycle from "./lib/Lifecycle"; +import RouteContext from "./lib/RouteContext"; +import browserHistory from "./lib/browserHistory"; +import hashHistory from "./lib/hashHistory"; +import useRoutes from "./lib/useRoutes"; +import { createRoutes } from "./lib/RouteUtils"; +import { formatPattern } from "./lib/PatternUtils"; +import RouterContext from "./lib/RouterContext"; +import PropTypes from "./lib/PropTypes"; +import match from "./lib/match"; +import useRouterHistory from "./lib/useRouterHistory"; +import createMemoryHistory from "./lib/createMemoryHistory"; +import withRouter from "./lib/withRouter"; +import applyRouterMiddleware from "./lib/applyRouterMiddleware"; + +// PlainRoute is defined in the API documented at: +// https://github.com/rackt/react-router/blob/master/docs/API.md +// but not included in any of the .../lib modules above. +export type PlainRoute = Router.PlainRoute; + +// The following definitions are also very useful to export +// because by using these types lots of potential type errors +// can be exposed: +export type EnterHook = Router.EnterHook; +export type LeaveHook = Router.LeaveHook; +export type ParseQueryString = Router.ParseQueryString; +export type LocationDescriptor = Router.LocationDescriptor; +export type RedirectFunction = Router.RedirectFunction; +export type RouteComponent = Router.RouteComponent; +export type RouteComponentProps = Router.RouteComponentProps; +export type RouteConfig = Router.RouteConfig; +export type RouteHook = Router.RouteHook; +export type StringifyQuery = Router.StringifyQuery; +export type RouterListener = Router.RouterListener; +export type RouterState = Router.RouterState; +export type InjectedRouter = Router.InjectedRouter; + +export type HistoryBase = History.HistoryBase; +export type RouterOnContext = Router.RouterOnContext; +export type RouteProps = Route.RouteProps; +export type LinkProps = Link.LinkProps; + +export { + Router, + Link, + IndexLink, + IndexRedirect, + IndexRoute, + Redirect, + Route, + History, + browserHistory, + hashHistory, + Lifecycle, + RouteContext, + useRoutes, + createRoutes, + formatPattern, + RouterContext, + PropTypes, + match, + useRouterHistory, + createMemoryHistory, + withRouter, + applyRouterMiddleware +}; + +export default Router; diff --git a/react-router/v2/lib/IndexLink.d.ts b/react-router/v2/lib/IndexLink.d.ts new file mode 100644 index 0000000000..56ecf82c1d --- /dev/null +++ b/react-router/v2/lib/IndexLink.d.ts @@ -0,0 +1,5 @@ +import Link from './Link'; + +declare const IndexLink: Link; +export default IndexLink; + diff --git a/react-router/v2/lib/IndexRedirect.d.ts b/react-router/v2/lib/IndexRedirect.d.ts new file mode 100644 index 0000000000..41dab299c8 --- /dev/null +++ b/react-router/v2/lib/IndexRedirect.d.ts @@ -0,0 +1,17 @@ +import Router from './Router'; +import * as React from 'react'; +import * as H from 'history'; + +declare const self: self.IndexRedirect; +type self = self.IndexRedirect; +export default self; + +declare namespace self { + interface IndexRedirectProps extends React.Props { + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface IndexRedirectElement extends React.ReactElement { } + interface IndexRedirect extends React.ComponentClass { } +} diff --git a/react-router/v2/lib/IndexRoute.d.ts b/react-router/v2/lib/IndexRoute.d.ts new file mode 100644 index 0000000000..b11b16d0e2 --- /dev/null +++ b/react-router/v2/lib/IndexRoute.d.ts @@ -0,0 +1,20 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.IndexRoute; +type self = self.IndexRoute; +export default self; + +declare namespace self { + interface IndexRouteProps extends React.Props { + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (location: H.Location, cb: (error: any, component?: Router.RouteComponent) => void) => void; + getComponents?: (location: H.Location, cb: (error: any, components?: Router.RouteComponents) => void) => void; + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + } + interface IndexRoute extends React.ComponentClass { } + interface IndexRouteElement extends React.ReactElement { } +} \ No newline at end of file diff --git a/react-router/lib/Lifecycle.d.ts b/react-router/v2/lib/Lifecycle.d.ts similarity index 100% rename from react-router/lib/Lifecycle.d.ts rename to react-router/v2/lib/Lifecycle.d.ts diff --git a/react-router/v2/lib/Link.d.ts b/react-router/v2/lib/Link.d.ts new file mode 100644 index 0000000000..d90578b9f9 --- /dev/null +++ b/react-router/v2/lib/Link.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; + +declare const Link: Link; +type Link = Link.Link; + +export default Link; + +declare namespace Link { + interface LinkProps extends React.HTMLAttributes { + activeStyle?: React.CSSProperties; + activeClassName?: string; + onlyActiveOnIndex?: boolean; + to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); + } + + interface Link extends React.ComponentClass {} + interface LinkElement extends React.ReactElement {} +} diff --git a/react-router/v2/lib/PatternUtils.d.ts b/react-router/v2/lib/PatternUtils.d.ts new file mode 100644 index 0000000000..50e90f6e49 --- /dev/null +++ b/react-router/v2/lib/PatternUtils.d.ts @@ -0,0 +1 @@ +export function formatPattern(pattern: string, params: {}): string; diff --git a/react-router/v2/lib/PropTypes.d.ts b/react-router/v2/lib/PropTypes.d.ts new file mode 100644 index 0000000000..bbd6431070 --- /dev/null +++ b/react-router/v2/lib/PropTypes.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; + +export function falsy(props: any, propName: string, componentName: string): Error; +export const history: React.Requireable; +export const location: React.Requireable; +export const component: React.Requireable; +export const components: React.Requireable; +export const route: React.Requireable; +export const routes: React.Requireable; + +export default { + falsy, + history, + location, + component, + components, + route +}; + diff --git a/react-router/v2/lib/Redirect.d.ts b/react-router/v2/lib/Redirect.d.ts new file mode 100644 index 0000000000..e09b576d53 --- /dev/null +++ b/react-router/v2/lib/Redirect.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import Router from './Router'; +import * as H from 'history'; + +declare const self: self.Redirect; +type self = typeof self; +export default self; + +declare namespace self { + interface RedirectProps extends React.Props { + path?: Router.RoutePattern; + from?: Router.RoutePattern; // alias for path + to: Router.RoutePattern; + query?: H.Query; + state?: H.LocationState; + } + interface Redirect extends React.ComponentClass { } + interface RedirectElement extends React.ReactElement { } +} diff --git a/react-router/v2/lib/Route.d.ts b/react-router/v2/lib/Route.d.ts new file mode 100644 index 0000000000..2f5425b55a --- /dev/null +++ b/react-router/v2/lib/Route.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import Router from './Router'; +import { Location } from 'history'; + +declare const self: self.Route; +type self = self.Route; +export default self; + +declare namespace self { + + interface RouteProps extends React.Props { + path?: Router.RoutePattern; + component?: Router.RouteComponent; + components?: Router.RouteComponents; + getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void + getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void + onEnter?: Router.EnterHook; + onLeave?: Router.LeaveHook; + onChange?: Router.ChangeHook; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; + } + interface Route extends React.ComponentClass {} + interface RouteElement extends React.ReactElement {} +} \ No newline at end of file diff --git a/react-router/lib/RouteContext.d.ts b/react-router/v2/lib/RouteContext.d.ts similarity index 100% rename from react-router/lib/RouteContext.d.ts rename to react-router/v2/lib/RouteContext.d.ts diff --git a/react-router/v2/lib/RouteUtils.d.ts b/react-router/v2/lib/RouteUtils.d.ts new file mode 100644 index 0000000000..7065056ff5 --- /dev/null +++ b/react-router/v2/lib/RouteUtils.d.ts @@ -0,0 +1,8 @@ +import * as React from 'react'; +import Router from './Router'; + +type E = React.ReactElement; +export function isReactChildren(object: E | E[]): boolean; +export function createRouteFromReactElement(element: E): Router.PlainRoute; +export function createRoutesFromReactChildren(children: E | E[], parentRoute: Router.PlainRoute): Router.PlainRoute[]; +export function createRoutes(routes: Router.RouteConfig): Router.PlainRoute[]; diff --git a/react-router/v2/lib/Router.d.ts b/react-router/v2/lib/Router.d.ts new file mode 100644 index 0000000000..a9c5417f47 --- /dev/null +++ b/react-router/v2/lib/Router.d.ts @@ -0,0 +1,116 @@ +import * as React from 'react'; +import RouterContext from './RouterContext'; +import { + QueryString, Query, + Location, LocationDescriptor, LocationState as HLocationState, + History, Href, + Pathname, Path } from 'history'; + +declare const Router: Router; +interface Router extends React.ComponentClass { } + +export default Router; + +// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md + +declare namespace Router { + type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; + type RoutePattern = string; + type RouteComponents = { [key: string]: RouteComponent }; + + type ParseQueryString = (queryString: QueryString) => Query; + type StringifyQuery = (queryObject: Query) => QueryString; + + type Component = React.ReactType; + type RouteComponent = Component; + + type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; + type LeaveHook = () => void; + type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; + type RouteHook = (nextLocation?: Location) => any; + + type Params = { [param: string]: string }; + + type RouterListener = (error: Error, nextState: RouterState) => void; + + type LocationDescriptor = { + pathname?: Pathname + query?: Query + hash?: Href + state?: HLocationState + } + + interface RedirectFunction { + (location: LocationDescriptor): void; + /** + * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated + */ + (state: HLocationState, pathname: Pathname | Path, query?: Query): void; + } + + interface RouterState { + location: Location; + routes: PlainRoute[]; + params: Params; + components: RouteComponent[]; + } + + interface RouterProps extends React.Props { + history?: History; + routes?: RouteConfig; // alias for children + createElement?: (component: RouteComponent, props: Object) => any; + onError?: (error: any) => any; + onUpdate?: () => any; + parseQueryString?: ParseQueryString; + stringifyQuery?: StringifyQuery; + basename?: string; + render?: (renderProps: React.Props<{}>) => RouterContext; + } + + interface PlainRoute { + path?: RoutePattern; + component?: RouteComponent; + components?: RouteComponents; + getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; + getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; + onEnter?: EnterHook; + onLeave?: LeaveHook; + indexRoute?: PlainRoute; + getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; + childRoutes?: PlainRoute[]; + getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; + } + + interface RouteComponentProps { + history?: History; + location?: Location; + params?: P; + route?: PlainRoute; + routeParams?: R; + routes?: PlainRoute[]; + children?: React.ReactElement; + } + + interface RouterOnContext extends History { + setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; + isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; + } + + // Wrap a component using withRouter(Component) to provide a router object + // to the Component's props, allowing the Component to programmatically call + // push and other functions. + // + // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md + + interface InjectedRouter { + push: (pathOrLoc: Path | LocationDescriptor) => void + replace: (pathOrLoc: Path | LocationDescriptor) => void + go: (n: number) => void + goBack: () => void + goForward: () => void + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void + createPath(path: History.Path, query?: History.Query): History.Path + createHref(path: History.Path, query?: History.Query): History.Href + isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean + } +} diff --git a/react-router/v2/lib/RouterContext.d.ts b/react-router/v2/lib/RouterContext.d.ts new file mode 100644 index 0000000000..b6eab5831c --- /dev/null +++ b/react-router/v2/lib/RouterContext.d.ts @@ -0,0 +1,25 @@ +import * as React from 'react'; +import * as H from 'history'; +import Router from './Router'; + +declare const self: self.RouterContext; +type self = self.RouterContext; +export default self; + +declare namespace self { + interface RouterContextProps extends React.Props { + history?: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; + location: H.Location; + routes: Router.RouteConfig; + params: Router.Params; + components?: Router.RouteComponent[]; + } + interface RouterContext extends React.ComponentClass {} + interface RouterContextElement extends React.ReactElement { + history?: H.History; + location: H.Location; + router?: Router; + } +} \ No newline at end of file diff --git a/react-router/v2/lib/applyRouterMiddleware.d.ts b/react-router/v2/lib/applyRouterMiddleware.d.ts new file mode 100644 index 0000000000..ed87d815db --- /dev/null +++ b/react-router/v2/lib/applyRouterMiddleware.d.ts @@ -0,0 +1,9 @@ +import * as React from 'react'; +import Router from './Router'; +import RouterContext from './RouterContext'; + +export interface Middleware { + renderRouterContext?: (previous: RouterContext, props: React.Props<{}>) => RouterContext; + renderRouteComponent?: (previous: Router.RouteComponent, props: React.Props<{}>) => Router.RouteComponent; +} +export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => RouterContext; diff --git a/react-router/v2/lib/browserHistory.d.ts b/react-router/v2/lib/browserHistory.d.ts new file mode 100644 index 0000000000..aabbdc23f9 --- /dev/null +++ b/react-router/v2/lib/browserHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const browserHistory: History; +export default browserHistory; diff --git a/react-router/v2/lib/createMemoryHistory.d.ts b/react-router/v2/lib/createMemoryHistory.d.ts new file mode 100644 index 0000000000..5df481bfa1 --- /dev/null +++ b/react-router/v2/lib/createMemoryHistory.d.ts @@ -0,0 +1,3 @@ +import * as H from 'history'; + +export default function createMemoryHistory(options?: H.HistoryOptions): H.History; \ No newline at end of file diff --git a/react-router/v2/lib/hashHistory.d.ts b/react-router/v2/lib/hashHistory.d.ts new file mode 100644 index 0000000000..79f89c2f1a --- /dev/null +++ b/react-router/v2/lib/hashHistory.d.ts @@ -0,0 +1,3 @@ +import { History } from './routerHistory'; +declare const hashHistory: History; +export default hashHistory; diff --git a/react-router/v2/lib/match.d.ts b/react-router/v2/lib/match.d.ts new file mode 100644 index 0000000000..e311ea69df --- /dev/null +++ b/react-router/v2/lib/match.d.ts @@ -0,0 +1,17 @@ +import * as H from 'history'; +import Router from './Router'; + +interface MatchArgs { + routes?: Router.RouteConfig; + history?: H.History; + location?: H.Location | string; + parseQueryString?: Router.ParseQueryString; + stringifyQuery?: Router.StringifyQuery; +} +interface MatchState extends Router.RouterState { + history: H.History; + router: Router; + createElement: (component: Router.RouteComponent, props: Object) => any; +} +export default function match(args: MatchArgs, cb: (error: any, nextLocation: H.Location, nextState: MatchState) => void): void; + diff --git a/react-router/lib/routerHistory.d.ts b/react-router/v2/lib/routerHistory.d.ts similarity index 100% rename from react-router/lib/routerHistory.d.ts rename to react-router/v2/lib/routerHistory.d.ts diff --git a/react-router/v2/lib/useRouterHistory.d.ts b/react-router/v2/lib/useRouterHistory.d.ts new file mode 100644 index 0000000000..d3e043b609 --- /dev/null +++ b/react-router/v2/lib/useRouterHistory.d.ts @@ -0,0 +1,7 @@ +import { History, HistoryOptions, HistoryQueries, CreateHistory } from 'history'; + +interface CreateRouterHistory { + (options?: HistoryOptions): History & HistoryQueries; +} + +export default function useRouterHistory(createHistory: CreateHistory): CreateRouterHistory; diff --git a/react-router/lib/useRoutes.d.ts b/react-router/v2/lib/useRoutes.d.ts similarity index 100% rename from react-router/lib/useRoutes.d.ts rename to react-router/v2/lib/useRoutes.d.ts diff --git a/react-router/v2/lib/withRouter.d.ts b/react-router/v2/lib/withRouter.d.ts new file mode 100644 index 0000000000..f698d94fd0 --- /dev/null +++ b/react-router/v2/lib/withRouter.d.ts @@ -0,0 +1,4 @@ +import * as React from 'react'; + +declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C +export default withRouter; From 61af45367251ddb146a5c483f4cb2e6e88883868 Mon Sep 17 00:00:00 2001 From: Hutson Betts Date: Tue, 17 Jan 2017 14:03:06 -0600 Subject: [PATCH 030/306] fix(mocha): add index definition Add index definition to IHookCallbackContext to support Mocha's built-in context shared between setup, tear-down, and test cases. Context is Mocha's support for Shared Behaviors (https://github.com/mochajs/mocha/wiki/Shared-Behaviours) --- mocha/index.d.ts | 2 ++ mocha/mocha-tests.ts | 58 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/mocha/index.d.ts b/mocha/index.d.ts index 9ac84fa097..ec6fc5e142 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -118,6 +118,7 @@ declare namespace Mocha { interface IHookCallbackContext { skip(): void; timeout(ms: number): void; + [index: string]: any; } @@ -126,6 +127,7 @@ declare namespace Mocha { timeout(ms: number): void; retries(n: number): void; slow(ms: number): void; + [index: string]: any; } /** Partial interface for Mocha's `Runnable` class. */ diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index fc17a18221..8e8dc0d938 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -47,6 +47,8 @@ function test_it() { it('does something', () => { }); + it('does something', function () { this['sharedState'] = true; }); + it('does something', (done) => { done(); }); it.only('does something', () => { }); @@ -64,6 +66,8 @@ function test_test() { test('does something', () => { }); + test('does something', function () { this['sharedState'] = true; }); + test('does something', (done) => { done(); }); test.only('does something', () => { }); @@ -81,6 +85,8 @@ function test_specify() { specify('does something', () => { }); + specify('does something', function () { this['sharedState'] = true; }); + specify('does something', (done) => { done(); }); specify.only('does something', () => { }); @@ -97,6 +103,8 @@ function test_specify() { function test_before() { before(() => { }); + before(function () { this['sharedState'] = true; }); + before((done) => { done(); }); before("my description", () => { }); @@ -120,6 +128,17 @@ function test_setup() { string = this.currentTest.state; }); + setup(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + setup(function (done) { done(); boolean = this.currentTest.async; @@ -135,6 +154,8 @@ function test_setup() { function test_after() { after(() => { }); + after(function () { this['sharedState'] = true; }); + after((done) => { done(); }); after("my description", () => { }); @@ -153,6 +174,17 @@ function test_teardown() { string = this.currentTest.state; }); + teardown(function() { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + teardown(function(done) { done(); boolean = this.currentTest.async; @@ -176,6 +208,17 @@ function test_beforeEach() { string = this.currentTest.state; }); + beforeEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + beforeEach(function (done) { done(); boolean = this.currentTest.async; @@ -212,6 +255,8 @@ function test_beforeEach() { function test_suiteSetup() { suiteSetup(() => { }); + suiteSetup(function () { this['sharedState'] = true; }); + suiteSetup((done) => { done(); }); } @@ -226,6 +271,17 @@ function test_afterEach() { string = this.currentTest.state; }); + afterEach(function () { + this['sharedState'] = true; + boolean = this.currentTest.async; + boolean = this.currentTest.pending; + boolean = this.currentTest.sync; + boolean = this.currentTest.timedOut; + string = this.currentTest.title; + string = this.currentTest.fullTitle(); + string = this.currentTest.state; + }); + afterEach(function (done) { done(); boolean = this.currentTest.async; @@ -263,6 +319,8 @@ function test_afterEach() { function test_suiteTeardown() { suiteTeardown(() => { }); + suiteTeardown(function () { this['sharedState'] = true; }); + suiteTeardown((done) => { done(); }); } From 42e178120b56f2bd1ec20fb1075f9b709ca68f13 Mon Sep 17 00:00:00 2001 From: Marco Arruda Date: Tue, 17 Jan 2017 20:20:21 -0200 Subject: [PATCH 031/306] get actionlib servers --- roslib/index.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/roslib/index.d.ts b/roslib/index.d.ts index fbb6deff6e..14fe2c1e3e 100644 --- a/roslib/index.d.ts +++ b/roslib/index.d.ts @@ -66,6 +66,16 @@ declare namespace ROSLIB { */ callOnConnection(message:any):void; + /** + * Retrieves list of actionlib servers in ROS as an array. + * + * @param callback function with params: + * * action_servers - Array of actionlib servers names + * @param failedCallback - the callback function when the ros call failed (optional). Params: + * * error - the error message reported by ROS + */ + getActionServers(callback:(action_servers:string[]) => void, failedCallback?:(error:any)=>void):void; + /** * Retrieves list of topics in ROS as an array. * From 9f396a35febe9d229c876d8cbeca26627594a604 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Wed, 18 Jan 2017 17:09:27 +0100 Subject: [PATCH 032/306] Add "tslint.json" file. Replace "major.minor.build" by "major.minor". --- express-rate-limit/index.d.ts | 2 +- express-rate-limit/tsconfig.json | 38 +++++++++++++++++--------------- express-rate-limit/tslint.json | 1 + shipit-utils/index.d.ts | 2 +- shipit-utils/tsconfig.json | 38 +++++++++++++++++--------------- shipit-utils/tslint.json | 1 + shipit/index.d.ts | 2 +- shipit/tsconfig.json | 38 +++++++++++++++++--------------- shipit/tslint.json | 1 + 9 files changed, 66 insertions(+), 57 deletions(-) create mode 100644 express-rate-limit/tslint.json create mode 100644 shipit-utils/tslint.json create mode 100644 shipit/tslint.json diff --git a/express-rate-limit/index.d.ts b/express-rate-limit/index.d.ts index 57eb003694..07cb5853a5 100644 --- a/express-rate-limit/index.d.ts +++ b/express-rate-limit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for express-rate-limit 2.6.0 +// Type definitions for express-rate-limit 2.6 // Project: https://github.com/nfriedly/express-rate-limit // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/express-rate-limit/tsconfig.json b/express-rate-limit/tsconfig.json index 560edfef9d..ca3c32c3bb 100644 --- a/express-rate-limit/tsconfig.json +++ b/express-rate-limit/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "express-rate-limit-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-rate-limit-tests.ts" + ] } diff --git a/express-rate-limit/tslint.json b/express-rate-limit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/express-rate-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/shipit-utils/index.d.ts b/shipit-utils/index.d.ts index a66b681c37..63df44974f 100644 --- a/shipit-utils/index.d.ts +++ b/shipit-utils/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for shipit-utils 1.4.0 +// Type definitions for shipit-utils 1.4 // Project: https://github.com/shipitjs/shipit-utils // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/shipit-utils/tsconfig.json b/shipit-utils/tsconfig.json index fa4b1ce3b6..d2fdb45d17 100644 --- a/shipit-utils/tsconfig.json +++ b/shipit-utils/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "shipit-utils-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-utils-tests.ts" + ] } diff --git a/shipit-utils/tslint.json b/shipit-utils/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit-utils/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/shipit/index.d.ts b/shipit/index.d.ts index ab44d7abd8..7b153ae197 100644 --- a/shipit/index.d.ts +++ b/shipit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for shipit-cli 1.5.1 +// Type definitions for shipit-cli 1.5 // Project: https://github.com/shipitjs/shipit // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/shipit/tsconfig.json b/shipit/tsconfig.json index 254ac2d9a5..17049e7271 100644 --- a/shipit/tsconfig.json +++ b/shipit/tsconfig.json @@ -1,20 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "shipit-tests.ts" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shipit-tests.ts" + ] } diff --git a/shipit/tslint.json b/shipit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/shipit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 65701d7b2b3d60b309a7acd2fda6c10d2a77aec1 Mon Sep 17 00:00:00 2001 From: Pablo Moleri Date: Wed, 18 Jan 2017 14:03:23 -0300 Subject: [PATCH 033/306] Fix getLocation return type Also renamed GeoLocation type because it was being merged with Location type. --- webdriverio/index.d.ts | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/webdriverio/index.d.ts b/webdriverio/index.d.ts index fbc6925fa9..f033ec2bfc 100644 --- a/webdriverio/index.d.ts +++ b/webdriverio/index.d.ts @@ -352,36 +352,37 @@ declare namespace WebdriverIO { ): Client

; getHTML

(includeSelectorTag: boolean): Client

; - getLocation(selector?: string): Size; - getLocation(selector: string, axis: string): number; - getLocation(axis: string): number; + getLocation(selector?: string): Location; + getLocation(selector: string, axis: Axis): number; + getLocation(axis: Axis): number; getLocation

(selector?: string): Client

; getLocation

( selector: string, - axis: string + axis: Axis ): Client

; - getLocation

(axis: string): Client

; + getLocation

(axis: Axis): Client

; - getLocationInView(selector: string): Size; - getLocationInView(selector: string): Size[]; - getLocationInView(): Size; - getLocationInView(): Size[]; + getLocationInView(selector: string): Location; + getLocationInView(selector: string): Location[]; + getLocationInView(): Location; + getLocationInView(): Location[]; getLocationInView( selector: string, - axis: string + axis: Axis ): number; getLocationInView( selector: string, - axis: string + axis: Axis ): number[]; - getLocationInView(axis: string): number; - getLocationInView(axis: string): number[]; + getLocationInView(axis: Axis): number; + getLocationInView(axis: Axis): number[]; getLocationInView

(selector?: string): Client

; getLocationInView

( selector: string, - axis: string + axis: Axis ): Client

; - getLocationInView

(axis: string): Client

; + getLocationInView

(axis: Axis): Client

; + getSource(): Client; getSource

(): Client

; @@ -428,7 +429,7 @@ declare namespace WebdriverIO { value: any; } - export interface Location { + export interface GeoLocation { latitude: number; longitude: number; altitude: number; @@ -983,6 +984,8 @@ declare namespace WebdriverIO { switchTab

(windowHandle?: string): Client

; } + export type Axis = "x" | "y"; + export interface Options { protocol: string; waitforTimeout: number; From b033ae77a87c91fb93f351a29088e3806aa55b12 Mon Sep 17 00:00:00 2001 From: Andrew Zheng Date: Wed, 18 Jan 2017 15:14:17 -0800 Subject: [PATCH 034/306] Add optional parameter to verifyNoOutstandingExpectation() --- angular-mocks/angular-mocks-tests.ts | 1 + angular-mocks/index.d.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/angular-mocks/angular-mocks-tests.ts b/angular-mocks/angular-mocks-tests.ts index 8ea42e4122..cabbf7c578 100644 --- a/angular-mocks/angular-mocks-tests.ts +++ b/angular-mocks/angular-mocks-tests.ts @@ -118,6 +118,7 @@ httpBackendService.flush(); httpBackendService.flush(1234); httpBackendService.resetExpectations(); httpBackendService.verifyNoOutstandingExpectation(); +httpBackendService.verifyNoOutstandingExpectation(false); httpBackendService.verifyNoOutstandingRequest(); requestHandler = httpBackendService.expect('GET', 'http://test.local'); diff --git a/angular-mocks/index.d.ts b/angular-mocks/index.d.ts index ddded4d0a8..767eb65f04 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -132,8 +132,9 @@ declare module 'angular' { /** * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. + * @param digest Do digest before checking expectation. Pass anything expect false to trigger digest. */ - verifyNoOutstandingExpectation(): void; + verifyNoOutstandingExpectation(digest?: boolean): void; /** * Verifies that there are no outstanding requests that need to be flushed. From d11a1c562bae120d910d3542552285e5a142fbb1 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 09:46:36 +0900 Subject: [PATCH 035/306] Update some definitions based on history v2 --- react-router/index.d.ts | 13 +++++++++++++ react-router/lib/Router.d.ts | 4 +++- react-router/lib/createMemoryHistory.d.ts | 3 ++- react-router/lib/useRouterHistory.d.ts | 5 +++-- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 8398838aef..2b10a4cbcb 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -3,6 +3,19 @@ // Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/* Replacement from old history definitions */ +export interface HistoryOptions { + getCurrentLocation?(): Location; + getUserConfirmation?(message: string, callback: (result: boolean) => void): void; + pushLocation?(nextLocation: Location): void; + replaceLocation?(nextLocation: Location): void; + go?(n: number): void; + keyLength?: number; +} + +export type CreateHistory = (options?: HistoryOptions) => T; +export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; + export { Basename, ChangeHook, diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index 160694953f..dbd2d43fff 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -1,5 +1,6 @@ import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; import { + Action, Hash, History, Href, @@ -11,12 +12,13 @@ import { } from "history"; import { PlainRoute } from "react-router"; +/* Replacement from old history definitions */ export type Basename = string; export type Query = any; -export type Action = "PUSH" | "REPLACE" | "POP"; export interface Params { [key: string]: string; } + export type RoutePattern = string; export type RouteComponent = ComponentClass | StatelessComponent; export interface RouteComponents { diff --git a/react-router/lib/createMemoryHistory.d.ts b/react-router/lib/createMemoryHistory.d.ts index bb2fed561b..038e707e6b 100644 --- a/react-router/lib/createMemoryHistory.d.ts +++ b/react-router/lib/createMemoryHistory.d.ts @@ -1,4 +1,5 @@ -import { History, CreateHistory } from "history"; +import { History } from "history"; +import { CreateHistory } from "react-router"; declare const createMemoryHistory: CreateHistory; diff --git a/react-router/lib/useRouterHistory.d.ts b/react-router/lib/useRouterHistory.d.ts index 1371baa07b..7dc2bdd3ab 100644 --- a/react-router/lib/useRouterHistory.d.ts +++ b/react-router/lib/useRouterHistory.d.ts @@ -1,5 +1,6 @@ -import { History, CreateHistoryEnhancer } from "history"; +import { History } from "history"; +import { CreateHistoryEnhancer } from "react-router"; -declare const useRouterHistory: CreateHistoryEnhancer; +declare const useRouterHistory: CreateHistoryEnhancer; export default useRouterHistory; From 5ce5e784689f0ddccc1e7cdba6df700f2f435cef Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 10:15:36 +0900 Subject: [PATCH 036/306] Remove unnecessary files, add tsconfig for old version --- react-router/index.d.ts.orig | 109 ---------- react-router/lib/Route.d.ts.orig | 49 ----- react-router/lib/Router.d.ts.orig | 213 -------------------- react-router/lib/useRouterHistory.d.ts.orig | 10 - react-router/lib/withRouter.d.ts.orig | 14 -- react-router/v2/tsconfig.json | 27 +++ 6 files changed, 27 insertions(+), 395 deletions(-) delete mode 100644 react-router/index.d.ts.orig delete mode 100644 react-router/lib/Route.d.ts.orig delete mode 100644 react-router/lib/Router.d.ts.orig delete mode 100644 react-router/lib/useRouterHistory.d.ts.orig delete mode 100644 react-router/lib/withRouter.d.ts.orig create mode 100644 react-router/v2/tsconfig.json diff --git a/react-router/index.d.ts.orig b/react-router/index.d.ts.orig deleted file mode 100644 index 52227f4d95..0000000000 --- a/react-router/index.d.ts.orig +++ /dev/null @@ -1,109 +0,0 @@ -<<<<<<< HEAD -// Type definitions for react-router 3.0 -======= -// Type definitions for react-router 2.0 ->>>>>>> upstream/master -// Project: https://github.com/rackt/react-router -// Definitions by: Sergey Buturlakin , Yuichi Murata , Václav Ostrožlík , Nathan Brown , Alex Wendland , Kostya Esmukov , Karol Janyst -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* Replacement from old history definitions */ -export interface HistoryOptions { - getCurrentLocation?(): Location; - getUserConfirmation?(message: string, callback: (result: boolean) => void): void; - pushLocation?(nextLocation: Location): void; - replaceLocation?(nextLocation: Location): void; - go?(n: number): void; - keyLength?: number; -} - -export type CreateHistory = (options?: HistoryOptions) => T; -export type CreateHistoryEnhancer = (createHistory: CreateHistory) => CreateHistory; - -<<<<<<< HEAD -export { - Basename, - ChangeHook, - EnterHook, - InjectedRouter, - LeaveHook, - Location, - LocationDescriptor, - ParseQueryString, - RouteComponent, - RouteComponents, - RouteComponentProps, - RouteConfig, - RoutePattern, - RouterProps, - RouterState, - StringifyQuery, - Query -} from "react-router/lib/Router"; -export { LinkProps } from "react-router/lib/Link"; -export { IndexLinkProps } from "react-router/lib/IndexLink"; -export { RouteProps, PlainRoute } from "react-router/lib/Route"; -export { IndexRouteProps } from "react-router/lib/IndexRoute"; -export { RedirectProps } from "react-router/lib/Redirect"; -export { IndexRedirectProps } from "react-router/lib/IndexRedirect"; -======= -import * as React from 'react'; - -export const routerShape: React.Requireable; - -export const locationShape: React.Requireable; - -import Router from "./lib/Router"; -import Link from "./lib/Link"; -import IndexLink from "./lib/IndexLink"; -import IndexRedirect from "./lib/IndexRedirect"; -import IndexRoute from "./lib/IndexRoute"; -import Redirect from "./lib/Redirect"; -import Route from "./lib/Route"; -import * as History from "./lib/routerHistory"; -import Lifecycle from "./lib/Lifecycle"; -import RouteContext from "./lib/RouteContext"; -import browserHistory from "./lib/browserHistory"; -import hashHistory from "./lib/hashHistory"; -import useRoutes from "./lib/useRoutes"; -import { createRoutes } from "./lib/RouteUtils"; -import { formatPattern } from "./lib/PatternUtils"; -import RouterContext from "./lib/RouterContext"; -import PropTypes from "./lib/PropTypes"; -import match from "./lib/match"; -import useRouterHistory from "./lib/useRouterHistory"; -import createMemoryHistory from "./lib/createMemoryHistory"; -import withRouter from "./lib/withRouter"; -import applyRouterMiddleware from "./lib/applyRouterMiddleware"; - -// PlainRoute is defined in the API documented at: -// https://github.com/rackt/react-router/blob/master/docs/API.md -// but not included in any of the .../lib modules above. -export type PlainRoute = Router.PlainRoute; ->>>>>>> upstream/master - -/* components */ -export { default as Router } from "react-router/lib/Router"; -export { default as Link } from "react-router/lib/Link"; -export { default as IndexLink } from "react-router/lib/IndexLink"; -export { default as withRouter } from "react-router/lib/withRouter"; - -/* components (configuration) */ -export { default as IndexRedirect } from "react-router/lib/IndexRedirect"; -export { default as IndexRoute } from "react-router/lib/IndexRoute"; -export { default as Redirect } from "react-router/lib/Redirect"; -export { default as Route } from "react-router/lib/Route"; - -/* utils */ -export { createRoutes } from "react-router/lib/RouteUtils"; -export { default as RouterContext } from "react-router/lib/RouterContext"; -export { routerShape, locationShape } from "react-router/lib/PropTypes"; -export { default as match } from "react-router/lib/match"; -export { default as useRouterHistory } from "react-router/lib/useRouterHistory"; -export { formatPattern } from "react-router/lib/PatternUtils"; -export { default as applyRouterMiddleware } from "react-router/lib/applyRouterMiddleware"; - -/* histories */ -export { default as browserHistory } from "react-router/lib/browserHistory"; -export { default as hashHistory } from "react-router/lib/hashHistory"; -export { default as createMemoryHistory } from "react-router/lib/createMemoryHistory"; diff --git a/react-router/lib/Route.d.ts.orig b/react-router/lib/Route.d.ts.orig deleted file mode 100644 index c8a211517c..0000000000 --- a/react-router/lib/Route.d.ts.orig +++ /dev/null @@ -1,49 +0,0 @@ -import { ComponentClass, ClassAttributes } from "react"; -import { LocationState } from "history"; -import { - EnterHook, - ChangeHook, - LeaveHook, - RouteComponent, - RouteComponents, - RoutePattern, - RouterState -} from "react-router"; -import { IndexRouteProps } from "react-router/lib/IndexRoute"; - -export interface RouteProps extends IndexRouteProps { - path?: RoutePattern; -} - -type Route = ComponentClass; -declare const Route: Route; - -<<<<<<< HEAD -export default Route; - -type RouteCallback = (err: any, route: PlainRoute) => void; -type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; - -export interface PlainRoute extends RouteProps { - childRoutes?: PlainRoute[]; - getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; - indexRoute?: PlainRoute; - getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): void; -} -======= - interface RouteProps extends React.Props { - path?: Router.RoutePattern; - component?: Router.RouteComponent; - components?: Router.RouteComponents; - getComponent?: (nextState: Router.RouterState, cb: (error: any, component?: Router.RouteComponent) => void) => void; - getComponents?: (nextState: Router.RouterState, cb: (error: any, components?: Router.RouteComponents) => void) => void; - onEnter?: Router.EnterHook; - onLeave?: Router.LeaveHook; - onChange?: Router.ChangeHook; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: Router.RouteConfig) => void) => void; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: Router.RouteConfig) => void) => void; - } - interface Route extends React.ComponentClass {} - interface RouteElement extends React.ReactElement {} -} ->>>>>>> upstream/master diff --git a/react-router/lib/Router.d.ts.orig b/react-router/lib/Router.d.ts.orig deleted file mode 100644 index 8b77e41bdf..0000000000 --- a/react-router/lib/Router.d.ts.orig +++ /dev/null @@ -1,213 +0,0 @@ -import { Component, ComponentClass, ClassAttributes, ReactNode, StatelessComponent } from "react"; -import { - Action, - Hash, - History, - Href, - LocationKey, - LocationState, - Path, - Pathname, - Search -} from "history"; -import { PlainRoute } from "react-router"; - -/* Replacement from old history definitions */ -export type Basename = string; -export type Query = any; -export interface Params { - [key: string]: string; -} - -export type RoutePattern = string; -export type RouteComponent = ComponentClass | StatelessComponent; -export interface RouteComponents { - [name: string]: RouteComponent; -} -export type RouteConfig = ReactNode | PlainRoute | PlainRoute[]; - -export type ParseQueryString = (queryString: Search) => Query; -export type StringifyQuery = (queryObject: Query) => Search; - -type AnyFunction = (...args: any[]) => any; - -export type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; -export type LeaveHook = (prevState: RouterState) => any; -export type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback?: AnyFunction) => any; -export type RouteHook = (nextLocation?: Location) => any; - -<<<<<<< HEAD -export interface Location { - patname: Pathname; - search: Search; - query: Query; - state: LocationState; - action: Action; - key: LocationKey; -======= -// types based on https://github.com/rackt/react-router/blob/master/docs/Glossary.md - -declare namespace Router { - type RouteConfig = React.ReactNode | PlainRoute | PlainRoute[]; - type RoutePattern = string; - interface RouteComponents { [key: string]: RouteComponent; } - - type ParseQueryString = (queryString: QueryString) => Query; - type StringifyQuery = (queryObject: Query) => QueryString; - - type Component = React.ReactType; - type RouteComponent = Component; - - type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void; - type LeaveHook = () => void; - type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; - type RouteHook = (nextLocation?: Location) => any; - - interface Params { [param: string]: string; } - - type RouterListener = (error: Error, nextState: RouterState) => void; - - interface LocationDescriptor { - pathname?: Pathname; - query?: Query; - hash?: Href; - state?: HLocationState; - } - - interface RedirectFunction { - (location: LocationDescriptor): void; - /** - * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated - */ - (state: HLocationState, pathname: Pathname | Path, query?: Query): void; - } - - interface RouterState { - location: Location; - routes: PlainRoute[]; - params: Params; - components: RouteComponent[]; - } - - interface RouterProps extends React.Props { - history?: History; - routes?: RouteConfig; // alias for children - createElement?: (component: RouteComponent, props: Object) => any; - onError?: (error: any) => any; - onUpdate?: () => any; - parseQueryString?: ParseQueryString; - stringifyQuery?: StringifyQuery; - basename?: string; - render?: (renderProps: React.Props<{}>) => RouterContext; - } - - interface PlainRoute { - path?: RoutePattern; - component?: RouteComponent; - components?: RouteComponents; - getComponent?: (location: Location, cb: (error: any, component?: RouteComponent) => void) => void; - getComponents?: (location: Location, cb: (error: any, components?: RouteComponents) => void) => void; - onEnter?: EnterHook; - onLeave?: LeaveHook; - indexRoute?: PlainRoute; - getIndexRoute?: (location: Location, cb: (error: any, indexRoute: RouteConfig) => void) => void; - childRoutes?: PlainRoute[]; - getChildRoutes?: (location: Location, cb: (error: any, childRoutes: RouteConfig) => void) => void; - } - - interface RouteComponentProps { - history?: History; - location?: Location; - params?: P; - route?: PlainRoute; - routeParams?: R; - routes?: PlainRoute[]; - children?: React.ReactElement; - } - - interface RouterOnContext extends History { - setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; - isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; - } - - // Wrap a component using withRouter(Component) to provide a router object - // to the Component's props, allowing the Component to programmatically call - // push and other functions. - // - // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md - - interface InjectedRouter { - push: (pathOrLoc: Path | LocationDescriptor) => void; - replace: (pathOrLoc: Path | LocationDescriptor) => void; - go: (n: number) => void; - goBack: () => void; - goForward: () => void; - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void; - createPath(path: History.Path, query?: History.Query): History.Path; - createHref(path: History.Path, query?: History.Query): History.Href; - isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean; - } ->>>>>>> upstream/master -} - -export interface LocationDescriptorObject { - pathname?: Pathname; - query?: Query; - hash?: Hash; - state?: LocationState; -} - -export type LocationDescriptor = Path | LocationDescriptorObject; - -export interface RedirectFunction { - (location: LocationDescriptor): void; - (state: LocationState, pathname: Pathname | Path, query?: Query): void; -} - -export interface RouterState { - location: Location; - routes: PlainRoute[]; - params: Params; - components: RouteComponent[]; -} - -type LocationFunction = (location: LocationDescriptor) => void; -type GoFunction = (n: number) => void; -type NavigateFunction = () => void; -type ActiveFunction = (location: LocationDescriptor, indexOnly?: boolean) => boolean; -type LeaveHookFunction = (route: any, callback: RouteHook) => void; -type CreatePartFunction = (path: Path, query?: any) => Part; - -export interface InjectedRouter { - push: LocationFunction; - replace: LocationFunction; - go: GoFunction; - goBack: NavigateFunction; - goForward: NavigateFunction; - setRouteLeaveHook: LeaveHookFunction; - createPath: CreatePartFunction; - createHref: CreatePartFunction; - isActive: ActiveFunction; -} - -export interface RouteComponentProps { - location?: Location; - params?: P & R; - route?: PlainRoute; - router?: InjectedRouter; - routeParams?: R; -} - -export interface RouterProps extends ClassAttributes { - routes?: RouteConfig; - history?: History; - createElement?(component: RouteComponent, props: any): any; - onError?(error: any): any; - onUpdate?(): any; - render?(props: any): ReactNode; -} - -type Router = ComponentClass; -declare const Router: Router; - -export default Router; diff --git a/react-router/lib/useRouterHistory.d.ts.orig b/react-router/lib/useRouterHistory.d.ts.orig deleted file mode 100644 index 01609c5a48..0000000000 --- a/react-router/lib/useRouterHistory.d.ts.orig +++ /dev/null @@ -1,10 +0,0 @@ -import { History } from "history"; -import { CreateHistoryEnhancer } from "react-router"; - -<<<<<<< HEAD -declare const useRouterHistory: CreateHistoryEnhancer; - -export default useRouterHistory; -======= -export default function useRouterHistory(createHistory: CreateHistory): (options?: HistoryOptions) => History & HistoryQueries; ->>>>>>> upstream/master diff --git a/react-router/lib/withRouter.d.ts.orig b/react-router/lib/withRouter.d.ts.orig deleted file mode 100644 index ab51b2111e..0000000000 --- a/react-router/lib/withRouter.d.ts.orig +++ /dev/null @@ -1,14 +0,0 @@ -import { ComponentClass, StatelessComponent } from "react"; - -<<<<<<< HEAD -interface Options { - withRef?: boolean; -} - -type ComponentConstructor

= ComponentClass

| StatelessComponent

; - -export default function withRouter

(component: ComponentConstructor

, options?: Options): ComponentClass

; -======= -declare function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C; -export default withRouter; ->>>>>>> upstream/master diff --git a/react-router/v2/tsconfig.json b/react-router/v2/tsconfig.json new file mode 100644 index 0000000000..7cc347abc4 --- /dev/null +++ b/react-router/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "history": ["history/v2"], + "react-router": ["react-router/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-router-redux-tests.ts" + ] +} From f49ca4f7ab7ee036e3aa1deab3558758c70326f0 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 11:13:06 +0900 Subject: [PATCH 037/306] Update react-router-bootstrap definitions --- react-router-bootstrap/index.d.ts | 44 ++----------------- .../lib/IndexLinkContainer.d.ts | 7 +++ react-router-bootstrap/lib/LinkContainer.d.ts | 7 +++ react-router-bootstrap/tsconfig.json | 3 -- 4 files changed, 18 insertions(+), 43 deletions(-) create mode 100644 react-router-bootstrap/lib/IndexLinkContainer.d.ts create mode 100644 react-router-bootstrap/lib/LinkContainer.d.ts diff --git a/react-router-bootstrap/index.d.ts b/react-router-bootstrap/index.d.ts index b4b36006ec..c414d8f3b0 100644 --- a/react-router-bootstrap/index.d.ts +++ b/react-router-bootstrap/index.d.ts @@ -1,43 +1,7 @@ -// Type definitions for react-router-bootstrap +// Type definitions for react-router-bootstrap 0.23 // Project: https://github.com/react-bootstrap/react-router-bootstrap -// Definitions by: Vincent Lesierse +// Definitions by: Vincent Lesierse , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// - -declare namespace ReactRouterBootstrap { - interface LinkContainerProps extends ReactRouter.LinkProps { - disabled?: boolean - } - interface LinkContainer extends React.ComponentClass {} - interface LinkContainerElement extends React.ReactElement {} - const LinkContainer: LinkContainer - - const IndexLinkContainer: LinkContainer -} - -declare module "react-router-bootstrap/lib/LinkContainer" { - - export default ReactRouterBootstrap.LinkContainer - -} - -declare module "react-router-bootstrap/lib/IndexLinkContainer" { - - export default ReactRouterBootstrap.IndexLinkContainer - -} - -declare module "react-router-bootstrap" { - - import LinkContainer from "react-router-bootstrap/lib/LinkContainer" - - import IndexLinkContainer from "react-router-bootstrap/lib/IndexLinkContainer" - - export { - LinkContainer, - IndexLinkContainer - } - -} +export { default as LinkContainer } from "react-router-bootstrap/lib/LinkContainer" +export { default as IndexLinkContainer } from "react-router-bootstrap/lib/IndexLinkContainer" diff --git a/react-router-bootstrap/lib/IndexLinkContainer.d.ts b/react-router-bootstrap/lib/IndexLinkContainer.d.ts new file mode 100644 index 0000000000..045edc1fde --- /dev/null +++ b/react-router-bootstrap/lib/IndexLinkContainer.d.ts @@ -0,0 +1,7 @@ +import { ComponentClass } from "react"; +import { IndexLinkProps } from "react-router/lib/IndexLink"; + +type IndexLinkContainer = ComponentClass; +declare const IndexLinkContainer: IndexLinkContainer; + +export default IndexLinkContainer; diff --git a/react-router-bootstrap/lib/LinkContainer.d.ts b/react-router-bootstrap/lib/LinkContainer.d.ts new file mode 100644 index 0000000000..df5ac3cbdb --- /dev/null +++ b/react-router-bootstrap/lib/LinkContainer.d.ts @@ -0,0 +1,7 @@ +import { ComponentClass } from "react"; +import { LinkProps } from "react-router/lib/Link"; + +type LinkContainer = ComponentClass; +declare const LinkContainer: LinkContainer; + +export default LinkContainer; diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index 7e111b1004..ecee2cb765 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -10,9 +10,6 @@ "strictNullChecks": false, "jsx": "preserve", "baseUrl": "../", - "paths": { - "history": ["history/v2"] - }, "typeRoots": [ "../" ], From 4b89363df8ae1f1da5edba6f365c8c0a50d2d3f5 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 11:17:58 +0900 Subject: [PATCH 038/306] Fix tsconfig files --- react-router-bootstrap/tsconfig.json | 3 +++ react-router/tsconfig.json | 13 ++++++++----- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index ecee2cb765..2fc57383ed 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -17,6 +17,9 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, + "include": [ + "lib/*.d.ts" + ], "files": [ "index.d.ts", "react-router-bootstrap-tests.tsx" diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index 8e5f5d47b6..e06f11b4a3 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -1,8 +1,4 @@ { - "files": [ - "index.d.ts", - "react-router-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -20,5 +16,12 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "include": [ + "lib/*.d.ts" + ], + "files": [ + "index.d.ts", + "react-router-tests.tsx" + ], } From 2bef57bed0b9d40a708e845f52ca30cb2374b9c2 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 11:22:18 +0900 Subject: [PATCH 039/306] Fix react-router tsconfig --- react-router/tsconfig.json | 2 +- react-router/tslint.json | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index e06f11b4a3..d13560189e 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -23,5 +23,5 @@ "files": [ "index.d.ts", "react-router-tests.tsx" - ], + ] } diff --git a/react-router/tslint.json b/react-router/tslint.json index e050abdce9..f9e30021f4 100644 --- a/react-router/tslint.json +++ b/react-router/tslint.json @@ -1,7 +1,3 @@ { - "extends": "../tslint.json", - "rules": { - "forbidden-types": false, - "no-empty-interface": false - } -} \ No newline at end of file + "extends": "../tslint.json" +} From 3ce2018675b0606bd4149c59e602f64219f2535a Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 12:12:31 +0900 Subject: [PATCH 040/306] Change include to files in tsconfig --- react-router-bootstrap/tsconfig.json | 5 ++--- react-router/tsconfig.json | 21 ++++++++++++++++++--- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/react-router-bootstrap/tsconfig.json b/react-router-bootstrap/tsconfig.json index 2fc57383ed..1760fc3f1a 100644 --- a/react-router-bootstrap/tsconfig.json +++ b/react-router-bootstrap/tsconfig.json @@ -17,11 +17,10 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "include": [ - "lib/*.d.ts" - ], "files": [ "index.d.ts", + "lib/IndexLinkContainer.d.ts", + "lib/LinkContainer.d.ts", "react-router-bootstrap-tests.tsx" ] } diff --git a/react-router/tsconfig.json b/react-router/tsconfig.json index d13560189e..c013e2c959 100644 --- a/react-router/tsconfig.json +++ b/react-router/tsconfig.json @@ -17,11 +17,26 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "include": [ - "lib/*.d.ts" - ], "files": [ "index.d.ts", + "lib/applyRouterMiddleware.d.ts", + "lib/browserHistory.d.ts", + "lib/createMemoryHistory.d.ts", + "lib/hashHistory.d.ts", + "lib/IndexLink.d.ts", + "lib/IndexRedirect.d.ts", + "lib/IndexRoute.d.ts", + "lib/Link.d.ts", + "lib/match.d.ts", + "lib/PatternUtils.d.ts", + "lib/PropTypes.d.ts", + "lib/Redirect.d.ts", + "lib/Route.d.ts", + "lib/Router.d.ts", + "lib/RouterContext.d.ts", + "lib/RouteUtils.d.ts", + "lib/useRouterHistory.d.ts", + "lib/withRouter.d.ts", "react-router-tests.tsx" ] } From ab95e31c3f86178515ec6450b50f5d80feaef881 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 19 Jan 2017 12:40:16 +0900 Subject: [PATCH 041/306] Remove test file from v2 tsconfig --- react-router/v2/tsconfig.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/react-router/v2/tsconfig.json b/react-router/v2/tsconfig.json index 7cc347abc4..c92402947c 100644 --- a/react-router/v2/tsconfig.json +++ b/react-router/v2/tsconfig.json @@ -21,7 +21,6 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", - "react-router-redux-tests.ts" + "index.d.ts" ] } From 2b5726e1b8f69514afd202e78c967e5cc6bac54a Mon Sep 17 00:00:00 2001 From: karak Date: Thu, 19 Jan 2017 15:19:50 +0900 Subject: [PATCH 042/306] [material-ui] Fixed muiThemeable on decorator usage #9843 --- material-ui/index.d.ts | 5 ++++- material-ui/material-ui-tests.tsx | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index 716505987d..f60bb7e7ae 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -452,7 +452,10 @@ declare namespace __MaterialUI { var lightBaseTheme: RawTheme; var darkBaseTheme: RawTheme; - export function muiThemeable, P, S>(): (component: TComponent) => TComponent; + export function muiThemeable(): < + TComponent extends React.ComponentClass

| React.StatelessComponent

, + P extends {muiTheme?: MuiTheme} + >(component: TComponent) => TComponent; interface MuiThemeProviderProps { muiTheme?: Styles.MuiTheme; diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index 04b8f0ec32..8dcc0fe07e 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -7,6 +7,7 @@ import * as React from 'react'; import {Component, PropTypes} from 'react'; import * as ReactDOM from 'react-dom'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; +import {muiThemeable} from 'material-ui/styles/muiThemeable'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import {MuiTheme} from 'material-ui/styles'; @@ -321,6 +322,35 @@ class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}, {}> { } +const MuiThemeableFunction = muiThemeable()((props: {label: string, muiTheme?: MuiTheme}) => { + return ( + + Applied the Theme to functional component: {props.label}. + + ); +}); + +@muiThemeable() +class MuiThemeableClass extends React.Component<{label: string} & {muiTheme?: MuiTheme}, {}> { + render() { + return ( + + Applied the Theme to class component decorated: {this.props.label}. + + ); + } +} + +const MuiThemeableContainer = (props: {}) => ( + +

+ + +
+ +); + + // "http://www.material-ui.com/#/customization/inline-styles" const InlineStylesCheckbox = () => ( Date: Thu, 19 Jan 2017 11:23:27 +0100 Subject: [PATCH 043/306] Add user object to Express.Request The JWT authentication middleware authenticates callers using a JWT. If the token is valid, req.user will be set with the JSON object decoded to be used by later middleware for authorization and access control. --- express-jwt/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/express-jwt/index.d.ts b/express-jwt/index.d.ts index e721094edc..edffeb9632 100644 --- a/express-jwt/index.d.ts +++ b/express-jwt/index.d.ts @@ -37,3 +37,10 @@ declare namespace jwt { unless?: typeof unless; } } +declare global { + namespace Express { + export interface Request { + user?: any + } + } +} From fac57d46263790b607f28881422aa9aac55d750c Mon Sep 17 00:00:00 2001 From: Jonathan Jayet Date: Thu, 19 Jan 2017 16:00:50 +0100 Subject: [PATCH 044/306] Fix a small issue withing the multer typing --- multer/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/multer/index.d.ts b/multer/index.d.ts index 2437f498db..1e388f7630 100644 --- a/multer/index.d.ts +++ b/multer/index.d.ts @@ -48,22 +48,22 @@ declare namespace multer { /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ destination?: string | ((req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void); /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ - filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, filename: string) => void) => void; + filename?: (req: Express.Request, file: Express.Multer.File, callback: (error?: Error, filename?: string) => void) => void; } interface Instance { - /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - single(): express.RequestHandler; - /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ - single(fieldame: string): express.RequestHandler; - /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - array(): express.RequestHandler; - /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ - array(fieldame: string, maxCount?: number): express.RequestHandler; - /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ - fields(fields: Field[]): express.RequestHandler; - /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ - any(): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + single(): express.RequestHandler; + /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ + single(fieldame: string): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + array(): express.RequestHandler; + /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ + array(fieldame: string, maxCount?: number): express.RequestHandler; + /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ + fields(fields: Field[]): express.RequestHandler; + /** In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()), req.body contains the text fields */ + any(): express.RequestHandler; } } From c779cebd7f18a885b1e956020d884438c1e5566e Mon Sep 17 00:00:00 2001 From: Jonathan Jayet Date: Thu, 19 Jan 2017 16:07:39 +0100 Subject: [PATCH 045/306] Better typing yet --- multer/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/multer/index.d.ts b/multer/index.d.ts index 1e388f7630..53fdcd7add 100644 --- a/multer/index.d.ts +++ b/multer/index.d.ts @@ -48,7 +48,7 @@ declare namespace multer { /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ destination?: string | ((req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void); /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ - filename?: (req: Express.Request, file: Express.Multer.File, callback: (error?: Error, filename?: string) => void) => void; + filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error | null, filename: string) => void) => void; } interface Instance { From e76c78bd71ea47bb417a853950844b9b320b86f9 Mon Sep 17 00:00:00 2001 From: Sergei Dorogin Date: Thu, 19 Jan 2017 21:26:35 +0300 Subject: [PATCH 046/306] jquery.fileupload added JQueryFileUploadXhr.headers field --- jquery.fileupload/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jquery.fileupload/index.d.ts b/jquery.fileupload/index.d.ts index 8eba9853b2..54ebb89c5c 100644 --- a/jquery.fileupload/index.d.ts +++ b/jquery.fileupload/index.d.ts @@ -284,6 +284,7 @@ interface JQueryFileUploadXhr { jqXHR: JQueryXHR; result: any; textStatus: string; + headers: {[key: string]: any}; } interface JQueryFileUploadFilesObject { From a4dec0334cc80b0f943f114770945bb154f9364d Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 20 Jan 2017 09:03:18 +0900 Subject: [PATCH 047/306] Fix react-breadcrumbs --- react-breadcrumbs/index.d.ts | 23 +++++++++-------------- react-breadcrumbs/tsconfig.json | 3 ++- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/react-breadcrumbs/index.d.ts b/react-breadcrumbs/index.d.ts index 1d247f215d..67f1a89090 100644 --- a/react-breadcrumbs/index.d.ts +++ b/react-breadcrumbs/index.d.ts @@ -1,13 +1,17 @@ -// Type definitions for react-breadcrumbs 1.3.16 +// Type definitions for react-breadcrumbs 1.3 // Project: https://github.com/svenanders/react-breadcrumbs // Definitions by: Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +import * as React from "react"; +import * as ReactRouter from "react-router"; -declare namespace ReactBreadcrumbs { - interface BreadcrumbsProps extends React.Props { +export = Breadcrumbs; +type Breadcrumbs = React.ComponentClass; +declare const Breadcrumbs: Breadcrumbs; + +declare namespace Breadcrumbs { + interface Props extends React.ClassAttributes { separator?: string | JSX.Element; displayMissing?: boolean; prettify?: boolean; @@ -26,13 +30,4 @@ declare namespace ReactBreadcrumbs { setDocumentTitle?: boolean; params?: any; // todo make it compatible with params of the ReactRouter.RouteComponentProps } - - interface Breadcrumbs extends React.ComponentClass {} - const Breadcrumbs: Breadcrumbs; -} - -declare module 'react-breadcrumbs' { - import Breadcrumbs = ReactBreadcrumbs.Breadcrumbs; - - export = Breadcrumbs; } diff --git a/react-breadcrumbs/tsconfig.json b/react-breadcrumbs/tsconfig.json index 0092616bce..d1a0ccc542 100644 --- a/react-breadcrumbs/tsconfig.json +++ b/react-breadcrumbs/tsconfig.json @@ -10,7 +10,8 @@ "strictNullChecks": false, "baseUrl": "../", "paths": { - "history": ["history/v2"] + "history": ["history/v2"], + "react-router": ["react-router/v2"] }, "typeRoots": [ "../" From 848999f5764d0a4af62ad49ee12ea6de80bcde51 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Fri, 20 Jan 2017 09:28:08 +0900 Subject: [PATCH 048/306] Add path mapping to react-i18next --- react-i18next/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/react-i18next/tsconfig.json b/react-i18next/tsconfig.json index bba519bbd3..5936e04b91 100644 --- a/react-i18next/tsconfig.json +++ b/react-i18next/tsconfig.json @@ -11,7 +11,8 @@ "baseUrl": "../", "paths": { "history": ["history/v2"], - "history/*": ["history/v2/*"] + "history/*": ["history/v2/*"], + "react-router": ["react-router/v2"], }, "typeRoots": [ "../" From 567657e3fab839bdeb535ea23c6593cbc8ce7588 Mon Sep 17 00:00:00 2001 From: Kir Dergachev Date: Thu, 19 Jan 2017 15:29:50 +0300 Subject: [PATCH 049/306] Added types for SIP.js --- SIP.js/SIP.js-tests.ts | 99 ++++++++++++ SIP.js/index.d.ts | 354 +++++++++++++++++++++++++++++++++++++++++ SIP.js/tsconfig.json | 23 +++ SIP.js/tslint.json | 1 + 4 files changed, 477 insertions(+) create mode 100644 SIP.js/SIP.js-tests.ts create mode 100644 SIP.js/index.d.ts create mode 100644 SIP.js/tsconfig.json create mode 100644 SIP.js/tslint.json diff --git a/SIP.js/SIP.js-tests.ts b/SIP.js/SIP.js-tests.ts new file mode 100644 index 0000000000..f688fe67ae --- /dev/null +++ b/SIP.js/SIP.js-tests.ts @@ -0,0 +1,99 @@ +import SIP = require("./index"); + +let ua: SIP.UA = new SIP.UA(); + +const mediaHandler = (session: SIP.Session, options: SIP.WebRTC.Options) => new SIP.WebRTC.MediaHandler(); +const logConnector = (level: string, category: string, label: string, content: string) => null; + +const uaWithConfig: SIP.UA = new SIP.UA({ + uri: "wss://uri", + wsServers: ["s1", "s2"], + allowLegacyNotifications: true, + authenticationFactory: mediaHandler, + authorizationUser: "user", + autostart: true, + connectionRecoveryMaxInterval: 1, + connectionRecoveryMinInterval: 1, + displayName: "name", + hackCleanJitsiSdpImageattr: true, + hackStripTcp: true, + hackIpInContact: true, + hackViaTcp: true, + hackWssInTransport: true, + iceCheckingTimeout: 1, + instanceId: "id", + log: { + builtinEnabled: true, + level: 1, + connector: logConnector + }, + mediaHandlerFactory: mediaHandler, + noAnswerTimeout: 1, + password: "", + register: true, + registerExpires: 1, + registrarServer: "sip:registrar.mydomain.com", + rel100: "", + replaces: "", + stunServers: ["", ""], + turnServers: [ + { + password: "", + username: "", + urls: ["", ""] + } + ], + usePreloadedRoute: true, + userAgentString: "", + wsServerMaxReconnection: 1, + wsServerReconnectionTimeout: 1 +}); + +ua.start(); +ua.stop(); + +ua.register(); +ua = ua.register({ extraHeaders: [""] }); + +ua.unregister() +ua.unregister({ extraHeaders: [""], all: true }); + +const isConnected: boolean = ua.isConnected(); +const isRegistered: boolean = ua.isRegistered(); + +const message: SIP.Message = ua.message("", "", { contentType: "" }); + +ua.subscribe("", "", { expires: 1, extraHeaders: [""]}); +const subscription: SIP.Subscription = ua.subscribe(new SIP.URI(), "", { expires: 1, extraHeaders: [""]}); + +let session = ua.invite("", new HTMLVideoElement()); + +const inviteOptions: SIP.InviteOptions = { + media: { + constraints: { audio: true, video: false }, + stream: new MediaStream(), + render: { remote: new Element(), local: new Element() }, + }, + anonymous: true, + rel100: "", + inviteWithoutSdp: true, + RTCConstraints: new RTCPeerConnection() +} + +session = ua.invite("", inviteOptions); + +ua.on('connected', (args: SIP.UA.EventArgs.ConnectedArgs) => {}); +ua.on('disconnected', () => {}); +ua.on('registered', () => {}); +ua.on('unregistered', (args: SIP.UA.EventArgs.UnregisteredArgs) => {}); +ua.on('registrationFailed', (args: SIP.UA.EventArgs.RegistrationFailedArgs) => {}); +ua.on('invite', (session: SIP.Session) => { + session.on('progress', (response) => { + }); + session.on('accepted', (response) => { + }); + session.on('rejected', (response) => { + }); + +}); +ua.on('message', (message: SIP.Message) => {}); diff --git a/SIP.js/index.d.ts b/SIP.js/index.d.ts new file mode 100644 index 0000000000..0eaabb9b48 --- /dev/null +++ b/SIP.js/index.d.ts @@ -0,0 +1,354 @@ +// Type definitions for SIP.js v0.7.6 +// Project: https://sipjs.com/ +// Definitions by: Kir Dergachev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = SIP; + +declare namespace SIP { + + class URI { + constructor( + scheme?: string, + user?: string, + host?: string, + port?: number, + parameters?: string[], + headers?: string[]); + + scheme?: string; + user?: string; + host?: string; + port?: number; + + setParam(key: string, value?: string): void; + getParam(key: string): string; + hasParam(key: string): string; + deleteParam(key: string): string; + clearParams(): void; + setHeader(name: string, value: string): void; + getHeader(name: string): string[]; + hasHeader(name: string): boolean; + deleteHeader(name: string): string[]; + clearHeaders(): void; + clone(): URI; + toString(): string; + + static parse(uri: string): URI; + } + + namespace UA.EventArgs { + interface ConnectedArgs { attempts: number } + interface UnregisteredArgs { response: string; cause: string; } + interface RegistrationFailedArgs extends UnregisteredArgs { } + } + + class UA { + constructor(configuration?: ConfigurationParameters); + start(): void; + stop(): void; + register(options?: ExtraHeadersOptions): UA; + unregister(options?: UnregisterOptions): void; + isRegistered(): boolean; + isConnected(): boolean; + message(target: string | URI, body: string, options?: MessageOptions): Message; + subscribe(target: string | URI, event: string, options?: SubscribeOptions): Subscription; + invite(target: string | URI, options?: InviteOptions): Session; + invite(target: string | URI, element?: HTMLAudioElement | HTMLVideoElement): Session; + request(method: string, target: string | URI, options?: RequestOptions): ClientContext; + + on(name: 'connected', callback: (args: UA.EventArgs.ConnectedArgs) => void): void; + on(name: 'disconnected' | 'registered', callback: () => void): void; + on(name: 'unregistered', callback: (args: UA.EventArgs.UnregisteredArgs) => void): void; + on(name: 'registrationFailed', callback: (args: UA.EventArgs.RegistrationFailedArgs) => void): void; + on(name: 'invite', callback: (session: Session) => void): void; + on(name: 'message', callback: (message: Message) => void): void; + } + + namespace UA.C { + class supported { + REQUIRED: string; + SUPPORTED: string; + UNSUPPORTED: string; + } + + class causes { + INVALID_TARGET: string; + CONNECTION_ERROR: string; + REQUEST_TIMEOUT: string; + SIP_FAILURE_CODE: string; + } + } + + class Session { + startTime?: Date; + endTime?: Date; + ua?: UA; + method?: string; + mediaHandler?: WebRTC.MediaHandler; + request?: IncomingRequest | OutgoingRequest; + localIdentity?: NameAddrHeader; + remoteIdentity?: NameAddrHeader; + data: ClientContext | ServerContext; + + dtmf(tone: string | number, options?: Session.DtmfOptions): Session; + terminate(options?: Session.CommonOptions): Session; + bye(options?: Session.CommonOptions): Session; + getLocalStreams(): MediaStream[]; + getRemoteStreams(): MediaStream[]; + refer(target: string | Session, options?: ExtraHeadersOptions): Session; + mute(options?: ExtraHeadersOptions): void; + unmute(options?: ExtraHeadersOptions): void; + cancel(options?: Session.CommonOptions): void; + progress(options?: Session.ProgressOptions): void; + accept(options?: Session.AcceptOptions): void; + reject(options?: Session.CommonOptions): void; + reply(options?: Session.CommonOptions): void; + followRefer(callback: Function): void; + + on(name: 'progress', callback: (response: IncomingResponse) => void): void; + on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; + on(name: 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; + on(name: 'failed', callback: (response: IncomingResponse, cause: string) => void): void; + on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; + on(name: 'refer', callback: (request: IncomingRequest) => void): void; + on(name: 'cancel', callback: () => void): void; + on(name: 'replaced', callback: (newSession: Session) => void): void; + on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; + on(name: 'muted', callback: (data: Session.Muted) => void): void; + on(name: 'unmuted', callback: (data: Session.Muted) => void): void; + on(name: 'bye', callback: (request: IncomingRequest) => void): void; + } + + namespace Session { + interface DtmfOptions extends ExtraHeadersOptions { + duration?: number; + interToneGap?: number; + } + + interface CommonOptions extends ExtraHeadersOptions { + status_code?: number; + reason_phrase?: string; + body?: string; + } + + interface ProgressOptions extends ExtraHeadersOptions { + rel100?: boolean; + media?: MediaConstraints; + } + + interface AcceptOptions { + RTCConstraints?: RTCPeerConnection; + media?: MediaOptions; + } + + interface DTMF { + } + + interface Muted { + audio?: boolean; + video?: boolean + } + } + + interface RenderHint { + remote?: Element; + local?: Element + } + + interface MediaConstraints { + audio: boolean; + video: boolean; + } + + interface TurnServer { + urls?: string | string[]; + username?: string; + password?: string; + } + + namespace WebRTC { + + interface Options { + stunServers?: string | string[]; + turnServers?: TurnServer | TurnServer[]; + RTCConstraints?: RTCPeerConnection; + } + + type MediaHandlerFactory = (session: Session, options: Options) => MediaHandler; + + class MediaHandler { + getLocalStreams(): MediaStream[]; + getRemoteStreams(): MediaStream[]; + render(renderHint: RenderHint): void; + + on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; + on(name: 'userMedia', callback: (stream: MediaStream) => void): void; + on(name: 'userMediaFailed', callback: (error: string) => void): void; + on(name: 'iceGathering', callback: () => void): void; + on(name: 'iceCandidate', callback: (candidate: RTCIceCandidate) => void): void; + on(name: 'iceGatheringComplete', callback: () => void): void; + on(name: 'iceConnection', callback: () => void): void; + on(name: 'iceConnectionChecking', callback: () => void): void; + on(name: 'iceConnectionConnected', callback: () => void): void; + on(name: 'iceConnectionCompleted', callback: () => void): void; + on(name: 'iceConnectionFailed', callback: () => void): void; + on(name: 'iceConnectionDisconnected', callback: () => void): void; + on(name: 'iceConnectionClosed', callback: () => void): void; + on(name: 'getDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; + on(name: 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; + on(name: 'dataChannel', callback: () => void): void; + on(name: 'addStream', callback: (stream: MediaStream) => void): void; + } + } + + /* Parameters */ + interface ConfigurationParameters { + uri?: string; + wsServers?: string | string[] | { ws_uri: string; weigth: number }[]; + allowLegacyNotifications?: boolean; + authenticationFactory?: WebRTC.MediaHandlerFactory; + authorizationUser?: string; + autostart?: boolean; + connectionRecoveryMaxInterval?: number; + connectionRecoveryMinInterval?: number; + displayName?: string; + hackCleanJitsiSdpImageattr?: boolean; + hackStripTcp?: boolean; + hackIpInContact?: boolean; + hackViaTcp?: boolean; + hackWssInTransport?: boolean; + iceCheckingTimeout?: number; + instanceId?: string; + log?: { + builtinEnabled?: boolean; + level?: number | string; + connector?: (level: string, category: string, label: string, content: string) => void; + }; + mediaHandlerFactory?: WebRTC.MediaHandlerFactory; + noAnswerTimeout?: number; + password?: string; + register?: boolean; + registerExpires?: number; + registrarServer?: string; + rel100?: string; + replaces?: string; + stunServers?: string | string[]; + traceSip?: boolean; + turnServers?: TurnServer | TurnServer[]; + usePreloadedRoute?: boolean; + userAgentString?: string; + wsServerMaxReconnection?: number; + wsServerReconnectionTimeout?: number; + } + + /* Options */ + interface ExtraHeadersOptions { + extraHeaders?: string[]; + } + + interface UnregisterOptions extends ExtraHeadersOptions { + all?: boolean; + } + + interface MessageOptions extends ExtraHeadersOptions { + contentType?: string; + } + + interface SubscribeOptions extends ExtraHeadersOptions { + expires?: number; + } + + interface MediaOptions { + constraints?: MediaConstraints; + stream?: MediaStream; + render?: RenderHint; + } + + interface InviteOptions extends ExtraHeadersOptions { + media?: MediaOptions; + anonymous?: boolean; + rel100?: string; + inviteWithoutSdp?: boolean; + RTCConstraints?: RTCPeerConnection; + } + + interface RequestOptions extends ExtraHeadersOptions { + body?: string; + } + + /* Contexts */ + interface Message extends ClientContext { + body: string; + } + + interface Subscription extends ClientContext { + id: string; + state: string; + event: string; + dialog: string; + timers: Object; + errorCodes: number[]; + subscribe(): Subscription; + unsubscribe(): void; + close(): void; + } + + /* Context */ + interface Context { + ua: UA; + method: string; + request: OutgoingRequest; + localIdentity: NameAddrHeader; + remoteIdentity: NameAddrHeader; + data: {}; + + on(name: 'progress', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'accepted', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'rejected', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'failed', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'notify', callback: (request: IncomingRequest) => void): void; + } + + interface ClientContext extends Context { + cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; + } + + interface ServerContext extends Context { + progress(options?: Session.ProgressOptions): void; + accept(options?: Session.AcceptOptions): void; + reject(options?: Session.CommonOptions): void; + reply(options?: Session.CommonOptions): void; + } + + /* Request */ + interface Request extends Context { + } + + interface IncomingRequest extends Request { + } + + interface OutgoingRequest extends Request { + } + + interface IncomingResponse extends Request { + } + + interface IncomingMessage extends Request { + } + + /* Header */ + class NameAddrHeader { + constructor(uri: string | URI, displayName: string, parameters: { key: string, value: string }[]); + + uri: string | URI; + displayName: string; + + setParam(key: string, value?: string): void; + getParam(key: string): string; + deleteParam(key: string): string; + clearParams(): void; + + static parse(name_addr_header: string): NameAddrHeader; + } +} diff --git a/SIP.js/tsconfig.json b/SIP.js/tsconfig.json new file mode 100644 index 0000000000..93cce57ffb --- /dev/null +++ b/SIP.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": ["webrtc"], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "SIP.js-tests.ts" + ] +} diff --git a/SIP.js/tslint.json b/SIP.js/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/SIP.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 3de4a245bdc0dab48b91b51c3937391d04ef2902 Mon Sep 17 00:00:00 2001 From: Kir Dergachev Date: Fri, 20 Jan 2017 12:14:28 +0300 Subject: [PATCH 050/306] Fixed package case --- {SIP.js => sip.js}/index.d.ts | 0 SIP.js/SIP.js-tests.ts => sip.js/sip.js-tests.ts | 0 {SIP.js => sip.js}/tsconfig.json | 2 +- {SIP.js => sip.js}/tslint.json | 0 4 files changed, 1 insertion(+), 1 deletion(-) rename {SIP.js => sip.js}/index.d.ts (100%) rename SIP.js/SIP.js-tests.ts => sip.js/sip.js-tests.ts (100%) rename {SIP.js => sip.js}/tsconfig.json (94%) rename {SIP.js => sip.js}/tslint.json (100%) diff --git a/SIP.js/index.d.ts b/sip.js/index.d.ts similarity index 100% rename from SIP.js/index.d.ts rename to sip.js/index.d.ts diff --git a/SIP.js/SIP.js-tests.ts b/sip.js/sip.js-tests.ts similarity index 100% rename from SIP.js/SIP.js-tests.ts rename to sip.js/sip.js-tests.ts diff --git a/SIP.js/tsconfig.json b/sip.js/tsconfig.json similarity index 94% rename from SIP.js/tsconfig.json rename to sip.js/tsconfig.json index 93cce57ffb..8c84c6273e 100644 --- a/SIP.js/tsconfig.json +++ b/sip.js/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "SIP.js-tests.ts" + "sip.js-tests.ts" ] } diff --git a/SIP.js/tslint.json b/sip.js/tslint.json similarity index 100% rename from SIP.js/tslint.json rename to sip.js/tslint.json From f0f803116b25f321fca2755a4e6c96129e6c4a7a Mon Sep 17 00:00:00 2001 From: Kir Dergachev Date: Fri, 20 Jan 2017 12:52:59 +0300 Subject: [PATCH 051/306] Move references from tsconfig --- sip.js/index.d.ts | 2 ++ sip.js/tsconfig.json | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/sip.js/index.d.ts b/sip.js/index.d.ts index 0eaabb9b48..3af04495c9 100644 --- a/sip.js/index.d.ts +++ b/sip.js/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + export = SIP; declare namespace SIP { diff --git a/sip.js/tsconfig.json b/sip.js/tsconfig.json index 8c84c6273e..b6532e5674 100644 --- a/sip.js/tsconfig.json +++ b/sip.js/tsconfig.json @@ -12,7 +12,7 @@ "typeRoots": [ "../" ], - "types": ["webrtc"], + "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, From cb6ec66ca995549337896b3e38dc79a097b50c08 Mon Sep 17 00:00:00 2001 From: Kir Dergachev Date: Fri, 20 Jan 2017 13:22:30 +0300 Subject: [PATCH 052/306] Fix lint error --- sip.js/index.d.ts | 48 ++++++++++++++-------------------------------- sip.js/tslint.json | 7 ++++++- 2 files changed, 20 insertions(+), 35 deletions(-) diff --git a/sip.js/index.d.ts b/sip.js/index.d.ts index 3af04495c9..8c7a297613 100644 --- a/sip.js/index.d.ts +++ b/sip.js/index.d.ts @@ -40,7 +40,7 @@ declare namespace SIP { } namespace UA.EventArgs { - interface ConnectedArgs { attempts: number } + interface ConnectedArgs { attempts: number; } interface UnregisteredArgs { response: string; cause: string; } interface RegistrationFailedArgs extends UnregisteredArgs { } } @@ -55,8 +55,7 @@ declare namespace SIP { isConnected(): boolean; message(target: string | URI, body: string, options?: MessageOptions): Message; subscribe(target: string | URI, event: string, options?: SubscribeOptions): Subscription; - invite(target: string | URI, options?: InviteOptions): Session; - invite(target: string | URI, element?: HTMLAudioElement | HTMLVideoElement): Session; + invite(target: string | URI, element?: InviteOptions | HTMLAudioElement | HTMLVideoElement): Session; request(method: string, target: string | URI, options?: RequestOptions): ClientContext; on(name: 'connected', callback: (args: UA.EventArgs.ConnectedArgs) => void): void; @@ -110,16 +109,13 @@ declare namespace SIP { on(name: 'progress', callback: (response: IncomingResponse) => void): void; on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; - on(name: 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; - on(name: 'failed', callback: (response: IncomingResponse, cause: string) => void): void; + on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; - on(name: 'refer', callback: (request: IncomingRequest) => void): void; on(name: 'cancel', callback: () => void): void; on(name: 'replaced', callback: (newSession: Session) => void): void; on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; - on(name: 'muted', callback: (data: Session.Muted) => void): void; - on(name: 'unmuted', callback: (data: Session.Muted) => void): void; - on(name: 'bye', callback: (request: IncomingRequest) => void): void; + on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; + on(name: 'refer' | 'bye', callback: (request: IncomingRequest) => void): void; } namespace Session { @@ -144,18 +140,17 @@ declare namespace SIP { media?: MediaOptions; } - interface DTMF { - } + interface DTMF extends Object {} interface Muted { audio?: boolean; - video?: boolean + video?: boolean; } } interface RenderHint { remote?: Element; - local?: Element + local?: Element; } interface MediaConstraints { @@ -185,29 +180,18 @@ declare namespace SIP { render(renderHint: RenderHint): void; on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; - on(name: 'userMedia', callback: (stream: MediaStream) => void): void; + on(name: 'addStream' | 'userMedia', callback: (stream: MediaStream) => void): void; on(name: 'userMediaFailed', callback: (error: string) => void): void; - on(name: 'iceGathering', callback: () => void): void; on(name: 'iceCandidate', callback: (candidate: RTCIceCandidate) => void): void; - on(name: 'iceGatheringComplete', callback: () => void): void; - on(name: 'iceConnection', callback: () => void): void; - on(name: 'iceConnectionChecking', callback: () => void): void; - on(name: 'iceConnectionConnected', callback: () => void): void; - on(name: 'iceConnectionCompleted', callback: () => void): void; - on(name: 'iceConnectionFailed', callback: () => void): void; - on(name: 'iceConnectionDisconnected', callback: () => void): void; - on(name: 'iceConnectionClosed', callback: () => void): void; - on(name: 'getDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; - on(name: 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; - on(name: 'dataChannel', callback: () => void): void; - on(name: 'addStream', callback: (stream: MediaStream) => void): void; + on(name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | 'iceConnectionDisconnected' | 'iceConnectionClosed', callback: () => void): void; + on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; } } /* Parameters */ interface ConfigurationParameters { uri?: string; - wsServers?: string | string[] | { ws_uri: string; weigth: number }[]; + wsServers?: string | string[] | Array<{ ws_uri: string; weigth: number }>; allowLegacyNotifications?: boolean; authenticationFactory?: WebRTC.MediaHandlerFactory; authorizationUser?: string; @@ -304,11 +288,7 @@ declare namespace SIP { localIdentity: NameAddrHeader; remoteIdentity: NameAddrHeader; data: {}; - - on(name: 'progress', callback: (response: IncomingMessage, cause: string) => void): void; - on(name: 'accepted', callback: (response: IncomingMessage, cause: string) => void): void; - on(name: 'rejected', callback: (response: IncomingMessage, cause: string) => void): void; - on(name: 'failed', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; on(name: 'notify', callback: (request: IncomingRequest) => void): void; } @@ -341,7 +321,7 @@ declare namespace SIP { /* Header */ class NameAddrHeader { - constructor(uri: string | URI, displayName: string, parameters: { key: string, value: string }[]); + constructor(uri: string | URI, displayName: string, parameters: Array<{ key: string, value: string }>); uri: string | URI; displayName: string; diff --git a/sip.js/tslint.json b/sip.js/tslint.json index 377cc837d4..105f5736e6 100644 --- a/sip.js/tslint.json +++ b/sip.js/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "no-empty-interface": false + } +} From 2cc1c6e25dc4fd757dc98503f985678ebf4a21ef Mon Sep 17 00:00:00 2001 From: Kir Dergachev Date: Fri, 20 Jan 2017 13:58:52 +0300 Subject: [PATCH 053/306] Fix type definition test errors --- sip.js/index.d.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/sip.js/index.d.ts b/sip.js/index.d.ts index 8c7a297613..a8d2b3c8db 100644 --- a/sip.js/index.d.ts +++ b/sip.js/index.d.ts @@ -1,13 +1,11 @@ -// Type definitions for SIP.js v0.7.6 +// Type definitions for SIP.js 0.7 // Project: https://sipjs.com/ // Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -export = SIP; - -declare namespace SIP { +export declare namespace SIP { class URI { constructor( @@ -105,7 +103,7 @@ declare namespace SIP { accept(options?: Session.AcceptOptions): void; reject(options?: Session.CommonOptions): void; reply(options?: Session.CommonOptions): void; - followRefer(callback: Function): void; + followRefer(callback: () => void): void; on(name: 'progress', callback: (response: IncomingResponse) => void): void; on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; @@ -273,7 +271,7 @@ declare namespace SIP { state: string; event: string; dialog: string; - timers: Object; + timers: {}; errorCodes: number[]; subscribe(): Subscription; unsubscribe(): void; From 1c753b2c69e2df6a45a06cdfa2568a30f7d655ba Mon Sep 17 00:00:00 2001 From: Kir Dergachev Date: Fri, 20 Jan 2017 14:40:08 +0300 Subject: [PATCH 054/306] Fix tslint errors, configure rules --- sip.js/index.d.ts | 10 ++++++---- sip.js/tslint.json | 3 ++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/sip.js/index.d.ts b/sip.js/index.d.ts index a8d2b3c8db..942a0d22b3 100644 --- a/sip.js/index.d.ts +++ b/sip.js/index.d.ts @@ -1,11 +1,13 @@ -// Type definitions for SIP.js 0.7 -// Project: https://sipjs.com/ -// Definitions by: Kir Dergachev +// Type definitions for sip.js 0.7 +// Project: http://sipjs.com +// Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -export declare namespace SIP { +export = SIP; + +declare namespace SIP { class URI { constructor( diff --git a/sip.js/tslint.json b/sip.js/tslint.json index 105f5736e6..c78c443ad2 100644 --- a/sip.js/tslint.json +++ b/sip.js/tslint.json @@ -1,6 +1,7 @@ { "extends": "../tslint.json", "rules": { - "no-empty-interface": false + "no-empty-interface": false, + "export-just-namespace": false } } From 6b1b8e745c79db044dc53eef44c6587113d03a60 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 20 Jan 2017 10:58:59 -0600 Subject: [PATCH 055/306] Fix props callbacks. Type dates as moment.Moment. --- react-datepicker/index.d.ts | 21 +++++++++++---------- react-datepicker/react-datepicker-tests.tsx | 6 +++--- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/react-datepicker/index.d.ts b/react-datepicker/index.d.ts index aec8b61b72..109e47626c 100644 --- a/react-datepicker/index.d.ts +++ b/react-datepicker/index.d.ts @@ -3,9 +3,10 @@ // Definitions by: Rajab Shakirov , Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "react-datepicker" { + import * as React from "react"; + import * as moment from "moment"; + interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; @@ -14,7 +15,7 @@ declare module "react-datepicker" { dateFormat?: string; dateFormatCalendar?: string; disabled?: boolean; - endDate?: {}; + endDate?: moment.Moment; excludeDates?: any[]; filterDate?(): any; fixedHeight?: boolean; @@ -22,12 +23,12 @@ declare module "react-datepicker" { includeDates?: any[]; isClearable?: boolean; locale?: string; - maxDate?: {}; - minDate?: {}; + maxDate?: moment.Moment; + minDate?: moment.Moment; name?: string; - onBlur?(handler: (e: any) => void): any; - onChange(handler: (date?: any, e?: any) => void): any; - onFocus?(handler: (e: any) => void): any; + onBlur?(event: React.FocusEvent): void; + onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): any; + onFocus?(event: React.FocusEvent): void; peekNextMonth?: boolean; placeholderText?: string; popoverAttachment?: string; @@ -37,13 +38,13 @@ declare module "react-datepicker" { renderCalendarTo?: any; required?: boolean; scrollableYearDropdown?: boolean; - selected?: {}; + selected?: moment.Moment | null; selectsEnd?: boolean; selectsStart?: boolean; showMonthDropdown?: boolean; showYearDropdown?: boolean; showWeekNumbers?: boolean; - startDate?: {}; + startDate?: moment.Moment; tabIndex?: number; tetherConstraints?: any[]; title?: string; diff --git a/react-datepicker/react-datepicker-tests.tsx b/react-datepicker/react-datepicker-tests.tsx index 53cd4723b5..df1b02dacf 100644 --- a/react-datepicker/react-datepicker-tests.tsx +++ b/react-datepicker/react-datepicker-tests.tsx @@ -2,8 +2,8 @@ import * as React from "react"; import * as moment from 'moment'; import * as DatePicker from 'react-datepicker'; -class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:string}> { - constructor(props:any) { +class ReactDatePicker extends React.Component<{}, { startDate: moment.Moment; displayName:string; }> { + constructor(props: {}) { super(); this.state = { startDate: moment(), @@ -12,7 +12,7 @@ class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:str this.handleChange = this.handleChange.bind(this); } - handleChange = function(date?:any) { + handleChange = function(date?: moment.Moment | null) { this.setState({ startDate: date }); From 0c26a340bb4b5f0c1f93ad66348cf72818d1302e Mon Sep 17 00:00:00 2001 From: John Date: Fri, 20 Jan 2017 11:05:05 -0600 Subject: [PATCH 056/306] Update version number --- react-datepicker/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-datepicker/index.d.ts b/react-datepicker/index.d.ts index 109e47626c..3ba6f91386 100644 --- a/react-datepicker/index.d.ts +++ b/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker v0.28.1 +// Type definitions for react-datepicker v0.40.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 1e4d93b30843687a5e88ebb5b1574d0a94eb6d92 Mon Sep 17 00:00:00 2001 From: Joel Date: Fri, 20 Jan 2017 17:50:22 -0500 Subject: [PATCH 057/306] fix seek(...) function so that it can return either a Howl object or a number --- howler/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/howler/index.d.ts b/howler/index.d.ts index 1b6604b1aa..df3f6a363b 100644 --- a/howler/index.d.ts +++ b/howler/index.d.ts @@ -66,7 +66,7 @@ interface Howl { rate(idOrSetRate: number): this | number; rate(rate: number, id: number): this; - seek(seek?: number, id?: number): this; + seek(seek?: number, id?: number): this | number; loop(loop?: boolean, id?: number): this; playing(id?: number): boolean; duration(id?: number): number; From cb95e528e74d728691e0a14482b5634685553893 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Sat, 21 Jan 2017 19:49:48 -0500 Subject: [PATCH 058/306] Add ArrayBuffer parameter to js-md5 --- js-md5/index.d.ts | 4 ++++ js-md5/js-md5-tests.ts | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 32ef8b30ff..d635a58a6c 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -9,24 +9,28 @@ interface JQuery { md5(value: string): string; md5(value: Array): string; md5(value: Uint8Array): string; + md5(value: ArrayBuffer): string; } interface JQueryStatic { md5(value: string): string; md5(value: Array): string; md5(value: Uint8Array): string; + md5(value: ArrayBuffer): string; } interface md5 { (value: string): string; (value: Array): string; (value: Uint8Array): string; + (value: ArrayBuffer): string; } interface String { md5(value: string): string; md5(value: Array): string; md5(value: Uint8Array): string; + md5(value: ArrayBuffer): string; } declare module "js-md5" { diff --git a/js-md5/js-md5-tests.ts b/js-md5/js-md5-tests.ts index 984a919ec3..77b10c09ce 100644 --- a/js-md5/js-md5-tests.ts +++ b/js-md5/js-md5-tests.ts @@ -5,6 +5,7 @@ md5(''); md5('中文'); md5([]); md5(new Uint8Array([])); +md5(new ArrayBuffer(0)); $.md5('message'); $.md5('Message to hash'); @@ -12,9 +13,11 @@ $.md5(''); $.md5('中文'); $.md5([]); $.md5(new Uint8Array([])); +$.md5(new ArrayBuffer(0)); 'message'.md5('Message to hash'); 'message'.md5(''); 'message'.md5('中文'); 'message'.md5([]); -'message'.md5(new Uint8Array([])); \ No newline at end of file +'message'.md5(new Uint8Array([])); +'message'.md5(new ArrayBuffer(0)); \ No newline at end of file From bccb2cadc334c36fc262838879d51a9646de3627 Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Sat, 21 Jan 2017 19:54:19 -0500 Subject: [PATCH 059/306] Add ArrayBuffer parameter to js-md5 --- js-md5/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index d635a58a6c..7292463815 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for js-md5 v0.3.0 // Project: https://github.com/emn178/js-md5 -// Definitions by: Roland Greim +// Definitions by: Roland Greim , Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ /// From f96596fa4efa2156052e8a98f4da302d8918fcac Mon Sep 17 00:00:00 2001 From: Michael McCarthy Date: Sat, 21 Jan 2017 20:02:09 -0500 Subject: [PATCH 060/306] Increase version number in header --- js-md5/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-md5/index.d.ts b/js-md5/index.d.ts index 7292463815..db202ed628 100644 --- a/js-md5/index.d.ts +++ b/js-md5/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-md5 v0.3.0 +// Type definitions for js-md5 v0.3.1 // Project: https://github.com/emn178/js-md5 // Definitions by: Roland Greim , Michael McCarthy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ From ab1d41bcd4200fb0e57995c534ddf5ea2bf95da4 Mon Sep 17 00:00:00 2001 From: Eiji Kitamura Date: Sat, 21 Jan 2017 15:50:12 +0900 Subject: [PATCH 061/306] Follow Payment Request spec updates --- paymentrequest/index.d.ts | 69 ++++++++++++++++---------- paymentrequest/paymentrequest-tests.ts | 15 ++++-- 2 files changed, 53 insertions(+), 31 deletions(-) diff --git a/paymentrequest/index.d.ts b/paymentrequest/index.d.ts index 50ef94e1e6..5231f53bc3 100644 --- a/paymentrequest/index.d.ts +++ b/paymentrequest/index.d.ts @@ -1,26 +1,33 @@ // Type definitions for PaymentRequest // Project: https://www.w3.org/TR/payment-request/ -// Definitions by: Adam Cmiel +// Definitions by: Adam Cmiel , Eiji Kitamura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface PaymentRequest extends EventTarget { new (methodData: PaymentMethodData[], details: PaymentDetails, options?: PaymentOptions): PaymentRequest; show(): PromiseLike; abort(): PromiseLike; - shippingAddress?: PaymentAddress; - shippingOption?: string; + canMakePayment(): Promise; + readonly paymentRequestID: string; + readonly shippingAddress?: PaymentAddress; + readonly shippingOption?: string; + readonly shippingType?: string; onshippingaddresschange: PaymentUpdateEventListener; onshippingoptionchange: PaymentUpdateEventListener; } interface PaymentMethodData { supportedMethods: string[]; - data?: Object; + data?: { + supportedNetworks: string[]; + supportedTypes: string[]; + }; } interface PaymentCurrencyAmount { currency: string; value: string; + currencySystem?:string; } interface PaymentDetails { @@ -28,55 +35,63 @@ interface PaymentDetails { displayItems?: PaymentItem[]; shippingOptions?: PaymentShippingOption[]; modifiers?: PaymentDetailsModifier[]; + error?: string; } interface PaymentDetailsModifier { supportedMethods: string[]; total?: PaymentItem; - additionalDisplayItems: PaymentItem[]; + additionalDisplayItems?: PaymentItem[]; + data?: Object; } interface PaymentOptions { - requestShipping: boolean; - requestPayerEmail: boolean; - requestPayerPhone: boolean; + requestShipping?: boolean; + requestPayerEmail?: boolean; + requestPayerPhone?: boolean; + requestPayerName?: boolean; + shippingType?: 'shipping' | 'delivery' | 'pickup'; } interface PaymentItem { label: string; - amount: PaymentCurrencyAmount + amount: PaymentCurrencyAmount; + pending?: boolean; } interface PaymentAddress { - country: string; - addressLine: string[]; - region: string; - city: string; - dependentLocality: string; - postalCode: string; - sortingCode: string; - languageCode: string; - organization: string; - recipient: string; - careOf: string; - phone: string; + readonly country: string; + readonly addressLine: string[]; + readonly region: string; + readonly city: string; + readonly dependentLocality: string; + readonly postalCode: string; + readonly sortingCode: string; + readonly languageCode: string; + readonly organization: string; + readonly recipient: string; + readonly phone: string; } interface PaymentShippingOption { id: string; label: string; amount: PaymentCurrencyAmount; + selected?: boolean; } interface PaymentResponse { - methodName: string; - details: Object; - shippingAddress?: PaymentAddress; - shippingOption?: string; - payerEmail?: string; - payerPhone?: string; + readonly paymentRequestID: string; + readonly methodName: string; + readonly details: Object; + readonly shippingAddress?: PaymentAddress; + readonly shippingOption?: string; + readonly payerEmail?: string; + readonly payerPhone?: string; + readonly payerName?: string; complete(result?: '' | 'success' | 'fail'): PromiseLike; + toJSON(): Object; } interface PaymentUpdateEventListener extends EventListener { diff --git a/paymentrequest/paymentrequest-tests.ts b/paymentrequest/paymentrequest-tests.ts index 4c36c3ff76..62c2721bfb 100644 --- a/paymentrequest/paymentrequest-tests.ts +++ b/paymentrequest/paymentrequest-tests.ts @@ -3,7 +3,7 @@ /// Code examples derived from /// https://developers.google.com/web/fundamentals/discovery-and-monetization/payment-request/ -function makeRequest() { +async function makeRequest() { if (!window.PaymentRequest) { return Promise.reject(new Error("PaymentRequest not available")) } @@ -31,10 +31,12 @@ function makeRequest() { } } - const options = { + const options: PaymentOptions = { requestShipping: true, requestPayerEmail: true, - requestPayerPhone: true + requestPayerPhone: true, + requestPayerName: true, + shippingType: 'delivery' } const request = new window.PaymentRequest(methodData, details, options) @@ -72,7 +74,12 @@ function makeRequest() { })(details, request.shippingAddress)); }) - return request.show() + let canMakePayment = await request.canMakePayment() + if (canMakePayment) { + return request.show() + } else { + throw 'can not make payment on this environment.' + } } async function processPayment(): Promise { From 453ffc9e8a24c7404ca2951fa28e9e54da42f20d Mon Sep 17 00:00:00 2001 From: "Angus.Fenying" Date: Sun, 22 Jan 2017 16:17:37 +0800 Subject: [PATCH 062/306] Added methods cork and uncork for RedisClient. --- redis/index.d.ts | 10 ++++++++++ redis/redis-tests.ts | 8 +++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/redis/index.d.ts b/redis/index.d.ts index 75745b99f4..0e7e2ec4de 100644 --- a/redis/index.d.ts +++ b/redis/index.d.ts @@ -94,6 +94,16 @@ export interface RedisClient extends NodeJS.EventEmitter { end(): void; unref(): void; + /** + * Stop sending commands and queue the commands. + */ + cork(): void; + + /** + * Resume and send the queued commands at once. + */ + uncork(): void; + // Low level command execution send_command(command: string, ...args: any[]): boolean; diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index d98979f256..e0315a809f 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -112,4 +112,10 @@ client.monitor(resCallback); // Send command client.send_command(str, args, resCallback); // Duplicate -client.duplicate(); \ No newline at end of file +client.duplicate(); + +// Pipeline +client.cork(); +client.set("abc", "fff", strCallback); +client.get("abc", resCallback); +client.uncork(); From d2be90a50693461d0e2e4dd20c3d578533a779db Mon Sep 17 00:00:00 2001 From: mkollers Date: Mon, 23 Jan 2017 10:26:59 +0100 Subject: [PATCH 063/306] added group to Node http://visjs.org/docs/network/nodes.html# --- vis/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/vis/index.d.ts b/vis/index.d.ts index 92b6ea6a08..3ee00ba03a 100644 --- a/vis/index.d.ts +++ b/vis/index.d.ts @@ -1497,6 +1497,7 @@ export interface Data { } export interface Node { + group?: string; id?: IdType; label?: string; x?: number; From 39772baa2c32da872c8482088c784eb497e303c0 Mon Sep 17 00:00:00 2001 From: SamSchelfhout Date: Mon, 23 Jan 2017 10:37:00 +0100 Subject: [PATCH 064/306] Update index.d.ts to support ajaxTransport Update index.d.ts to jQuery.ajaxTransport(). See https://api.jquery.com/jQuery.ajaxTransport/ --- jquery/index.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/jquery/index.d.ts b/jquery/index.d.ts index e0bf072983..3a785530aa 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -786,6 +786,15 @@ interface JQueryStatic { */ ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * Creates an object that handles the actual transmission of Ajax data. + * + * @param dataType A string identifying the data type to use. + * @param handler A handler to return the new transport object to use with the data type provided in the first argument. + * @see {@link https://api.jquery.com/jQuery.ajaxTransport/} + */ + ajaxTransport(dataType: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + ajaxSettings: JQueryAjaxSettings; /** From 2e002b40c39a71e25cf438c0303a38740012692e Mon Sep 17 00:00:00 2001 From: Carl Winkler Date: Mon, 23 Jan 2017 18:49:03 +0800 Subject: [PATCH 065/306] Implement types and tests for Dockerode --- dockerode/dockerode-tests.ts | 58 ++++ dockerode/index.d.ts | 643 +++++++++++++++++++++++++++++++++++ dockerode/tsconfig.json | 20 ++ dockerode/tslint.json | 3 + 4 files changed, 724 insertions(+) create mode 100644 dockerode/dockerode-tests.ts create mode 100644 dockerode/index.d.ts create mode 100644 dockerode/tsconfig.json create mode 100644 dockerode/tslint.json diff --git a/dockerode/dockerode-tests.ts b/dockerode/dockerode-tests.ts new file mode 100644 index 0000000000..e1533e91f7 --- /dev/null +++ b/dockerode/dockerode-tests.ts @@ -0,0 +1,58 @@ +import * as Docker from 'dockerode'; + +// Code samples from Dockerode 'Getting started' +const docker = new Docker(); +const docker1 = new Docker({ socketPath: '/var/run/docker.sock' }); +const docker2 = new Docker({ host: 'http://192.168.1.10', port: 3000 }); +const docker3 = new Docker({ protocol: 'http', host: '127.0.0.1', port: 3000 }); +const docker4 = new Docker({ host: '127.0.0.1', port: 3000 }); + +const docker5 = new Docker({ + host: '192.168.1.10', + port: process.env.DOCKER_PORT || 2375, + ca: 'ca', + cert: 'cert', + key: 'key' +}); + +const docker6 = new Docker({ + protocol: 'https', //you can enforce a protocol + host: '192.168.1.10', + port: process.env.DOCKER_PORT || 2375, + ca: 'ca', + cert: 'cert', + key: 'key' +}); + +const container = docker.getContainer('container-id'); +container.inspect((err, data) => { + // NOOP +}); + +container.start((err, data) => { + // NOOP +}); + +container.remove((err, data) => { + // NOOP +}); + +docker.listContainers((err, containers) => { + containers.forEach(container => { + docker + .getContainer(container.Id) + .stop((err, data) => { + // NOOP + }); + }); +}); + +docker.buildImage('archive.tar', { t: 'imageName' }, (err, response) => { + // NOOP +}); + +docker.createContainer({ Tty: true }, (err, container) => { + container.start((err, data) => { + // NOOP + }); +}); \ No newline at end of file diff --git a/dockerode/index.d.ts b/dockerode/index.d.ts new file mode 100644 index 0000000000..2c5caaf9cc --- /dev/null +++ b/dockerode/index.d.ts @@ -0,0 +1,643 @@ +// Type definitions for dockerode 2.3 +// Project: https://github.com/apocas/dockerode +// Definitions by: Carl Winkler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as stream from 'stream'; +import * as events from 'events'; + + +declare namespace Dockerode { + interface Container { + inspect(options: {}, callback: Callback): void; + inspect(callback: Callback): void; + inspect(options?: {}): { id: string }; + + rename(options: {}, callback: Callback): void; + + update(options: {}, callback: Callback): void; + + top(options: {}, callback: Callback): void; + top(callback: Callback): void; + + changes(callback: Callback): void; + + export(callback: Callback): void; + + start(options: {}, callback: Callback): void; + start(callback: Callback): void; + + pause(options: {}, callback: Callback): void; + pause(callback: Callback): void; + + unpause(options: {}, callback: Callback): void; + unpause(callback: Callback): void; + + exec(options: {}, callback: Callback): void; + + commit(options: {}, callback: Callback): void; + commit(callback: Callback): void; + + stop(options: {}, callback: Callback): void; + stop(callback: Callback): void; + + restart(options: {}, callback: Callback): void; + restart(callback: Callback): void; + + kill(options: {}, callback: Callback): void; + kill(callback: Callback): void; + + resize(options: {}, callback: Callback): void; + resize(callback: Callback): void; + + wait(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + /** Deprecated since RAPI v1.20 */ + copy(options: {}, callback: Callback): void; + /** Deprecated since RAPI v1.20 */ + copy(callback: Callback): void; + + getArchive(options: {}, callback: Callback): void; + + infoArchive(options: {}, callback: Callback): void; + + /** @param file Filename (will read synchronously), Buffer or stream */ + putArchive(file: string | Buffer | NodeJS.ReadableStream, options: {}, callback: Callback): void; + + logs(options: { stdout?: boolean, stderr?: boolean, follow?: boolean, since?: number, details?: boolean, tail?: number, timestamps?: boolean }, callback: Callback): void; + logs(callback: Callback): void; + + stats(options: {}, callback: Callback): void; + stats(callback: Callback): void; + + attach(options: {}, callback: Callback): void; + + modem: any; + id?: string; + } + + interface Image { + inspect(callback: Callback): void; + + history(callback: Callback): void; + + get(callback: Callback): void; + + push(options: {}, callback: Callback): void; + push(callback: Callback): void; + + tag(options: {}, callback: Callback): void; + tag(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Volume { + inspect(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + modem: any; + name?: string; + } + + interface Service { + inspect(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + update(options: {}, callback: Callback): void; + + modem: any; + id?: string; + } + + interface Task { + inspect(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Node { + inspect(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Network { + inspect(callback: Callback): void; + + remove(options: {}, callback: Callback): void; + remove(callback: Callback): void; + + connect(options: {}, callback: Callback): void; + connect(callback: Callback): void; + + disconnect(options: {}, callback: Callback): void; + disconnect(callback: Callback): void; + + modem: any; + id?: string; + } + + interface Exec { + inspect(callback: Callback): void; + + start(options: {}, callback: Callback): void; + + resize(options: {}, callback: Callback): void; + + modem: any; + id?: string; + } + + interface ImageInfo { + Id: string; + ParentId: string; + RepoTags: string[]; + RepoDigests?: string[]; + Created: number; + Size: number; + VirtualSize: number; + Labels: { [label: string]: string }; + } + + interface ContainerInfo { + Id: string; + Names: string[]; + Image: string; + ImageID: string; + Command: string; + Created: number; + Ports: Port[]; + Labels: { [label: string]: string }; + Status: string; + HostConfig: { + NetworkMode: string; + }; + NetworkSettings: { + Networks: { [networkType: string]: NetworkInfo } + }; + } + + interface Port { + IP: string; + PrivatePort: number; + PublicPort: number; + Type: string; + } + + interface NetworkInfo { + IPAMConfig?: any; + Links?: any; + Aliases?: any; + NetworkID: string; + EndpointID: string; + Gateway: string; + IPAddress: string; + IPPrefixLen: number; + IPv6Gateway: string; + GlobalIPv6Address: string; + GlobalIPv6PrefixLen: number; + MacAddress: string; + } + + interface ContainerInspectInfo { + Id: string; + Created: string; + Path: string; + Args: string[]; + State: { + Status: string; + Running: boolean; + Paused: boolean; + Restarting: boolean; + OOMKilled: boolean; + Dead: boolean; + Pid: number; + ExitCode: number; + Error: string; + StartedAt: string; + FinishedAt: string; + }; + Image: string; + ResolvConfPath: string; + HostnamePath: string; + HostsPath: string; + LogPath: string; + Name: string; + RestartCount: number; + Driver: string; + MountLabel: string; + ProcessLabel: string; + AppArmorProfile: string; + ExecIDs?: any; + HostConfig: HostConfig; + GraphDriver: { + Name: string; + Data: { + DeviceId: string; + DeviceName: string; + DeviceSize: string; + } + }; + Mounts: Array<{ + Source: string; + Destination: string; + Mode: string; + RW: boolean; + Propagation: string; + }>; + Config: { + Hostname: string; + Domainname: string; + User: string; + AttachStdin: boolean; + AttachStdout: boolean; + AttachStderr: boolean; + ExposedPorts: { [portAndProtocol: string]: {} }; + Tty: boolean; + OpenStdin: boolean; + StdinOnce: boolean; + Env: string[]; + Cmd: string[]; + Image: string; + Volumes: { [volume: string]: {} }; + WorkingDir: string; + Entrypoint?: any; + OnBuild?: any; + Labels: { [label: string]: string } + }; + NetworkSettings: { + Bridge: string; + SandboxID: string; + HairpinMode: boolean; + LinkLocalIPv6Address: string; + LinkLocalIPv6PrefixLen: number; + Ports: { + [portAndProtocol: string]: { + HostIp: string; + HostPort: string; + } + }; + SandboxKey: string; + SecondaryIPAddresses?: any; + SecondaryIPv6Addresses?: any; + EndpointID: string; + Gateway: string; + GlobalIPv6Address: string; + GlobalIPv6PrefixLen: number; + IPAddress: string; + IPPrefixLen: number; + IPv6Gateway: string; + MacAddress: string; + Networks: { + [type: string]: { + IPAMConfig?: any; + Links?: any; + Aliases?: any; + NetworkID: string; + EndpointID: string; + Gateway: string; + IPAddress: string; + IPPrefixLen: number; + IPv6Gateway: string; + GlobalIPv6Address: string; + GlobalIPv6PrefixLen: number; + MacAddress: string; + } + } + }; + } + + interface HostConfig { + Binds: string[]; + ContainerIDFile: string; + LogConfig: { + Type: string; + Config: any; + }; + NetworkMode: string; + PortBindings?: any; + RestartPolicy: { + Name: string; + MaximumRetryCount: number; + }; + VolumeDriver: string; + VolumesFrom?: any; + CapAdd?: any; + CapDrop?: any; + Dns: any[]; + DnsOptions: any[]; + DnsSearch: any[]; + ExtraHosts?: any; + IpcMode: string; + Links?: any; + OomScoreAdj: number; + PidMode: string; + Privileged: boolean; + PublishAllPorts: boolean; + ReadonlyRootfs: boolean; + SecurityOpt?: any; + UTSMode: string; + ShmSize: number; + ConsoleSize: number[]; + Isolation: string; + CpuShares: number; + CgroupParent: string; + BlkioWeight: number; + BlkioWeightDevice?: any; + BlkioDeviceReadBps?: any; + BlkioDeviceWriteBps?: any; + BlkioDeviceReadIOps?: any; + BlkioDeviceWriteIOps?: any; + CpuPeriod: number; + CpuQuota: number; + CpusetCpus: string; + CpusetMems: string; + Devices?: any; + KernelMemory: number; + Memory: number; + MemoryReservation: number; + MemorySwap: number; + MemorySwappiness: number; + OomKillDisable: boolean; + PidsLimit: number; + Ulimits?: any; + } + + interface ImageInspectInfo { + Id: string; + RepoTags: string[]; + RepoDigests: string[]; + Parent: string; + Comment: string; + Created: string; + Container: string; + ContainerConfig: + { + Hostname: string; + Domainname: string; + User: string; + AttachStdin: boolean; + AttachStdout: boolean; + AttachStderr: boolean; + ExposedPorts: { [portAndProtocol: string]: {} }; + Tty: boolean; + OpenStdin: boolean; + StdinOnce: boolean; + Env: string[]; + Cmd: string[]; + ArgsEscaped: boolean; + Image: string; + Volumes: { [path: string]: {} }, + WorkingDir: string; + Entrypoint?: any; + OnBuild?: any[]; + Labels: { [label: string]: string } + }; + DockerVersion: string; + Author: string; + Config: + { + Hostname: string; + Domainname: string; + User: string; + AttachStdin: boolean; + AttachStdout: boolean; + AttachStderr: boolean; + ExposedPorts: { [portAndProtocol: string]: {} } + Tty: boolean; + OpenStdin: boolean; + StdinOnce: boolean; + Env: string[]; + Cmd: string[]; + ArgsEscaped: boolean; + Image: string; + Volumes: { [path: string]: {} }, + WorkingDir: string; + Entrypoint?: any; + OnBuild: any[]; + Labels: { [label: string]: string } + }; + Architecture: string; + Os: string; + Size: number; + VirtualSize: number; + GraphDriver: + { + Name: string; + Data: + { + DeviceId: string; + DeviceName: string; + DeviceSize: string; + } + }; + } + + interface ContainerCreateOptions { + name?: string; + Hostname?: string; + Domainname?: string; + User?: string; + AttachStdin?: boolean; + AttachStdout?: boolean; + AttachStderr?: boolean; + Tty?: boolean; + OpenStdin?: boolean; + StdinOnce?: boolean; + Env?: string[]; + Cmd?: string[]; + Entrypoint?: string; + Image?: string; + Labels?: { [label: string]: string }; + Volumes?: { [volume: string]: {} }; + WorkingDir?: string; + NetworkDisabled?: boolean; + MacAddress?: boolean; + ExposedPorts?: { [port: string]: {} }; + StopSignal?: string; + HostConfig?: { + Binds?: string[]; + Links?: string[]; + Memory?: number; + MemorySwap?: number; + MemoryReservation?: number; + KernelMemory?: number; + CpuPercent?: number; + CpuShares?: number; + CpuPeriod?: number; + CpuQuota?: number; + CpusetMems?: string; + MaximumIOps?: number; + MaxmimumIOBps?: number; + BlkioWeightDevice?: Array<{}>; + BlkioDeviceReadBps?: Array<{}>; + BlkioDeviceReadIOps?: Array<{}>; + BlkioDeviceWriteBps?: Array<{}>; + BlkioDeviceWriteIOps?: Array<{}>; + MemorySwappiness?: number; + OomKillDisable?: boolean; + OomScoreAdj?: number; + PidMode?: string; + PidsLimit?: number; + PortBindings?: { [portAndProtocol: string]: Array<{ [index: string]: string }> }; + PublishAllPorts?: boolean; + Privileged?: boolean; + ReadonlyRootfs?: boolean; + Dns?: string[]; + DnsOptions?: string[]; + DnsSearch?: string[]; + ExtraHosts?: any; + VolumesFrom?: string[]; + CapAdd?: string[]; + CapDrop?: string[]; + GroupAdd?: string[]; + RestartPolicy?: { [index: string]: number | string }; + NetworkMode?: string; + Devices?: any[]; + Sysctls?: { [index: string]: string }; + Ulimits?: Array<{}>; + LogConfig?: { [index: string]: string | {} }; + SecurityOpt?: { [index: string]: any }; + CgroupParent?: string; + VolumeDriver?: string; + ShmSize?: number; + }; + NetworkingConfig?: { + EndpointsConfig?: { + [index: string]: any; + isolated_nw?: { + [index: string]: any; + IPAMConfig?: { + IPv4Address?: string; + IPv6Adress?: string; + LinkLocalIPs?: string[]; + } + Links?: string[]; + Aliases?: string[]; + } + } + }; + } + + interface DockerOptions { + socketPath?: string; + host?: string; + port?: number; + ca?: string; + cert?: string; + key?: string; + protocol?: "https" | "http"; + timeout?: number; + } +} + +type Callback = (error?: any, result?: T) => void; + +declare class Dockerode { + constructor(options?: Dockerode.DockerOptions); + + createContainer(options: Dockerode.ContainerCreateOptions, callback: Callback): void; + + createImage(options: {}, callback: Callback): void; + createImage(auth: any, options: {}, callback: Callback): void; + + loadImage(file: string, options: {}, callback: Callback): void; + loadImage(file: string, callback: Callback): void; + + importImage(file: string, options: {}, callback: Callback): void; + importImage(file: string, callback: Callback): void; + + checkAuth(options: any, callback: Callback): void; + + buildImage(file: string | NodeJS.ReadableStream, options: {}, callback: Callback): void; + buildImage(file: string | NodeJS.ReadableStream, callback: Callback): void; + + getContainer(id: string): Dockerode.Container; + + getImage(name: string): Dockerode.Image; + + getVolume(name: string): Dockerode.Volume; + + getService(id: string): Dockerode.Service; + + getTask(id: string): Dockerode.Task; + + getNode(id: string): Node; + + getNetwork(id: string): Dockerode.Network; + + getExec(id: string): Dockerode.Exec; + + listContainers(options: {}, callback: Callback): void; + listContainers(callback: Callback): void; + + listImages(options: {}, callback: Callback): void; + listImages(callback: Callback): void; + + listServices(options: {}, callback: Callback): void; + listServices(callback: Callback): void; + + listNodes(options: {}, callback: Callback): void; + listNodes(callback: Callback): void; + + listTasks(options: {}, callback: Callback): void; + listTasks(callback: Callback): void; + + listVolumes(options: {}, callback: Callback): void; + listVolumes(callback: Callback): void; + + listNetworks(options: {}, callback: Callback): void; + listNetworks(callback: Callback): void; + + createVolume(options: {}, callback: Callback): void; + + createService(options: {}, callback: Callback): void; + + createNetwork(options: {}, callback: Callback): void; + + searchImages(options: {}, callback: Callback): void; + + info(callback: Callback): void; + + version(callback: Callback): void; + + ping(callback: Callback): void; + + getEvents(options: {}, callback: Callback): void; + getEvents(callback: Callback): void; + + pull(repoTag: string, options: {}, callback: Callback, auth?: {}): Dockerode.Image; + + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, createOptions: {}, startOptions: {}, callback: Callback): events.EventEmitter; + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, startOptions: {}, callback: Callback): events.EventEmitter; + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, callback: Callback): events.EventEmitter; + run(image: string, cmd: string[], outputStream: NodeJS.WritableStream, createOptions: {}, callback: Callback): events.EventEmitter; + + swarmInit(options: {}, callback: Callback): void; + + swarmJoin(options: {}, callback: Callback): void; + + swarmLeave(options: {}, callback: Callback): void; + + swarmUpdate(options: {}, callback: Callback): void; + + modem: any; +} + +export = Dockerode; \ No newline at end of file diff --git a/dockerode/tsconfig.json b/dockerode/tsconfig.json new file mode 100644 index 0000000000..a077f02e3c --- /dev/null +++ b/dockerode/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dockerode-tests.ts" + ] +} \ No newline at end of file diff --git a/dockerode/tslint.json b/dockerode/tslint.json new file mode 100644 index 0000000000..785a601162 --- /dev/null +++ b/dockerode/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file From ff113b3b1cfb2b7c98e2efd6e10ddb04d43bc031 Mon Sep 17 00:00:00 2001 From: darlin Date: Mon, 23 Jan 2017 20:14:41 +0800 Subject: [PATCH 066/306] add sub module export --- crypto-js/index.d.ts | 237 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 234 insertions(+), 3 deletions(-) diff --git a/crypto-js/index.d.ts b/crypto-js/index.d.ts index 5fdf193254..a2c0ee381d 100644 --- a/crypto-js/index.d.ts +++ b/crypto-js/index.d.ts @@ -3,9 +3,6 @@ // Definitions by: Michael Zabka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = CryptoJS; -export as namespace CryptoJS; - declare var CryptoJS: CryptoJS.Hashes; declare namespace CryptoJS { type Hash = (message: string, key?: string, ...options: any[]) => string; @@ -113,5 +110,239 @@ declare namespace CryptoJS { NoPadding: Padding; }; } + } +declare module "crypto-js" { + var CryptoJS: CryptoJS.Hashes; + export = CryptoJS; +} + +/* --------------------------------- */ +declare module "crypto-js/core" { + var core: any; + export = core; +} + +declare module "crypto-js/x64-core" { + var x64: any; + export = x64; +} + +declare module "crypto-js/lib-typedarrays" { + var libWordArray: any; + export = libWordArray; +} + +/* --------------------------------- */ +declare module "crypto-js/md5" { + var MD5: CryptoJS.Hash; + export = MD5; +} + +declare module "crypto-js/sha1" { + var SHA1: CryptoJS.Hash; + export = SHA1; +} + +declare module "crypto-js/sha256" { + var SHA256: CryptoJS.Hash; + export = SHA256; +} + +declare module "crypto-js/sha224" { + var SHA224: CryptoJS.Hash; + export = SHA224; +} + +declare module "crypto-js/sha512" { + var SHA512: CryptoJS.Hash; + export = SHA512; +} + +declare module "crypto-js/sha384" { + var SHA384: CryptoJS.Hash; + export = SHA384; +} + +declare module "crypto-js/sha3" { + var SHA3: CryptoJS.Hash; + export = SHA3; +} + +declare module "crypto-js/ripemd160" { + var RIPEMD160: CryptoJS.Hash; + export = RIPEMD160; +} + +/* --------------------------------- */ +declare module "crypto-js/hmac-md5" { + var HmacMD5: CryptoJS.Hash; + export = HmacMD5; +} + +declare module "crypto-js/hmac-sha1" { + var HmacSHA1: CryptoJS.Hash; + export = HmacSHA1; +} + +declare module "crypto-js/hmac-sha256" { + var HmacSHA256: CryptoJS.Hash; + export = HmacSHA256; +} + +declare module "crypto-js/hmac-sha224" { + var HmacSHA224: CryptoJS.Hash; + export = HmacSHA224; +} + +declare module "crypto-js/hmac-sha512" { + var HmacSHA512: CryptoJS.Hash; + export = HmacSHA512; +} + +declare module "crypto-js/hmac-sha384" { + var HmacSHA384: CryptoJS.Hash; + export = HmacSHA384; +} + +declare module "crypto-js/hmac-sha3" { + var HmacSHA3: CryptoJS.Hash; + export = HmacSHA3; +} + +declare module "crypto-js/hmac-ripemd160" { + var HmacRIPEMD160: CryptoJS.Hash; + export = HmacRIPEMD160; +} + +/* --------------------------------- */ +declare module "crypto-js/pbkdf2" { + var PBKDF2: CryptoJS.Hash; + export = PBKDF2; +} + +/* --------------------------------- */ +declare module "crypto-js/aes" { + var AES: CryptoJS.Cipher; + export = AES; +} + +declare module "crypto-js/tripledes" { + var TripleDES: CryptoJS.Cipher; + export = TripleDES; +} + +declare module "crypto-js/rc4" { + var RC4: CryptoJS.Cipher; + export = RC4; +} + +declare module "crypto-js/rabbit" { + var Rabbit: CryptoJS.Cipher; + export = Rabbit; +} + +declare module "crypto-js/rabbit-legacy" { + var RabbitLegacy: CryptoJS.Cipher; + export = RabbitLegacy; +} + +declare module "crypto-js/evpkdf" { + var EvpKDF: CryptoJS.Cipher; + export = EvpKDF; +} + +/* --------------------------------- */ +declare module "crypto-js/format-openssl" { + var FormatOpenssl: any; + export = FormatOpenssl; +} + +declare module "crypto-js/format-hex" { + var FormatHex: any; + export = FormatHex; +} + +/* --------------------------------- */ +declare module "crypto-js/enc-latin1" { + var encLatin1: CryptoJS.Encoder; + export = encLatin1; +} + +declare module "crypto-js/enc-utf8" { + var encUtf8: CryptoJS.Encoder; + export = encUtf8; +} + +declare module "crypto-js/enc-hex" { + var encHex: CryptoJS.Encoder; + export = encHex; +} + +declare module "crypto-js/enc-utf16" { + var encUtf16: CryptoJS.Encoder; + export = encUtf16; +} + +declare module "crypto-js/enc-base64" { + var encBase64: CryptoJS.Encoder; + export = encBase64; +} + +/* --------------------------------- */ +declare module "crypto-js/mode-cfb" { + var modeCFB: CryptoJS.Mode; + export = modeCFB; +} + +declare module "crypto-js/mode-ctr" { + var modeCTR: CryptoJS.Mode; + export = modeCTR; +} + +declare module "crypto-js/mode-ctr-gladman" { + var modeCTRGladman: CryptoJS.Mode; + export = modeCTRGladman; +} + +declare module "crypto-js/mode-ofb" { + var modeOFB: CryptoJS.Mode; + export = modeOFB; +} + +declare module "crypto-js/mode-ecb" { + var modeECB: CryptoJS.Mode; + export = modeECB; +} + +/* --------------------------------- */ +declare module "crypto-js/pad-pkcs7" { + var padPkcs7: CryptoJS.Padding; + export = padPkcs7; +} + +declare module "crypto-js/pad-ansix923" { + var padAnsiX923: CryptoJS.Padding; + export = padAnsiX923; +} + +declare module "crypto-js/pad-iso10126" { + var padIso10126: CryptoJS.Padding; + export = padIso10126; +} + +declare module "crypto-js/pad-iso97971" { + var padIso97971: CryptoJS.Padding; + export = padIso97971; +} + +declare module "crypto-js/pad-zeropadding" { + var padZeroPadding: CryptoJS.Padding; + export = padZeroPadding; +} + +declare module "crypto-js/pad-nopadding" { + var padNoPadding: CryptoJS.Padding; + export = padNoPadding; +} From 7ba0fa586127729532dbe3aad56f6547385745fd Mon Sep 17 00:00:00 2001 From: darlin Date: Mon, 23 Jan 2017 20:35:35 +0800 Subject: [PATCH 067/306] add typescript module export to suport import * as SimpleMDE from 'simplemde' --- simplemde/index.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/simplemde/index.d.ts b/simplemde/index.d.ts index 6c199f48a7..eb463ae655 100644 --- a/simplemde/index.d.ts +++ b/simplemde/index.d.ts @@ -127,4 +127,8 @@ declare class SimpleMDE { static toggleFullScreen: (editor: SimpleMDE) => void; static undo: (editor: SimpleMDE) => void; static redo: (editor: SimpleMDE) => void; -} \ No newline at end of file +} + +declare module "simplemde" { + export = SimpleMDE; +} From fc6a9729df46769b7a50cffe4414dc913ba6da28 Mon Sep 17 00:00:00 2001 From: Kir Dergachev Date: Mon, 23 Jan 2017 16:14:33 +0300 Subject: [PATCH 068/306] Fixes errors references. Removes references to webrtc --- sip.js/index.d.ts | 68 ++++++++++++++++++++---------------------- sip.js/sip.js-tests.ts | 36 +++++++++++----------- sip.js/tslint.json | 3 +- 3 files changed, 51 insertions(+), 56 deletions(-) diff --git a/sip.js/index.d.ts b/sip.js/index.d.ts index 942a0d22b3..be01cd3682 100644 --- a/sip.js/index.d.ts +++ b/sip.js/index.d.ts @@ -3,21 +3,23 @@ // Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +declare interface SIP { + UA: { + new (configuration?: sipjs.ConfigurationParameters): sipjs.UA; + }; + URI: { + new (scheme?: string, user?: string, host?: string, port?: number, parameters?: string[], headers?: string[]): sipjs.URI; + parse(uri: string): sipjs.URI; + }; + NameAddrHeader: { + new (uri: string | sipjs.URI, displayName: string, parameters: Array<{ key: string, value: string }>): sipjs.NameAddrHeader; + parse(name_addr_header: string): sipjs.NameAddrHeader; + }; +} -export = SIP; - -declare namespace SIP { - - class URI { - constructor( - scheme?: string, - user?: string, - host?: string, - port?: number, - parameters?: string[], - headers?: string[]); +declare namespace sipjs { + interface URI { scheme?: string; user?: string; host?: string; @@ -35,8 +37,6 @@ declare namespace SIP { clearHeaders(): void; clone(): URI; toString(): string; - - static parse(uri: string): URI; } namespace UA.EventArgs { @@ -45,8 +45,7 @@ declare namespace SIP { interface RegistrationFailedArgs extends UnregisteredArgs { } } - class UA { - constructor(configuration?: ConfigurationParameters); + interface UA { start(): void; stop(): void; register(options?: ExtraHeadersOptions): UA; @@ -59,7 +58,7 @@ declare namespace SIP { request(method: string, target: string | URI, options?: RequestOptions): ClientContext; on(name: 'connected', callback: (args: UA.EventArgs.ConnectedArgs) => void): void; - on(name: 'disconnected' | 'registered', callback: () => void): void; + on(name: 'disconnected' | 'registered' | string, callback: () => void): void; on(name: 'unregistered', callback: (args: UA.EventArgs.UnregisteredArgs) => void): void; on(name: 'registrationFailed', callback: (args: UA.EventArgs.RegistrationFailedArgs) => void): void; on(name: 'invite', callback: (session: Session) => void): void; @@ -81,7 +80,7 @@ declare namespace SIP { } } - class Session { + interface Session { startTime?: Date; endTime?: Date; ua?: UA; @@ -95,8 +94,8 @@ declare namespace SIP { dtmf(tone: string | number, options?: Session.DtmfOptions): Session; terminate(options?: Session.CommonOptions): Session; bye(options?: Session.CommonOptions): Session; - getLocalStreams(): MediaStream[]; - getRemoteStreams(): MediaStream[]; + getLocalStreams(): any[]; + getRemoteStreams(): any[]; refer(target: string | Session, options?: ExtraHeadersOptions): Session; mute(options?: ExtraHeadersOptions): void; unmute(options?: ExtraHeadersOptions): void; @@ -111,7 +110,7 @@ declare namespace SIP { on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; - on(name: 'cancel', callback: () => void): void; + on(name: 'cancel' | string, callback: () => void): void; on(name: 'replaced', callback: (newSession: Session) => void): void; on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; @@ -136,7 +135,7 @@ declare namespace SIP { } interface AcceptOptions { - RTCConstraints?: RTCPeerConnection; + RTCConstraints?: any; media?: MediaOptions; } @@ -169,21 +168,21 @@ declare namespace SIP { interface Options { stunServers?: string | string[]; turnServers?: TurnServer | TurnServer[]; - RTCConstraints?: RTCPeerConnection; + RTCConstraints?: any; } type MediaHandlerFactory = (session: Session, options: Options) => MediaHandler; class MediaHandler { - getLocalStreams(): MediaStream[]; - getRemoteStreams(): MediaStream[]; + getLocalStreams(): any[]; + getRemoteStreams(): any[]; render(renderHint: RenderHint): void; on(name: 'userMediaRequest', callback: (constraints: MediaConstraints) => void): void; - on(name: 'addStream' | 'userMedia', callback: (stream: MediaStream) => void): void; + on(name: 'addStream' | 'userMedia', callback: (stream: any) => void): void; on(name: 'userMediaFailed', callback: (error: string) => void): void; - on(name: 'iceCandidate', callback: (candidate: RTCIceCandidate) => void): void; - on(name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | 'iceConnectionDisconnected' | 'iceConnectionClosed', callback: () => void): void; + on(name: 'iceCandidate', callback: (candidate: any) => void): void; + on(name: 'iceGathering' | 'iceGatheringComplete' | 'iceConnection' | 'iceConnectionChecking' | 'iceConnectionConnected' | 'iceConnectionCompleted' | 'iceConnectionFailed' | 'iceConnectionDisconnected' | 'iceConnectionClosed' | string, callback: () => void): void; on(name: 'dataChannel' | 'getDescription' | 'setDescription', callback: (sdpWrapper: { type: string, sdp: string }) => void): void; } } @@ -247,7 +246,7 @@ declare namespace SIP { interface MediaOptions { constraints?: MediaConstraints; - stream?: MediaStream; + stream?: any; render?: RenderHint; } @@ -256,7 +255,7 @@ declare namespace SIP { anonymous?: boolean; rel100?: string; inviteWithoutSdp?: boolean; - RTCConstraints?: RTCPeerConnection; + RTCConstraints?: any; } interface RequestOptions extends ExtraHeadersOptions { @@ -290,6 +289,7 @@ declare namespace SIP { data: {}; on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; on(name: 'notify', callback: (request: IncomingRequest) => void): void; + on(name: string, callback: () => void): void; } interface ClientContext extends Context { @@ -320,9 +320,7 @@ declare namespace SIP { } /* Header */ - class NameAddrHeader { - constructor(uri: string | URI, displayName: string, parameters: Array<{ key: string, value: string }>); - + interface NameAddrHeader { uri: string | URI; displayName: string; @@ -330,7 +328,5 @@ declare namespace SIP { getParam(key: string): string; deleteParam(key: string): string; clearParams(): void; - - static parse(name_addr_header: string): NameAddrHeader; } } diff --git a/sip.js/sip.js-tests.ts b/sip.js/sip.js-tests.ts index f688fe67ae..524caf1827 100644 --- a/sip.js/sip.js-tests.ts +++ b/sip.js/sip.js-tests.ts @@ -1,11 +1,11 @@ -import SIP = require("./index"); +declare var sip: SIP; -let ua: SIP.UA = new SIP.UA(); +let ua: sipjs.UA = new sip.UA(); -const mediaHandler = (session: SIP.Session, options: SIP.WebRTC.Options) => new SIP.WebRTC.MediaHandler(); +const mediaHandler = (session: sipjs.Session, options: sipjs.WebRTC.Options) => new sipjs.WebRTC.MediaHandler(); const logConnector = (level: string, category: string, label: string, content: string) => null; -const uaWithConfig: SIP.UA = new SIP.UA({ +const uaWithConfig: sipjs.UA = new sip.UA({ uri: "wss://uri", wsServers: ["s1", "s2"], allowLegacyNotifications: true, @@ -38,7 +38,7 @@ const uaWithConfig: SIP.UA = new SIP.UA({ stunServers: ["", ""], turnServers: [ { - password: "", + password: "", username: "", urls: ["", ""] } @@ -61,15 +61,15 @@ ua.unregister({ extraHeaders: [""], all: true }); const isConnected: boolean = ua.isConnected(); const isRegistered: boolean = ua.isRegistered(); -const message: SIP.Message = ua.message("", "", { contentType: "" }); +const message: sipjs.Message = ua.message("", "", { contentType: "" }); -ua.subscribe("", "", { expires: 1, extraHeaders: [""]}); -const subscription: SIP.Subscription = ua.subscribe(new SIP.URI(), "", { expires: 1, extraHeaders: [""]}); +ua.subscribe("", "", { expires: 1, extraHeaders: [""] }); +const subscription: sipjs.Subscription = ua.subscribe(new sip.URI(), "", { expires: 1, extraHeaders: [""] }); let session = ua.invite("", new HTMLVideoElement()); -const inviteOptions: SIP.InviteOptions = { - media: { +const inviteOptions: sipjs.InviteOptions = { + media: { constraints: { audio: true, video: false }, stream: new MediaStream(), render: { remote: new Element(), local: new Element() }, @@ -77,17 +77,17 @@ const inviteOptions: SIP.InviteOptions = { anonymous: true, rel100: "", inviteWithoutSdp: true, - RTCConstraints: new RTCPeerConnection() + RTCConstraints: {} } session = ua.invite("", inviteOptions); -ua.on('connected', (args: SIP.UA.EventArgs.ConnectedArgs) => {}); -ua.on('disconnected', () => {}); -ua.on('registered', () => {}); -ua.on('unregistered', (args: SIP.UA.EventArgs.UnregisteredArgs) => {}); -ua.on('registrationFailed', (args: SIP.UA.EventArgs.RegistrationFailedArgs) => {}); -ua.on('invite', (session: SIP.Session) => { +ua.on('connected', (args: sipjs.UA.EventArgs.ConnectedArgs) => { }); +ua.on('disconnected', () => { }); +ua.on('registered', () => { }); +ua.on('unregistered', (args: sipjs.UA.EventArgs.UnregisteredArgs) => { }); +ua.on('registrationFailed', (args: sipjs.UA.EventArgs.RegistrationFailedArgs) => { }); +ua.on('invite', (session: sipjs.Session) => { session.on('progress', (response) => { }); session.on('accepted', (response) => { @@ -96,4 +96,4 @@ ua.on('invite', (session: SIP.Session) => { }); }); -ua.on('message', (message: SIP.Message) => {}); +ua.on('message', (message: sipjs.Message) => { }); diff --git a/sip.js/tslint.json b/sip.js/tslint.json index c78c443ad2..105f5736e6 100644 --- a/sip.js/tslint.json +++ b/sip.js/tslint.json @@ -1,7 +1,6 @@ { "extends": "../tslint.json", "rules": { - "no-empty-interface": false, - "export-just-namespace": false + "no-empty-interface": false } } From ebf5d7ce980cd6ed58e13894bd957248d50e2c35 Mon Sep 17 00:00:00 2001 From: Jan Varwig Date: Mon, 23 Jan 2017 15:57:31 +0100 Subject: [PATCH 069/306] Add spline property to c3 ChartConfiguration This has been added to C3 in 0.4.11: https://github.com/c3js/c3/commit/bbb6d1c0366164b6c472b87d2cbde7dbc7c4629e --- c3/index.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/c3/index.d.ts b/c3/index.d.ts index aa960b0b60..5edb096395 100644 --- a/c3/index.d.ts +++ b/c3/index.d.ts @@ -248,6 +248,15 @@ declare namespace c3 { */ width?: number; }; + + spline?: { + interpolation?: { + /** + * Set custom spline interpolation + */ + type?: 'linear' | 'linear-closed' | 'basis' | 'basis-open' | 'basis-closed' | 'bundle' | 'cardinal' | 'cardinal-open' | 'cardinal-closed' | 'monotone'; + }; + }; } interface Data { From ef8a64d27c4036fe9e1103736aaedd5890aa347d Mon Sep 17 00:00:00 2001 From: Oleg Solomka Date: Mon, 23 Jan 2017 16:14:41 -0600 Subject: [PATCH 070/306] rename `createBrowserHistory` to `createHistory ` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `createBrowserHistory ` was only introduced in the `history@4.0.0-1` prior to that the `createHistory` was used. So if you will install `@types/history@^2.0.0` and `history@^2.0.0`(or even `^3.x.x`) it will break with the next error: ``` ./src/client/history.ts (1,10): error TS2305: Module ‘”/@types/history/index"' has no exported member 'createHistory'. ``` This commit brings the `createHistory` back thus solves the issue for `history@^2.x.x` and `history@^3.x.x`. --- history/v2/history-tests.ts | 20 ++++++++++---------- history/v2/index.d.ts | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/history/v2/history-tests.ts b/history/v2/history-tests.ts index 454b223e09..598d934e8d 100644 --- a/history/v2/history-tests.ts +++ b/history/v2/history-tests.ts @@ -1,4 +1,4 @@ -import { createBrowserHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' +import { createHistory, createLocation, useBasename, useBeforeUnload, useQueries } from 'history' import { getUserConfirmation } from 'history/lib/DOMUtils' @@ -10,7 +10,7 @@ let doSomethingAsync: () => Promise; let input = { value: "" }; { - let history = createBrowserHistory() + let history = createHistory() // Listen for changes to the current location. The // listener is called once immediately. @@ -46,7 +46,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() // Pushing a path string. history.push('/the/path') @@ -63,7 +63,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory() + let history = createHistory() history.listenBefore(function(location) { if (input.value !== '') return 'Are you sure you want to leave this page?' @@ -75,7 +75,7 @@ let input = { value: "" }; } { - let history = createBrowserHistory({ + let history = createHistory({ getUserConfirmation(message, callback) { callback(window.confirm(message)) // The default behavior } @@ -83,7 +83,7 @@ let input = { value: "" }; } { - let history = useBeforeUnload(createBrowserHistory)() + let history = useBeforeUnload(createHistory)() history.listenBeforeUnload(function() { return 'Are you sure you want to leave this page?' @@ -91,7 +91,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)() + let history = useQueries(createHistory)() history.listen(function(location) { console.log(location.query) @@ -99,7 +99,7 @@ let input = { value: "" }; } { - let history = useQueries(createBrowserHistory)({ + let history = useQueries(createHistory)({ parseQueryString: function(queryString) { // TODO: return a parsed version of queryString return {}; @@ -116,7 +116,7 @@ let input = { value: "" }; { // Run our app under the /base URL. - let history = useBasename(createBrowserHistory)({ + let history = useBasename(createHistory)({ basename: '/base' }) @@ -128,4 +128,4 @@ let input = { value: "" }; history.createPath('/the/path') // /base/the/path history.push('/the/path') // push /base/the/path -} \ No newline at end of file +} diff --git a/history/v2/index.d.ts b/history/v2/index.d.ts index 5f719c2f0b..6b61fa1b77 100644 --- a/history/v2/index.d.ts +++ b/history/v2/index.d.ts @@ -127,7 +127,7 @@ export interface Module { }; } -export { default as createBrowserHistory } from "./lib/createBrowserHistory"; +export { default as createHistory } from "./lib/createBrowserHistory"; export { default as createHashHistory } from "./lib/createHashHistory"; export { default as createMemoryHistory } from "./lib/createMemoryHistory"; export { default as createLocation } from "./lib/createLocation"; From 59b9f7939c60302143d6d499392260a09315e46c Mon Sep 17 00:00:00 2001 From: Eiji Kitamura Date: Tue, 24 Jan 2017 10:23:47 +0900 Subject: [PATCH 071/306] [paymentrequest] Added `target: "es6"` --- paymentrequest/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/paymentrequest/tsconfig.json b/paymentrequest/tsconfig.json index 221e0618af..e5754a139a 100644 --- a/paymentrequest/tsconfig.json +++ b/paymentrequest/tsconfig.json @@ -5,6 +5,7 @@ "es6", "dom" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, From 8829f99d006174525b8e4d00f7720722690cbda5 Mon Sep 17 00:00:00 2001 From: Steven Liekens Date: Tue, 24 Jan 2017 10:43:42 +0100 Subject: [PATCH 072/306] Mark optional properties as such --- jquery.datatables/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jquery.datatables/index.d.ts b/jquery.datatables/index.d.ts index c7c4bd8682..5d1bbd50c9 100644 --- a/jquery.datatables/index.d.ts +++ b/jquery.datatables/index.d.ts @@ -908,7 +908,7 @@ declare namespace DataTables { * @param d Data to use for the row. */ data(d: any[] | Object): DataTable; - + /** * Get the id of the selected row. Since: 1.10.8 @@ -1456,9 +1456,9 @@ declare namespace DataTables { } export interface AjaxData { - draw: number; - recordsTotal: number; - recordsFiltered: number; + draw?: number; + recordsTotal?: number; + recordsFiltered?: number; data: any; error?: string; } From 6d81c90395104ca52bfd30e3574bd13f4b39861a Mon Sep 17 00:00:00 2001 From: denis Date: Tue, 24 Jan 2017 15:18:31 +0100 Subject: [PATCH 073/306] MetisMenu: add missing types for 2.6.1 Add events types, preventDefault properties, and 'dispose' option. --- metismenu/index.d.ts | 8 ++++++-- metismenu/metismenu-tests.ts | 19 ++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/metismenu/index.d.ts b/metismenu/index.d.ts index 43faa279c7..1816090f87 100644 --- a/metismenu/index.d.ts +++ b/metismenu/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for metisMenu 2.0.3 +// Type definitions for metisMenu 2.6.1 // Project: http://github.com/onokumus/metisMenu // Definitions by: onokums // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,8 +12,12 @@ interface MetisMenuOptions { collapseClass?: string; collapseInClass?: string; collapsingClass?: string; + preventDefault?: boolean; } +type MetisMenuEvents = "show.metisMenu" | "shown.metisMenu" | "hide.metisMenu" | "hidden.metisMenu"; + interface JQuery { - metisMenu(options?: MetisMenuOptions): JQuery; + metisMenu(options?: MetisMenuOptions | "dispose"): JQuery; + on(events: MetisMenuEvents, handler: (eventObject: JQueryEventObject) => any): JQuery; } diff --git a/metismenu/metismenu-tests.ts b/metismenu/metismenu-tests.ts index b2e36f1d53..625a4877ab 100644 --- a/metismenu/metismenu-tests.ts +++ b/metismenu/metismenu-tests.ts @@ -1,12 +1,29 @@ /// $('#menu').metisMenu(); + $('.metismenu').metisMenu({toggle: false}); + $('.test').metisMenu({ toggle: false, doubleTapToGo: true, activeClass: 'active', collapseClass: 'collapse', collapseInClass: 'in', - collapsingClass: 'collapsing' + collapsingClass: 'collapsing', + preventDefault: true }); + +$('.metismenu').metisMenu('dispose'); + +$('.metismenu') + .metisMenu() + .on('show.metisMenu', function(e) { + // empty logic + }).on('shown.metisMenu', function(e) { + // empty logic + }).on('hide.metisMenu', function(e) { + // empty logic + }).on('hidden.metisMenu', function(e) { + // empty logic + }); From 2c380af908a2e6261078153598170b1fd84bd39f Mon Sep 17 00:00:00 2001 From: Sergei Dorogin Date: Tue, 24 Jan 2017 17:44:31 +0300 Subject: [PATCH 074/306] jquery.fileupload added `add` callback signature (was `any`) changed `fail` callback signature (JQueryFileInputOptions => JQueryFileUploadDone) added JQueryFileUploadXhr.errorThrown field --- jquery.fileupload/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jquery.fileupload/index.d.ts b/jquery.fileupload/index.d.ts index 54ebb89c5c..e113d2733c 100644 --- a/jquery.fileupload/index.d.ts +++ b/jquery.fileupload/index.d.ts @@ -198,7 +198,7 @@ interface JQueryFileInputOptions { * handlers using jQuery's Deferred callbacks: * data.submit().done(func).fail(func).always(func); */ - add?: any; + add?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: @@ -228,7 +228,7 @@ interface JQueryFileInputOptions { // Other callbacks: submit?: Function; done?: (e: JQueryEventObject, data: JQueryFileUploadDone) => void; - fail?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; + fail?: (e: JQueryEventObject, data: JQueryFileUploadDone) => void; always?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; progressall?: (e: JQueryEventObject, data: JQueryFileUploadProgressAllObject) => void; start?: (e: JQueryEventObject) => void; @@ -284,6 +284,7 @@ interface JQueryFileUploadXhr { jqXHR: JQueryXHR; result: any; textStatus: string; + errorThrown: any; headers: {[key: string]: any}; } From fbbdd4fa3c62077b1829fe1850c20ffb50c7044c Mon Sep 17 00:00:00 2001 From: Chris Scribner Date: Tue, 24 Jan 2017 10:41:26 -0800 Subject: [PATCH 075/306] Add promise-based interceptor definitions --- axios/axios-tests.ts | 20 +++++++++++++++++++- axios/index.d.ts | 20 ++++++++++++++++---- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/axios/axios-tests.ts b/axios/axios-tests.ts index eb98e2710c..2587222b36 100644 --- a/axios/axios-tests.ts +++ b/axios/axios-tests.ts @@ -13,6 +13,13 @@ interface Issue { title: string; } +function makePromise(val: any) { + return >{ + then: () => val, + catch: () => val + }; +} + axios.interceptors.request.use(config => { console.log("Method:" + config.method + " Url:" +config.url); return config; @@ -30,12 +37,23 @@ const requestId: number = axios.interceptors.request.use( axios.interceptors.request.eject(requestId); axios.interceptors.request.eject(7); +const requestId2: number = axios.interceptors.request.use( + (config) => { + console.log("Method:" + config.method + " Url:" +config.url); + return makePromise(config); + }, + (error: any) => error); axios.interceptors.response.use(config => { console.log("Status:" + config.status); return config; }); +axios.interceptors.response.use(config => { + console.log("Status:" + config.status); + return makePromise(config); +}); + const responseId: number = axios.interceptors.response.use( config => { console.log("Status:" + config.status); @@ -104,4 +122,4 @@ axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; -axiosInstance.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; \ No newline at end of file +axiosInstance.defaults.headers.common['Authorization'] = "AUTH_TOKEN"; diff --git a/axios/index.d.ts b/axios/index.d.ts index 681fefc806..b32a78ebe0 100644 --- a/axios/index.d.ts +++ b/axios/index.d.ts @@ -99,10 +99,10 @@ declare namespace Axios { * change the response data to be made before it is passed to then/catch */ transformResponse?: (data: T) => U; - - /** - * defines whether to resolve or reject the promise for a given HTTP response status code. - * If returns `true` (or is set to `null` or `undefined`), the promise will be resolved; + + /** + * defines whether to resolve or reject the promise for a given HTTP response status code. + * If returns `true` (or is set to `null` or `undefined`), the promise will be resolved; * otherwise, the promise will be rejected */ validateStatus?: (status: number) => boolean | undefined; @@ -199,6 +199,12 @@ declare namespace Axios { rejectedFn: (error: any) => any) : InterceptorId; + use(fulfilledFn: (config: AxiosXHRConfig) => IPromise>): InterceptorId; + + use(fulfilledFn: (config: AxiosXHRConfig) => IPromise>, + rejectedFn: (error: any) => any) + : InterceptorId; + eject(interceptorId: InterceptorId): void; } @@ -209,10 +215,16 @@ declare namespace Axios { use(fulfilledFn: (config: Axios.AxiosXHR) => Axios.AxiosXHR): InterceptorId; + use(fulfilledFn: (config: Axios.AxiosXHR) => IPromise>): InterceptorId; + use(fulfilledFn: (config: Axios.AxiosXHR) => Axios.AxiosXHR, rejectedFn: (error: any) => any) : InterceptorId; + use(fulfilledFn: (config: Axios.AxiosXHR) => IPromise>, + rejectedFn: (error: any) => any) + : InterceptorId; + eject(interceptorId: InterceptorId): void; } From b435dd3c8bfa4ad23cb34246c777e7d0f8db39dd Mon Sep 17 00:00:00 2001 From: Adrian Chia Date: Mon, 23 Jan 2017 18:14:36 -0600 Subject: [PATCH 076/306] auth0-js v8.1.3 --- auth0-js/auth0-js-tests.ts | 160 +++++++++- auth0-js/index.d.ts | 584 ++++++++++++++++++++++++++-------- auth0-js/v7/auth0-js-tests.ts | 22 ++ auth0-js/v7/index.d.ts | 136 ++++++++ auth0-js/v7/tsconfig.json | 28 ++ 5 files changed, 782 insertions(+), 148 deletions(-) create mode 100644 auth0-js/v7/auth0-js-tests.ts create mode 100644 auth0-js/v7/index.d.ts create mode 100644 auth0-js/v7/tsconfig.json diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts index 197256ddd5..68d4e1797b 100644 --- a/auth0-js/auth0-js-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,23 +1,151 @@ /// -var auth0 = new Auth0({ +let webAuth = new auth0.WebAuth({ domain: 'mine.auth0.com', - clientID: 'dsa7d77dsa7d7', - callbackURL: 'http://my-app.com/callback', - callbackOnLocationHash: true + clientID: 'dsa7d77dsa7d7' }); -auth0.login({ - connection: 'google-oauth2', - popup: true, - popupOptions: { - width: 450, - height: 800 +webAuth.authorize({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + responseType: 'token', + redirectUri: 'https://example.com/auth/callback' +}); + +webAuth.parseHash(window.location.hash, (err, authResult) => { + if (err) { + return console.log(err); } -}, (err, profile, idToken, accessToken, state) => { - if (err) { - alert("something went wrong: " + err.message); - return; - } - alert('hello ' + profile.name); + + // The contents of authResult depend on which authentication parameters were used. + // It can include the following: + // authResult.accessToken - access token for the API specified by `audience` + // authResult.expiresIn - string with the access token's expiration time in seconds + // authResult.idToken - ID token JWT containing user profile information + + webAuth.client.userInfo(authResult.accessToken, (err, user) => { + // Now you have the user's information }); +}); + +webAuth.renewAuth({ + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', + redirectUri: 'https://example.com/auth/silent-callback', + + // this will use postMessage to comunicate between the silent callback + // and the SPA. When false the SDK will attempt to parse the url hash + // should ignore the url hash and no extra behaviour is needed. + usePostMessage: true +}, function (err, authResult) { + // Renewed tokens or error +}); + +webAuth.changePassword({connection: 'the_connection', + email: 'me@example.com', + password: '123456' +}, (err) => {}); + +webAuth.passwordlessStart({ + connection: 'the_connection', + email: 'me@example.com', + send: 'code' +}, (err, data) => {}); + +webAuth.signupAndAuthorize({ + connection: 'the_connection', + email: 'me@example.com', + password: '123456', + scope: 'openid' +}, function (err, data) { + +}); + + + +webAuth.client.login({ + ealm: 'Username-Password-Authentication', //connection name or HRD domain + username: 'info@auth0.com', + password: 'areallystrongpassword', + audience: 'https://mystore.com/api/v2', + scope: 'read:order write:order', +}, function(err, authResult) { + // Auth tokens in the result or an error +}); + +let authentication = new auth0.Authentication({ + domain: 'me.auth0.com', + clientID: '...', + redirectUri: 'http://page.com/callback', + responseType: 'code', + _sendTelemetry: false +}); + +authentication.buildAuthorizeUrl({state:'1234'}); +authentication.buildAuthorizeUrl({ + responseType: 'token', + redirectUri: 'http://anotherpage.com/callback2', + prompt: 'none', + state: '1234', + connection_scope: 'scope1,scope2' +}); + +authentication.buildLogoutUrl('asdfasdfds'); +authentication.buildLogoutUrl(); +authentication.userInfo('abcd1234', (err, data) => { + //user info retrieved +}); + +authentication.delegation({ + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + refresh_token: 'your_refresh_token', + api_type: 'app' +}, (err, data) => { + +}); + +authentication.loginWithDefaultDirectory({ + username: 'someUsername', + password: '123456' +}, (err, data) => { + +}); + +authentication.oauthToken({ + username: 'someUsername', + password: '123456', + grantType: 'password' +}, (err, data) => { + +}); + +authentication.getUserCountry((err, data) => { + +}); + +authentication.getSSOData(); +authentication.getSSOData(true, (err, data) => {}); + +authentication.dbConnection.signup({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); +authentication.dbConnection.changePassword({connection: 'bla', email: 'blabla', password: '123456'}, () => {}); + +authentication.passwordless.start({ connection: 'bla', send: 'blabla' }, () => {}); +authentication.passwordless.verify({ connection: 'bla', send: 'link', verificationCode: 'asdfasd', email: 'me@example.com' }, () => {}); + +authentication.loginWithResourceOwner({ + username: 'the username', + password: 'the password', + connection: 'the_connection', + scope: 'openid' +}, (err, data) => {}); + +let management = new auth0.Management({ + domain: 'me.auth0.com', + token: 'token' +}); + +management.getUser('asd', (err, user) => {}); + +management.patchUserMetadata('asd', {role: 'admin'}, (err, user) => {}); + +management.linkUser('asd', 'eqwe', (err, user) => {}); diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index bd97fed1cc..6def04ab89 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -1,136 +1,456 @@ -// Type definitions for Auth0.js +// Type definitions for Auth0.js v8.1.3 // Project: https://github.com/auth0/auth0.js -// Definitions by: Robert McLaws +// Definitions by: Adrian Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** Extensions to the browser Window object. */ -interface Window { - /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ - token: string; -} - -/** This is the interface for the main Auth0 client. */ -interface Auth0Static { - - new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; - decodeJwt(jwt: string): any; - login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; - loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - logout(query: string): void; - getConnections(callback?: Function): void; - refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; - parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; - validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; -} - -/** Represents constructor options for the Auth0 client. */ -interface Auth0ClientOptions { - clientID: string; - callbackURL: string; - callbackOnLocationHash?: boolean; - responseType?: string; - domain: string; - forceJSONP?: boolean; -} - -/** Represents a normalized UserProfile. */ -interface Auth0UserProfile { - email: string; - email_verified: boolean; - family_name: string; - gender: string; - given_name: string; - locale: string; - name: string; - nickname: string; - picture: string; - user_id: string; - /** Represents one or more Identities that may be associated with the User. */ - identities: Auth0Identity[]; - user_metadata?: any; - app_metadata?: any; -} - -/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ -interface MicrosoftUserProfile extends Auth0UserProfile { - emails: string[]; -} - -/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ -interface Office365UserProfile extends Auth0UserProfile { - tenantid: string; - upn: string; -} - -/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ -interface AdfsUserProfile extends Auth0UserProfile { - issuer: string; -} - -/** Represents multiple identities assigned to a user. */ -interface Auth0Identity { - access_token: string; - connection: string; - isSocial: boolean; - provider: string; - user_id: string; -} - -interface Auth0DecodedHash { - access_token: string; - idToken: string; - profile: Auth0UserProfile; - state: any; - error: string; -} - -interface Auth0PopupOptions { - width: number; - height: number; -} - -interface Auth0LoginOptions { - auto_login?: boolean; - responseType?: string; - connection?: string; - email?: string; - username?: string; - password?: string; - popup?: boolean; - popupOptions?: Auth0PopupOptions; -} - -interface Auth0SignupOptions extends Auth0LoginOptions { - auto_login: boolean; -} - -interface Auth0Error { - code: any; - details: any; - name: string; - message: string; - status: any; -} - -/** Represents the response from an API Token Delegation request. */ -interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - expires_in: string; - /** The JWT for delegated access. */ - id_token: string; - /** The type of token being returned. Possible values: "Bearer" */ - token_type: string; -} - -declare const Auth0: Auth0Static; - -declare module "auth0-js" { - export = Auth0 +declare namespace auth0 { + + export class Authentication { + constructor(options: AuthOptions); + + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; + + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; + + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; + + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + * @deprecated `delegation` will be soon deprecated. + */ + delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; + } + + export class PasswordlessAuthentication { + constructor(request: any, option: any); + + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; + + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: any): void; + } + + export class DBConnection { + constructor(request: any, option: any); + + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: any): void; + + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: any): void; + } + + export class Management { + constructor(options: ManagementOptions); + + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; + } + + export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; + + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; + + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: any): void; + + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: any): void; + + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; + + passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; + + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + } + + export class Redirect { + constructor(client: any, options: any); + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + export class Popup { + constructor(client: any, options: any); + + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; + + /** + * Internal use. + * + * @method getPopupHandler + */ + getPopupHandler(options: any, preload: boolean): any; + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: any): void; + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } + + interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } + + interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; + } + + interface Auth0Error { + error: any; + errorDescription: string + } + + interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; + } + + /** Represents the response from an API Token Delegation request. */ + interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + ExpiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; + } + + interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; + } + + interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string, + authParams?: any; + } + + interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; + } + } diff --git a/auth0-js/v7/auth0-js-tests.ts b/auth0-js/v7/auth0-js-tests.ts new file mode 100644 index 0000000000..d5ca0250d4 --- /dev/null +++ b/auth0-js/v7/auth0-js-tests.ts @@ -0,0 +1,22 @@ +/// +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0-js/v7/index.d.ts b/auth0-js/v7/index.d.ts new file mode 100644 index 0000000000..ee834d5c61 --- /dev/null +++ b/auth0-js/v7/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for Auth0.js v7.x +// Project: https://github.com/auth0/auth0.js +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: Function): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: Function): void; + refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getDelegationToken(options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: Function): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: Function): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: Function): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLocationHash?: boolean; + responseType?: string; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + email_verified: boolean; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + idToken: string; + profile: Auth0UserProfile; + state: any; + error: string; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + responseType?: string; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare const Auth0: Auth0Static; + +declare module "auth0-js" { + export = Auth0 +} diff --git a/auth0-js/v7/tsconfig.json b/auth0-js/v7/tsconfig.json new file mode 100644 index 0000000000..7413e97f44 --- /dev/null +++ b/auth0-js/v7/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "auth0-js": [ + "auth0-js/v7" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "auth0-js-tests.ts" + ] +} From 961480480b66dc34420b8f997e97d79d9d6ef899 Mon Sep 17 00:00:00 2001 From: Adrian Chia Date: Tue, 24 Jan 2017 14:21:46 -0600 Subject: [PATCH 077/306] Update references to auth0-js/v7 --- auth0-lock/auth0-lock-tests.ts | 2 +- auth0-lock/index.d.ts | 2 +- auth0.widget/auth0.widget-tests.ts | 2 +- auth0.widget/index.d.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/auth0-lock/auth0-lock-tests.ts b/auth0-lock/auth0-lock-tests.ts index deb046f3e7..4b72edcfa1 100644 --- a/auth0-lock/auth0-lock-tests.ts +++ b/auth0-lock/auth0-lock-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts index fc9a047115..09c3f4fedd 100644 --- a/auth0-lock/index.d.ts +++ b/auth0-lock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index ec5502ca7e..6277d4cc3a 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,4 +1,4 @@ -/// +/// var widget: Auth0WidgetStatic = new Auth0Widget({ diff --git a/auth0.widget/index.d.ts b/auth0.widget/index.d.ts index 1c30d83b6f..cdefd9e0fd 100644 --- a/auth0.widget/index.d.ts +++ b/auth0.widget/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0WidgetStatic { From da84c6d42b1b7c9d28de48c7115767682b513c8f Mon Sep 17 00:00:00 2001 From: Adrian Chia Date: Tue, 24 Jan 2017 14:50:59 -0600 Subject: [PATCH 078/306] Convert tab to spaces for consistency --- auth0-js/index.d.ts | 790 ++++++++++++++++++++++---------------------- 1 file changed, 395 insertions(+), 395 deletions(-) diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index 6def04ab89..0a0e004303 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -5,452 +5,452 @@ declare namespace auth0 { - export class Authentication { - constructor(options: AuthOptions); + export class Authentication { + constructor(options: AuthOptions); - passwordless: PasswordlessAuthentication; - dbConnection: DBConnection; + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; - /** - * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction - * - * @method buildAuthorizeUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - buildAuthorizeUrl(options: any): string; + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; - /** - * Builds and returns the Logout url in order to initialize a new authN/authZ transaction - * - * @method buildLogoutUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - buildLogoutUrl(options?: any): string; + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; - /** - * Makes a call to the `oauth/token` endpoint with `password` grant type - * - * @method loginWithDefaultDirectory - * @param {Object} options: https://auth0.com/docs/api-auth/grant/password - * @param {Function} callback - */ - loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ro` endpoint - * @param {any} options - * @param {Function} callback - * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. - */ - loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `oauth/token` endpoint with `password-realm` grant type - * @param {any} options - * @param {Function} callback - */ - login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `oauth/token` endpoint - * @param {any} options - * @param {Function} callback - */ - oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/userinfo` endpoint and returns the user profile - * - * @method userInfo - * @param {String} accessToken - * @param {Function} callback - */ - userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; - /** - * Makes a call to the `/delegation` endpoint - * - * @method delegation - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation - * @param {Function} callback - * @deprecated `delegation` will be soon deprecated. - */ - delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + * @deprecated `delegation` will be soon deprecated. + */ + delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; - /** - * Fetches the user country based on the ip. - * - * @method getUserCountry - * @param {Function} callback - */ - getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; - } + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; + } - export class PasswordlessAuthentication { - constructor(request: any, option: any); + export class PasswordlessAuthentication { + constructor(request: any, option: any); - /** - * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - buildVerifyUrl(options: any): string; + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; - /** - * Initializes a new passwordless authN/authZ transaction - * - * @method start - * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless - * @param {Function} callback - */ - start(options: PasswordlessStartOptions, callback: any): void; + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: any): void; - /** - * Verifies the passwordless TOTP and returns an error if any. - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - verify(options: any, callback: any): void; - } + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: any): void; + } - export class DBConnection { - constructor(request: any, option: any); + export class DBConnection { + constructor(request: any, option: any); - /** - * Signup a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} calback - */ - signup(options: any, callback: any): void; + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: any): void; - /** - * Initializes the change password flow - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: ChangePasswordOptions, callback: any): void; - } + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: any): void; + } - export class Management { - constructor(options: ManagementOptions); + export class Management { + constructor(options: ManagementOptions); - /** - * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id - * - * @method getUser - * @param {String} userId - * @param {Function} callback - */ - getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; - /** - * Updates the user metdata. It will patch the user metdata with the attributes sent. - * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id - * - * @method patchUserMetadata - * @param {String} userId - * @param {Object} userMetadata - * @param {Function} callback - */ - patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; - /** - * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities - * - * @method linkUser - * @param {String} userId - * @param {String} secondaryUserToken - * @param {Function} callback - */ - linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; - } + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; + } - export class WebAuth { - constructor(options: AuthOptions); - client: Authentication; - popup: Popup; - redirect: Redirect; + export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; - /** - * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - authorize(options: any): void; + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; - /** - * Parse the url hash and extract the returned tokens depending on the transaction. - * - * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed - * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be - * accepted. - * - * @method parseHash - * @param {Object} options: - * @param {String} options.state [OPTIONAL] to verify the response - * @param {String} options.nonce [OPTIONAL] to verify the id_token - * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash - * @param {Function} callback: any(err, token_payload) - */ - parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Decodes the id_token and verifies the nonce. - * - * @method validateToken - * @param {String} token - * @param {String} state - * @param {String} nonce - * @param {Function} callback: function(err, {payload, transaction}) - */ - validateToken(token: string, state: string, nonce: string, callback: any): void; + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: any): void; - /** - * Executes a silent authentication transaction under the hood in order to fetch a new token. - * - * @method renewAuth - * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint - * @param {Function} callback - */ - renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Initialices a change password transaction - * - * @method changePassword - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Signs up a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signup(options: any, callback: any): void; + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: any): void; - /** - * Signs up a new user, automatically logs the user in after the signup and returns the user token. - * The login will be done using /oauth/token with password-realm grant type. - * - * @method signupAndAuthorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Redirects to the auth0 logout page - * - * @method logout - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - logout(options: any): void; + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; - passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; + passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; - /** - * Verifies the passwordless TOTP and redirects to finish the passwordless transaction - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; - } + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + } - export class Redirect { - constructor(client: any, options: any); + export class Redirect { + constructor(client: any, options: any); - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } - export class Popup { - constructor(client: any, options: any); + export class Popup { + constructor(client: any, options: any); - /** - * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. - * - * @method preload - * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open - */ - preload(options: any): any; + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; - /** - * Internal use. - * - * @method getPopupHandler - */ - getPopupHandler(options: any, preload: boolean): any; - /** - * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - * @param {Function} callback - */ - authorize(options: any, callback: any): void; + /** + * Internal use. + * + * @method getPopupHandler + */ + getPopupHandler(options: any, preload: boolean): any; + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: any): void; - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; - /** - * Verifies the passwordless TOTP and returns the requested token - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; + } - interface ManagementOptions { - domain: string; - token: string; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } + interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } - interface AuthOptions { - domain: string; - clientID: string; - responseType?: string; - responseMode?: string; - redirectUri?: string; - scope?: string; - audience?: string; - leeway?: number; - _disableDeprecationWarnings?: boolean; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } + interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; + } - interface PasswordlessAuthOptions { - connection: string; - verificationCode: string; - phoneNumber: string; - email: string; - } + interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; + } - interface Auth0Error { - error: any; - errorDescription: string - } + interface Auth0Error { + error: any; + errorDescription: string + } - interface Auth0DecodedHash { - accessToken?: string; - idToken?: string; - idTokenPayload?: any; - refreshToken?: string; - state?: string; - expiresIn?: number; - tokenType?: string; - } + interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; + } - /** Represents the response from an API Token Delegation request. */ - interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - ExpiresIn: number; - /** The JWT for delegated access. */ - idToken: string; - /** The type of token being returned. Possible values: "Bearer" */ - tokenType: string; - } + /** Represents the response from an API Token Delegation request. */ + interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + ExpiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; + } - interface ChangePasswordOptions { - connection: string; - email: string; - password?: string; - } + interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; + } - interface PasswordlessStartOptions { - connection: string; - send: string; - phoneNumber?: string; - email?: string, - authParams?: any; - } + interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string, + authParams?: any; + } - interface PasswordlessVerifyOptions { - connection: string; - verificationCode: string; - phoneNumber?: string; - email?: string; - } + interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; + } } From 4184a8342abde8c56c2ee137b5184044a6727002 Mon Sep 17 00:00:00 2001 From: "Smith, Blake (bs557j)" Date: Tue, 24 Jan 2017 15:00:33 -0600 Subject: [PATCH 079/306] Adding Filter as a type to Request.filter(filter) --- elastic.js/elastic.js-tests.ts | 9 ++++++++- elastic.js/index.d.ts | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/elastic.js/elastic.js-tests.ts b/elastic.js/elastic.js-tests.ts index e7bd65ea16..b683559490 100644 --- a/elastic.js/elastic.js-tests.ts +++ b/elastic.js/elastic.js-tests.ts @@ -1,6 +1,13 @@ import * as elasticjs from 'elastic.js'; -let body = new elasticjs.Request({}) +new elasticjs.Request({}) .query(new elasticjs.MatchQuery('title_field', 'testQuery')) .facet(new elasticjs.TermsFacet('tags').field('tags')) .toJSON(); + +new elasticjs.Request({}) + .query(new elasticjs.MatchAllQuery()) + .filter(new elasticjs.BoolFilter().must([ + new elasticjs.TermFilter('a', 'b'), + new elasticjs.TermFilter('c', 'd')])) + .toJSON(); diff --git a/elastic.js/index.d.ts b/elastic.js/index.d.ts index adb0db6950..9e25076906 100644 --- a/elastic.js/index.d.ts +++ b/elastic.js/index.d.ts @@ -6765,7 +6765,7 @@ declare module elasticjs { /* Allows you to set a specified filter on this request object. */ - filter(filter: Object): Request; + filter(filter: Object | Filter): Request; /* A search result set could be very large (think Google). Setting the From 8698554563f4acdf0942ffe9f74b6cce394f9f10 Mon Sep 17 00:00:00 2001 From: darlin Date: Wed, 25 Jan 2017 10:13:32 +0800 Subject: [PATCH 080/306] use appropriate export --- simplemde/index.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/simplemde/index.d.ts b/simplemde/index.d.ts index eb463ae655..c78d4fb408 100644 --- a/simplemde/index.d.ts +++ b/simplemde/index.d.ts @@ -129,6 +129,5 @@ declare class SimpleMDE { static redo: (editor: SimpleMDE) => void; } -declare module "simplemde" { - export = SimpleMDE; -} +export = SimpleMDE; +export as namespace SimpleMDE; From a6e94fdb0a80fbeacea1786d60cc0a67deaf9d6b Mon Sep 17 00:00:00 2001 From: Shun Date: Tue, 24 Jan 2017 21:54:20 -0800 Subject: [PATCH 081/306] Add module --- forever-monitor/forever-monitor-tests.ts | 0 forever-monitor/index.d.ts | 104 +++++++++++++++++++++++ forever-monitor/tsconfig.json | 20 +++++ forever-monitor/tslint.json | 1 + 4 files changed, 125 insertions(+) create mode 100644 forever-monitor/forever-monitor-tests.ts create mode 100644 forever-monitor/index.d.ts create mode 100644 forever-monitor/tsconfig.json create mode 100644 forever-monitor/tslint.json diff --git a/forever-monitor/forever-monitor-tests.ts b/forever-monitor/forever-monitor-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/forever-monitor/index.d.ts b/forever-monitor/index.d.ts new file mode 100644 index 0000000000..b22905cae2 --- /dev/null +++ b/forever-monitor/index.d.ts @@ -0,0 +1,104 @@ +// Type definitions for forever-monitor 1.7 +// Project: https://github.com/nodejitsu/forever-monitor#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +interface spawnWith { + customFds: number[]; + setsid: boolean; + uid: number; + gid: number; +} + +interface parserArgs { + command: string; + args: string[]; +} + +interface Options { + silent?: boolean; + uid?: "autogen" | string; + pidFile?: string; + max?: number; + killTree?: boolean; + minUptime?: number; + spinSleepTime?: number; + command?: "node" | string; + args?: string[]; + sourceDir?: string; + watch?: boolean; + watchIgnoreDotFiles?: boolean; + watchIgnorePatters?: string[]; + watchDirectory?: string; + spawnWith?: spawnWith; + env?: { [envKey: string]: string; }; + cwd?: string; + logFile?: string; + outFile?: string; + errFile?: string; + parser?: (command: string, args: string[]) => { command: string, args: string[] }; +} + + +export declare class Monitor extends NodeJS.EventEmitter { + + /** + * @param script - Location of the target script to run. + * @param [options] - Configuration for this instance. + */ + constructor(script: string, options?: Options); + + /** + * @description Start the process that this instance is configured for + * @param [restart] - Value indicating whether this is a restart. + */ + public start(restart?: boolean): this; + + /** + * @description Tries to spawn the target Forever child process. + */ + public trySpawn(): boolean; + + /** + * @description Restarts the target script associated with this instance. + */ + public restart(): this; + + /** + * @description Stops the target script associated with this instance. Prevents it from auto-respawning + */ + public stop(): this; + + /** + * @description Kills the ChildProcess object associated with this instance + * @param [forceStop] - Value indicating whether short circuit forever auto-restart + */ + public kill(forceStop?: boolean): this; + + /** + * @description Sends a message to a forked ChildProcess object associated with this instance + */ + public send(msg?: any): this; + + /** + * respond with JSON for this instance + */ + public toString(): string; + + /** + * @param command - Command string to parse + * @param args - Additional default arguments + */ + public parseCommand(command: string, args?: string[]): (false | { command: string, args?: string[]}); +} + +interface forever { + Monitor: Monitor; + start: (script: string, options: Options) => Monitor; + kill: (pid: number, killTree?: boolean, signal?: string, callback?: () => any) => void; + checkProcess: (pid: number) => boolean; + version: string; +} + +export default forever; diff --git a/forever-monitor/tsconfig.json b/forever-monitor/tsconfig.json new file mode 100644 index 0000000000..8c6d4986b5 --- /dev/null +++ b/forever-monitor/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "forever-monitor-tests.ts" + ] +} diff --git a/forever-monitor/tslint.json b/forever-monitor/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/forever-monitor/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 1ca0a1b3f98ad5ce8713543791b97014d5250bd6 Mon Sep 17 00:00:00 2001 From: darlin Date: Wed, 25 Jan 2017 14:26:11 +0800 Subject: [PATCH 082/306] update submodule --- crypto-js/aes/index.d.ts | 3 + crypto-js/core/index.d.ts | 3 + crypto-js/enc-base64/index.d.ts | 4 + crypto-js/enc-hex/index.d.ts | 4 + crypto-js/enc-latin1/index.d.ts | 4 + crypto-js/enc-utf16/index.d.ts | 4 + crypto-js/enc-utf8/index.d.ts | 4 + crypto-js/evpkdf/index.d.ts | 3 + crypto-js/format-hex/index.d.ts | 4 + crypto-js/format-openssl/index.d.ts | 4 + crypto-js/hmac-md5/index.d.ts | 3 + crypto-js/hmac-ripemd160/index.d.ts | 3 + crypto-js/hmac-sha1/index.d.ts | 3 + crypto-js/hmac-sha224/index.d.ts | 3 + crypto-js/hmac-sha256/index.d.ts | 3 + crypto-js/hmac-sha3/index.d.ts | 3 + crypto-js/hmac-sha384/index.d.ts | 3 + crypto-js/hmac-sha512/index.d.ts | 3 + crypto-js/index.d.ts | 237 +------------------------- crypto-js/lib-typedarrays/index.d.ts | 2 + crypto-js/md5/index.d.ts | 3 + crypto-js/mode-cfb/index.d.ts | 4 + crypto-js/mode-ctr-gladman/index.d.ts | 4 + crypto-js/mode-ctr/index.d.ts | 4 + crypto-js/mode-ecb/index.d.ts | 4 + crypto-js/mode-ofb/index.d.ts | 4 + crypto-js/pad-ansix923/index.d.ts | 4 + crypto-js/pad-iso10126/index.d.ts | 4 + crypto-js/pad-iso97971/index.d.ts | 4 + crypto-js/pad-nopadding/index.d.ts | 4 + crypto-js/pad-pkcs7/index.d.ts | 4 + crypto-js/pad-zeropadding/index.d.ts | 4 + crypto-js/pbkdf2/index.d.ts | 3 + crypto-js/rabbit-legacy/index.d.ts | 3 + crypto-js/rabbit/index.d.ts | 3 + crypto-js/rc4/index.d.ts | 3 + crypto-js/ripemd160/index.d.ts | 3 + crypto-js/sha1/index.d.ts | 3 + crypto-js/sha224/index.d.ts | 3 + crypto-js/sha256/index.d.ts | 3 + crypto-js/sha3/index.d.ts | 3 + crypto-js/sha384/index.d.ts | 3 + crypto-js/sha512/index.d.ts | 3 + crypto-js/tripledes/index.d.ts | 3 + crypto-js/x64-core/index.d.ts | 3 + 45 files changed, 152 insertions(+), 234 deletions(-) create mode 100644 crypto-js/aes/index.d.ts create mode 100644 crypto-js/core/index.d.ts create mode 100644 crypto-js/enc-base64/index.d.ts create mode 100644 crypto-js/enc-hex/index.d.ts create mode 100644 crypto-js/enc-latin1/index.d.ts create mode 100644 crypto-js/enc-utf16/index.d.ts create mode 100644 crypto-js/enc-utf8/index.d.ts create mode 100644 crypto-js/evpkdf/index.d.ts create mode 100644 crypto-js/format-hex/index.d.ts create mode 100644 crypto-js/format-openssl/index.d.ts create mode 100644 crypto-js/hmac-md5/index.d.ts create mode 100644 crypto-js/hmac-ripemd160/index.d.ts create mode 100644 crypto-js/hmac-sha1/index.d.ts create mode 100644 crypto-js/hmac-sha224/index.d.ts create mode 100644 crypto-js/hmac-sha256/index.d.ts create mode 100644 crypto-js/hmac-sha3/index.d.ts create mode 100644 crypto-js/hmac-sha384/index.d.ts create mode 100644 crypto-js/hmac-sha512/index.d.ts create mode 100644 crypto-js/lib-typedarrays/index.d.ts create mode 100644 crypto-js/md5/index.d.ts create mode 100644 crypto-js/mode-cfb/index.d.ts create mode 100644 crypto-js/mode-ctr-gladman/index.d.ts create mode 100644 crypto-js/mode-ctr/index.d.ts create mode 100644 crypto-js/mode-ecb/index.d.ts create mode 100644 crypto-js/mode-ofb/index.d.ts create mode 100644 crypto-js/pad-ansix923/index.d.ts create mode 100644 crypto-js/pad-iso10126/index.d.ts create mode 100644 crypto-js/pad-iso97971/index.d.ts create mode 100644 crypto-js/pad-nopadding/index.d.ts create mode 100644 crypto-js/pad-pkcs7/index.d.ts create mode 100644 crypto-js/pad-zeropadding/index.d.ts create mode 100644 crypto-js/pbkdf2/index.d.ts create mode 100644 crypto-js/rabbit-legacy/index.d.ts create mode 100644 crypto-js/rabbit/index.d.ts create mode 100644 crypto-js/rc4/index.d.ts create mode 100644 crypto-js/ripemd160/index.d.ts create mode 100644 crypto-js/sha1/index.d.ts create mode 100644 crypto-js/sha224/index.d.ts create mode 100644 crypto-js/sha256/index.d.ts create mode 100644 crypto-js/sha3/index.d.ts create mode 100644 crypto-js/sha384/index.d.ts create mode 100644 crypto-js/sha512/index.d.ts create mode 100644 crypto-js/tripledes/index.d.ts create mode 100644 crypto-js/x64-core/index.d.ts diff --git a/crypto-js/aes/index.d.ts b/crypto-js/aes/index.d.ts new file mode 100644 index 0000000000..4f435688c5 --- /dev/null +++ b/crypto-js/aes/index.d.ts @@ -0,0 +1,3 @@ +import { AES } from '../index'; + +export = AES; diff --git a/crypto-js/core/index.d.ts b/crypto-js/core/index.d.ts new file mode 100644 index 0000000000..c5d6e00410 --- /dev/null +++ b/crypto-js/core/index.d.ts @@ -0,0 +1,3 @@ +import * as Core from '../index'; + +export = Core; diff --git a/crypto-js/enc-base64/index.d.ts b/crypto-js/enc-base64/index.d.ts new file mode 100644 index 0000000000..55001a7115 --- /dev/null +++ b/crypto-js/enc-base64/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Base64: typeof enc.Base64; +export = Base64; diff --git a/crypto-js/enc-hex/index.d.ts b/crypto-js/enc-hex/index.d.ts new file mode 100644 index 0000000000..3718860123 --- /dev/null +++ b/crypto-js/enc-hex/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Hex: typeof enc.Hex; +export = Hex; diff --git a/crypto-js/enc-latin1/index.d.ts b/crypto-js/enc-latin1/index.d.ts new file mode 100644 index 0000000000..7f27822daf --- /dev/null +++ b/crypto-js/enc-latin1/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Latin1: typeof enc.Latin1; +export = Latin1; diff --git a/crypto-js/enc-utf16/index.d.ts b/crypto-js/enc-utf16/index.d.ts new file mode 100644 index 0000000000..76fa98774a --- /dev/null +++ b/crypto-js/enc-utf16/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Utf16: typeof enc.Utf16; +export = Utf16; diff --git a/crypto-js/enc-utf8/index.d.ts b/crypto-js/enc-utf8/index.d.ts new file mode 100644 index 0000000000..828dcb9391 --- /dev/null +++ b/crypto-js/enc-utf8/index.d.ts @@ -0,0 +1,4 @@ +import { enc } from '../index'; + +declare const Utf8: typeof enc.Utf8; +export = Utf8; diff --git a/crypto-js/evpkdf/index.d.ts b/crypto-js/evpkdf/index.d.ts new file mode 100644 index 0000000000..8946b9d3a1 --- /dev/null +++ b/crypto-js/evpkdf/index.d.ts @@ -0,0 +1,3 @@ +import { EvpKDF } from '../index'; + +export = EvpKDF; diff --git a/crypto-js/format-hex/index.d.ts b/crypto-js/format-hex/index.d.ts new file mode 100644 index 0000000000..1b0f573824 --- /dev/null +++ b/crypto-js/format-hex/index.d.ts @@ -0,0 +1,4 @@ +import { format } from '../index'; + +declare const Hex: typeof format.Hex; +export = Hex; diff --git a/crypto-js/format-openssl/index.d.ts b/crypto-js/format-openssl/index.d.ts new file mode 100644 index 0000000000..02c35a3688 --- /dev/null +++ b/crypto-js/format-openssl/index.d.ts @@ -0,0 +1,4 @@ +import { format } from '../index'; + +declare const OpenSSL: typeof format.OpenSSL; +export = OpenSSL; diff --git a/crypto-js/hmac-md5/index.d.ts b/crypto-js/hmac-md5/index.d.ts new file mode 100644 index 0000000000..7240576710 --- /dev/null +++ b/crypto-js/hmac-md5/index.d.ts @@ -0,0 +1,3 @@ +import { HmacMD5 } from '../index'; + +export = HmacMD5; diff --git a/crypto-js/hmac-ripemd160/index.d.ts b/crypto-js/hmac-ripemd160/index.d.ts new file mode 100644 index 0000000000..6c371e9435 --- /dev/null +++ b/crypto-js/hmac-ripemd160/index.d.ts @@ -0,0 +1,3 @@ +import { HmacRIPEMD160 } from '../index'; + +export = HmacRIPEMD160; diff --git a/crypto-js/hmac-sha1/index.d.ts b/crypto-js/hmac-sha1/index.d.ts new file mode 100644 index 0000000000..1995cf87f6 --- /dev/null +++ b/crypto-js/hmac-sha1/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA1 } from '../index'; + +export = HmacSHA1; diff --git a/crypto-js/hmac-sha224/index.d.ts b/crypto-js/hmac-sha224/index.d.ts new file mode 100644 index 0000000000..f25334c64c --- /dev/null +++ b/crypto-js/hmac-sha224/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA224 } from '../index'; + +export = HmacSHA224; diff --git a/crypto-js/hmac-sha256/index.d.ts b/crypto-js/hmac-sha256/index.d.ts new file mode 100644 index 0000000000..ca1a1ca267 --- /dev/null +++ b/crypto-js/hmac-sha256/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA256 } from '../index'; + +export = HmacSHA256; diff --git a/crypto-js/hmac-sha3/index.d.ts b/crypto-js/hmac-sha3/index.d.ts new file mode 100644 index 0000000000..0fa0db9321 --- /dev/null +++ b/crypto-js/hmac-sha3/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA3 } from '../index'; + +export = HmacSHA3; diff --git a/crypto-js/hmac-sha384/index.d.ts b/crypto-js/hmac-sha384/index.d.ts new file mode 100644 index 0000000000..2e17420c1b --- /dev/null +++ b/crypto-js/hmac-sha384/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA384 } from '../index'; + +export = HmacSHA384; diff --git a/crypto-js/hmac-sha512/index.d.ts b/crypto-js/hmac-sha512/index.d.ts new file mode 100644 index 0000000000..439b2ffd5e --- /dev/null +++ b/crypto-js/hmac-sha512/index.d.ts @@ -0,0 +1,3 @@ +import { HmacSHA512 } from '../index'; + +export = HmacSHA512; diff --git a/crypto-js/index.d.ts b/crypto-js/index.d.ts index a2c0ee381d..a8068161e1 100644 --- a/crypto-js/index.d.ts +++ b/crypto-js/index.d.ts @@ -3,6 +3,9 @@ // Definitions by: Michael Zabka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = CryptoJS; +export as namespace CryptoJS; + declare var CryptoJS: CryptoJS.Hashes; declare namespace CryptoJS { type Hash = (message: string, key?: string, ...options: any[]) => string; @@ -112,237 +115,3 @@ declare namespace CryptoJS { } } - -declare module "crypto-js" { - var CryptoJS: CryptoJS.Hashes; - export = CryptoJS; -} - -/* --------------------------------- */ -declare module "crypto-js/core" { - var core: any; - export = core; -} - -declare module "crypto-js/x64-core" { - var x64: any; - export = x64; -} - -declare module "crypto-js/lib-typedarrays" { - var libWordArray: any; - export = libWordArray; -} - -/* --------------------------------- */ -declare module "crypto-js/md5" { - var MD5: CryptoJS.Hash; - export = MD5; -} - -declare module "crypto-js/sha1" { - var SHA1: CryptoJS.Hash; - export = SHA1; -} - -declare module "crypto-js/sha256" { - var SHA256: CryptoJS.Hash; - export = SHA256; -} - -declare module "crypto-js/sha224" { - var SHA224: CryptoJS.Hash; - export = SHA224; -} - -declare module "crypto-js/sha512" { - var SHA512: CryptoJS.Hash; - export = SHA512; -} - -declare module "crypto-js/sha384" { - var SHA384: CryptoJS.Hash; - export = SHA384; -} - -declare module "crypto-js/sha3" { - var SHA3: CryptoJS.Hash; - export = SHA3; -} - -declare module "crypto-js/ripemd160" { - var RIPEMD160: CryptoJS.Hash; - export = RIPEMD160; -} - -/* --------------------------------- */ -declare module "crypto-js/hmac-md5" { - var HmacMD5: CryptoJS.Hash; - export = HmacMD5; -} - -declare module "crypto-js/hmac-sha1" { - var HmacSHA1: CryptoJS.Hash; - export = HmacSHA1; -} - -declare module "crypto-js/hmac-sha256" { - var HmacSHA256: CryptoJS.Hash; - export = HmacSHA256; -} - -declare module "crypto-js/hmac-sha224" { - var HmacSHA224: CryptoJS.Hash; - export = HmacSHA224; -} - -declare module "crypto-js/hmac-sha512" { - var HmacSHA512: CryptoJS.Hash; - export = HmacSHA512; -} - -declare module "crypto-js/hmac-sha384" { - var HmacSHA384: CryptoJS.Hash; - export = HmacSHA384; -} - -declare module "crypto-js/hmac-sha3" { - var HmacSHA3: CryptoJS.Hash; - export = HmacSHA3; -} - -declare module "crypto-js/hmac-ripemd160" { - var HmacRIPEMD160: CryptoJS.Hash; - export = HmacRIPEMD160; -} - -/* --------------------------------- */ -declare module "crypto-js/pbkdf2" { - var PBKDF2: CryptoJS.Hash; - export = PBKDF2; -} - -/* --------------------------------- */ -declare module "crypto-js/aes" { - var AES: CryptoJS.Cipher; - export = AES; -} - -declare module "crypto-js/tripledes" { - var TripleDES: CryptoJS.Cipher; - export = TripleDES; -} - -declare module "crypto-js/rc4" { - var RC4: CryptoJS.Cipher; - export = RC4; -} - -declare module "crypto-js/rabbit" { - var Rabbit: CryptoJS.Cipher; - export = Rabbit; -} - -declare module "crypto-js/rabbit-legacy" { - var RabbitLegacy: CryptoJS.Cipher; - export = RabbitLegacy; -} - -declare module "crypto-js/evpkdf" { - var EvpKDF: CryptoJS.Cipher; - export = EvpKDF; -} - -/* --------------------------------- */ -declare module "crypto-js/format-openssl" { - var FormatOpenssl: any; - export = FormatOpenssl; -} - -declare module "crypto-js/format-hex" { - var FormatHex: any; - export = FormatHex; -} - -/* --------------------------------- */ -declare module "crypto-js/enc-latin1" { - var encLatin1: CryptoJS.Encoder; - export = encLatin1; -} - -declare module "crypto-js/enc-utf8" { - var encUtf8: CryptoJS.Encoder; - export = encUtf8; -} - -declare module "crypto-js/enc-hex" { - var encHex: CryptoJS.Encoder; - export = encHex; -} - -declare module "crypto-js/enc-utf16" { - var encUtf16: CryptoJS.Encoder; - export = encUtf16; -} - -declare module "crypto-js/enc-base64" { - var encBase64: CryptoJS.Encoder; - export = encBase64; -} - -/* --------------------------------- */ -declare module "crypto-js/mode-cfb" { - var modeCFB: CryptoJS.Mode; - export = modeCFB; -} - -declare module "crypto-js/mode-ctr" { - var modeCTR: CryptoJS.Mode; - export = modeCTR; -} - -declare module "crypto-js/mode-ctr-gladman" { - var modeCTRGladman: CryptoJS.Mode; - export = modeCTRGladman; -} - -declare module "crypto-js/mode-ofb" { - var modeOFB: CryptoJS.Mode; - export = modeOFB; -} - -declare module "crypto-js/mode-ecb" { - var modeECB: CryptoJS.Mode; - export = modeECB; -} - -/* --------------------------------- */ -declare module "crypto-js/pad-pkcs7" { - var padPkcs7: CryptoJS.Padding; - export = padPkcs7; -} - -declare module "crypto-js/pad-ansix923" { - var padAnsiX923: CryptoJS.Padding; - export = padAnsiX923; -} - -declare module "crypto-js/pad-iso10126" { - var padIso10126: CryptoJS.Padding; - export = padIso10126; -} - -declare module "crypto-js/pad-iso97971" { - var padIso97971: CryptoJS.Padding; - export = padIso97971; -} - -declare module "crypto-js/pad-zeropadding" { - var padZeroPadding: CryptoJS.Padding; - export = padZeroPadding; -} - -declare module "crypto-js/pad-nopadding" { - var padNoPadding: CryptoJS.Padding; - export = padNoPadding; -} diff --git a/crypto-js/lib-typedarrays/index.d.ts b/crypto-js/lib-typedarrays/index.d.ts new file mode 100644 index 0000000000..91c5a7933b --- /dev/null +++ b/crypto-js/lib-typedarrays/index.d.ts @@ -0,0 +1,2 @@ +declare const libWordArray: any; +export = libWordArray; diff --git a/crypto-js/md5/index.d.ts b/crypto-js/md5/index.d.ts new file mode 100644 index 0000000000..faa064511e --- /dev/null +++ b/crypto-js/md5/index.d.ts @@ -0,0 +1,3 @@ +import { MD5 } from '../index'; + +export = MD5; diff --git a/crypto-js/mode-cfb/index.d.ts b/crypto-js/mode-cfb/index.d.ts new file mode 100644 index 0000000000..74c5c6e3d1 --- /dev/null +++ b/crypto-js/mode-cfb/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const CFB: typeof mode.CFB; +export = CFB; diff --git a/crypto-js/mode-ctr-gladman/index.d.ts b/crypto-js/mode-ctr-gladman/index.d.ts new file mode 100644 index 0000000000..3ca8f8b367 --- /dev/null +++ b/crypto-js/mode-ctr-gladman/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const CTRGladman: typeof mode.CTRGladman; +export = CTRGladman; diff --git a/crypto-js/mode-ctr/index.d.ts b/crypto-js/mode-ctr/index.d.ts new file mode 100644 index 0000000000..6007a4ca88 --- /dev/null +++ b/crypto-js/mode-ctr/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const CTR: typeof mode.CTR; +export = CTR; diff --git a/crypto-js/mode-ecb/index.d.ts b/crypto-js/mode-ecb/index.d.ts new file mode 100644 index 0000000000..569d2b2286 --- /dev/null +++ b/crypto-js/mode-ecb/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const ECB: typeof mode.ECB; +export = ECB; diff --git a/crypto-js/mode-ofb/index.d.ts b/crypto-js/mode-ofb/index.d.ts new file mode 100644 index 0000000000..484406979d --- /dev/null +++ b/crypto-js/mode-ofb/index.d.ts @@ -0,0 +1,4 @@ +import { mode } from '../index'; + +declare const OFB: typeof mode.OFB; +export = OFB; diff --git a/crypto-js/pad-ansix923/index.d.ts b/crypto-js/pad-ansix923/index.d.ts new file mode 100644 index 0000000000..2bb6c2dffb --- /dev/null +++ b/crypto-js/pad-ansix923/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const AnsiX923: typeof pad.AnsiX923; +export = AnsiX923; diff --git a/crypto-js/pad-iso10126/index.d.ts b/crypto-js/pad-iso10126/index.d.ts new file mode 100644 index 0000000000..6e52e96197 --- /dev/null +++ b/crypto-js/pad-iso10126/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const Iso10126: typeof pad.Iso10126; +export = Iso10126; diff --git a/crypto-js/pad-iso97971/index.d.ts b/crypto-js/pad-iso97971/index.d.ts new file mode 100644 index 0000000000..0ab1cecbfb --- /dev/null +++ b/crypto-js/pad-iso97971/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const Iso97971: typeof pad.Iso97971; +export = Iso97971; diff --git a/crypto-js/pad-nopadding/index.d.ts b/crypto-js/pad-nopadding/index.d.ts new file mode 100644 index 0000000000..f71bb2de73 --- /dev/null +++ b/crypto-js/pad-nopadding/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const NoPadding: typeof pad.NoPadding; +export = NoPadding; diff --git a/crypto-js/pad-pkcs7/index.d.ts b/crypto-js/pad-pkcs7/index.d.ts new file mode 100644 index 0000000000..1b194673a2 --- /dev/null +++ b/crypto-js/pad-pkcs7/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const Pkcs7: typeof pad.Pkcs7; +export = Pkcs7; diff --git a/crypto-js/pad-zeropadding/index.d.ts b/crypto-js/pad-zeropadding/index.d.ts new file mode 100644 index 0000000000..cf481402ab --- /dev/null +++ b/crypto-js/pad-zeropadding/index.d.ts @@ -0,0 +1,4 @@ +import { pad } from '../index'; + +declare const ZeroPadding: typeof pad.ZeroPadding; +export = ZeroPadding; diff --git a/crypto-js/pbkdf2/index.d.ts b/crypto-js/pbkdf2/index.d.ts new file mode 100644 index 0000000000..e242e6fe05 --- /dev/null +++ b/crypto-js/pbkdf2/index.d.ts @@ -0,0 +1,3 @@ +import { PBKDF2 } from '../index'; + +export = PBKDF2; diff --git a/crypto-js/rabbit-legacy/index.d.ts b/crypto-js/rabbit-legacy/index.d.ts new file mode 100644 index 0000000000..6befe37563 --- /dev/null +++ b/crypto-js/rabbit-legacy/index.d.ts @@ -0,0 +1,3 @@ +import { RabbitLegacy } from '../index'; + +export = RabbitLegacy; diff --git a/crypto-js/rabbit/index.d.ts b/crypto-js/rabbit/index.d.ts new file mode 100644 index 0000000000..f708a6f20b --- /dev/null +++ b/crypto-js/rabbit/index.d.ts @@ -0,0 +1,3 @@ +import { Rabbit } from '../index'; + +export = Rabbit; diff --git a/crypto-js/rc4/index.d.ts b/crypto-js/rc4/index.d.ts new file mode 100644 index 0000000000..38a929f490 --- /dev/null +++ b/crypto-js/rc4/index.d.ts @@ -0,0 +1,3 @@ +import { RC4 } from '../index'; + +export = RC4; diff --git a/crypto-js/ripemd160/index.d.ts b/crypto-js/ripemd160/index.d.ts new file mode 100644 index 0000000000..90e3e770ce --- /dev/null +++ b/crypto-js/ripemd160/index.d.ts @@ -0,0 +1,3 @@ +import { RIPEMD160 } from '../index'; + +export = RIPEMD160; diff --git a/crypto-js/sha1/index.d.ts b/crypto-js/sha1/index.d.ts new file mode 100644 index 0000000000..14fb4d2a6b --- /dev/null +++ b/crypto-js/sha1/index.d.ts @@ -0,0 +1,3 @@ +import { SHA1 } from '../index'; + +export = SHA1; diff --git a/crypto-js/sha224/index.d.ts b/crypto-js/sha224/index.d.ts new file mode 100644 index 0000000000..3ff1ff4596 --- /dev/null +++ b/crypto-js/sha224/index.d.ts @@ -0,0 +1,3 @@ +import { SHA224 } from '../index'; + +export = SHA224; diff --git a/crypto-js/sha256/index.d.ts b/crypto-js/sha256/index.d.ts new file mode 100644 index 0000000000..59781b01f3 --- /dev/null +++ b/crypto-js/sha256/index.d.ts @@ -0,0 +1,3 @@ +import { SHA256 } from '../index'; + +export = SHA256; diff --git a/crypto-js/sha3/index.d.ts b/crypto-js/sha3/index.d.ts new file mode 100644 index 0000000000..241574a711 --- /dev/null +++ b/crypto-js/sha3/index.d.ts @@ -0,0 +1,3 @@ +import { SHA3 } from '../index'; + +export = SHA3; diff --git a/crypto-js/sha384/index.d.ts b/crypto-js/sha384/index.d.ts new file mode 100644 index 0000000000..5bad55498a --- /dev/null +++ b/crypto-js/sha384/index.d.ts @@ -0,0 +1,3 @@ +import { SHA384 } from '../index'; + +export = SHA384; diff --git a/crypto-js/sha512/index.d.ts b/crypto-js/sha512/index.d.ts new file mode 100644 index 0000000000..0f764329e2 --- /dev/null +++ b/crypto-js/sha512/index.d.ts @@ -0,0 +1,3 @@ +import { SHA512 } from '../index'; + +export = SHA512; diff --git a/crypto-js/tripledes/index.d.ts b/crypto-js/tripledes/index.d.ts new file mode 100644 index 0000000000..ea22173d98 --- /dev/null +++ b/crypto-js/tripledes/index.d.ts @@ -0,0 +1,3 @@ +import { TripleDES } from '../index'; + +export = TripleDES; diff --git a/crypto-js/x64-core/index.d.ts b/crypto-js/x64-core/index.d.ts new file mode 100644 index 0000000000..1ef7a67477 --- /dev/null +++ b/crypto-js/x64-core/index.d.ts @@ -0,0 +1,3 @@ +import * as X64Core from '../index'; + +export = X64Core; From 9be29e7b530932ecc1b0165713a1e49936de78a1 Mon Sep 17 00:00:00 2001 From: darlin Date: Wed, 25 Jan 2017 15:10:10 +0800 Subject: [PATCH 083/306] add files in tsconfig --- crypto-js/lib-typedarrays/index.d.ts | 4 +-- crypto-js/tsconfig.json | 48 ++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crypto-js/lib-typedarrays/index.d.ts b/crypto-js/lib-typedarrays/index.d.ts index 91c5a7933b..761e38b1cd 100644 --- a/crypto-js/lib-typedarrays/index.d.ts +++ b/crypto-js/lib-typedarrays/index.d.ts @@ -1,2 +1,2 @@ -declare const libWordArray: any; -export = libWordArray; +declare const LibTypedarrays: any; +export = LibTypedarrays; diff --git a/crypto-js/tsconfig.json b/crypto-js/tsconfig.json index 94793c83ae..7fc335c24a 100644 --- a/crypto-js/tsconfig.json +++ b/crypto-js/tsconfig.json @@ -18,6 +18,50 @@ }, "files": [ "index.d.ts", - "crypto-js-tests.ts" + "crypto-js-tests.ts", + "core/index.d.ts", + "x64-core/index.d.ts", + "lib-typedarrays/index.d.ts", + "md5/index.d.ts", + "sha1/index.d.ts", + "sha256/index.d.ts", + "sha224/index.d.ts", + "sha512/index.d.ts", + "sha384/index.d.ts", + "sha3/index.d.ts", + "ripemd160/index.d.ts", + "hmac-md5/index.d.ts", + "hmac-sha1/index.d.ts", + "hmac-sha256/index.d.ts", + "hmac-sha224/index.d.ts", + "hmac-sha512/index.d.ts", + "hmac-sha384/index.d.ts", + "hmac-sha3/index.d.ts", + "hmac-ripemd160/index.d.ts", + "pbkdf2/index.d.ts", + "aes/index.d.ts", + "tripledes/index.d.ts", + "rc4/index.d.ts", + "rabbit/index.d.ts", + "rabbit-legacy/index.d.ts", + "evpkdf/index.d.ts", + "format-openssl/index.d.ts", + "format-hex/index.d.ts", + "enc-latin1/index.d.ts", + "enc-utf8/index.d.ts", + "enc-hex/index.d.ts", + "enc-utf16/index.d.ts", + "enc-base64/index.d.ts", + "mode-cfb/index.d.ts", + "mode-ctr/index.d.ts", + "mode-ctr-gladman/index.d.ts", + "mode-ofb/index.d.ts", + "mode-ecb/index.d.ts", + "pad-pkcs7/index.d.ts", + "pad-ansix923/index.d.ts", + "pad-iso10126/index.d.ts", + "pad-iso97971/index.d.ts", + "pad-zeropadding/index.d.ts", + "pad-nopadding/index.d.ts" ] -} \ No newline at end of file +} From d2febcc480606fab9d8564fd6e2d77f576ae39d7 Mon Sep 17 00:00:00 2001 From: darlin Date: Wed, 25 Jan 2017 16:03:50 +0800 Subject: [PATCH 084/306] add submodule tests --- crypto-js/index.d.ts | 1 - crypto-js/test/submodule-tests.ts | 184 ++++++++++++++++++++++++++++++ crypto-js/tsconfig.json | 1 + 3 files changed, 185 insertions(+), 1 deletion(-) create mode 100644 crypto-js/test/submodule-tests.ts diff --git a/crypto-js/index.d.ts b/crypto-js/index.d.ts index a8068161e1..07a8d18dfc 100644 --- a/crypto-js/index.d.ts +++ b/crypto-js/index.d.ts @@ -113,5 +113,4 @@ declare namespace CryptoJS { NoPadding: Padding; }; } - } diff --git a/crypto-js/test/submodule-tests.ts b/crypto-js/test/submodule-tests.ts new file mode 100644 index 0000000000..0cfd8cd83f --- /dev/null +++ b/crypto-js/test/submodule-tests.ts @@ -0,0 +1,184 @@ +import Core = require('../core'); +import X64Core = require('../x64-core'); +import LibTypedarrays = require('../lib-typedarrays'); +// --- +import MD5 = require('../md5'); +import SHA1 = require('../sha1'); +import SHA256 = require('../sha256'); +import SHA224 = require('../sha224'); +import SHA512 = require('../sha512'); +import SHA384 = require('../sha384'); +import SHA3 = require('../sha3'); +import RIPEMD160 = require('../ripemd160'); +// --- +import HmacMD5 = require('../hmac-md5'); +import HmacSHA1 = require('../hmac-sha1'); +import HmacSHA256 = require('../hmac-sha256'); +import HmacSHA224 = require('../hmac-sha224'); +import HmacSHA512 = require('../hmac-sha512'); +import HmacSHA384 = require('../hmac-sha384'); +import HmacSHA3 = require('../hmac-sha3'); +import HmacRIPEMD160 = require('../hmac-ripemd160'); +// --- +import PBKDF2 = require('../pbkdf2'); +// --- +import AES = require('../aes'); +import TripleDES = require('../tripledes'); +import RC4 = require('../rc4'); +import Rabbit = require('../rabbit'); +import RabbitLegacy = require('../rabbit-legacy'); +import EvpKDF = require('../evpkdf'); +// --- +import FormatOpenSSL = require('../format-openssl'); +import FormatHex = require('../format-hex'); +// --- +import EncLatin1 = require('../enc-latin1'); +import EncUtf8 = require('../enc-utf8'); +import EncHex = require('../enc-hex'); +import EncUtf16 = require('../enc-utf16'); +import EncBase64 = require('../enc-base64'); +// --- +import ModeCFB = require('../mode-cfb'); +import ModeCTR = require('../mode-ctr'); +import ModeCTRGladman = require('../mode-ctr-gladman'); +import ModeOFB = require('../mode-ofb'); +import ModeECB = require('../mode-ecb'); +// --- +import PadPkcs7 = require('../pad-pkcs7'); +import PadAnsiX923 = require('../pad-ansix923'); +import PadIso10126 = require('../pad-iso10126'); +import PadIso97971 = require('../pad-iso97971'); +import PadZeroPadding = require('../pad-zeropadding'); +import PadNoPadding = require('../pad-nopadding'); + +// Hashers +var str: string; +str = MD5('some message'); +str = MD5('some message', 'some key'); + +str = SHA1('some message'); +str = SHA1('some message', 'some key', { any: true }); + +str = FormatOpenSSL('some message'); +str = FormatOpenSSL('some message', 'some key'); + + +// Ciphers +var encrypted: CryptoJS.WordArray; +var decrypted: CryptoJS.DecryptedMessage; + +encrypted = AES.encrypt("Message", "Secret Passphrase"); +decrypted = AES.decrypt(encrypted, "Secret Passphrase"); + +encrypted = Core.DES.encrypt("Message", "Secret Passphrase"); +decrypted = Core.DES.decrypt(encrypted, "Secret Passphrase"); + +encrypted = TripleDES.encrypt("Message", "Secret Passphrase"); +decrypted = TripleDES.decrypt(encrypted, "Secret Passphrase"); + + +encrypted = Rabbit.encrypt("Message", "Secret Passphrase"); +decrypted = Rabbit.decrypt(encrypted, "Secret Passphrase"); + +encrypted = RC4.encrypt("Message", "Secret Passphrase"); +decrypted = RC4.decrypt(encrypted, "Secret Passphrase"); + +encrypted = Core.RC4Drop.encrypt("Message", "Secret Passphrase"); +encrypted = Core.RC4Drop.encrypt("Message", "Secret Passphrase", { drop: 3072 / 4 }); +decrypted = Core.RC4Drop.decrypt(encrypted, "Secret Passphrase", { drop: 3072 / 4 }); + +var key = EncHex.parse('000102030405060708090a0b0c0d0e0f'); +var iv = EncHex.parse('101112131415161718191a1b1c1d1e1f'); +encrypted = AES.encrypt("Message", key, { iv: iv }); + +encrypted = AES.encrypt("Message", "Secret Passphrase", { + mode: ModeCFB, + padding: PadAnsiX923 +}); + + +// The Cipher Output +encrypted = AES.encrypt("Message", "Secret Passphrase"); +alert(encrypted.key); +// 74eb593087a982e2a6f5dded54ecd96d1fd0f3d44a58728cdcd40c55227522223 +alert(encrypted.iv); +// 7781157e2629b094f0e3dd48c4d786115 +alert(encrypted.salt); +// 7a25f9132ec6a8b34 +alert(encrypted.ciphertext); +// 73e54154a15d1beeb509d9e12f1e462a0 +alert(encrypted); +// U2FsdGVkX1+iX5Ey7GqLND5UFUoV0b7rUJ2eEvHkYqA= + +var JsonFormatter = { + stringify: function(cipherParams: any) { + // create json object with ciphertext + var jsonObj: any = { + ct: cipherParams.ciphertext.toString(EncBase64) + }; + // optionally add iv and salt + if (cipherParams.iv) { + jsonObj.iv = cipherParams.iv.toString(); + } + if (cipherParams.salt) { + jsonObj.s = cipherParams.salt.toString(); + } + // stringify json object + return JSON.stringify(jsonObj); + }, + parse: function (jsonStr: any) { + // parse json string + var jsonObj = JSON.parse(jsonStr); + // extract ciphertext from json object, and create cipher params object + var cipherParams = (Core).lib.CipherParams.create({ + ciphertext: EncBase64.parse(jsonObj.ct) + }); + // optionally extract iv and salt + if (jsonObj.iv) { + cipherParams.iv = EncHex.parse(jsonObj.iv); + } + if (jsonObj.s) { + cipherParams.salt = EncHex.parse(jsonObj.s); + } return cipherParams; + } +}; +encrypted = AES.encrypt("Message", "Secret Passphrase", { + format: JsonFormatter +}); +alert(encrypted); +// {"ct":"tZ4MsEnfbcDOwqau68aOrQ==","iv":"8a8c8fd8fe33743d3638737ea4a00698","s":"ba06373c8f57179c"} +decrypted = AES.decrypt(encrypted, "Secret Passphrase", { + format: JsonFormatter +}); +alert(decrypted.toString(EncUtf8)); // Message + + +// Progressive Ciphering +var key = EncHex.parse('000102030405060708090a0b0c0d0e0f'); +var iv = EncHex.parse('101112131415161718191a1b1c1d1e1f'); +var aesEncryptor = Core.algo.AES.createEncryptor(key, { iv: iv }); +var ciphertextPart1 = aesEncryptor.process("Message Part 1"); +var ciphertextPart2 = aesEncryptor.process("Message Part 2"); +var ciphertextPart3 = aesEncryptor.process("Message Part 3"); +var ciphertextPart4 = aesEncryptor.finalize(); +var aesDecryptor = Core.algo.AES.createDecryptor(key, { iv: iv }); +var plaintextPart1 = aesDecryptor.process(ciphertextPart1); +var plaintextPart2 = aesDecryptor.process(ciphertextPart2); +var plaintextPart3 = aesDecryptor.process(ciphertextPart3); +var plaintextPart4 = aesDecryptor.process(ciphertextPart4); +var plaintextPart5 = aesDecryptor.finalize(); + + +// Encoders +var words = EncBase64.parse('SGVsbG8sIFdvcmxkIQ=='); +var base64 = EncBase64.stringify(words); +var words = EncLatin1.parse('Hello, World!'); +var latin1 = EncLatin1.stringify(words); +var words = EncHex.parse('48656c6c6f2c20576f726c6421'); +var hex = EncHex.stringify(words); +var words = EncUtf8.parse('𤭢'); +var utf8 = EncUtf8.stringify(words); +var words = EncUtf16.parse('Hello, World!'); +var utf16 = EncUtf16.stringify(words); +var words = Core.enc.Utf16LE.parse('Hello, World!'); +var utf16 = Core.enc.Utf16LE.stringify(words); diff --git a/crypto-js/tsconfig.json b/crypto-js/tsconfig.json index 7fc335c24a..10865613d3 100644 --- a/crypto-js/tsconfig.json +++ b/crypto-js/tsconfig.json @@ -19,6 +19,7 @@ "files": [ "index.d.ts", "crypto-js-tests.ts", + "test/submodule-tests.ts", "core/index.d.ts", "x64-core/index.d.ts", "lib-typedarrays/index.d.ts", From e364a9dd6a0627b52a3aed03a86a45391ee54771 Mon Sep 17 00:00:00 2001 From: Kacper Polak Date: Wed, 25 Jan 2017 13:16:39 +0100 Subject: [PATCH 085/306] Add missing options to isInt method Missing options: `allow_leading_zeroes`: https://github.com/chriso/validator.js/blob/master/src/lib/isInt.js#L13 `lt`: https://github.com/chriso/validator.js/blob/master/src/lib/isInt.js#L20 `gt`: https://github.com/chriso/validator.js/blob/master/src/lib/isInt.js#L21 --- validator/index.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/validator/index.d.ts b/validator/index.d.ts index 0eae66c3c9..57107ae017 100644 --- a/validator/index.d.ts +++ b/validator/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for validator.js v5.7.0 // Project: https://github.com/chriso/validator.js -// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad +// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ValidatorJS { @@ -276,6 +276,9 @@ declare namespace ValidatorJS { interface IsIntOptions { min?: number; max?: number; + allow_leading_zeroes?: boolean; + lt?: number; + gt?: number; } // options for IsLength From d8e58075a061bc85004701690fa512e98fc071a8 Mon Sep 17 00:00:00 2001 From: Kacper Polak Date: Wed, 25 Jan 2017 13:35:27 +0100 Subject: [PATCH 086/306] Increase version number --- validator/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/validator/index.d.ts b/validator/index.d.ts index 57107ae017..ec1a74c19a 100644 --- a/validator/index.d.ts +++ b/validator/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for validator.js v5.7.0 +// Type definitions for validator.js v6.2.1 // Project: https://github.com/chriso/validator.js // Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From b2af2d23e5c0ff1f2e74390f6d93752a6631d594 Mon Sep 17 00:00:00 2001 From: Pablo Moleri Date: Wed, 25 Jan 2017 10:29:43 -0300 Subject: [PATCH 087/306] Move getLocation "Axis" overloads before string ones --- webdriverio/index.d.ts | 35 ++++++++++------------------------- 1 file changed, 10 insertions(+), 25 deletions(-) diff --git a/webdriverio/index.d.ts b/webdriverio/index.d.ts index f033ec2bfc..b79b17e98d 100644 --- a/webdriverio/index.d.ts +++ b/webdriverio/index.d.ts @@ -352,37 +352,22 @@ declare namespace WebdriverIO { ): Client

; getHTML

(includeSelectorTag: boolean): Client

; - getLocation(selector?: string): Location; - getLocation(selector: string, axis: Axis): number; getLocation(axis: Axis): number; - getLocation

(selector?: string): Client

; - getLocation

( - selector: string, - axis: Axis - ): Client

; getLocation

(axis: Axis): Client

; + getLocation(selector?: string): Location; + getLocation

(selector?: string): Client

; + getLocation(selector: string, axis: Axis): number; + getLocation

(selector: string, axis: Axis): Client

; - getLocationInView(selector: string): Location; - getLocationInView(selector: string): Location[]; - getLocationInView(): Location; - getLocationInView(): Location[]; - getLocationInView( - selector: string, - axis: Axis - ): number; - getLocationInView( - selector: string, - axis: Axis - ): number[]; getLocationInView(axis: Axis): number; getLocationInView(axis: Axis): number[]; - getLocationInView

(selector?: string): Client

; - getLocationInView

( - selector: string, - axis: Axis - ): Client

; getLocationInView

(axis: Axis): Client

; - + getLocationInView(selector?: string): Location; + getLocationInView(selector?: string): Location[]; + getLocationInView

(selector?: string): Client

; + getLocationInView(selector: string, axis: Axis): number; + getLocationInView(selector: string, axis: Axis): number[]; + getLocationInView

(selector: string, axis: Axis): Client

; getSource(): Client; getSource

(): Client

; From 9294d370402f80b83a397cca709897623ca1f1f1 Mon Sep 17 00:00:00 2001 From: "LAWO\\heinigu1" Date: Wed, 25 Jan 2017 15:58:19 +0100 Subject: [PATCH 088/306] Add tv4 --- chai-json-schema/chai-json-schema-tests.ts | 20 +++++++++++++++++--- chai-json-schema/index.d.ts | 5 +++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/chai-json-schema/chai-json-schema-tests.ts b/chai-json-schema/chai-json-schema-tests.ts index 8559d3caae..d0c1234e17 100644 --- a/chai-json-schema/chai-json-schema-tests.ts +++ b/chai-json-schema/chai-json-schema-tests.ts @@ -9,19 +9,19 @@ import ChaiJsonSchema = require('chai-json-schema'); chai.use(ChaiJsonSchema); chai.should(); -let goodApple = { +const goodApple = { skin: 'thin', colors: ['red', 'green', 'yellow'], taste: 10 }; -let badApple = { +const badApple = { colors: ['brown'], taste: 0, worms: 2 }; -let fruitSchema = { +const fruitSchema = { title: 'fresh fruit schema v1', type: 'object', required: ['skin', 'colors', 'taste'], @@ -54,3 +54,17 @@ badApple.should.not.be.jsonSchema(fruitSchema); //tdd style assert.jsonSchema(goodApple, fruitSchema); assert.notJsonSchema(badApple, fruitSchema); + +// tv4 +const schema = { + items: { + type: 'boolean' + } +}; + +const data1 = [true, false]; +const data2 = [true, 123]; + +expect(chai.tv4.validate(data1, schema)).to.be.true; +expect(chai.tv4.validate(data2, schema)).to.be.false; + diff --git a/chai-json-schema/index.d.ts b/chai-json-schema/index.d.ts index e66e2c96af..1498510f9f 100644 --- a/chai-json-schema/index.d.ts +++ b/chai-json-schema/index.d.ts @@ -5,6 +5,7 @@ // // +import tv4 = require('tv4'); declare global { namespace Chai { @@ -16,6 +17,10 @@ declare global { export interface LanguageChains { jsonSchema(schema: any, msg?: string): void; } + + export interface ChaiStatic { + tv4: tv4.TV4; + } } } From 201dab6133daa473861a04631e2e6bc1abe914a8 Mon Sep 17 00:00:00 2001 From: york yao Date: Wed, 25 Jan 2017 23:58:49 +0800 Subject: [PATCH 089/306] add types of node-zookeeper-client --- node-zookeeper-client/index.d.ts | 168 ++++++++++++ .../node-zookeeper-client-tests.ts | 253 ++++++++++++++++++ node-zookeeper-client/tsconfig.json | 22 ++ node-zookeeper-client/tslint.json | 1 + 4 files changed, 444 insertions(+) create mode 100644 node-zookeeper-client/index.d.ts create mode 100644 node-zookeeper-client/node-zookeeper-client-tests.ts create mode 100644 node-zookeeper-client/tsconfig.json create mode 100644 node-zookeeper-client/tslint.json diff --git a/node-zookeeper-client/index.d.ts b/node-zookeeper-client/index.d.ts new file mode 100644 index 0000000000..f405aeffc7 --- /dev/null +++ b/node-zookeeper-client/index.d.ts @@ -0,0 +1,168 @@ +// Type definitions for Jasmine 2.5 +// Project: https://github.com/alexguan/node-zookeeper-client +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as EventEmitter from "events"; + +export class Id { + scheme: string; + id: string; + constructor(scheme: string, id: string); +} + +export class ACL { + perms: number; + id: Id; + constructor(perms: number, id: Id); +} + +export const Permission: { + READ: number, + WRITE: number, + CREATE: number, + DELETE: number, + ADMIN: number, + ALL: number, +}; + +export interface Stat { + czxid: number; + mzxid: number; + ctime: number; + mtime: number; + version: number; + cversion: number; + aversion: number; + ephemeralOwner: number; + dataLength: number; + numChildren: number; + pzxid: number; +} + +export class State { + static DISCONNECTED: State; + static SYNC_CONNECTED: State; + static AUTH_FAILED: State; + static CONNECTED_READ_ONLY: State; + static SASL_AUTHENTICATED: State; + static EXPIRED: State; + + name: string; + code: number; + constructor(name: string, code: number); + toString(): string; +} + +export class Event { + static NODE_CREATED: number; + static NODE_DELETED: number; + static NODE_DATA_CHANGED: number; + static NODE_CHILDREN_CHANGED: number; + type: string; + name: string; + path: string; + constructor(type: string, name: string, path: string); + toString(): string; + getType(): string; + getName(): string; + getPath(): string; +} + +export class Transaction { + create(path: string, dataOrAclsOrmode1?: Buffer | ACL[] | number, dataOrAclsOrmode2?: Buffer | ACL[] | number, dataOrAclsOrmode3?: Buffer | ACL[] | number): this; + setData(path: string, data: Buffer | null, version?: number): this; + check(path: string, version?: number): this; + remove(path: string, version?: number): this; + commit(callback: (error: Error | Exception, results: any) => void): void; +} + +export class Client extends EventEmitter { + connect(): void; + close(): void; + create(path: string, callback: (error: Error | Exception, path: string) => void): void; + create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + create(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, dataOrAclsOrmode3: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + remove(path: string, callback: (error: Error | Exception) => void): void; + remove(path: string, version: number, callback: (error: Error | Exception) => void): void; + exists(path: string, callback: (error: Error | Exception, stat: Stat) => void): void; + exists(path: string, watcher: (event: Event) => void, callback: (error: Error | Exception, stat: Stat) => void): void; + getChildren(path: string, callback: (error: Error | Exception, children: string[], stat: Stat) => void): void; + getChildren(path: string, watcher: (event: Event) => void, callback: (error: Error | Exception, children: string[], stat: Stat) => void): void; + getData(path: string, callback: (error: Error | Exception, data: Buffer, stat: Stat) => void): void; + getData(path: string, watcher: (event: Event) => void, callback: (error: Error | Exception, data: Buffer, stat: Stat) => void): void; + setData(path: string, data: Buffer | null, callback: (error: Error | Exception, stat: Stat) => void): void; + setData(path: string, data: Buffer | null, version: number, callback: (error: Error | Exception, stat: Stat) => void): void; + getACL(path: string, callback: (error: Error | Exception, acls: ACL[], stat: Stat) => void): void; + setACL(path: string, acls: ACL[], callback: (error: Error | Exception, stat: Stat) => void): void; + setACL(path: string, acls: ACL[], version: number, callback: (error: Error | Exception, stat: Stat) => void): void; + transaction(): Transaction; + mkdirp(path: string, callback: (error: Error | Exception, path: string) => void): void; + mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + mkdirp(path: string, dataOrAclsOrmode1: Buffer | ACL[] | number, dataOrAclsOrmode2: Buffer | ACL[] | number, dataOrAclsOrmode3: Buffer | ACL[] | number, callback: (error: Error | Exception, path: string) => void): void; + addAuthInfo(scheme: string, auth: Buffer): void; + getState(): State; + getSessionId(): Buffer; + getSessionPassword(): Buffer; + getSessionTimeout(): number; + + on(event: "state", cb: (state: State) => void): this; + on(event: "connected" | "connectedReadOnly" | "disconnected" | "expired" | "authenticationFailed" | string, cb: () => void): this; + + once(event: "state", cb: (state: State) => void): this; + once(event: "connected" | "connectedReadOnly" | "disconnected" | "expired" | "authenticationFailed" | string, cb: () => void): this; + + addListener(event: "state", cb: (state: State) => void): this; + addListener(event: "connected" | "connectedReadOnly" | "disconnected" | "expired" | "authenticationFailed" | string, cb: () => void): this; +} + +export interface Option { + sessionTimeout: number; + spinDelay: number; + retries: number; +} + +export function createClient(connectionString: string, options?: Partial

).render() || + mount(
).render(); - var reactElement: ReactElement, - objectVal: Object, - boolVal: Boolean, - stringVal: String, - elementWrapper: CheerioWrapper, {}> - - function test_find() { - elementWrapper = cheerioWrapper.find('.selector'); - cheerioWrapper = cheerioWrapper.find(MyComponent); - cheerioWrapper.find(MyStatelessComponent).props().stateless; - cheerioWrapper.find({ prop: 'myprop' }); - } - - function test_findWhere() { - cheerioWrapper = - cheerioWrapper.findWhere((aCheerioWrapper: CheerioWrapper) => true); - } - - function test_filter() { - elementWrapper = cheerioWrapper.filter('.selector'); - cheerioWrapper = cheerioWrapper.filter(MyComponent); - cheerioWrapper = cheerioWrapper.filter({ prop: 'myprop' }); - } - - function test_filterWhere() { - cheerioWrapper = - cheerioWrapper.filterWhere(wrapper => { - wrapper.props().propsProperty; - return true; - }); - } - - function test_contains() { - boolVal = cheerioWrapper.contains(
); - } - - function test_containsMatchingElement() { - boolVal = cheerioWrapper.contains(
); - } - - function test_containsAllMatchingElements() { - boolVal = cheerioWrapper.containsAllMatchingElements([
]); - } - - function test_containsAnyMatchingElement() { - boolVal = cheerioWrapper.containsAnyMatchingElements([
]); - } - - function test_equals() { - boolVal = cheerioWrapper.equals(
); - } - - function test_matchesElement() { - boolVal = cheerioWrapper.matchesElement(
); - } - - function test_hasClass() { - boolVal = cheerioWrapper.find('.my-button').hasClass('disabled'); - } - - function test_is() { - boolVal = cheerioWrapper.is('.some-class'); - } - - function test_isEmpty() { - boolVal = cheerioWrapper.isEmpty() - } - - function test_not() { - elementWrapper = cheerioWrapper.find('.foo').not('.bar'); - } - - function test_children() { - cheerioWrapper = cheerioWrapper.children(); - } - - function test_childAt() { - const childWrapper: CheerioWrapper = cheerioWrapper.childAt(0); - - interface TmpType1 { - foo: any - } - - interface TmpType2 { - bar: any - } - - const childWrapper2: CheerioWrapper = cheerioWrapper.childAt(0); - } - - function test_parents() { - cheerioWrapper = cheerioWrapper.parents(); - } - - function test_parent() { - cheerioWrapper = cheerioWrapper.parent(); - } - - function test_closest() { - elementWrapper = cheerioWrapper.closest('.selector'); - cheerioWrapper = cheerioWrapper.closest(MyComponent); - cheerioWrapper = cheerioWrapper.closest({ prop: 'myprop' }); - } - - function test_text() { - stringVal = cheerioWrapper.text(); - } - - function test_html() { - stringVal = cheerioWrapper.html(); - } - - function test_get() { - reactElement = cheerioWrapper.get(1); - } - - function test_at() { - cheerioWrapper = cheerioWrapper.at(1); - } - - function test_first() { - cheerioWrapper = cheerioWrapper.first(); - } - - function test_last() { - cheerioWrapper = cheerioWrapper.last(); - } - - function test_state() { - cheerioWrapper.state(); - cheerioWrapper.state('key'); - const tmp: String = cheerioWrapper.state('key'); - } - - function test_context() { - cheerioWrapper.context(); - cheerioWrapper.context('key'); - const tmp: String = cheerioWrapper.context('key'); - } - - function test_props() { - objectVal = cheerioWrapper.props(); - } - - function test_prop() { - cheerioWrapper.prop('key'); - const tmp: String = cheerioWrapper.prop('key'); - } - - function test_key() { - stringVal = cheerioWrapper.key(); - } - - function test_simulate(...args: any[]) { - cheerioWrapper.simulate('click'); - cheerioWrapper.simulate('click', args); - } - - function test_setState() { - cheerioWrapper = cheerioWrapper.setState({ stateProperty: 'state' }); - } - - function test_setProps() { - cheerioWrapper = cheerioWrapper.setProps({ propsProperty: 'foo' }); - } - - function test_setContext() { - cheerioWrapper = cheerioWrapper.setContext({ name: 'baz' }); - } - - function test_instance() { - var myComponent: MyComponent = cheerioWrapper.instance(); - } - - function test_update() { - cheerioWrapper = cheerioWrapper.update(); - } - - function test_debug() { - stringVal = cheerioWrapper.debug(); - } - - function test_type() { - var stringOrFunction: String | Function = cheerioWrapper.type(); - } - - function test_name() { - var str: String = cheerioWrapper.name(); - } - - function test_forEach() { - cheerioWrapper = - cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper) => { - }); - } - - function test_map() { - var arrayNumbers: Array = - cheerioWrapper.map(wrapper => wrapper.props().numberProp); - } - - function test_reduce() { - const total: number = - cheerioWrapper.reduce( - (amount: number, n: CheerioWrapper) => amount + n.prop('amount') - ); - } - - function test_reduceRight() { - const total: number = - cheerioWrapper.reduceRight( - (amount: number, n: CheerioWrapper) => amount + n.prop('amount') - ); - } - - function test_some() { - boolVal = cheerioWrapper.some('.selector'); - boolVal = cheerioWrapper.some(MyComponent); - } - - function test_someWhere() { - boolVal = cheerioWrapper.someWhere((aCheerioWrapper: CheerioWrapper) => true); - } - - function test_every() { - boolVal = cheerioWrapper.every('.selector'); - boolVal = cheerioWrapper.every(MyComponent); - } - - function test_everyWhere() { - boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper) => true); - } + wrapper.toggleClass('className'); } diff --git a/enzyme/index.d.ts b/enzyme/index.d.ts index 5502b0eb85..7559985e21 100644 --- a/enzyme/index.d.ts +++ b/enzyme/index.d.ts @@ -1,16 +1,27 @@ -// Type definitions for Enzyme v2.7.0 +// Type definitions for Enzyme 2.7 // Project: https://github.com/airbnb/enzyme -// Definitions by: Marian Palkus , Cap3 , Ivo Stratev , Tom Crockett +// Definitions by: Marian Palkus , Cap3 , Ivo Stratev , Tom Crockett , jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -import { ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; +/// +import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; export class ElementClass extends Component { } +/* These are purposefully stripped down versions of React.ComponentClass and React.StatelessComponent. + * The optional static properties on them break overload ordering for wrapper methods if they're not + * all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics + */ +interface ComponentClass { + new(props?: Props, context?: any): Component; +} + +type StatelessComponent = (props: Props, context?: any) => JSX.Element; + /** * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the * following three categories: @@ -21,34 +32,12 @@ export class ElementClass extends Component { * 4. A React Stateless component * 5. A React component property map */ -export type EnzymeSelector = string | StatelessComponent | ComponentClass | { [key: string]: any }; -export type EnzymePropSelector = { [key: string]: any }; +export interface EnzymePropSelector { + [key: string]: any; +} +export type EnzymeSelector = string | StatelessComponent | ComponentClass | EnzymePropSelector; interface CommonWrapper { - /** - * Find every node in the render tree that matches the provided selector. - * @param selector The selector to match. - */ - find(component: ComponentClass): CommonWrapper; - find(statelessComponent: StatelessComponent): CommonWrapper; - find(props: EnzymePropSelector): CommonWrapper; - find(selector: string): CommonWrapper; - - /** - * Finds every node in the render tree that returns true for the provided predicate function. - * @param predicate - */ - findWhere(predicate: (wrapper: CommonWrapper) => boolean): CommonWrapper; - - /** - * Removes nodes in the current wrapper that do not match the provided selector. - * @param selector The selector to match. - */ - filter(component: ComponentClass): CommonWrapper; - filter(statelessComponent: StatelessComponent): CommonWrapper; - filter(props: EnzymePropSelector): CommonWrapper; - filter(selector: string): CommonWrapper; - /** * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. * @param predicate @@ -71,13 +60,13 @@ interface CommonWrapper { * Returns whether or not all the given react elements exists in the shallow render tree * @param nodes */ - containsAllMatchingElements(nodes: ReactElement[]): boolean; + containsAllMatchingElements(nodes: Array>): boolean; /** * Returns whether or not one of the given react elements exists in the shallow render tree. * @param nodes */ - containsAnyMatchingElements(nodes: ReactElement[]): boolean; + containsAnyMatchingElements(nodes: Array>): boolean; /** * Returns whether or not the current render tree is equal to the given node, based on the expected value. @@ -118,54 +107,6 @@ interface CommonWrapper { */ not(selector: EnzymeSelector): this; - /** - * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector - * can be provided and it will filter the children by this selector. - * @param [selector] - */ - children(component: ComponentClass): CommonWrapper; - children(statelessComponent: StatelessComponent): CommonWrapper; - children(props: EnzymePropSelector): CommonWrapper; - children(selector: string): CommonWrapper; - children(): CommonWrapper; - - /** - * Returns a new wrapper with child at the specified index. - * @param index - */ - childAt(index: number): CommonWrapper; - childAt(index: number): CommonWrapper; - - /** - * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the - * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. - * - * Note: can only be called on a wrapper of a single node. - * @param [selector] - */ - parents(component: ComponentClass): CommonWrapper; - parents(statelessComponent: StatelessComponent): CommonWrapper; - parents(props: EnzymePropSelector): CommonWrapper; - parents(selector: string): CommonWrapper; - parents(): CommonWrapper; - - /** - * Returns a wrapper with the direct parent of the node in the current wrapper. - */ - parent(): CommonWrapper; - - /** - * Returns a wrapper of the first element that matches the selector by traversing up through the current node's - * ancestors in the tree, starting with itself. - * - * Note: can only be called on a wrapper of a single node. - * @param selector - */ - closest(component: ComponentClass): CommonWrapper; - closest(statelessComponent: StatelessComponent): CommonWrapper; - closest(props: EnzymePropSelector): CommonWrapper; - closest(selector: string): CommonWrapper; - /** * Returns a string of the rendered text of the current render tree. This function should be looked at with * skepticism if being used to test what the actual HTML output of the component will be. If that is what you @@ -209,14 +150,14 @@ interface CommonWrapper { * @param [key] */ state(): S; - state(key: string): any; + state(key: K): S[K]; state(key: string): T; /** * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. */ - context(key?: string): any; - context(key?: string): T; + context(): any; + context(key: string): T; /** * Returns the props hash for the current node of the wrapper. @@ -231,7 +172,7 @@ interface CommonWrapper { * NOTE: can only be called on a wrapper of a single node. * @param key */ - prop(key: string): any; + prop(key: K): P[K]; prop(key: string): T; /** @@ -260,7 +201,7 @@ interface CommonWrapper { * @param state * @param [callback] */ - setState(state: S, callback?: () => void): this; + setState(state: Pick, callback?: () => void): this; /** * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test @@ -274,7 +215,7 @@ interface CommonWrapper { * @param props * @param [callback] */ - setProps(props: P, callback?: () => void): this; + setProps(props: Pick): this; /** * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to @@ -284,7 +225,7 @@ interface CommonWrapper { * NOTE: can only be called on a wrapper instance that is also the root instance. * @param state */ - setContext(context: Object): this; + setContext(context: any): this; /** * Gets the instance of the component being rendered as the root node passed into shallow(). @@ -308,14 +249,6 @@ interface CommonWrapper { */ debug(): string; - /** - * Returns the type of the current node of this wrapper. If it's a composite component, this will be the - * component constructor. If it's native DOM node, it will be a string of the tag name. - * - * Note: can only be called on a wrapper of a single node. - */ - type(): string | Function; - /** * Returns the name of the current node of the wrapper. */ @@ -381,12 +314,29 @@ interface CommonWrapper { */ everyWhere(fn: (wrapper: this) => boolean): boolean; + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; + + /** + * Renders the component to static markup and returns a Cheerio wrapper around the result. + */ + render(): Cheerio; + + /** + * Returns the type of the current node of this wrapper. If it's a composite component, this will be the + * component constructor. If it's native DOM node, it will be a string of the tag name. + * + * Note: can only be called on a wrapper of a single node. + */ + type(): string | ComponentClass

| StatelessComponent

; + length: number; } export interface ShallowWrapper extends CommonWrapper { shallow(): ShallowWrapper; - render(): CheerioWrapper; unmount(): ShallowWrapper; /** @@ -394,7 +344,7 @@ export interface ShallowWrapper extends CommonWrapper { * @param selector The selector to match. */ find(component: ComponentClass): ShallowWrapper; - find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; + find(statelessComponent: StatelessComponent): ShallowWrapper; find(props: EnzymePropSelector): ShallowWrapper; find(selector: string): ShallowWrapper; @@ -403,7 +353,7 @@ export interface ShallowWrapper extends CommonWrapper { * @param selector The selector to match. */ filter(component: ComponentClass): ShallowWrapper; - filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(statelessComponent: StatelessComponent): ShallowWrapper; filter(props: EnzymePropSelector): ShallowWrapper; filter(selector: string): ShallowWrapper; @@ -411,7 +361,7 @@ export interface ShallowWrapper extends CommonWrapper { * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => boolean): ShallowWrapper; + findWhere(predicate: (wrapper: ShallowWrapper) => boolean): ShallowWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector @@ -419,10 +369,9 @@ export interface ShallowWrapper extends CommonWrapper { * @param [selector] */ children(component: ComponentClass): ShallowWrapper; - children(statelessComponent: StatelessComponent): ShallowWrapper; - children(props: EnzymePropSelector): ShallowWrapper; + children(statelessComponent: StatelessComponent): ShallowWrapper; children(selector: string): ShallowWrapper; - children(): ShallowWrapper; + children(props?: EnzymePropSelector): ShallowWrapper; /** * Returns a new wrapper with child at the specified index. @@ -432,13 +381,13 @@ export interface ShallowWrapper extends CommonWrapper { childAt(index: number): ShallowWrapper; /** - * Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result. - * NOTE: can only be called on wrapper of a single non-DOM component element node. - * @param [options] - */ - dive(options?: ShallowRendererProps): ShallowWrapper; + * Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result. + * NOTE: can only be called on wrapper of a single non-DOM component element node. + * @param [options] + */ + dive(options?: ShallowRendererProps): ShallowWrapper; - /** + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * @@ -446,10 +395,9 @@ export interface ShallowWrapper extends CommonWrapper { * @param [selector] */ parents(component: ComponentClass): ShallowWrapper; - parents(statelessComponent: StatelessComponent): ShallowWrapper; - parents(props: EnzymePropSelector): ShallowWrapper; + parents(statelessComponent: StatelessComponent): ShallowWrapper; parents(selector: string): ShallowWrapper; - parents(): ShallowWrapper; + parents(props?: EnzymePropSelector): ShallowWrapper; /** * Returns a wrapper of the first element that matches the selector by traversing up through the current node's @@ -459,7 +407,7 @@ export interface ShallowWrapper extends CommonWrapper { * @param selector */ closest(component: ComponentClass): ShallowWrapper; - closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(statelessComponent: StatelessComponent): ShallowWrapper; closest(props: EnzymePropSelector): ShallowWrapper; closest(selector: string): ShallowWrapper; @@ -467,17 +415,11 @@ export interface ShallowWrapper extends CommonWrapper { * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ShallowWrapper; - - /** - * Returns true if renderer returned null - */ - isEmptyRender(): boolean; } export interface ReactWrapper extends CommonWrapper { unmount(): ReactWrapper; mount(): ReactWrapper; - render(): CheerioWrapper; /** * Returns a wrapper of the node that matches the provided reference name. @@ -503,7 +445,7 @@ export interface ReactWrapper extends CommonWrapper { * @param selector The selector to match. */ find(component: ComponentClass): ReactWrapper; - find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(statelessComponent: StatelessComponent): ReactWrapper; find(props: EnzymePropSelector): ReactWrapper; find(selector: string): ReactWrapper; @@ -511,14 +453,14 @@ export interface ReactWrapper extends CommonWrapper { * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => boolean): ReactWrapper; + findWhere(predicate: (wrapper: ReactWrapper) => boolean): ReactWrapper; /** * Removes nodes in the current wrapper that do not match the provided selector. * @param selector The selector to match. */ filter(component: ComponentClass): ReactWrapper; - filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(statelessComponent: StatelessComponent): ReactWrapper; filter(props: EnzymePropSelector): ReactWrapper; filter(selector: string): ReactWrapper; @@ -528,10 +470,9 @@ export interface ReactWrapper extends CommonWrapper { * @param [selector] */ children(component: ComponentClass): ReactWrapper; - children(statelessComponent: StatelessComponent): ReactWrapper; - children(props: EnzymePropSelector): ReactWrapper; + children(statelessComponent: StatelessComponent): ReactWrapper; children(selector: string): ReactWrapper; - children(): ReactWrapper; + children(props?: EnzymePropSelector): ReactWrapper; /** * Returns a new wrapper with child at the specified index. @@ -548,10 +489,9 @@ export interface ReactWrapper extends CommonWrapper { * @param [selector] */ parents(component: ComponentClass): ReactWrapper; - parents(statelessComponent: StatelessComponent): ReactWrapper; - parents(props: EnzymePropSelector): ReactWrapper; + parents(statelessComponent: StatelessComponent): ReactWrapper; parents(selector: string): ReactWrapper; - parents(): ReactWrapper; + parents(props?: EnzymePropSelector): ReactWrapper; /** * Returns a wrapper of the first element that matches the selector by traversing up through the current node's @@ -561,7 +501,7 @@ export interface ReactWrapper extends CommonWrapper { * @param selector */ closest(component: ComponentClass): ReactWrapper; - closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(statelessComponent: StatelessComponent): ReactWrapper; closest(props: EnzymePropSelector): ReactWrapper; closest(selector: string): ReactWrapper; @@ -569,15 +509,6 @@ export interface ReactWrapper extends CommonWrapper { * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ReactWrapper; - - /** - * Returns true if renderer returned null - */ - isEmptyRender(): boolean; -} - -export interface CheerioWrapper extends CommonWrapper { - } export interface ShallowRendererProps { @@ -626,8 +557,4 @@ export function mount(node: ReactElement

, options?: MountRendererProps) * @param node * @param [options] */ -export function render(node: ReactElement

, options?: any): CheerioWrapper; - -export function describeWithDOM(description: string, fn: Function): void; - -export function spyLifecycle(component: typeof Component): void; +export function render(node: ReactElement

, options?: any): Cheerio; diff --git a/enzyme/tslint.json b/enzyme/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/enzyme/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} From dc32857218307d8a96e640854ed4e62d144cb18c Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 26 Jan 2017 14:53:33 +0900 Subject: [PATCH 108/306] Add typings for react-json-pretty --- react-json-pretty/index.d.ts | 21 +++++++++++++++++++ react-json-pretty/react-json-pretty-tests.tsx | 17 +++++++++++++++ react-json-pretty/tsconfig.json | 21 +++++++++++++++++++ react-json-pretty/tslint.json | 1 + 4 files changed, 60 insertions(+) create mode 100644 react-json-pretty/index.d.ts create mode 100644 react-json-pretty/react-json-pretty-tests.tsx create mode 100644 react-json-pretty/tsconfig.json create mode 100644 react-json-pretty/tslint.json diff --git a/react-json-pretty/index.d.ts b/react-json-pretty/index.d.ts new file mode 100644 index 0000000000..5ca8bbf13b --- /dev/null +++ b/react-json-pretty/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for react-json-pretty 1.3 +// Project: https://github.com/chenckang/react-json-pretty +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { ComponentClass, HTMLProps } from "react"; + +export as namespace JSONPretty; + +export = JSONPretty; + +declare const JSONPretty: JSONPretty; +type JSONPretty = ComponentClass; + +declare namespace JSONPretty { + + export interface JSONPrettyProps extends HTMLProps { + json: {} | string; + } + +} diff --git a/react-json-pretty/react-json-pretty-tests.tsx b/react-json-pretty/react-json-pretty-tests.tsx new file mode 100644 index 0000000000..59f8eb74f3 --- /dev/null +++ b/react-json-pretty/react-json-pretty-tests.tsx @@ -0,0 +1,17 @@ +import * as React from "react"; +import * as JSONPretty from "react-json-pretty"; + +export class Test extends React.Component { + render() { + const json = { + foo: "bar" + } + + return ( +

+ + +
+ ); + } +} diff --git a/react-json-pretty/tsconfig.json b/react-json-pretty/tsconfig.json new file mode 100644 index 0000000000..ddb38d587e --- /dev/null +++ b/react-json-pretty/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "jsx": "preserve", + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-json-pretty-tests.tsx" + ] +} diff --git a/react-json-pretty/tslint.json b/react-json-pretty/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-json-pretty/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } From 748431211f8bc7306c1384f44f4b9bbe05222cee Mon Sep 17 00:00:00 2001 From: Shun Date: Wed, 25 Jan 2017 23:37:18 -0800 Subject: [PATCH 109/306] Add typing files for forever-monitor 1.7 --- forever-monitor/forever-monitor-tests.ts | 15 +++++++++++++++ forever-monitor/index.d.ts | 18 +++++++++--------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/forever-monitor/forever-monitor-tests.ts b/forever-monitor/forever-monitor-tests.ts index e69de29bb2..f679c4704a 100644 --- a/forever-monitor/forever-monitor-tests.ts +++ b/forever-monitor/forever-monitor-tests.ts @@ -0,0 +1,15 @@ +// Test from https://github.com/foreverjs/forever-monitor + +import * as forever from "forever-monitor"; + +const child = new (forever.Monitor)('your-filename.js', { + max: 3, + silent: true, + args: [] +}); + +child.on('exit', function() { + console.log('your-filename.js has exited after 3 restarts'); +}); + +child.start(); diff --git a/forever-monitor/index.d.ts b/forever-monitor/index.d.ts index b22905cae2..58c32ec5e6 100644 --- a/forever-monitor/index.d.ts +++ b/forever-monitor/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for forever-monitor 1.7 // Project: https://github.com/nodejitsu/forever-monitor#readme -// Definitions by: My Self +// Definitions by: Shun Takahashi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -53,44 +53,44 @@ export declare class Monitor extends NodeJS.EventEmitter { * @description Start the process that this instance is configured for * @param [restart] - Value indicating whether this is a restart. */ - public start(restart?: boolean): this; + start(restart?: boolean): this; /** * @description Tries to spawn the target Forever child process. */ - public trySpawn(): boolean; + trySpawn(): boolean; /** * @description Restarts the target script associated with this instance. */ - public restart(): this; + restart(): this; /** * @description Stops the target script associated with this instance. Prevents it from auto-respawning */ - public stop(): this; + stop(): this; /** * @description Kills the ChildProcess object associated with this instance * @param [forceStop] - Value indicating whether short circuit forever auto-restart */ - public kill(forceStop?: boolean): this; + kill(forceStop?: boolean): this; /** * @description Sends a message to a forked ChildProcess object associated with this instance */ - public send(msg?: any): this; + send(msg?: any): this; /** * respond with JSON for this instance */ - public toString(): string; + toString(): string; /** * @param command - Command string to parse * @param args - Additional default arguments */ - public parseCommand(command: string, args?: string[]): (false | { command: string, args?: string[]}); + parseCommand(command: string, args?: string[]): (false | { command: string, args?: string[]}); } interface forever { From d34e301e35d6bac5d7b6b8c44ba3580cbd3d0d5b Mon Sep 17 00:00:00 2001 From: Kacper Polak Date: Thu, 26 Jan 2017 09:17:44 +0100 Subject: [PATCH 110/306] Downgrade version --- validator/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/validator/index.d.ts b/validator/index.d.ts index ec1a74c19a..36b7d23088 100644 --- a/validator/index.d.ts +++ b/validator/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for validator.js v6.2.1 +// Type definitions for validator.js v6.2.0 // Project: https://github.com/chriso/validator.js // Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From e297d2677fb7bb82e6c06ef4a34532c8d65bcb0b Mon Sep 17 00:00:00 2001 From: york yao Date: Thu, 26 Jan 2017 19:20:44 +0800 Subject: [PATCH 111/306] fix name, class to interface, var to const, enable strictNullChecks --- node-zookeeper-client/index.d.ts | 6 +++--- .../node-zookeeper-client-tests.ts | 14 +++++++------- node-zookeeper-client/tsconfig.json | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/node-zookeeper-client/index.d.ts b/node-zookeeper-client/index.d.ts index cb9979e9f4..a85d14b7cc 100644 --- a/node-zookeeper-client/index.d.ts +++ b/node-zookeeper-client/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jasmine 2.5 +// Type definitions for node-zookeeper-client 0.2 // Project: https://github.com/alexguan/node-zookeeper-client // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -72,7 +72,7 @@ export class Event { getPath(): string; } -export class Transaction { +interface Transaction { create(path: string, dataOrAclsOrmode1?: Buffer | ACL[] | number, dataOrAclsOrmode2?: Buffer | ACL[] | number, dataOrAclsOrmode3?: Buffer | ACL[] | number): this; setData(path: string, data: Buffer | null, version?: number): this; check(path: string, version?: number): this; @@ -80,7 +80,7 @@ export class Transaction { commit(callback: (error: Error | Exception, results: any) => void): void; } -export class Client extends EventEmitter { +interface Client extends EventEmitter { connect(): void; close(): void; create(path: string, callback: (error: Error | Exception, path: string) => void): void; diff --git a/node-zookeeper-client/node-zookeeper-client-tests.ts b/node-zookeeper-client/node-zookeeper-client-tests.ts index 19cca8628b..91c434bafa 100644 --- a/node-zookeeper-client/node-zookeeper-client-tests.ts +++ b/node-zookeeper-client/node-zookeeper-client-tests.ts @@ -1,8 +1,8 @@ import * as zookeeper from "node-zookeeper-client"; { - var client = zookeeper.createClient('localhost:2181'); - var path = process.argv[2]; + const client = zookeeper.createClient('localhost:2181'); + const path = process.argv[2]; client.once('connected', function () { console.log('Connected to the server.'); @@ -44,8 +44,8 @@ function listChildren(client: zookeeper.Client, path: string) { } { - var client = zookeeper.createClient('localhost:2181'); - var path = process.argv[2]; + const client = zookeeper.createClient('localhost:2181'); + const path = process.argv[2]; client.once('connected', function () { console.log('Connected to ZooKeeper.'); @@ -55,7 +55,7 @@ function listChildren(client: zookeeper.Client, path: string) { client.connect(); } -var client = zookeeper.createClient( +const client = zookeeper.createClient( 'localhost:2181/test', { sessionTimeout: 10000 } ); @@ -188,12 +188,12 @@ var client = zookeeper.createClient( } { - var state = client.getState(); + const state = client.getState(); console.log('Current state is: %s', state); } { - var id = client.getSessionId(); + const id = client.getSessionId(); console.log('Session id is: %s', id.toString('hex')); } diff --git a/node-zookeeper-client/tsconfig.json b/node-zookeeper-client/tsconfig.json index d93291d45b..1f5ffdedf8 100644 --- a/node-zookeeper-client/tsconfig.json +++ b/node-zookeeper-client/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From c4cee4d79eb3b6d8eb5e99424913ea5af103ec10 Mon Sep 17 00:00:00 2001 From: york yao Date: Thu, 26 Jan 2017 20:01:15 +0800 Subject: [PATCH 112/306] fix wrong CreateMode value --- node-zookeeper-client/index.d.ts | 2 +- node-zookeeper-client/node-zookeeper-client-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/node-zookeeper-client/index.d.ts b/node-zookeeper-client/index.d.ts index a85d14b7cc..227ebd45ad 100644 --- a/node-zookeeper-client/index.d.ts +++ b/node-zookeeper-client/index.d.ts @@ -132,7 +132,7 @@ export function createClient(connectionString: string, options?: Partial